Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(ai): ai text steps pick from the shared model picker, tiers included (#16603)

Louai Boumediene77f8e08a0d4b
diff --git a/brain/knowledge/ai-intelligence/model-picker.md b/brain/knowledge/ai-intelligence/model-picker.md
index ba2c08290b6..b9fcae370b0 100644
--- a/brain/knowledge/ai-intelligence/model-picker.md
+++ b/brain/knowledge/ai-intelligence/model-picker.md
@@ -34,7 +34,10 @@ On `agent` and `chat` a tier whose main model can't call tools is hidden, and so
- A stored deleted tier shows its live replacement ("Moved"), because the runtime follows `replacedBy` too. The picker sends its stored `tierId` and `movedTiers` follows only that chain; without a `tierId` it is empty.
- On chat, a key with a typed-in model list (Vertex, Custom) offers exactly that list, not the curated list. The chat runner (`agentModelResolution`) picks only from the manual list, so a curated model outside it would be silently swapped.
- A stored model that the admin hid with the specific-models toggle shows "Hidden by admin". It still runs, because the toggle is not enforced at run time.
-- `surface='flow'` turns off the tool-calling filter (`callsTools` in `aiModelOptionsService`), so it is only for text AI steps. The Run Agent step needs tools, so it uses `surface='agent'`.
+- `surface='flow'` turns off the tool-calling filter (`callsTools` in `aiModelOptionsService`), so it is only for Ask AI, Summarize and Classify. Run Agent and Extract Structured Data answer through tools, so they use `surface='agent'` (`agentModelUtils.fieldFor`).
+- **AI piece text steps (piece-ai 0.15.0+) store the same `aiProviderModel` value as Run Agent** (`{provider, model, configId?} | {modelTierId}`), rendered by `AgentModelField` from the generic property renderer (`selectGenericFormComponentForProperty`, piece-ai + that prop name). Older steps keep their `provider` + `model` dropdowns until flow migration v28 moves them. Image steps keep their dropdowns: tiers are text only. A custom field in that renderer must sit inside `AutoFormFieldWrapper`, or it loses the expression switch (it lives in the wrapper's label row); the picker skips the wrapper only when `allowDynamicValues` is false, which is Run Agent's settings form. Switching back from expression mode restores the value through `formUtils.parseDynamicValue`, which needs a case per property type; a type without one comes back as its default, and the picker then writes the default model on its own (Object got its case in PR 8).
+- **Flow migration v28 picks AI steps by what they store, never by piece version.** A text step with `provider`/`model` and no `aiProviderModel` is moved; an old Credits id (`anthropic/claude-haiku-4.5`, `sonnet-4.6`, `opus-4.8`) becomes `fast`/`smart`/`premium` on any non-image step. The id map is frozen inside the migration; never import `ACTIVEPIECES_CHAT_TIERS` there, it will change. It landed **not armed** (outside the migrations list, schema stays 28); a later PR arms it, so a one-release rollback stays safe.
+- **Agent rows (`agent.draft/published.modelName`) holding an old Credits id are not migrated, and they throw** in `resolveNamedModelId` once the built-in tier list drops the 4.x ids (an AI piece step just passes the id through). Rewrite them before or with any release that changes `ACTIVEPIECES_CHAT_TIERS`.
- The Run Agent step does not go through `/v1/ai/execute`. Its piece posts to `/v1/agents/runs`, and the agent runtime resolves the model (`getAgentConfig` → `agentModelTier.resolveRun`). Steps pin an exact piece version, so a field the piece learns to forward reaches only steps on that version or newer.
- The Run Agent step stores a tier as `{ modelTierId }` and only piece-ai 0.14.1+ forwards it. On an older step `AgentModelField` hides tiers and shows a one-line hint to update the step. Downgrading a step below 0.14.1 keeps the stored tier, and the old piece drops it, so that run uses the Default AI key.
- A flow step has no server create hook, so `AgentModelField` writes `defaultChoice` once when the stored value is empty and the step is editable. On an old step it writes the credits default or the first key model instead of a tier.
@@ -57,4 +60,5 @@ On `agent` and `chat` a tier whose main model can't call tools is hidden, and so
## Key files
- `packages/web/src/features/agents/ai-model/`: `ModelPicker`, `ModelPickerPopover`, `ModelDetailCard`
- `packages/server/api/src/app/ai/`: `aiModelOptionsService`
-- `packages/web/src/app/builder/step-settings/agent-settings/`: `AgentModelField`, `agentModelUtils` (the Run Agent step)
+- `packages/web/src/app/builder/step-settings/agent-settings/`: `AgentModelField`, `agentModelUtils` (Run Agent and the AI piece text steps)
+- `packages/server/api/src/app/flows/flow-version/migrations/`: `migrateV28AiPieceModelPicker`
diff --git a/brain/knowledge/decisions/000049-ai-step-picker-and-tier-slug-rewrite-share-one-flow-migration.md b/brain/knowledge/decisions/000049-ai-step-picker-and-tier-slug-rewrite-share-one-flow-migration.md
new file mode 100644
index 00000000000..4a5c013e324
--- /dev/null
+++ b/brain/knowledge/decisions/000049-ai-step-picker-and-tier-slug-rewrite-share-one-flow-migration.md
@@ -0,0 +1,17 @@
+---
+status: accepted
+---
+
+# AI step picker move and tier-slug rewrite share one flow migration, armed a release later
+
+## Decision
+Flow migration v28 → 29 (`migrateV28AiPieceModelPicker`) does two jobs at once. It moves AI piece text steps from `provider` + `model` onto the `aiProviderModel` picker value (piece-ai 0.15.0). It also rewrites the three old Credits model ids to the tier slugs they were picked as (ENG-753). It ships in one PR without being registered, and a three-line follow-up arms it one release later. Agent rows are not part of it.
+
+## Context
+ENG-753 (from the configurable-tiers stack) was postponed on 2026-09-26: old steps keep their pinned Credits model and only miss tier moves. Platform tiers PR 8 had to rewrite the same steps to move them onto the shared picker. Main had already used v27 → 28 for Oracle, so both wanted v28 → 29.
+
+## Why
+One migration means one schema bump and one flow-cache refill instead of two, and the two rewrites touch the same field on the same steps. It lands disarmed because the migration moves steps onto a piece version only the new release can render. Rolling a server back past a schema bump fails silently, so the code ships one release before the migration runs. Rejected: two migrations (v29 + v30), which double the deploy cost for no gain.
+
+## Consequences
+The id map is frozen in the migration and must never import `ACTIVEPIECES_CHAT_TIERS`. Agent rows with old Credits ids still need their own rewrite before the built-in tier list changes, because `resolveNamedModelId` throws on them.
diff --git a/brain/knowledge/pieces-engine/pieces.md b/brain/knowledge/pieces-engine/pieces.md
index 42860a62636..c92cf7bf048 100644
--- a/brain/knowledge/pieces-engine/pieces.md
+++ b/brain/knowledge/pieces-engine/pieces.md
@@ -23,7 +23,7 @@ The metadata catalog of automation integrations ("pieces") — each a named inte
- EE/Cloud per-piece and per-action/trigger visibility flows through `resolveVisibility` (`ee/pieces/filters/piece-filtering-utils.ts`), which returns a `VisibilityPolicy` or `null` on CE / when `platformId`/`projectId` is nil (callers treat `null` as no filtering). The policy is derived from the project's **piece set** (via `project.pieceSetId`, falling back to the platform Default).
- Install and sync also enqueue a tool-search reindex, but only when `isToolSearchEnabled()`; no-op otherwise.
- `delete` removes all versions sharing the name on that platform, and only for `CUSTOM` pieces the caller owns.
-- **A piece silently vanishes from the list when its `minimumSupportedRelease` is ahead of the root `package.json` version.** `fetchLatestPieces` filters every piece through `isSupportedRelease(apVersionUtil.getCurrentRelease(), piece)`. Pieces are routinely merged targeting the *next* release, so on `main` a couple dozen are invisible locally until the version bump lands. No warning is logged — it just isn't there. The same gate hides the version from exact-version lookups (`findExactVersion`), so a flow step saved on it fails to load on an older server, and `AP_DEV_PIECES` does not bypass it: the database copies are dropped by name and the dev copy by release, so the piece vanishes entirely. To test a piece that targets the next release, bump the root `package.json` version locally and do not commit it. A server that already reports that release but lacks the server code the piece needs is the dangerous case; check `origin/main`'s root version at merge time.
+- **A piece silently vanishes from the list when its `minimumSupportedRelease` is ahead of the root `package.json` version.** `fetchLatestPieces` filters every piece through `isSupportedRelease(apVersionUtil.getCurrentRelease(), piece)`. Pieces are routinely merged targeting the *next* release, so on `main` a couple dozen are invisible locally until the version bump lands. No warning is logged — it just isn't there. The same gate hides the version from exact-version lookups (`findExactVersion`), so a flow step saved on it fails to load on an older server, and `AP_DEV_PIECES` does not bypass it: the database copies are dropped by name and the dev copy by release, so the piece vanishes entirely. To test a piece that targets the next release, bump the root `package.json` version locally and do not commit it. A server that already reports that release but lacks the server code the piece needs is the dangerous case; check `origin/main`'s root version at merge time. Cloud runs the same gate on its root version: on 2026-10-20 cloud reported 0.92.2 and served piece-ai 0.11.0 while main had 0.14.1, so every version gated on the next release (0.12 to 0.15) switches on for everyone at once with the bump. See what cloud serves with `curl https://cloud.activepieces.com/api/v1/pieces/@activepieces/piece-<name>` (`version`, `minimumSupportedRelease`). Merging publishes the piece to the registry at once (`release-pieces.yml` on push to main), before any deploy. That is safe because the gate also covers self-hosted: sync asks the registry with `release=<own version>` (`listCloudPieces`), so an older backend never downloads it.
- **`/v1/pieces` is uncached, so a new `piece_metadata` column must be added to `PIECE_COLUMNS_WITHOUT_TRANSLATIONS` or it silently will not appear in the list.** `pieceCache` caches only the *registry* (name/version/platformId tuples) for `get`/`findExactVersion`/`registry`; the list path never touches it, and the `dedupe()` helper in `piece-metadata-service.ts` is in-flight-only (it deletes the key in `finally`), so it collapses concurrent callers but caches nothing between requests. Every request therefore re-runs the whole pipeline against the DB. Because of that, `fetchLatestCompatiblePiecesFromDB` selects an explicit column list that deliberately omits `i18n` — that column holds every locale for the piece (~50 MB across the catalogue, written by `pieceInstallService`) and the list path discards it, so loading it was pure waste. Non-English requests now pull only the one locale in a second query (`pm."i18n" -> :locale`) and hand it to `pieceTranslation.translatePiece`. The single-piece path (`get`/`getOrThrow`) selects the same columns and goes through the same `translatePieces`, so no response ever carries `i18n`. The cost is that the explicit select is a list to keep in sync with the entity.
- **Piece sorting mutates its input, which is why the list result cannot simply be cached.** `pieceSorting`'s comparators and `reverseIfDesc` sort in place (`pieces.sort(...)`, `pieces.reverse()`). That is safe only because the array is rebuilt per request; making them non-mutating is a prerequisite for ever caching the built list, or requests would reorder shared state under each other.
- **`translatePiece` is copy-on-write: never deep-clone a piece to translate it, and never cache translated lists.** It copies only the objects on a translated path and returns the input's other subtrees by reference, in one walk over a tree built from `pathsToValuesToTranslate`. The input is shared through `dedupe()` across concurrent requests in different locales, so mutating it leaks one locale into another. The old `JSON.parse(JSON.stringify(piece))` made every non-English list ~3x slower than English (GIT-1891), and caching the translated catalogue per locale was tried twice (#15340, #15639) and dropped over memory. `packages/pieces/framework/test/i18n.test.ts` fails if a deep clone comes back. Translations are read from `piece_translation` (one row per piece version and locale, `pieceTranslationService`), not from the `json` `i18n` column: extracting one locale from that column re-parsed every locale (~160 ms on prod, paid even for a locale with no rows) and was ~5x slower than the table (GIT-2013).
diff --git a/packages/pieces/community/ai/package.json b/packages/pieces/community/ai/package.json
index 8b13df807ba..1cbe3e945ea 100644
--- a/packages/pieces/community/ai/package.json
+++ b/packages/pieces/community/ai/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-ai",
- "version": "0.14.1",
+ "version": "0.15.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
diff --git a/packages/pieces/community/ai/src/lib/actions/output-shape.test.ts b/packages/pieces/community/ai/src/lib/actions/output-shape.test.ts
index ea8e9d09126..3b97286f260 100644
--- a/packages/pieces/community/ai/src/lib/actions/output-shape.test.ts
+++ b/packages/pieces/community/ai/src/lib/actions/output-shape.test.ts
@@ -18,6 +18,7 @@ vi.mock('@activepieces/pieces-common', async (importOriginal) => {
const sendRequest = vi.mocked(httpClient.sendRequest);
const provider = { provider: 'openai', configId: 'config-1' };
+const aiProviderModel = { provider: 'openai', model: 'gpt-test', configId: 'config-1' };
function answered(answer: unknown, conversation?: unknown) {
return { body: { output: { answer, conversation } } };
@@ -35,7 +36,7 @@ beforeEach(() => {
describe('the shape every AI action returns once the worker answers', () => {
it('Ask AI returns the answer as a bare string', async () => {
const output = await askAI.run(createMockActionContext({
- propsValue: { provider, model: 'gpt-test', prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
+ propsValue: { aiProviderModel, prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
resumePayload: answered('sunny'),
}));
@@ -45,8 +46,7 @@ describe('the shape every AI action returns once the worker answers', () => {
it('Ask AI returns text and sources together when web search asks for sources', async () => {
const output = await askAI.run(createMockActionContext({
propsValue: {
- provider,
- model: 'gpt-test',
+ aiProviderModel,
prompt: 'weather?',
webSearch: true,
webSearchOptions: { includeSources: true },
@@ -60,7 +60,7 @@ describe('the shape every AI action returns once the worker answers', () => {
it('Summarize Text returns the summary as a bare string', async () => {
const output = await summarizeText.run(createMockActionContext({
- propsValue: { provider, model: 'gpt-test', text: 'a long article', prompt: 'Summarize', maxOutputTokens: 2000 },
+ propsValue: { aiProviderModel, text: 'a long article', prompt: 'Summarize', maxOutputTokens: 2000 },
resumePayload: answered('the short version'),
}));
@@ -69,7 +69,7 @@ describe('the shape every AI action returns once the worker answers', () => {
it('Classify Text returns the chosen label as a bare string', async () => {
const output = await classifyText.run(createMockActionContext({
- propsValue: { provider, model: 'gpt-test', text: 'it is warm today', categories: ['sunny', 'rainy'] },
+ propsValue: { aiProviderModel, text: 'it is warm today', categories: ['sunny', 'rainy'] },
resumePayload: answered('sunny'),
}));
@@ -79,8 +79,7 @@ describe('the shape every AI action returns once the worker answers', () => {
it('Extract Structured Data returns the extracted object itself', async () => {
const output = await extractStructuredData.run(createMockActionContext({
propsValue: {
- provider,
- model: 'gpt-test',
+ aiProviderModel,
text: 'an invoice totalling 42',
mode: 'simple',
schema: { fields: [{ name: 'total', type: 'number', isRequired: true }] },
@@ -107,7 +106,7 @@ describe('handing the step to the worker', () => {
const waitedOn: string[] = [];
const output = await askAI.run(createMockActionContext({
- propsValue: { provider, model: 'gpt-test', prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
+ propsValue: { aiProviderModel, prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
onWaitForWaitpoint: (waitpointId) => waitedOn.push(waitpointId),
}));
@@ -120,7 +119,7 @@ describe('handing the step to the worker', () => {
const created: { resumeDateTime?: string }[] = [];
await askAI.run(createMockActionContext({
- propsValue: { provider, model: 'gpt-test', prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
+ propsValue: { aiProviderModel, prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
onCreateWaitpoint: (waitpoint) => created.push(waitpoint),
}));
@@ -132,7 +131,7 @@ describe('handing the step to the worker', () => {
sendRequest.mockResolvedValue(answered('sunny') as never);
const output = await askAI.run(createMockActionContext({
- propsValue: { provider, model: 'gpt-test', prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
+ propsValue: { aiProviderModel, prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
canPause: false,
}));
@@ -142,14 +141,14 @@ describe('handing the step to the worker', () => {
it('raises the failure the worker reported', async () => {
await expect(askAI.run(createMockActionContext({
- propsValue: { provider, model: 'gpt-test', prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
+ propsValue: { aiProviderModel, prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
resumePayload: { body: { failure: 'the model refused' } },
}))).rejects.toThrow('the model refused');
});
it('raises a clear error when the backstop fires with nothing to report', async () => {
await expect(askAI.run(createMockActionContext({
- propsValue: { provider, model: 'gpt-test', prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
+ propsValue: { aiProviderModel, prompt: 'weather?', webSearch: false, maxOutputTokens: 2000 },
resumePayload: { body: undefined },
}))).rejects.toThrow('did not report a result');
});
@@ -158,7 +157,7 @@ describe('handing the step to the worker', () => {
describe('what a saved flow sends over the wire', () => {
it('turns categories saved as numbers into strings', async () => {
await classifyText.run(createMockActionContext({
- propsValue: { provider, model: 'gpt-test', text: 'two', categories: [1, 2] },
+ propsValue: { aiProviderModel, text: 'two', categories: [1, 2] },
}));
expect(requestBody()['categories']).toEqual(['1', '2']);
@@ -167,8 +166,7 @@ describe('what a saved flow sends over the wire', () => {
it('skips an empty file row instead of sending it', async () => {
await extractStructuredData.run(createMockActionContext({
propsValue: {
- provider,
- model: 'gpt-test',
+ aiProviderModel,
text: 'an invoice',
files: [{ file: undefined }],
mode: 'simple',
@@ -181,7 +179,7 @@ describe('what a saved flow sends over the wire', () => {
it('reads an Ask AI history stored in the legacy messages wrapper', async () => {
const context = createMockActionContext({
- propsValue: { provider, model: 'gpt-test', prompt: 'and then?', conversationKey: 'thread-1', webSearch: false },
+ propsValue: { aiProviderModel, prompt: 'and then?', conversationKey: 'thread-1', webSearch: false },
});
context.store.get = (async () => ({ messages: [{ role: 'user', content: 'hello' }] })) as typeof context.store.get;
@@ -207,8 +205,7 @@ describe('what a saved flow sends over the wire', () => {
it('turns a web search limit saved as text into the number the schema accepts', async () => {
await askAI.run(createMockActionContext({
propsValue: {
- provider,
- model: 'gpt-test',
+ aiProviderModel,
prompt: 'weather?',
webSearch: true,
webSearchOptions: { maxUses: '7', allowedDomains: ['example.com'] },
@@ -223,8 +220,7 @@ describe('what a saved flow sends over the wire', () => {
it('drops a stale Include Sources left behind by a provider that has no native search', async () => {
await askAI.run(createMockActionContext({
propsValue: {
- provider: { provider: 'openrouter', configId: 'config-1' },
- model: 'some/model',
+ aiProviderModel: { provider: 'openrouter', model: 'some/model', configId: 'config-1' },
prompt: 'weather?',
webSearch: true,
webSearchOptions: { includeSources: true },
@@ -235,11 +231,27 @@ describe('what a saved flow sends over the wire', () => {
expect(webSearch.options).not.toHaveProperty('includeSources');
});
+ it('sends only the tier id and drops Include Sources when the step runs on a platform tier', async () => {
+ await askAI.run(createMockActionContext({
+ propsValue: {
+ aiProviderModel: { modelTierId: 'tier_1' },
+ prompt: 'weather?',
+ webSearch: true,
+ webSearchOptions: { includeSources: true, maxUses: 3 },
+ },
+ }));
+
+ const body = requestBody();
+ expect(body['modelTierId']).toBe('tier_1');
+ expect(body).not.toHaveProperty('provider');
+ expect(body).not.toHaveProperty('modelId');
+ expect((body['webSearch'] as { options: Record<string, unknown> }).options).toEqual({ maxUses: 3 });
+ });
+
it('still runs an Extract whose only file row is empty, as it did before', async () => {
await extractStructuredData.run(createMockActionContext({
propsValue: {
- provider,
- model: 'gpt-test',
+ aiProviderModel,
files: [{ file: undefined }],
mode: 'simple',
schema: { fields: [] },
@@ -251,7 +263,7 @@ describe('what a saved flow sends over the wire', () => {
it('sends the creativity as a temperature the model understands', async () => {
await askAI.run(createMockActionContext({
- propsValue: { provider, model: 'gpt-test', prompt: 'weather?', creativity: 50, webSearch: false },
+ propsValue: { aiProviderModel, prompt: 'weather?', creativity: 50, webSearch: false },
}));
expect(requestBody()['temperature']).toBe(0.5);
@@ -275,8 +287,7 @@ describe('what a resumed step does before it reads its answer', () => {
it('Extract Structured Data does not upload its attachments a second time', async () => {
const { context, uploads } = countingUploads(createMockActionContext({
propsValue: {
- provider,
- model: 'gpt-test',
+ aiProviderModel,
text: 'an invoice totalling 42',
files: [fileProp()],
mode: 'simple',
@@ -309,8 +320,7 @@ describe('what a resumed step does before it reads its answer', () => {
it('still uploads on the first run, so the worker has something to read', async () => {
const { context, uploads } = countingUploads(createMockActionContext({
propsValue: {
- provider,
- model: 'gpt-test',
+ aiProviderModel,
text: 'an invoice totalling 42',
files: [fileProp()],
mode: 'simple',
diff --git a/packages/pieces/community/ai/src/lib/actions/text/ask-ai.ts b/packages/pieces/community/ai/src/lib/actions/text/ask-ai.ts
index ca5d17e9530..aa33b56a044 100644
--- a/packages/pieces/community/ai/src/lib/actions/text/ask-ai.ts
+++ b/packages/pieces/community/ai/src/lib/actions/text/ask-ai.ts
@@ -1,6 +1,6 @@
-import { AiStepAction, createAction, isNil, Property, spreadIfDefined } from '@activepieces/pieces-framework';
+import { AgentPieceProps, AiStepAction, createAction, isNil, Property, spreadIfDefined } from '@activepieces/pieces-framework';
import { runOnWorker } from '../../common/ai-step';
-import { aiProps, aiProviderSelection } from '../../common/props';
+import { aiModel, AiModelRequestFields } from '../../common/props';
import { buildWebSearchOptionsProperty, sanitizeWebSearchOptions, usesNativeWebSearchTools } from '../../common/web-search';
export const askAI = createAction({
@@ -9,14 +9,14 @@ export const askAI = createAction({
classification: 'READ',
displayName: 'Ask AI',
description: 'Ask AI to analyze, explain, draft or decide using your flow data.',
- aiMetadata: { description: 'Sends a free-form prompt to a text model and returns its answer, optionally continuing a multi-turn thread via a Conversation Key or grounding the reply with web search. Pick it for open-ended reasoning, drafting, or judgement over flow data; prefer summarizeText to condense text, classifyText for a fixed label set, extractStructuredData for typed fields, or run_agent when the task needs tools and multiple steps. Requires a provider/model plus a prompt; not idempotent, since each call generates a fresh answer and a Conversation Key appends the exchange to stored history.', idempotent: false },
+ aiMetadata: { description: 'Sends a free-form prompt to a text model and returns its answer, optionally continuing a multi-turn thread via a Conversation Key or grounding the reply with web search. Pick it for open-ended reasoning, drafting, or judgement over flow data; prefer summarizeText to condense text, classifyText for a fixed label set, extractStructuredData for typed fields, or run_agent when the task needs tools and multiple steps. Requires an AI Model (a tier or a provider/model) plus a prompt; not idempotent, since each call generates a fresh answer and a Conversation Key appends the exchange to stored history.', idempotent: false },
propertyGroups: [
{
key: 'ai_model',
display: 'section',
label: 'AI Model',
icon: 'sliders',
- props: ['provider', 'model'],
+ props: [AgentPieceProps.AI_PROVIDER_MODEL],
},
{
key: 'request',
@@ -27,8 +27,7 @@ export const askAI = createAction({
},
],
props: {
- provider: aiProps({ modelType: 'text' }).provider,
- model: aiProps({ modelType: 'text' }).model,
+ [AgentPieceProps.AI_PROVIDER_MODEL]: aiModel.prop(),
prompt: Property.LongText({
displayName: 'Prompt',
required: true,
@@ -64,19 +63,15 @@ export const askAI = createAction({
description: 'Let the AI search the web before it answers.',
}),
webSearchOptions: buildWebSearchOptionsProperty(
- (propsValue) => ({
- provider: aiProviderSelection.resolve(propsValue['provider'])?.provider,
- model: propsValue['model'] as string | undefined,
- }),
- ['webSearch', 'provider', 'model'],
+ (propsValue) => webSearchModelOf(aiModel.resolve(propsValue[AgentPieceProps.AI_PROVIDER_MODEL])),
+ ['webSearch', AgentPieceProps.AI_PROVIDER_MODEL],
),
},
async run(context) {
- const { provider, configId } = aiProviderSelection.resolveOrThrow(context.propsValue.provider);
+ const model = aiModel.resolveOrThrow(context.propsValue.aiProviderModel);
const webSearchEnabled = !!context.propsValue.webSearch;
const webSearchOptions = webSearchOptionsToSend({
- provider,
- model: context.propsValue.model,
+ ...webSearchModelOf(model),
saved: context.propsValue.webSearchOptions,
});
const storageKey = conversationStorageKey(context.propsValue.conversationKey);
@@ -85,9 +80,7 @@ export const askAI = createAction({
context,
buildRequest: async () => ({
action: AiStepAction.ASK_AI,
- provider,
- ...spreadIfDefined('providerConfigId', configId),
- modelId: context.propsValue.model,
+ ...model,
prompt: context.propsValue.prompt,
...spreadIfDefined('maxOutputTokens', context.propsValue.maxOutputTokens),
...spreadIfDefined('temperature', isNil(context.propsValue.creativity) ? undefined : context.propsValue.creativity / 100),
@@ -108,9 +101,16 @@ export const askAI = createAction({
},
});
-function webSearchOptionsToSend({ provider, model, saved }: { provider: string; model: string; saved: unknown }): Record<string, unknown> {
+function webSearchModelOf(fields: AiModelRequestFields | undefined): { provider: string | undefined; model: string | undefined } {
+ if (isNil(fields) || 'modelTierId' in fields) {
+ return { provider: undefined, model: undefined };
+ }
+ return { provider: fields.provider, model: fields.modelId };
+}
+
+function webSearchOptionsToSend({ provider, model, saved }: { provider: string | undefined; model: string | undefined; saved: unknown }): Record<string, unknown> {
const options = sanitizeWebSearchOptions(saved);
- if (usesNativeWebSearchTools({ provider, model })) {
+ if (!isNil(provider) && usesNativeWebSearchTools({ provider, model })) {
return options;
}
const { includeSources: _onlyWithNativeTools, ...rest } = options;
diff --git a/packages/pieces/community/ai/src/lib/actions/text/summarize-text.ts b/packages/pieces/community/ai/src/lib/actions/text/summarize-text.ts
index ae4dd9ce3c0..993aa4fd686 100644
--- a/packages/pieces/community/ai/src/lib/actions/text/summarize-text.ts
+++ b/packages/pieces/community/ai/src/lib/actions/text/summarize-text.ts
@@ -1,6 +1,6 @@
-import { AiStepAction, createAction, Property, spreadIfDefined } from '@activepieces/pieces-framework';
+import { AgentPieceProps, AiStepAction, createAction, Property, spreadIfDefined } from '@activepieces/pieces-framework';
import { runOnWorker } from '../../common/ai-step';
-import { aiProps, aiProviderSelection } from '../../common/props';
+import { aiModel } from '../../common/props';
export const summarizeText = createAction({
audience: 'both',
@@ -8,10 +8,9 @@ export const summarizeText = createAction({
classification: 'READ',
displayName: 'Summarize Text',
description: 'Summarize long emails, articles, or documents into what matters.',
- aiMetadata: { description: 'Condenses one block of supplied text into a shorter summary using a chosen text model. Pick it when the goal is a shorter version of text you already have; use extractStructuredData for specific typed fields, classifyText for a label, or askAi for open-ended questions. Requires a provider/model, the text inline (it fetches no URLs and reads no files) and the Prompt prop, which carries a default guide instruction but is still required; not idempotent, as generation is non-deterministic, so identical text returns differently worded summaries.', idempotent: false },
+ aiMetadata: { description: 'Condenses one block of supplied text into a shorter summary using a chosen text model. Pick it when the goal is a shorter version of text you already have; use extractStructuredData for specific typed fields, classifyText for a label, or askAi for open-ended questions. Requires an AI Model (a tier or a provider/model), the text inline (it fetches no URLs and reads no files) and the Prompt prop, which carries a default guide instruction but is still required; not idempotent, as generation is non-deterministic, so identical text returns differently worded summaries.', idempotent: false },
props: {
- provider: aiProps({ modelType: 'text' }).provider,
- model: aiProps({ modelType: 'text' }).model,
+ [AgentPieceProps.AI_PROVIDER_MODEL]: aiModel.prop(),
text: Property.LongText({
displayName: 'Text',
required: true,
@@ -32,15 +31,13 @@ export const summarizeText = createAction({
}),
},
async run(context) {
- const { provider, configId } = aiProviderSelection.resolveOrThrow(context.propsValue.provider);
+ const model = aiModel.resolveOrThrow(context.propsValue.aiProviderModel);
const result = await runOnWorker({
context,
buildRequest: async () => ({
action: AiStepAction.SUMMARIZE_TEXT,
- provider,
- ...spreadIfDefined('providerConfigId', configId),
- modelId: context.propsValue.model,
+ ...model,
prompt: context.propsValue.prompt,
text: context.propsValue.text,
...spreadIfDefined('maxOutputTokens', context.propsValue.maxOutputTokens),
diff --git a/packages/pieces/community/ai/src/lib/actions/text/temperature.test.ts b/packages/pieces/community/ai/src/lib/actions/text/temperature.test.ts
index 946480e50b4..1e6f65c3134 100644
--- a/packages/pieces/community/ai/src/lib/actions/text/temperature.test.ts
+++ b/packages/pieces/community/ai/src/lib/actions/text/temperature.test.ts
@@ -15,8 +15,7 @@ vi.mock('@activepieces/pieces-common', async (importOriginal) => {
const sendRequest = vi.mocked(httpClient.sendRequest);
const baseProps = {
- provider: { provider: 'openai', configId: 'config1' },
- model: 'gpt-test',
+ aiProviderModel: { provider: 'openai', model: 'gpt-test', configId: 'config1' },
maxOutputTokens: 2000,
};
diff --git a/packages/pieces/community/ai/src/lib/actions/utility/classify-text.ts b/packages/pieces/community/ai/src/lib/actions/utility/classify-text.ts
index ca28d5e0c4f..0cea8f01d02 100644
--- a/packages/pieces/community/ai/src/lib/actions/utility/classify-text.ts
+++ b/packages/pieces/community/ai/src/lib/actions/utility/classify-text.ts
@@ -1,6 +1,6 @@
-import { AiStepAction, createAction, Property, spreadIfDefined } from '@activepieces/pieces-framework';
+import { AgentPieceProps, AiStepAction, createAction, Property } from '@activepieces/pieces-framework';
import { runOnWorker } from '../../common/ai-step';
-import { aiProps, aiProviderSelection } from '../../common/props';
+import { aiModel } from '../../common/props';
export const classifyText = createAction({
audience: 'both',
@@ -10,8 +10,7 @@ export const classifyText = createAction({
description: 'Sort text into one of your categories to branch the flow.',
aiMetadata: { description: 'Assigns exactly one label from a caller-supplied Categories list to a block of text using a text model, and errors if the model answers with anything outside that list. Pick it for routing or branching where the outcomes are known up front; use extractStructuredData for multiple typed fields, summarizeText to shorten text, or askAi when the answer is not one of a fixed set. Requires the text plus a non-empty Categories array matched by exact string, so keep labels short; read-only and idempotent.', idempotent: true },
props: {
- provider: aiProps({ modelType: 'text' }).provider,
- model: aiProps({ modelType: 'text' }).model,
+ [AgentPieceProps.AI_PROVIDER_MODEL]: aiModel.prop(),
text: Property.LongText({
displayName: 'Text',
required: true,
@@ -23,16 +22,14 @@ export const classifyText = createAction({
}),
},
async run(context) {
- const { provider, configId } = aiProviderSelection.resolveOrThrow(context.propsValue.provider);
+ const model = aiModel.resolveOrThrow(context.propsValue.aiProviderModel);
const categories = ((context.propsValue.categories as unknown[]) ?? []).map((category) => String(category));
const result = await runOnWorker({
context,
buildRequest: async () => ({
action: AiStepAction.CLASSIFY_TEXT,
- provider,
- ...spreadIfDefined('providerConfigId', configId),
- modelId: context.propsValue.model,
+ ...model,
text: context.propsValue.text,
categories,
}),
diff --git a/packages/pieces/community/ai/src/lib/actions/utility/extract-structured-data.ts b/packages/pieces/community/ai/src/lib/actions/utility/extract-structured-data.ts
index 2b61238f3b6..625d957d400 100644
--- a/packages/pieces/community/ai/src/lib/actions/utility/extract-structured-data.ts
+++ b/packages/pieces/community/ai/src/lib/actions/utility/extract-structured-data.ts
@@ -1,8 +1,8 @@
-import { AiStepAction, ApFile, createAction, PieceAuth, Property, spreadIfDefined } from '@activepieces/pieces-framework';
+import { AgentPieceProps, AiStepAction, ApFile, createAction, PieceAuth, Property, spreadIfDefined } from '@activepieces/pieces-framework';
import Ajv from 'ajv';
import mime from 'mime-types';
import { runOnWorker, uploadAiFiles } from '../../common/ai-step';
-import { aiProps, aiProviderSelection } from '../../common/props';
+import { aiModel } from '../../common/props';
export const extractStructuredData = createAction({
audience: 'both',
@@ -17,7 +17,7 @@ export const extractStructuredData = createAction({
display: 'section',
label: 'AI Model',
icon: 'sliders',
- props: ['provider', 'model'],
+ props: [AgentPieceProps.AI_PROVIDER_MODEL],
},
{
key: 'source',
@@ -35,8 +35,7 @@ export const extractStructuredData = createAction({
},
],
props: {
- provider: aiProps({ modelType: 'text' }).provider,
- model: aiProps({ modelType: 'text' }).model,
+ [AgentPieceProps.AI_PROVIDER_MODEL]: aiModel.prop(),
text: Property.LongText({
displayName: 'Text',
description: 'Text to extract from. Fill this, Files, or both.',
@@ -151,7 +150,7 @@ export const extractStructuredData = createAction({
}),
},
async run(context) {
- const { provider, configId } = aiProviderSelection.resolveOrThrow(context.propsValue.provider);
+ const model = aiModel.resolveOrThrow(context.propsValue.aiProviderModel);
const attachments = ((context.propsValue.files as { file?: ApFile }[] | undefined) ?? []).map((row) => row?.file);
if (!context.propsValue.text && attachments.length === 0) {
@@ -166,9 +165,7 @@ export const extractStructuredData = createAction({
context,
buildRequest: async () => ({
action: AiStepAction.EXTRACT_STRUCTURED_DATA,
- provider,
- ...spreadIfDefined('providerConfigId', configId),
- modelId: context.propsValue.model,
+ ...model,
...spreadIfDefined('text', context.propsValue.text),
...spreadIfDefined('prompt', context.propsValue.prompt),
files: await uploadAiFiles({ context, files: attachments, mimeTypeOf: documentMimeType }),
diff --git a/packages/pieces/community/ai/src/lib/common/ai-step.ts b/packages/pieces/community/ai/src/lib/common/ai-step.ts
index 7104bc78e25..2104e4594b5 100644
--- a/packages/pieces/community/ai/src/lib/common/ai-step.ts
+++ b/packages/pieces/community/ai/src/lib/common/ai-step.ts
@@ -99,9 +99,10 @@ export type AiStepFile = {
export type AiStepRequest = {
action: AiStepAction;
- provider: string;
+ provider?: string;
providerConfigId?: string;
- modelId: string;
+ modelId?: string;
+ modelTierId?: string;
prompt?: string;
text?: string;
categories?: string[];
diff --git a/packages/pieces/community/ai/src/lib/common/props.test.ts b/packages/pieces/community/ai/src/lib/common/props.test.ts
index 29d6240ff89..30d50203d18 100644
--- a/packages/pieces/community/ai/src/lib/common/props.test.ts
+++ b/packages/pieces/community/ai/src/lib/common/props.test.ts
@@ -1,7 +1,7 @@
import { httpClient } from '@activepieces/pieces-common';
import { createMockActionContext } from '@activepieces/pieces-framework';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { aiProps } from './props';
+import { aiModel, aiProps } from './props';
vi.mock('@activepieces/pieces-common', async (importOriginal) => {
const original = await importOriginal<Record<string, unknown>>();
@@ -27,12 +27,6 @@ const publishedTiers = {
},
};
-const bundledTierOptions = [
- { label: 'Fast', value: 'fast' },
- { label: 'Expert', value: 'smart' },
- { label: 'Heavy', value: 'premium' },
-];
-
const catalog = [
{ id: 'anthropic/claude-haiku-4.5', name: 'Claude Haiku 4.5', type: 'text' },
{ id: 'anthropic/claude-sonnet-4.6', name: 'Claude Sonnet 4.6', type: 'text' },
@@ -67,39 +61,6 @@ beforeEach(() => {
answer({ tiers: publishedTiers });
});
-describe('the managed text model dropdown', () => {
- it('offers the published flow tiers and stores the tier id', async () => {
- const state = await modelOptions({ provider: 'activepieces', modelType: 'text' });
-
- expect(state.options).toEqual([
- { label: 'Fast', value: 'fast' },
- { label: 'Deep', value: 'deep' },
- ]);
- });
-
- it('never asks for the model catalog, because a tier is all a managed text step stores', async () => {
- await modelOptions({ provider: 'activepieces', modelType: 'text' });
-
- expect(requestedUrls().some((url) => url.includes('v1/ai-providers/tiers'))).toBe(true);
- expect(requestedUrls().some((url) => url.includes('/models'))).toBe(false);
- });
-
- it('offers the release\'s tiers, still as tier ids, when the server has no tiers route', async () => {
- answer({ tiers: null });
- const state = await modelOptions({ provider: 'activepieces', modelType: 'text' });
-
- expect(state.options).toEqual(bundledTierOptions);
- expect(requestedUrls().some((url) => url.includes('/models'))).toBe(false);
- });
-
- it('offers the release\'s tiers when the published flow list is empty', async () => {
- answer({ tiers: { ...publishedTiers, flow: { tiers: [], defaultTierId: '' } } });
- const state = await modelOptions({ provider: 'activepieces', modelType: 'text' });
-
- expect(state.options).toEqual(bundledTierOptions);
- });
-});
-
describe('the managed image model dropdown', () => {
it('stays on concrete models, because no image tier is published', async () => {
const state = await modelOptions({ provider: 'activepieces', modelType: 'image' });
@@ -112,18 +73,17 @@ describe('the managed image model dropdown', () => {
});
describe('a provider the customer brought their own key for', () => {
- it('lists concrete models and never asks for tiers', async () => {
- const state = await modelOptions({ provider: 'openai', modelType: 'text' });
+ it('lists concrete image models and never asks for tiers', async () => {
+ const state = await modelOptions({ provider: 'openai', modelType: 'image' });
expect(state.options).toEqual([
- { label: 'Claude Haiku 4.5', value: 'anthropic/claude-haiku-4.5' },
- { label: 'Claude Sonnet 4.6', value: 'anthropic/claude-sonnet-4.6' },
+ { label: 'Gemini Flash Image', value: 'google/gemini-3.1-flash-image' },
]);
expect(requestedUrls().every((url) => !url.includes('/tiers'))).toBe(true);
});
it('asks for a provider first when none is picked', async () => {
- const state = await aiProps({ modelType: 'text' }).model.options(
+ const state = await aiProps({ modelType: 'image' }).model.options(
{},
createMockActionContext({ propsValue: {} }),
);
@@ -132,3 +92,27 @@ describe('a provider the customer brought their own key for', () => {
expect(state.placeholder).toBe('Select a provider first');
});
});
+
+describe('the AI Model pick on text steps', () => {
+ it('sends a platform tier as a tier id only', () => {
+ expect(aiModel.resolve({ modelTierId: 'tier_1', provider: 'openai', model: 'gpt-5.5' })).toEqual({ modelTierId: 'tier_1' });
+ });
+
+ it('sends a model pick with its key', () => {
+ expect(aiModel.resolve({ provider: 'openai', model: 'gpt-5.5', configId: 'key_1' })).toEqual({
+ provider: 'openai',
+ modelId: 'gpt-5.5',
+ providerConfigId: 'key_1',
+ });
+ });
+
+ it('sends a Credits tier slug as the model id', () => {
+ expect(aiModel.resolve({ provider: 'activepieces', model: 'smart' })).toEqual({ provider: 'activepieces', modelId: 'smart' });
+ });
+
+ it('refuses an empty or unknown pick with a clear message', () => {
+ expect(() => aiModel.resolveOrThrow({})).toThrow('Pick a tier or a provider and model for this step');
+ expect(() => aiModel.resolveOrThrow({ provider: 'nope', model: 'x' })).toThrow();
+ expect(() => aiModel.resolveOrThrow('{{step_1.model}}')).toThrow();
+ });
+});
diff --git a/packages/pieces/community/ai/src/lib/common/props.ts b/packages/pieces/community/ai/src/lib/common/props.ts
index 8406ca2cc06..a17cfe4c9cd 100644
--- a/packages/pieces/community/ai/src/lib/common/props.ts
+++ b/packages/pieces/community/ai/src/lib/common/props.ts
@@ -1,4 +1,4 @@
-import { ACTIVEPIECES_CHAT_TIERS, ACTIVEPIECES_IMAGE_TIERS, PieceAuth, Property, tryCatch } from '@activepieces/pieces-framework';
+import { ACTIVEPIECES_IMAGE_TIERS, PieceAuth, Property, spreadIfDefined } from '@activepieces/pieces-framework';
import { httpClient, HttpMethod } from '@activepieces/pieces-common';
import { isNil } from '@activepieces/pieces-framework';
import { AIProviderModel, AIProviderName, ProjectAIProvider } from '@activepieces/pieces-framework';
@@ -22,24 +22,6 @@ async function listProviders(ctx: {
return body;
}
-async function listFlowTiers(ctx: {
- server: { apiUrl: string; token: string };
-}): Promise<ListedTier[]> {
- const { data } = await tryCatch(async () => {
- const { body } = await httpClient.sendRequest<ListedTiers>({
- method: HttpMethod.GET,
- url: `${ctx.server.apiUrl}v1/ai-providers/tiers`,
- headers: {
- Authorization: `Bearer ${ctx.server.token}`,
- },
- });
- return body.flow.tiers;
- });
- return isNil(data) || data.length === 0
- ? ACTIVEPIECES_CHAT_TIERS.map(({ id, label }) => ({ id, label }))
- : data;
-}
-
function providerOptionsOf(provider: ListedProvider): {
label: string;
value: AIProviderSelection;
@@ -123,15 +105,6 @@ export const aiProps = <T extends AIModelType>({
}
const { provider, configId } = selection;
- if (provider === AIProviderName.ACTIVEPIECES && modelType === 'text') {
- const tiers = await listFlowTiers(ctx);
- return {
- placeholder: 'Select AI Model',
- disabled: false,
- options: tiers.map((tier) => ({ label: tier.label, value: tier.id })),
- };
- }
-
const { body: allModels } =
await httpClient.sendRequest<AIProviderModel[]>({
method: HttpMethod.GET,
@@ -165,6 +138,53 @@ function resolveSelectionOrThrow(value: unknown): AIProviderSelection {
return selection;
}
+function aiModelProp() {
+ return Property.Object({
+ displayName: 'Model',
+ description: 'A tier your admin set up, or a specific model.',
+ required: true,
+ });
+}
+
+function resolveModelPick(value: unknown): AiModelRequestFields | undefined {
+ if (typeof value !== 'object' || isNil(value) || Array.isArray(value)) {
+ return undefined;
+ }
+ const pick: Record<string, unknown> = { ...value };
+ const modelTierId = stringOf(pick['modelTierId']);
+ if (!isNil(modelTierId)) {
+ return { modelTierId };
+ }
+ const provider = toProviderName(stringOf(pick['provider']) ?? '');
+ const modelId = stringOf(pick['model']);
+ if (isNil(provider) || isNil(modelId)) {
+ return undefined;
+ }
+ return {
+ provider,
+ modelId,
+ ...spreadIfDefined('providerConfigId', stringOf(pick['configId'])),
+ };
+}
+
+function resolveModelPickOrThrow(value: unknown): AiModelRequestFields {
+ const fields = resolveModelPick(value);
+ if (isNil(fields)) {
+ throw new Error('Pick a tier or a provider and model for this step');
+ }
+ return fields;
+}
+
+function stringOf(value: unknown): string | undefined {
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
+}
+
+export const aiModel = {
+ prop: aiModelProp,
+ resolve: resolveModelPick,
+ resolveOrThrow: resolveModelPickOrThrow,
+};
+
export const aiProviderSelection = {
resolve: resolveSelection,
resolveOrThrow: resolveSelectionOrThrow,
@@ -184,11 +204,6 @@ type ListedProvider = Omit<ProjectAIProvider, 'keys'> & {
keys?: ProjectAIProvider['keys'];
};
-type ListedTier = {
- id: string;
- label: string;
-};
-
-type ListedTiers = {
- flow: { tiers: ListedTier[] };
-};
+export type AiModelRequestFields =
+ | { modelTierId: string }
+ | { provider: AIProviderName; modelId: string; providerConfigId?: string };
diff --git a/packages/pieces/community/ai/src/lib/common/web-search.ts b/packages/pieces/community/ai/src/lib/common/web-search.ts
index c1e81851fcd..608c50f177f 100644
--- a/packages/pieces/community/ai/src/lib/common/web-search.ts
+++ b/packages/pieces/community/ai/src/lib/common/web-search.ts
@@ -144,7 +144,7 @@ export function buildWebSearchOptionsProperty(
}
const { provider, model } = getProviderAndModel(propsValue);
if (!provider) {
- return {};
+ return buildWebSearchOptionsProps('', params);
}
const { provider: effectiveProvider } = getEffectiveProviderAndModel({ provider, model });
return buildWebSearchOptionsProps(effectiveProvider ?? provider, params);
diff --git a/packages/server/api/src/app/flows/flow-version/migrations/migrate-v28-ai-piece-model-picker.ts b/packages/server/api/src/app/flows/flow-version/migrations/migrate-v28-ai-piece-model-picker.ts
new file mode 100644
index 00000000000..4cdc2b15799
--- /dev/null
+++ b/packages/server/api/src/app/flows/flow-version/migrations/migrate-v28-ai-piece-model-picker.ts
@@ -0,0 +1,131 @@
+import { AIProviderName, extractMustacheTokens, isNil } from '@activepieces/core-utils'
+import { AgentPieceProps, AI_PIECE_NAME, FlowActionType, flowStructureUtil, FlowVersion, PropertyExecutionType, PropertySettings } from '@activepieces/shared'
+import semver from 'semver'
+import { Migration } from '.'
+
+export const migrateV28AiPieceModelPicker: Migration = {
+ targetSchemaVersion: '28',
+ migrate: async (flowVersion: FlowVersion): Promise<FlowVersion> => {
+ const newVersion = flowStructureUtil.transferFlow(flowVersion, (step) => {
+ if (step.type !== FlowActionType.PIECE || step.settings.pieceName !== AI_PIECE_NAME) {
+ return step
+ }
+ const { actionName, input, propertySettings, pieceVersion } = step.settings
+ const moved = TEXT_ACTIONS.has(actionName ?? '') ? movedToPicker({ input, propertySettings }) : null
+ if (!isNil(moved)) {
+ return {
+ ...step,
+ settings: {
+ ...step.settings,
+ pieceVersion: atLeastPickerVersion(pieceVersion),
+ input: moved.input,
+ propertySettings: moved.propertySettings,
+ },
+ }
+ }
+ if (actionName === IMAGE_ACTION) {
+ return step
+ }
+ const pick = withTierSlug(input[AgentPieceProps.AI_PROVIDER_MODEL])
+ if (isNil(pick)) {
+ return step
+ }
+ return {
+ ...step,
+ settings: {
+ ...step.settings,
+ input: { ...input, [AgentPieceProps.AI_PROVIDER_MODEL]: pick },
+ },
+ }
+ })
+ return { ...newVersion, schemaVersion: '29' }
+ },
+}
+
+function movedToPicker({ input, propertySettings }: { input: Record<string, unknown>, propertySettings: Record<string, PropertySettings> }): MovedInput | null {
+ if (AgentPieceProps.AI_PROVIDER_MODEL in input) {
+ return null
+ }
+ const storedProvider = input[LEGACY_PROVIDER]
+ const storedModel = input[LEGACY_MODEL]
+ if (holdsExpression({ value: storedProvider, settings: propertySettings[LEGACY_PROVIDER] }) || holdsExpression({ value: storedModel, settings: propertySettings[LEGACY_MODEL] })) {
+ return null
+ }
+ const selection = providerSelectionOf(storedProvider)
+ if (isNil(selection) || typeof storedModel !== 'string' || storedModel.length === 0) {
+ return null
+ }
+ const { [LEGACY_PROVIDER]: _provider, [LEGACY_MODEL]: _model, ...rest } = input
+ const { [LEGACY_PROVIDER]: _providerSettings, [LEGACY_MODEL]: _modelSettings, ...restSettings } = propertySettings
+ return {
+ input: {
+ ...rest,
+ [AgentPieceProps.AI_PROVIDER_MODEL]: {
+ provider: selection.provider,
+ model: tierSlugFor({ provider: selection.provider, model: storedModel }) ?? storedModel,
+ ...(isNil(selection.configId) ? {} : { configId: selection.configId }),
+ },
+ },
+ propertySettings: restSettings,
+ }
+}
+
+function withTierSlug(pick: unknown): Record<string, unknown> | null {
+ if (!isRecord(pick)) {
+ return null
+ }
+ const slug = tierSlugFor({ provider: pick['provider'], model: pick['model'] })
+ return isNil(slug) ? null : { ...pick, model: slug }
+}
+
+function tierSlugFor({ provider, model }: { provider: unknown, model: unknown }): string | undefined {
+ if (provider !== AIProviderName.ACTIVEPIECES || typeof model !== 'string') {
+ return undefined
+ }
+ return LEGACY_CREDITS_MODEL_TO_TIER[model]
+}
+
+function providerSelectionOf(value: unknown): { provider: AIProviderName, configId?: string } | undefined {
+ const raw = isRecord(value) ? value['provider'] : value
+ const provider = Object.values(AIProviderName).find((name) => name === raw)
+ if (isNil(provider)) {
+ return undefined
+ }
+ const configId = isRecord(value) && typeof value['configId'] === 'string' && value['configId'].length > 0 ? value['configId'] : undefined
+ return { provider, ...(isNil(configId) ? {} : { configId }) }
+}
+
+function holdsExpression({ value, settings }: { value: unknown, settings: PropertySettings | undefined }): boolean {
+ if (settings?.type === PropertyExecutionType.DYNAMIC) {
+ return true
+ }
+ return typeof value === 'string' && extractMustacheTokens(value).length > 0
+}
+
+function atLeastPickerVersion(pieceVersion: string): string {
+ const current = semver.coerce(pieceVersion)
+ if (isNil(current) || semver.lt(current, AI_PIECE_MODEL_PICKER_VERSION)) {
+ return AI_PIECE_MODEL_PICKER_VERSION
+ }
+ return pieceVersion
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+const AI_PIECE_MODEL_PICKER_VERSION = '0.15.0'
+const LEGACY_PROVIDER = 'provider'
+const LEGACY_MODEL = 'model'
+const IMAGE_ACTION = 'generateImage'
+const TEXT_ACTIONS: ReadonlySet<string> = new Set(['askAi', 'summarizeText', 'classifyText', 'extractStructuredData'])
+const LEGACY_CREDITS_MODEL_TO_TIER: Record<string, string> = {
+ 'anthropic/claude-haiku-4.5': 'fast',
+ 'anthropic/claude-sonnet-4.6': 'smart',
+ 'anthropic/claude-opus-4.8': 'premium',
+}
+
+type MovedInput = {
+ input: Record<string, unknown>
+ propertySettings: Record<string, PropertySettings>
+}
diff --git a/packages/server/api/src/app/mcp/tools/ap-list-ai-models.ts b/packages/server/api/src/app/mcp/tools/ap-list-ai-models.ts
index 2e175c16ed3..2a999458737 100644
--- a/packages/server/api/src/app/mcp/tools/ap-list-ai-models.ts
+++ b/packages/server/api/src/app/mcp/tools/ap-list-ai-models.ts
@@ -15,7 +15,7 @@ const listAiModelsInput = z.object({
export const apListAiModelsTool = (mcp: ProjectScopedMcpServer, log: FastifyBaseLogger): McpToolDefinition => {
return {
title: 'ap_list_ai_models',
- description: 'List configured AI providers and their available models. Use this to discover valid provider and model values for configuring Run Agent steps. The output shows provider names and model IDs needed for the aiProviderModel input.',
+ description: 'List configured AI providers and their available models. Use this to discover valid provider and model values for AI steps (Ask AI, Summarize, Classify, Extract and Run Agent). The output shows provider names and model IDs needed for the aiProviderModel input.',
inputSchema: listAiModelsInput.shape,
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
execute: async (args) => {
@@ -77,7 +77,7 @@ export const apListAiModelsTool = (mcp: ProjectScopedMcpServer, log: FastifyBase
return {
content: [{
type: 'text',
- text: `Configured AI Providers:\n\n${sections.join('\n\n')}\n\nUsage: Set aiProviderModel to {"provider": "<provider>", "model": "<model id>"} when configuring a Run Agent step.`,
+ text: `Configured AI Providers:\n\n${sections.join('\n\n')}\n\nUsage: Set aiProviderModel to {"provider": "<provider>", "model": "<model id>"} when configuring an AI step (Ask AI, Summarize, Classify, Extract or Run Agent).`,
}],
structuredContent: { providers: structuredProviders },
}
diff --git a/packages/server/api/src/app/mcp/tools/ap-setup-guide.ts b/packages/server/api/src/app/mcp/tools/ap-setup-guide.ts
index 833f46585f1..6ff8bc4f0ac 100644
--- a/packages/server/api/src/app/mcp/tools/ap-setup-guide.ts
+++ b/packages/server/api/src/app/mcp/tools/ap-setup-guide.ts
@@ -223,7 +223,7 @@ async function aiProviderGuide(mcp: ProjectScopedMcpServer, log: FastifyBaseLogg
'',
'5. Click Save',
'',
- 'After setup, use ap_list_ai_models to discover available models for Run Agent steps.',
+ 'After setup, use ap_list_ai_models to discover available models for AI steps.',
)
return { content: [{ type: 'text', text: lines.join('\n') }] }
diff --git a/packages/server/api/test/unit/app/flows/flow-version/migrate-v28-ai-piece-model-picker.test.ts b/packages/server/api/test/unit/app/flows/flow-version/migrate-v28-ai-piece-model-picker.test.ts
new file mode 100644
index 00000000000..2bf56722abd
--- /dev/null
+++ b/packages/server/api/test/unit/app/flows/flow-version/migrate-v28-ai-piece-model-picker.test.ts
@@ -0,0 +1,202 @@
+import { readFileSync } from 'node:fs'
+import path from 'node:path'
+import {
+ AI_PIECE_NAME,
+ FlowActionType,
+ FlowTriggerType,
+ FlowVersion,
+ FlowVersionState,
+ PropertyExecutionType,
+ PropertySettings,
+} from '@activepieces/shared'
+import semver from 'semver'
+import { describe, expect, it } from 'vitest'
+import { migrateV28AiPieceModelPicker } from '../../../../../src/app/flows/flow-version/migrations/migrate-v28-ai-piece-model-picker'
+
+const baseVersion = (trigger: FlowVersion['trigger']): FlowVersion => ({
+ id: 'fv-1',
+ displayName: 'fixture',
+ flowId: 'flow-1',
+ created: new Date().toISOString(),
+ updated: new Date().toISOString(),
+ updatedBy: null,
+ valid: true,
+ trigger,
+ state: FlowVersionState.DRAFT,
+ schemaVersion: '28',
+ connectionIds: [],
+ agentIds: [],
+ notes: [],
+})
+
+const withAiStep = ({ pieceVersion = '0.11.0', actionName = 'askAi', pieceName = AI_PIECE_NAME, input, propertySettings = {} }: {
+ pieceVersion?: string
+ actionName?: string
+ pieceName?: string
+ input: Record<string, unknown>
+ propertySettings?: Record<string, PropertySettings>
+}): FlowVersion => baseVersion({
+ type: FlowTriggerType.PIECE,
+ name: 'trigger',
+ displayName: 'Trigger',
+ valid: true,
+ lastUpdatedDate: new Date().toISOString(),
+ settings: {
+ pieceName: '@activepieces/piece-webhook',
+ pieceVersion: '0.0.1',
+ triggerName: 'catch_request',
+ input: {},
+ propertySettings: {},
+ },
+ nextAction: {
+ type: FlowActionType.PIECE,
+ name: 'step_1',
+ displayName: 'Step 1',
+ skip: false,
+ valid: true,
+ lastUpdatedDate: new Date().toISOString(),
+ settings: {
+ pieceName,
+ pieceVersion,
+ actionName,
+ input,
+ propertySettings,
+ },
+ },
+})
+
+async function migratedStep(version: FlowVersion): Promise<MigratedStep> {
+ const result = await migrateV28AiPieceModelPicker.migrate(version)
+ const settings = result.trigger.nextAction?.settings
+ return {
+ schemaVersion: result.schemaVersion,
+ pieceVersion: settings?.pieceVersion,
+ input: settings?.input,
+ propertySettings: settings?.propertySettings,
+ }
+}
+
+describe('migrateV28AiPieceModelPicker', () => {
+ it('moves a Credits tier pick into the picker value and moves the step to 0.15.0', async () => {
+ const step = await migratedStep(withAiStep({
+ pieceVersion: '0.12.0',
+ input: { provider: { provider: 'activepieces' }, model: 'smart', prompt: 'hi' },
+ propertySettings: { provider: { type: PropertyExecutionType.MANUAL }, prompt: { type: PropertyExecutionType.MANUAL } },
+ }))
+
+ expect(step.pieceVersion).toBe('0.15.0')
+ expect(step.input).toEqual({ prompt: 'hi', aiProviderModel: { provider: 'activepieces', model: 'smart' } })
+ expect(step.propertySettings).toEqual({ prompt: { type: PropertyExecutionType.MANUAL } })
+ expect(step.schemaVersion).toBe('29')
+ })
+
+ it('turns an old pinned Credits model into the tier it was picked as', async () => {
+ const steps = await Promise.all([
+ ['anthropic/claude-haiku-4.5', 'fast'],
+ ['anthropic/claude-sonnet-4.6', 'smart'],
+ ['anthropic/claude-opus-4.8', 'premium'],
+ ].map(async ([model, tier]) => {
+ const step = await migratedStep(withAiStep({ actionName: 'summarizeText', input: { provider: { provider: 'activepieces' }, model } }))
+ return { tier, stored: step.input?.['aiProviderModel'] }
+ }))
+
+ for (const { tier, stored } of steps) {
+ expect(stored).toEqual({ provider: 'activepieces', model: tier })
+ }
+ })
+
+ it('keeps a Credits model it does not know as it is', async () => {
+ const step = await migratedStep(withAiStep({ input: { provider: { provider: 'activepieces' }, model: 'openai/gpt-4o' } }))
+
+ expect(step.input?.['aiProviderModel']).toEqual({ provider: 'activepieces', model: 'openai/gpt-4o' })
+ })
+
+ it('keeps the key on a pick made with the customer\'s own key', async () => {
+ const step = await migratedStep(withAiStep({ actionName: 'extractStructuredData', input: { provider: { provider: 'openai', configId: 'key_1' }, model: 'gpt-5.5', mode: 'simple' } }))
+
+ expect(step.input).toEqual({ mode: 'simple', aiProviderModel: { provider: 'openai', model: 'gpt-5.5', configId: 'key_1' } })
+ expect(step.pieceVersion).toBe('0.15.0')
+ })
+
+ it('reads a provider saved as a bare string', async () => {
+ const step = await migratedStep(withAiStep({ actionName: 'classifyText', input: { provider: 'anthropic', model: 'claude-sonnet-4-6' } }))
+
+ expect(step.input?.['aiProviderModel']).toEqual({ provider: 'anthropic', model: 'claude-sonnet-4-6' })
+ })
+
+ it('leaves a step alone when the provider or model comes from an expression', async () => {
+ const mustache = withAiStep({ input: { provider: { provider: 'openai' }, model: '{{step_0.model}}' } })
+ const dynamic = withAiStep({
+ input: { provider: { provider: 'openai' }, model: 'gpt-5.5' },
+ propertySettings: { provider: { type: PropertyExecutionType.DYNAMIC } },
+ })
+
+ for (const version of [mustache, dynamic]) {
+ const step = await migratedStep(version)
+ expect(step.pieceVersion).toBe('0.11.0')
+ expect(step.input).not.toHaveProperty('aiProviderModel')
+ }
+ })
+
+ it('leaves a step alone when the provider is unknown or the model is empty', async () => {
+ for (const input of [{ provider: { provider: 'nope' }, model: 'x' }, { provider: { provider: 'openai' }, model: '' }, {}]) {
+ const step = await migratedStep(withAiStep({ input }))
+ expect(step.pieceVersion).toBe('0.11.0')
+ expect(step.input).toEqual(input)
+ }
+ })
+
+ it('never touches an image step', async () => {
+ const input = { provider: { provider: 'activepieces' }, model: 'google/gemini-3.1-flash-image', prompt: 'a cat' }
+ const step = await migratedStep(withAiStep({ actionName: 'generateImage', input }))
+
+ expect(step.pieceVersion).toBe('0.11.0')
+ expect(step.input).toEqual(input)
+ })
+
+ it('turns an old Credits model on Run Agent into its tier without moving the step', async () => {
+ const step = await migratedStep(withAiStep({
+ actionName: 'run_agent',
+ input: { aiProviderModel: { provider: 'activepieces', model: 'anthropic/claude-opus-4.8' }, prompt: 'go' },
+ }))
+
+ expect(step.pieceVersion).toBe('0.11.0')
+ expect(step.input).toEqual({ aiProviderModel: { provider: 'activepieces', model: 'premium' }, prompt: 'go' })
+ })
+
+ it('fixes an old Credits model on a step already on the picker, and leaves the rest of it alone', async () => {
+ const oldId = await migratedStep(withAiStep({ pieceVersion: '0.15.0', input: { aiProviderModel: { provider: 'activepieces', model: 'anthropic/claude-haiku-4.5' } } }))
+ const tier = await migratedStep(withAiStep({ pieceVersion: '0.15.0', input: { aiProviderModel: { modelTierId: 'tier_1' } } }))
+
+ expect(oldId.input).toEqual({ aiProviderModel: { provider: 'activepieces', model: 'fast' } })
+ expect(tier.input).toEqual({ aiProviderModel: { modelTierId: 'tier_1' } })
+ expect(tier.pieceVersion).toBe('0.15.0')
+ })
+
+ it('never moves a step backwards', async () => {
+ const step = await migratedStep(withAiStep({ pieceVersion: '0.16.2', input: { provider: { provider: 'openai' }, model: 'gpt-5.5' } }))
+
+ expect(step.pieceVersion).toBe('0.16.2')
+ })
+
+ it('leaves other pieces alone', async () => {
+ const input = { provider: { provider: 'activepieces' }, model: 'anthropic/claude-haiku-4.5' }
+ const step = await migratedStep(withAiStep({ pieceName: '@activepieces/piece-openai', input }))
+
+ expect(step.input).toEqual(input)
+ })
+
+ it('never lets the v23 upgrade register move an AI step onto the picker version', () => {
+ const register: { pieces: Record<string, Record<string, { target: string }>> } = JSON.parse(readFileSync(path.resolve('packages/server/api/src/assets/piece-upgrade-register.json'), 'utf-8'))
+ const targets = Object.values(register.pieces[AI_PIECE_NAME] ?? {}).map((entry) => entry.target)
+ expect(targets.length).toBeGreaterThan(0)
+ expect(targets.filter((target) => semver.gte(target, '0.15.0'))).toEqual([])
+ })
+})
+
+type MigratedStep = {
+ schemaVersion: string | null | undefined
+ pieceVersion: string | undefined
+ input: Record<string, unknown> | undefined
+ propertySettings: Record<string, PropertySettings> | undefined
+}
diff --git a/packages/web/src/app/builder/piece-properties/properties-utils.tsx b/packages/web/src/app/builder/piece-properties/properties-utils.tsx
index 02e94edf80b..6dbdd7bfec6 100644
--- a/packages/web/src/app/builder/piece-properties/properties-utils.tsx
+++ b/packages/web/src/app/builder/piece-properties/properties-utils.tsx
@@ -4,10 +4,15 @@ import {
PiecePropertyMap,
PropertyType,
} from '@activepieces/pieces-framework';
-import { PropertySettings } from '@activepieces/shared';
+import {
+ AgentPieceProps,
+ AI_PIECE_NAME,
+ PropertySettings,
+} from '@activepieces/shared';
import { t } from 'i18next';
import { ControllerRenderProps, UseFormReturn } from 'react-hook-form';
+import { AgentModelField } from '@/app/builder/step-settings/agent-settings/agent-model-field';
import { SecretInput } from '@/app/connections/secret-input';
import { ColorPicker } from '@/components/custom/color-picker';
import { DictionaryInput } from '@/components/custom/dictionary-input';
@@ -74,6 +79,38 @@ export const selectGenericFormComponentForProperty = ({
</AutoFormFieldWrapper>
);
case PropertyType.OBJECT:
+ if (
+ dynamicPropsInfo?.pieceName === AI_PIECE_NAME &&
+ propertyName === AgentPieceProps.AI_PROVIDER_MODEL
+ ) {
+ const modelField = (
+ <AgentModelField
+ value={field.value}
+ onChange={field.onChange}
+ pieceVersion={dynamicPropsInfo.pieceVersion}
+ actionName={dynamicPropsInfo.actionOrTriggerName}
+ disabled={disabled}
+ hideHeading={allowDynamicValues}
+ />
+ );
+ if (!allowDynamicValues) {
+ return modelField;
+ }
+ return (
+ <AutoFormFieldWrapper
+ property={property}
+ propertyName={propertyName}
+ field={field}
+ hideLabel={hideLabel}
+ inputName={inputName}
+ disabled={disabled}
+ allowDynamicValues={allowDynamicValues}
+ dynamicInputModeToggled={dynamicInputModeToggled}
+ >
+ {modelField}
+ </AutoFormFieldWrapper>
+ );
+ }
return (
<AutoFormFieldWrapper
property={property}
diff --git a/packages/web/src/app/builder/step-settings/agent-settings/agent-model-field.tsx b/packages/web/src/app/builder/step-settings/agent-settings/agent-model-field.tsx
index 86a64fe1d3b..1bc20eea14a 100644
--- a/packages/web/src/app/builder/step-settings/agent-settings/agent-model-field.tsx
+++ b/packages/web/src/app/builder/step-settings/agent-settings/agent-model-field.tsx
@@ -13,13 +13,16 @@ export function AgentModelField({
value,
onChange,
pieceVersion,
+ actionName,
disabled,
+ hideHeading = false,
}: AgentModelFieldProps) {
+ const { surface, showHeading } = agentModelUtils.fieldFor({ actionName });
const { project } = projectCollectionUtils.useCurrentProject();
const withTiers = agentModelUtils.supportsTiers({ pieceVersion });
const { data: options } = aiModelHooks.useModelOptions({
projectId: project.id,
- surface: 'agent',
+ surface,
});
const wroteDefault = useRef(false);
@@ -42,10 +45,12 @@ export function AgentModelField({
return (
<div className="space-y-2">
- <h2 className="text-sm font-medium">{t('AI Model *')}</h2>
+ {showHeading && !hideHeading && (
+ <h2 className="text-sm font-medium">{t('AI Model *')}</h2>
+ )}
<ModelPicker
projectId={project.id}
- surface="agent"
+ surface={surface}
value={agentModelUtils.choiceOf({ value })}
onChange={(choice) => onChange(agentModelUtils.valueOf({ choice }))}
withTiers={withTiers}
@@ -64,5 +69,7 @@ type AgentModelFieldProps = {
value: unknown;
onChange: (value: AgentProviderModel) => void;
pieceVersion: string;
+ actionName: string;
disabled: boolean;
+ hideHeading?: boolean;
};
diff --git a/packages/web/src/app/builder/step-settings/agent-settings/agent-model-utils.ts b/packages/web/src/app/builder/step-settings/agent-settings/agent-model-utils.ts
index 06a690374de..52cd76f7c0c 100644
--- a/packages/web/src/app/builder/step-settings/agent-settings/agent-model-utils.ts
+++ b/packages/web/src/app/builder/step-settings/agent-settings/agent-model-utils.ts
@@ -3,6 +3,7 @@ import {
AgentProviderModel,
ModelChoice,
ModelOptions,
+ ModelOptionsSurface,
} from '@activepieces/shared';
import semver from 'semver';
@@ -80,7 +81,11 @@ function supportsTiers({ pieceVersion }: { pieceVersion: string }): boolean {
}
function isEmpty({ value }: { value: unknown }): boolean {
- return !isRecord(value) || Object.keys(value).length === 0;
+ return isNil(value) || (isRecord(value) && Object.keys(value).length === 0);
+}
+
+function fieldFor({ actionName }: { actionName: string }): ModelFieldLayout {
+ return MODEL_FIELD_BY_ACTION[actionName] ?? DEFAULT_MODEL_FIELD;
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -93,10 +98,29 @@ function stringOf(value: unknown): string | undefined {
const FIRST_PIECE_VERSION_WITH_TIERS = '0.14.1';
+const DEFAULT_MODEL_FIELD: ModelFieldLayout = {
+ surface: 'agent',
+ showHeading: true,
+};
+
+const MODEL_FIELD_BY_ACTION: Record<string, ModelFieldLayout> = {
+ run_agent: DEFAULT_MODEL_FIELD,
+ extractStructuredData: { surface: 'agent', showHeading: false },
+ askAi: { surface: 'flow', showHeading: false },
+ summarizeText: { surface: 'flow', showHeading: true },
+ classifyText: { surface: 'flow', showHeading: true },
+};
+
export const agentModelUtils = {
choiceOf,
valueOf,
defaultFor,
supportsTiers,
isEmpty,
+ fieldFor,
+};
+
+type ModelFieldLayout = {
+ surface: ModelOptionsSurface;
+ showHeading: boolean;
};
diff --git a/packages/web/src/app/builder/step-settings/agent-settings/index.tsx b/packages/web/src/app/builder/step-settings/agent-settings/index.tsx
index 553cbd3b8b9..e00ec324b87 100644
--- a/packages/web/src/app/builder/step-settings/agent-settings/index.tsx
+++ b/packages/web/src/app/builder/step-settings/agent-settings/index.tsx
@@ -8,7 +8,6 @@ import { useFormContext } from 'react-hook-form';
import { AgentLink } from '@/app/builder/step-settings/agent-settings/agent-link';
import { agentLinkUtils } from '@/app/builder/step-settings/agent-settings/agent-link-utils';
-import { AgentModelField } from '@/app/builder/step-settings/agent-settings/agent-model-field';
import { AgentTools } from '@/app/builder/step-settings/agent-settings/agent-tools';
import { FormField } from '@/components/ui/form';
import { Skeleton } from '@/components/ui/skeleton';
@@ -150,16 +149,6 @@ const selectAgentFormComponentForProperty = (
/>
);
}
- case AgentPieceProps.AI_PROVIDER_MODEL: {
- return (
- <AgentModelField
- value={field.value}
- onChange={field.onChange}
- pieceVersion={params.dynamicPropsInfo?.pieceVersion ?? ''}
- disabled={disabled}
- />
- );
- }
default: {
return selectGenericFormComponentForProperty({
...params,
diff --git a/packages/web/src/features/pieces/utils/form-utils.tsx b/packages/web/src/features/pieces/utils/form-utils.tsx
index f6215accb53..7926fa01b8b 100644
--- a/packages/web/src/features/pieces/utils/form-utils.tsx
+++ b/packages/web/src/features/pieces/utils/form-utils.tsx
@@ -2,6 +2,7 @@ import {
Metadata,
extractMustacheTokens,
isNil,
+ isObject,
parseToJsonIfPossible,
} from '@activepieces/core-utils';
import {
@@ -138,6 +139,8 @@ function parseDynamicValue({
}
case PropertyType.COLOR:
return typeof value === 'string' && value !== '' ? value : undefined;
+ case PropertyType.OBJECT:
+ return isObject(parsed) ? parsed : undefined;
default:
return undefined;
}
diff --git a/packages/web/test/app/builder/step-settings/agent-settings/agent-model-field.test.tsx b/packages/web/test/app/builder/step-settings/agent-settings/agent-model-field.test.tsx
index c96c860fe4b..b0db31de45a 100644
--- a/packages/web/test/app/builder/step-settings/agent-settings/agent-model-field.test.tsx
+++ b/packages/web/test/app/builder/step-settings/agent-settings/agent-model-field.test.tsx
@@ -9,17 +9,23 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const state = vi.hoisted(() => ({
options: undefined as unknown,
- pickerProps: undefined as { withTiers?: boolean } | undefined,
+ pickerProps: undefined as
+ | { withTiers?: boolean; surface?: string }
+ | undefined,
+ hookSurface: undefined as string | undefined,
}));
vi.mock('@/features/agents/ai-model/hooks', () => ({
aiModelHooks: {
- useModelOptions: () => ({ data: state.options }),
+ useModelOptions: ({ surface }: { surface: string }) => {
+ state.hookSurface = surface;
+ return { data: state.options };
+ },
},
}));
vi.mock('@/features/agents/ai-model/model-picker', () => ({
- ModelPicker: (props: { withTiers?: boolean }) => {
+ ModelPicker: (props: { withTiers?: boolean; surface?: string }) => {
state.pickerProps = props;
return <div data-testid="model-picker" />;
},
@@ -49,12 +55,16 @@ function render({
value,
onChange,
pieceVersion = '0.14.1',
+ actionName = 'run_agent',
disabled = false,
+ hideHeading,
}: {
value: unknown;
onChange: (value: unknown) => void;
pieceVersion?: string;
+ actionName?: string;
disabled?: boolean;
+ hideHeading?: boolean;
}) {
act(() => {
root.render(
@@ -62,8 +72,10 @@ function render({
value={value}
onChange={onChange}
pieceVersion={pieceVersion}
+ actionName={actionName}
disabled={disabled}
- />
+ hideHeading={hideHeading}
+ />,
);
});
}
@@ -136,7 +148,7 @@ describe('the model field on a Run Agent step', () => {
expect(state.pickerProps?.withTiers).toBe(false);
expect(container.textContent).toContain(
- 'Update this step to the latest version to use your tiers.'
+ 'Update this step to the latest version to use your tiers.',
);
expect(onChange).toHaveBeenCalledWith({
provider: AIProviderName.ACTIVEPIECES,
@@ -145,3 +157,69 @@ describe('the model field on a Run Agent step', () => {
});
});
});
+
+describe('the model field on an AI piece text step', () => {
+ it('lists flow models for Ask AI and leaves the heading to its section', () => {
+ render({
+ value: undefined,
+ onChange: vi.fn(),
+ pieceVersion: '0.15.0',
+ actionName: 'askAi',
+ });
+
+ expect(state.hookSurface).toBe('flow');
+ expect(state.pickerProps?.surface).toBe('flow');
+ expect(state.pickerProps?.withTiers).toBe(true);
+ expect(container.textContent).not.toContain('AI Model *');
+ });
+
+ it('lists tool-calling models for Extract, which answers through a tool', () => {
+ render({
+ value: undefined,
+ onChange: vi.fn(),
+ pieceVersion: '0.15.0',
+ actionName: 'extractStructuredData',
+ });
+
+ expect(state.pickerProps?.surface).toBe('agent');
+ });
+
+ it('writes the default once on a new Summarize step and shows its own heading', () => {
+ const onChange = vi.fn();
+
+ render({
+ value: undefined,
+ onChange,
+ pieceVersion: '0.15.0',
+ actionName: 'summarizeText',
+ });
+
+ expect(onChange).toHaveBeenCalledWith({ modelTierId: 'tier-1' });
+ expect(container.textContent).toContain('AI Model *');
+ });
+
+ it('drops its heading when the form label above it carries the expression switch', () => {
+ render({
+ value: undefined,
+ onChange: vi.fn(),
+ pieceVersion: '0.15.0',
+ actionName: 'summarizeText',
+ hideHeading: true,
+ });
+
+ expect(container.textContent).not.toContain('AI Model *');
+ });
+
+ it('never overwrites a model held in an expression', () => {
+ const onChange = vi.fn();
+
+ render({
+ value: '{{step_1.model}}',
+ onChange,
+ pieceVersion: '0.15.0',
+ actionName: 'askAi',
+ });
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/web/test/app/builder/step-settings/agent-settings/agent-model-utils.test.ts b/packages/web/test/app/builder/step-settings/agent-settings/agent-model-utils.test.ts
index 0f1a378f7c7..a2a467cdb1d 100644
--- a/packages/web/test/app/builder/step-settings/agent-settings/agent-model-utils.test.ts
+++ b/packages/web/test/app/builder/step-settings/agent-settings/agent-model-utils.test.ts
@@ -161,3 +161,13 @@ function options(): ModelOptions {
specificModelsHidden: false,
};
}
+
+describe('agentModelUtils.isEmpty', () => {
+ it('treats only a missing value or an empty object as empty', () => {
+ expect(agentModelUtils.isEmpty({ value: undefined })).toBe(true);
+ expect(agentModelUtils.isEmpty({ value: null })).toBe(true);
+ expect(agentModelUtils.isEmpty({ value: {} })).toBe(true);
+ expect(agentModelUtils.isEmpty({ value: '{{step_1.model}}' })).toBe(false);
+ expect(agentModelUtils.isEmpty({ value: { modelTierId: 't' } })).toBe(false);
+ });
+});
diff --git a/packages/web/test/features/pieces/parse-dynamic-value.test.ts b/packages/web/test/features/pieces/parse-dynamic-value.test.ts
index 1f428b4da56..6e412e8e8ed 100644
--- a/packages/web/test/features/pieces/parse-dynamic-value.test.ts
+++ b/packages/web/test/features/pieces/parse-dynamic-value.test.ts
@@ -15,6 +15,7 @@ const checkbox = Property.Checkbox({
});
const shortText = Property.ShortText({ displayName: 'Text', required: false });
const color = Property.Color({ displayName: 'Brand', required: false });
+const object = Property.Object({ displayName: 'Model', required: true });
const staticDropdown = Property.StaticDropdown({
displayName: 'Channel',
required: true,
@@ -27,6 +28,12 @@ describe('formUtils.parseDynamicValue', () => {
['[]', multiSelect, []],
['true', checkbox, true],
['false', checkbox, false],
+ [
+ '{"provider":"openai","model":"gpt-5","configId":"key-1"}',
+ object,
+ { provider: 'openai', model: 'gpt-5', configId: 'key-1' },
+ ],
+ ['{"modelTierId":"tier-1"}', object, { modelTierId: 'tier-1' }],
])('restores %s', (value, property, expected) => {
expect(formUtils.parseDynamicValue({ property, value })).toEqual(expected);
});
@@ -74,6 +81,9 @@ describe('formUtils.parseDynamicValue', () => {
[undefined, staticDropdown],
['', color],
[undefined, color],
+ ['{{ trigger.body.model }}', object],
+ ['["a"]', object],
+ ['', object],
])('has nothing unambiguous to restore in %s', (value, property) => {
expect(formUtils.parseDynamicValue({ property, value })).toBeUndefined();
});