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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(ai): run platform tier flow steps with ranked fallback models (#16003)
Louai Boumediene1c1ce82d7c27
diff --git a/brain/knowledge/ai-intelligence/ai-providers.md b/brain/knowledge/ai-intelligence/ai-providers.mdindex 2668dcc553a..8def67e8fa7 100644--- a/brain/knowledge/ai-intelligence/ai-providers.md+++ b/brain/knowledge/ai-intelligence/ai-providers.md@@ -77,6 +77,10 @@ after a file without chat keys it seeds the chat list from the live flow list.- **Deleting a platform tier needs a replacement, except the last live tier, and there is no usage count.** Refs to a deleted tier are never rewritten; they reach a live tier through `replacedBy` (flattened to one hop on delete). The last tier may always go with no replacement: without that exit, a platform's last tier and the key it uses could never be removed, because the key guard refuses keys a live tier uses. Tier delete is also deliberately **not** plan-gated (writes are), so a platform that downgrades can still clear its tiers and then remove its key. Its refs then point at a tier with `replacedBy: null`, and the resolver must fail them with a clear "tier removed" error. An exact "used by N flows" count needs a `LIKE` scan over every flow version's `trigger` text, plus agent jsonb and conversations, on the whole platform. We dropped it rather than pay that. If counts come back, add a denormalized `flow_version.modelTierIds` array + GIN index (the `connectionIds` pattern) instead of scanning.- **The live-name unique index is `lower("name")`, which `EntitySchema` cannot express.** The entity declares it `synchronize: false` (so `check-migrations` skips it), which means test DBs built by `synchronize` don't have it. The case-insensitive check that tests rely on is the service's `assertNameIsFree`, which is race-free because it runs under the `platform` row lock; the index is the backstop.- **`lockPlatform` takes `FOR NO KEY UPDATE`, not `FOR UPDATE`.** Every FK insert that references `platform` (projects, users, …) takes `FOR KEY SHARE` on the platform row, which `FOR UPDATE` blocks until commit. `FOR NO KEY UPDATE` serialises tier writes just the same without stalling those inserts.+- **The tier grant lives in one function: `aiModelCandidates.resolve` (via `platformModelTierService.getForRun`) is the only path that hands out a key without `rowAllowsScope`.** The `configId`s come from a live tier on the caller's platform, never from the caller; keep it that way. A specific pick still goes through `getConfigOrThrow` with the project scope.+- **A platform tier step falls back only on provider failures, decided by `isFallbackWorthy` on a signal from `aiProviderSignal.fromError`.** 401/402/403/404/408/429/5xx, network errors (ai 7 throws them as `APICallError` with **no status** and `isRetryable: true`) and billing bodies (Anthropic sends low credit as a **400**) fall back; any other 4xx and our own errors (classify mismatch, no structured data, web search unsupported) stop. No fallback once a web-search step finished, since it was already billed.+- **Worker-built models report no key health through `createModel`: no reporter is installed in the worker.** Tier steps report explicitly via the `reportAiKeyOutcome` RPC, and only provider signals (`fromProvider`) plus recoveries of non-active keys. Reporting our own errors would demote healthy keys to `unreachable`. The API never writes a worker-reported status for most providers: `confirmReportedOutcome` runs in the background and only triggers a `recheck` of the real key (once per key per 10s) when the report disagrees with the stored status. The exception is providers flagged `validationSkipsModelEndpoint` (CUSTOM, Vertex): their check never reaches the model, so a recheck would always pass, and the report is recorded as-is. Any direct `aiProviderHealth.record` from concurrent callers must pass `expectVersion` (the `statusVersion` it read), or an older report landing late overwrites a newer one. The worker token is shared and a shared worker serves every platform, so a report can't be bound to a platform; a forged one can at most cause a recheck. Don't pass `platformId`/`providerConfigId` to `createModel` in the worker, or a future reporter double-counts.+- **`ExecuteAiJobData` is a zod schema that strips unknown keys** (`JobData.parse` in `worker.ts` and `job-broker.ts`). A field added only to the TS type silently never reaches the worker; add it to `AiStepJobBase`.- **Builders read the slim tier list (`GET /v1/platform-model-tiers`) with no `configId` or key names; the full entries are `GET /admin` only.** Don't widen the builder view: it would show project users the ids of keys scoped away from them.- **The managed key only runs models the tiers or the chat allow-list permit, enforced in `aiUtils.createModel`.** The managed provider is OpenRouter underneath, so before this guard a crafted step naming any OpenRouter model ran on our key; the picker hid it but nothing denied it. `assertManagedModelAllowed` (`server/utils/src/ai-utils.ts`) checks `managedChatModelIds()` plus both surfaces' published tier `modelId`s and throws a `VALIDATION` error. Image models are checked too, in `createModel` (`imageGeneration: true`) and `createModelForImages`: only `ACTIVEPIECES_IMAGE_TIERS` model ids, plus the id the chat path passes as `adminChosenImageModelId` (the server-chosen Capabilities model). The worker now calls `modelTierCatalog.warmUp()` at start so a cold worker does not judge a newly published tier against the bundled list.- **A catalog change takes up to ~2 days to reach a dropdown, through three caches in series.** CDN edge (`--cache-control max-age=3600`, 1h) → the server's in-memory catalog (`CATALOG_TTL_MS`, 24h) → `modelsCache` (flushed by the nightly `cron.schedule('0 0 * * *')`). So "I republished but the UI still shows the old price" is expected, not a bug; restarting the API short-circuits the two in-process layers. The edge TTL is deliberately 1h and not the 604800 that `publish-embed-sdk.yml` uses — that path is version-stamped, ours is a stable key rewritten in place, so a week-long edge cache would pin stale prices for a week.diff --git a/brain/knowledge/engineering/ci-pr-review-hygiene.md b/brain/knowledge/engineering/ci-pr-review-hygiene.mdindex fe6a5caee7e..ec968423190 100644--- a/brain/knowledge/engineering/ci-pr-review-hygiene.md+++ b/brain/knowledge/engineering/ci-pr-review-hygiene.md@@ -22,7 +22,9 @@ Which team gets asked to review comes entirely from `.github/CODEOWNERS` — theEnforcement is the **`Codeowners review` repository ruleset** (active on the default branch), not classic branch protection: `require_code_owner_review: true` plus `required_approving_review_count: 1` and `required_review_thread_resolution: true`. Eight bypass actors are configured, which is why an owner-team request can look non-blocking on some PRs.## Gotchas-- **When merging main, `rerere` can replay a stale `bun.lock` resolution.** "Staged 'bun.lock' using previous resolution" means git reused an old answer, which can carry workspace versions that no longer match any `package.json` (seen: core-utils `0.8.6` in the lockfile against `0.8.5` in the manifest). If the branch adds no dependencies, take main's `bun.lock` and edit only the branch's own workspace `version` lines.+- **When merging main, `rerere` can replay a stale `bun.lock` resolution.** "Staged 'bun.lock' using previous resolution" means git reused an old answer, which can carry workspace versions that no longer match any `package.json` (seen: core-utils `0.8.6` in the lockfile against `0.8.5` in the manifest). If the branch adds no dependencies, take main's `bun.lock` and edit only the branch's own workspace `version` lines. Expect `bun install` to then rewrite a few lines for pieces the branch never touched: piece PRs on `main` often bump a `package.json` without its `bun.lock` entry (seen 2026-10-05: grist, microsoft-todo, ticktick, zendesk). Those lines are main catching up, not your change; keep them, because the lock should match the manifests.+- **Any change to `bun.lock` runs every package's tests in `build-test`, all 700+ pieces included.** The `changes` job in `ci.yml` sets `all=true` when a changed file is outside `packages/`, `docs/`, `brain/`, `.agents/` and `.claude/` and is not a `*.md` file (so root Markdown alone does not count), and `tools/scripts/test-filters.ts` then adds every package with a `test` script **except `api`** (it lists with `--filter=!api`). API tests run in the separate `api-tests` matrix job (`api (ce)`, `api (cloud)`, `api (ee, unit, migrations)`), so look there for their results, not in `build-test`. Without that, a piece only runs when its own files or `pieces/framework` / `pieces/common` change; a `core-utils` change alone does not pull pieces in. Any workspace version bump edits `bun.lock`, so this hits most PRs that bump a package. A CPU-heavy piece test can then fail on the starved runner with no change of yours: an Odoo polling test that takes ~350ms locally passed vitest's 5s default in 3 of 3 runs, reruns included. Don't keep rerunning: give the heavy test an explicit timeout (third `it` argument). Even a test-only change needs that piece's patch bump (and its `bun.lock` line): `validate-publishable-packages` diffs the whole package folder against `origin/main`.+- **After the base PR of a stack merges, merging main into the next PR silently keeps the base PR's old lines.** The merge base predates the base PR, so code the base PR dropped during review (fields, routes, columns) looks like a branch addition and survives with no conflict. Check with `git diff --name-only origin/main`: every file must be one the stacked PR itself changed. If not, save the stacked PR's own patch first (`git diff --binary <base-PR tip it was built on> <head before the merge> > pr.patch`; without `--binary`, an image or other binary file is written as "Binary files differ" and `read-tree` deletes it with no way back), then `git read-tree -u --reset origin/main` and `git apply --3way pr.patch`, and commit. `read-tree` also deletes files that exist only on the branch (a file the base PR added, then dropped), which `git checkout origin/main -- .` would leave behind. Use `origin/main`, not `MERGE_HEAD`: a merge with no conflicts commits itself and `MERGE_HEAD` is gone. Then retarget it (`gh pr edit <n> --base main`): a PR still pointed at the merged base branch shows every main change since then (seen: 1,285 files for a 28-file PR). No rebase or force push needed.- **The tests bucket keys off a path *segment*, so a feature folder named `test-step` is not mistaken for tests.** `packages/web/src/app/builder/test-step/` and `latest-test.ts` stay in `packages/web`; the regex requires `test/` as a whole segment or a `.test.`/`.spec.` suffix. The one deliberate overlap is `packages/pieces/framework/src/lib/test/index.ts` — shipped `createMockActionContext` helpers, counted as tests, and exempt either way because pieces are exempt.- **A job-level `env:` in `ci.yml` does not reach anything turbo runs.** Turbo 2.x defaults to `--env-mode=strict`: a task's process only receives variables named in `globalPassThroughEnv` / `passThroughEnv` / `env`, plus turbo's own system list. Everything else is dropped silently, so the task falls back to whatever `packages/server/api/.env.tests` set (dotenv there runs without `override`, so a real env var would otherwise win). Symptom: the workflow clearly sets the variable and the test still uses the old value. Add the name to `globalPassThroughEnv` in `turbo.json` — that is why `AP_DB_TYPE` and `AP_POSTGRES_*` are already listed. Jobs that call `npx vitest` directly, like `tool-search-postgres`, are unaffected, which is what makes the difference easy to miss. Verify with a throwaway test that `console.log`s the variable through `npx turbo run <task> --filter=<pkg>`.- **A GitHub service container is not reachable by its name from a non-container job.** `services:` attaches the container to a docker network with a `--network-alias`, but the runner itself is on the host, so the alias does not resolve (`getaddrinfo EAI_AGAIN redis`) and only the published `ports:` mapping on `localhost` works. `.env.tests` pins `AP_REDIS_HOST=redis` for `docker-compose`, so any test that opens a real connection needs `localhost` forced past it.diff --git a/bun.lock b/bun.lockindex a4162aa4329..7c064272752 100644--- a/bun.lock+++ b/bun.lock@@ -120,7 +120,7 @@},"packages/core/execution": {"name": "@activepieces/core-execution",- "version": "0.23.5",+ "version": "0.23.6","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -188,7 +188,7 @@},"packages/core/utils": {"name": "@activepieces/core-utils",- "version": "0.8.5",+ "version": "0.8.6","dependencies": {"deepmerge-ts": "8.0.2","ipaddr.js": "2.3.0",@@ -3903,7 +3903,7 @@},"packages/pieces/community/google-gemini": {"name": "@activepieces/piece-google-gemini",- "version": "0.3.0",+ "version": "0.4.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -4167,7 +4167,7 @@},"packages/pieces/community/grist": {"name": "@activepieces/piece-grist",- "version": "0.2.0",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -5983,7 +5983,7 @@},"packages/pieces/community/microsoft-todo": {"name": "@activepieces/piece-microsoft-todo",- "version": "0.4.0",+ "version": "0.5.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -6465,7 +6465,7 @@},"packages/pieces/community/odoo": {"name": "@activepieces/piece-odoo",- "version": "0.2.0",+ "version": "0.2.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -9095,7 +9095,7 @@},"packages/pieces/community/ticktick": {"name": "@activepieces/piece-ticktick",- "version": "0.2.1",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -10109,7 +10109,7 @@},"packages/pieces/community/youtube": {"name": "@activepieces/piece-youtube",- "version": "0.7.0",+ "version": "0.8.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -10140,7 +10140,7 @@},"packages/pieces/community/zendesk": {"name": "@activepieces/piece-zendesk",- "version": "0.4.0",+ "version": "0.5.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -10984,7 +10984,7 @@},"packages/server/utils": {"name": "@activepieces/server-utils",- "version": "0.3.0",+ "version": "0.3.1","dependencies": {"@activepieces/ai-providers": "workspace:*","@activepieces/core-formula": "workspace:*",diff --git a/packages/core/execution/package.json b/packages/core/execution/package.jsonindex e8fa3d370d0..70d4935f90a 100644--- a/packages/core/execution/package.json+++ b/packages/core/execution/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/core-execution",- "version": "0.23.5",+ "version": "0.23.6","type": "commonjs","main": "./dist/src/index.js","scripts": {diff --git a/packages/core/execution/src/lib/workers/job-data.ts b/packages/core/execution/src/lib/workers/job-data.tsindex 5da507e4951..e77fba85e11 100644--- a/packages/core/execution/src/lib/workers/job-data.ts+++ b/packages/core/execution/src/lib/workers/job-data.ts@@ -415,6 +415,7 @@ const AiStepJobBase = z.object({provider: z.enum(AIProviderName),providerConfigId: z.string().optional(),modelId: z.string(),+ modelTierId: z.string().optional(),prompt: z.string().optional(),maxOutputTokens: z.number().optional(),temperature: z.number().optional(),diff --git a/packages/core/execution/src/lib/workers/worker-contract.ts b/packages/core/execution/src/lib/workers/worker-contract.tsindex 23a3fd0a0cf..a2f4beac78f 100644--- a/packages/core/execution/src/lib/workers/worker-contract.ts+++ b/packages/core/execution/src/lib/workers/worker-contract.ts@@ -1,4 +1,4 @@-import { ActivepiecesAiBilling, AiChargeBasis, AIProviderName, AiProviderCredentials } from '@activepieces/core-utils'+import { ActivepiecesAiBilling, AiChargeBasis, AIProviderName, AiProviderCredentials, AiProviderKeyStatus, ProviderOutcomeSignal } from '@activepieces/core-utils'import { AgentPieceToolMetadata, PiecePackage } from '@activepieces/core-piece-types'import { StreamStepProgress } from '../engine/engine-operation'import { GetFlowVersionForWorkerRequest, UploadRunLogsRequest } from '../engine/requests'@@ -98,6 +98,8 @@ export type WorkerToApiContract = {executeAgentTool(input: ExecuteAgentToolRequest): Promise<ExecuteAgentToolResponse>resumeFlowStep(input: ResumeFlowStepRequest): Promise<void>resolveAiProvider(input: ResolveAiProviderRequest): Promise<ResolveAiProviderResponse>+ resolveAiModelCandidates(input: ResolveAiModelCandidatesRequest): Promise<ResolveAiModelCandidatesResponse>+ reportAiKeyOutcome(input: ReportAiKeyOutcomeRequest): Promise<void>saveFlowStepFile(input: SaveFlowStepFileRequest): Promise<SaveFlowStepFileResponse>readFlowStepFile(input: ReadFlowStepFileRequest): Promise<ReadFlowStepFileResponse>reportAiUsage(input: ReportAiUsageRequest): Promise<void>@@ -443,6 +445,28 @@ export type ResolveAiProviderResponse = AiProviderCredentials & {providerConfigId: string}+export type ResolveAiModelCandidatesRequest = {+ projectId: string+ platformId: string+ modelTierId: string+}++export type AiModelCandidate = ResolveAiProviderResponse & {+ modelId: string+ status: AiProviderKeyStatus+}++export type ResolveAiModelCandidatesResponse = {+ tierName: string+ candidates: AiModelCandidate[]+}++export type ReportAiKeyOutcomeRequest = {+ platformId: string+ providerConfigId: string+ signal: ProviderOutcomeSignal+}+export type SaveFlowStepFileRequest = {projectId: stringplatformId: stringdiff --git a/packages/core/utils/package.json b/packages/core/utils/package.jsonindex 6165ede95c7..152abf24ca8 100644--- a/packages/core/utils/package.json+++ b/packages/core/utils/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/core-utils",- "version": "0.8.5",+ "version": "0.8.6","type": "commonjs","main": "./dist/src/index.js","scripts": {diff --git a/packages/core/utils/src/lib/ai-provider-health.ts b/packages/core/utils/src/lib/ai-provider-health.tsindex 6f787ae8760..fa567f02955 100644--- a/packages/core/utils/src/lib/ai-provider-health.ts+++ b/packages/core/utils/src/lib/ai-provider-health.ts@@ -103,6 +103,18 @@ export function classifyProviderOutcome({ statusCode, body, message }: ProviderOreturn text.length === 0 ? 'no_change' : 'unreachable'}+export function isFallbackWorthy({ statusCode, body, message, retryable }: ProviderOutcomeSignal): boolean {+ const haystack = `${body ?? ''} ${message ?? ''}`+ if (isProviderBillingError(haystack)) {+ return true+ }+ if (!isNil(statusCode)) {+ return FALLBACK_STATUS_CODES.has(statusCode) || statusCode >= 500+ }+ const text = message ?? ''+ return retryable === true || isProviderCreditError(text) || isTransientProviderError(text)+}+function classifyByStatus({ statusCode, haystack }: { statusCode: number, haystack: string }): AiProviderKeyStatus | NoStatusChange {if (statusCode >= 200 && statusCode < 300) {return 'active'@@ -146,6 +158,8 @@ const RATE_LIMIT_BODY_PATTERN = /per minute|per day|per_minute|per_day|requests?const MODEL_NOT_FOUND_PATTERN = /model|deployment|engine/i+const FALLBACK_STATUS_CODES = new Set([401, 402, 403, 404, 408, 429])+export const AiProviderKeyStatus = z.enum(['active', 'out_of_credits', 'rejected', 'unreachable'])export type AiProviderKeyStatus = z.infer<typeof AiProviderKeyStatus>@@ -155,6 +169,8 @@ export type ProviderOutcomeSignal = {statusCode?: numberbody?: stringmessage?: string+ retryable?: boolean+ fromProvider?: boolean}export type ProviderOutcomeReporter = (signal: ProviderOutcomeSignal) => void | Promise<void>diff --git a/packages/core/utils/test/ai-provider-health.test.ts b/packages/core/utils/test/ai-provider-health.test.tsindex aabc7c32a0c..d4b510c9d9d 100644--- a/packages/core/utils/test/ai-provider-health.test.ts+++ b/packages/core/utils/test/ai-provider-health.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest'-import { classifyProviderOutcome, observedProviderFetch, ProviderOutcomeSignal } from '../src/lib/ai-provider-health'+import { classifyProviderOutcome, isFallbackWorthy, observedProviderFetch, ProviderOutcomeSignal } from '../src/lib/ai-provider-health'describe('classifyProviderOutcome', () => {it('reads a 2xx as a working key', () => {@@ -198,3 +198,30 @@ describe('observedProviderFetch', () => {expect(signals).toMatchObject([{ statusCode: 200 }])})})++describe('isFallbackWorthy', () => {+ it('moves on when the provider fails or refuses the key', () => {+ for (const statusCode of [401, 402, 403, 404, 408, 429, 500, 503]) {+ expect(isFallbackWorthy({ statusCode })).toBe(true)+ }+ })++ it('stops on a bad request, since the next model would get the same one', () => {+ expect(isFallbackWorthy({ statusCode: 400, body: '{"error":"invalid schema"}' })).toBe(false)+ expect(isFallbackWorthy({ statusCode: 422 })).toBe(false)+ })++ it('moves on when a 400 is really the key out of credits', () => {+ expect(isFallbackWorthy({ statusCode: 400, body: 'Your credit balance is too low to access the Anthropic API.' })).toBe(true)+ })++ it('moves on for network failures that carry no status', () => {+ expect(isFallbackWorthy({ message: 'read ECONNRESET' })).toBe(true)+ expect(isFallbackWorthy({ message: 'Cannot connect to API: connect ECONNREFUSED 10.0.0.1:443', retryable: true })).toBe(true)+ })++ it('stops on our own errors', () => {+ expect(isFallbackWorthy({ message: 'Unable to classify the text into the provided categories.' })).toBe(false)+ expect(isFallbackWorthy({ message: 'Provider foo is not supported for web search' })).toBe(false)+ })+})diff --git a/packages/pieces/community/odoo/package.json b/packages/pieces/community/odoo/package.jsonindex 787a1eb7829..f2b3a2c8236 100644--- a/packages/pieces/community/odoo/package.json+++ b/packages/pieces/community/odoo/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-odoo",- "version": "0.2.0",+ "version": "0.2.1","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/odoo/test/pr-a.test.ts b/packages/pieces/community/odoo/test/pr-a.test.tsindex 667fda9d099..4e250666824 100644--- a/packages/pieces/community/odoo/test/pr-a.test.ts+++ b/packages/pieces/community/odoo/test/pr-a.test.ts@@ -578,7 +578,7 @@ describe('polling triggers: 5-minute look-back cursor', () => {const late = asRecords(await newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store })));expect(late.map((r) => r['id'])).toEqual([5000, 20000]);await expect(newRecordTrigger.run(triggerCtx({ propsValue: { model: 'res.partner' }, store }))).resolves.toEqual([]);- });+ }, HEAVY_POLL_TEST_TIMEOUT_MS);it('keeps the stored cursor under 512 KB with 5,000 ranges of large ids spread over the whole window', async () => {route({ key: 'res.partner.fields_get', handler: () => partnerFields });@@ -1022,3 +1022,5 @@ function triggerCtx({ propsValue, store, isRepublish }: TriggerCtxParams) {type ActionCtxParams = { propsValue: Record<string, unknown>; extra?: Record<string, unknown> };type TriggerCtxParams = { propsValue: Record<string, unknown>; store: ReturnType<typeof memoryStore>; isRepublish?: boolean };++const HEAVY_POLL_TEST_TIMEOUT_MS = 30_000;diff --git a/packages/server/api/src/app/ai/ai-execute-controller.ts b/packages/server/api/src/app/ai/ai-execute-controller.tsindex 7f309ff6f57..24c5c5a0ef3 100644--- a/packages/server/api/src/app/ai/ai-execute-controller.ts+++ b/packages/server/api/src/app/ai/ai-execute-controller.ts@@ -1,5 +1,6 @@-import { ActivepiecesError, AIProviderName, apId, ErrorCode, isNil } from '@activepieces/core-utils'+import { ActivepiecesError, AIProviderName, ApId, apId, ErrorCode, isNil } from '@activepieces/core-utils'import { AiStepAction, AiStepFile, AiStepSchema, AiStepWebSearch, ExecuteAiJobData, LATEST_JOB_DATA_SCHEMA_VERSION, maxSocketHttpBufferSizeBytes, PrincipalType, WorkerJobType } from '@activepieces/shared'+import { FastifyBaseLogger } from 'fastify'import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'import { StatusCodes } from 'http-status-codes'import { z } from 'zod'@@ -8,6 +9,7 @@ import { system } from '../helper/system/system'import { AppSystemProp } from '../helper/system/system-props'import { assertCreditsAndAppSumoNotExceeded } from '../platform/billing-provider'import { aiExecution } from './ai-execution'+import { aiModelCandidates } from './ai-model-candidates'import { aiModelResolution } from './ai-model-resolution'export const aiExecuteController: FastifyPluginAsyncZod = async (app) => {@@ -27,16 +29,14 @@ export const aiExecuteController: FastifyPluginAsyncZod = async (app) => {const requestId = apId()const log = request.log.child({ flowRun: { id: body.flowRunId }, requestId })const execution = aiExecution(log)- const modelId = body.action === AiStepAction.GENERATE_IMAGE- ? body.modelId- : aiModelResolution.resolveTierModelId({ provider: body.provider, modelId: body.modelId, log })+ const model = await pickModel({ body, platformId: platform.id, log })const answerInThisRequest = isNil(body.waitpointId)const timeoutMs = system.getNumberOrThrow(AppSystemProp.FLOW_TIMEOUT_SECONDS) * 1000const answer = answerInThisRequest ? execution.waitForAnswer({ requestId, timeoutMs }) : undefinedawait execution.enqueue(aiJobFor({body,- modelId,+ model,requestId,projectId,platformId: platform.id,@@ -44,8 +44,9 @@ export const aiExecuteController: FastifyPluginAsyncZod = async (app) => {}))log.info({project: { id: projectId },- model: { id: modelId },- tier: modelId === body.modelId ? undefined : { id: body.modelId },+ model: { id: model.modelId },+ tier: isNil(body.modelTierId) && model.modelId !== body.modelId ? { id: body.modelId } : undefined,+ platformTier: isNil(body.modelTierId) ? undefined : { id: body.modelTierId },}, '[aiExecuteController] Enqueued AI step')if (!isNil(answer)) {@@ -55,9 +56,29 @@ export const aiExecuteController: FastifyPluginAsyncZod = async (app) => {})}-function aiJobFor({ body, modelId, requestId, projectId, platformId, webserverId }: {+async function pickModel({ body, platformId, log }: {body: z.infer<typeof ExecuteAiRequest>- modelId: string+ platformId: string+ log: FastifyBaseLogger+}): Promise<PickedModel> {+ if (!isNil(body.modelTierId)) {+ if (body.action === AiStepAction.GENERATE_IMAGE) {+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: 'Image steps pick a specific model, not a tier' } })+ }+ return aiModelCandidates(log).firstCandidate({ platformId, tierId: body.modelTierId })+ }+ if (isNil(body.provider) || isNil(body.modelId)) {+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: 'Pick a tier or a provider and model' } })+ }+ const modelId = body.action === AiStepAction.GENERATE_IMAGE+ ? body.modelId+ : aiModelResolution.resolveTierModelId({ provider: body.provider, modelId: body.modelId, log })+ return { provider: body.provider, providerConfigId: body.providerConfigId, modelId }+}++function aiJobFor({ body, model, requestId, projectId, platformId, webserverId }: {+ body: z.infer<typeof ExecuteAiRequest>+ model: PickedModelrequestId: stringprojectId: stringplatformId: string@@ -73,10 +94,11 @@ function aiJobFor({ body, modelId, requestId, projectId, platformId, webserverIdflowRunId: body.flowRunId,waitpointId: body.waitpointId,webserverId,- provider: body.provider,- modelId,+ provider: model.provider,+ modelId: model.modelId,+ modelTierId: body.modelTierId,prompt: body.prompt,- providerConfigId: body.providerConfigId,+ providerConfigId: model.providerConfigId,maxOutputTokens: body.maxOutputTokens,temperature: body.temperature,webSearch: body.webSearch,@@ -119,9 +141,10 @@ const ExecuteAiRequest = z.object({flowId: z.string(),flowRunId: z.string(),waitpointId: z.string().optional(),- provider: z.enum(AIProviderName),+ provider: z.enum(AIProviderName).optional(),providerConfigId: z.string().optional(),- modelId: z.string(),+ modelId: z.string().optional(),+ modelTierId: z.optional(ApId),prompt: z.string().optional(),text: z.string().optional(),categories: z.array(z.string()).optional(),@@ -134,6 +157,12 @@ const ExecuteAiRequest = z.object({webSearch: AiStepWebSearch.optional(),})+type PickedModel = {+ provider: AIProviderName+ providerConfigId?: string+ modelId: string+}+const ExecuteAiResponse = z.object({requestId: z.string(),output: z.unknown().optional(),diff --git a/packages/server/api/src/app/ai/ai-model-candidates.ts b/packages/server/api/src/app/ai/ai-model-candidates.tsnew file mode 100644index 00000000000..5f687544075--- /dev/null+++ b/packages/server/api/src/app/ai/ai-model-candidates.ts@@ -0,0 +1,35 @@+import { ActivepiecesError, AIProviderName, ErrorCode, isNil, PlatformId, tryCatch } from '@activepieces/core-utils'+import { ResolveAiModelCandidatesResponse } from '@activepieces/shared'+import { FastifyBaseLogger } from 'fastify'+import { aiProviderService } from './ai-provider-service'+import { platformModelTierService } from './platform-model-tier-service'++export const aiModelCandidates = (log: FastifyBaseLogger) => ({+ async firstCandidate({ platformId, tierId }: { platformId: PlatformId, tierId: string }): Promise<FirstCandidate> {+ const { entries: [first] } = await platformModelTierService.getForRun({ platformId, id: tierId })+ return { provider: first.key.provider, providerConfigId: first.key.id, modelId: first.modelId }+ },++ async resolve({ platformId, tierId }: { platformId: PlatformId, tierId: string }): Promise<ResolveAiModelCandidatesResponse> {+ const { tier, entries } = await platformModelTierService.getForRun({ platformId, id: tierId })+ const decrypted = await Promise.all(entries.map(async ({ modelId, key }) => {+ const { data: credentials, error } = await tryCatch(() => aiProviderService(log).credentialsForTierKey({ platformId, key }))+ if (!isNil(error) || isNil(credentials)) {+ log.warn({ error, aiProvider: { id: key.id }, platformTier: { id: tier.id } }, '[aiModelCandidates] Skipping a tier entry whose key cannot be read')+ return []+ }+ return [{ ...credentials, providerConfigId: key.id, modelId, status: key.status }]+ }))+ const candidates = decrypted.flat()+ if (candidates.length === 0) {+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: `No model in tier "${tier.name}" can run` } })+ }+ return { tierName: tier.name, candidates }+ },+})++export type FirstCandidate = {+ provider: AIProviderName+ providerConfigId: string+ modelId: string+}diff --git a/packages/server/api/src/app/ai/ai-provider-service.ts b/packages/server/api/src/app/ai/ai-provider-service.tsindex 60dbb58242e..e196cad5f8e 100644--- a/packages/server/api/src/app/ai/ai-provider-service.ts+++ b/packages/server/api/src/app/ai/ai-provider-service.ts@@ -1,4 +1,4 @@-import { ActivepiecesError, AiProviderKeyStatus, AIProviderName, apId, classifyProviderOutcome, ErrorCode, isNil, PlatformId, ProviderOutcomeSignal, spreadIfDefined, spreadIfNotUndefined, toProviderOutcomeSignal, tryCatch, unique } from '@activepieces/core-utils'+import { ActivepiecesError, AiProviderCredentials, AiProviderKeyStatus, AIProviderName, apId, classifyProviderOutcome, ErrorCode, isNil, PlatformId, ProviderOutcomeSignal, spreadIfDefined, spreadIfNotUndefined, toProviderOutcomeSignal, tryCatch, unique } from '@activepieces/core-utils'import { modelCatalog, modelTierCatalog } from '@activepieces/server-utils'import { ActivePiecesProviderAuthConfig, AI_PROVIDER_ENTITY_TYPES, AIProviderAuthConfig, AIProviderConfig, aiProviderCredentials, AIProviderModel, AIProviderModelType, AiProviderProjectScope, aiProviderUtils, AIProviderWithoutSensitiveData, CreateAIProviderRequest, GetProviderConfigResponse, ProjectAIProvider, UpdateAIProviderRequest } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'@@ -219,6 +219,26 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({)},+ async confirmReportedOutcome({ platformId, providerId, signal }: { platformId: PlatformId, providerId: string, signal: ProviderOutcomeSignal }): Promise<void> {+ const status = classifyProviderOutcome(signal)+ if (status === 'no_change') {+ return+ }+ const aiProvider = await aiProviderRepo().findOneBy({ id: providerId, platformId })+ if (isNil(aiProvider) || aiProvider.status === status || aiProvider.provider === AIProviderName.ACTIVEPIECES) {+ return+ }+ if (aiProviders[aiProvider.provider].validationSkipsModelEndpoint === true) {+ await aiProviderHealth(log).record({ platformId, providerId, signal, expectVersion: aiProvider.statusVersion })+ return+ }+ await distributedStore.runOnceWithin(+ getAiProviderConfirmKey(providerId),+ CONFIRM_MIN_INTERVAL_SECONDS,+ () => this.recheck({ platformId, providerId, expectVersion: aiProvider.statusVersion }),+ )+ },+async recheck({ platformId, providerId, expectVersion }: { platformId: PlatformId, providerId: string, expectVersion?: number }): Promise<AiProviderKeyStatus> {const aiProvider = await getRowByIdOrThrow({ platformId, configId: providerId })if (aiProvider.provider === AIProviderName.ACTIVEPIECES) {@@ -260,6 +280,10 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({const auth = await decryptRowAuth({ aiProvider, platformId })return { ...aiProviderCredentials({ provider: aiProvider.provider, auth, config: aiProvider.config }), configId: aiProvider.id, platformId, modelScope: aiProvider.modelScope, modelIds: aiProvider.modelIds }},+ async credentialsForTierKey({ platformId, key }: { platformId: PlatformId, key: AIProviderSchema }): Promise<AiProviderCredentials> {+ const auth = await decryptRowAuth({ aiProvider: key, platformId })+ return aiProviderCredentials({ provider: key.provider, auth, config: key.config })+ },async getOrCreateActivePiecesProviderAuthConfig(platformId: PlatformId): Promise<ActivePiecesProviderAuthConfig> {await ensureManagedProviderRow({ platformId })const { auth } = await this.getConfigOrThrow({ platformId, provider: AIProviderName.ACTIVEPIECES, scope: { type: 'platform' } })diff --git a/packages/server/api/src/app/ai/ai-rpc-handlers.ts b/packages/server/api/src/app/ai/ai-rpc-handlers.tsindex 5976758774e..c6bb776fd45 100644--- a/packages/server/api/src/app/ai/ai-rpc-handlers.ts+++ b/packages/server/api/src/app/ai/ai-rpc-handlers.ts@@ -1,13 +1,15 @@import { ActivepiecesError, ErrorCode, isNil, sanitizeObjectForPostgresql, tryCatch } from '@activepieces/core-utils'-import { FileCompression, FileSizeError, FileType, ReadFlowStepFileRequest, ReadFlowStepFileResponse, ReportAiUsageRequest, ResolveAiProviderRequest, ResolveAiProviderResponse, ResumeAiStepRequest, SaveFlowStepFileRequest, SaveFlowStepFileResponse, spreadIfDefined } from '@activepieces/shared'+import { FileCompression, FileSizeError, FileType, ReadFlowStepFileRequest, ReadFlowStepFileResponse, ReportAiKeyOutcomeRequest, ReportAiUsageRequest, ResolveAiModelCandidatesRequest, ResolveAiModelCandidatesResponse, ResolveAiProviderRequest, ResolveAiProviderResponse, ResumeAiStepRequest, SaveFlowStepFileRequest, SaveFlowStepFileResponse, spreadIfDefined } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { fileService } from '../file/file.service'import { filesService } from '../file/files-service'import { flowRunService } from '../flows/flow-run/flow-run-service'+import { rejectedPromiseHandler } from '../helper/promise-handler'import { system } from '../helper/system/system'import { AppSystemProp } from '../helper/system/system-props'import { projectService } from '../project/project-service'import { resumeService } from '../waitpoints/resume-service'+import { aiModelCandidates } from './ai-model-candidates'import { aiProviderService } from './ai-provider-service'import { aiUsageService } from './ai-usage-service'@@ -26,6 +28,15 @@ export const aiRpcHandlers = (log: FastifyBaseLogger) => ({}},+ async resolveAiModelCandidates(input: ResolveAiModelCandidatesRequest): Promise<ResolveAiModelCandidatesResponse> {+ await assertProjectBelongsToPlatform({ ...input, log })+ return aiModelCandidates(log).resolve({ platformId: input.platformId, tierId: input.modelTierId })+ },++ async reportAiKeyOutcome(input: ReportAiKeyOutcomeRequest): Promise<void> {+ rejectedPromiseHandler(aiProviderService(log).confirmReportedOutcome({ platformId: input.platformId, providerId: input.providerConfigId, signal: input.signal }), log)+ },+async saveFlowStepFile(input: SaveFlowStepFileRequest): Promise<SaveFlowStepFileResponse> {await assertProjectBelongsToPlatform({ ...input, log })const maxFileSizeMb = system.getNumberOrThrow(AppSystemProp.MAX_FILE_SIZE_MB)diff --git a/packages/server/api/src/app/ai/platform-model-tier-service.ts b/packages/server/api/src/app/ai/platform-model-tier-service.tsindex 1ef9c905a1f..3ef06df1cab 100644--- a/packages/server/api/src/app/ai/platform-model-tier-service.ts+++ b/packages/server/api/src/app/ai/platform-model-tier-service.ts@@ -11,6 +11,8 @@ const tierRepo = repoFactory<PlatformModelTierSchema>(PlatformModelTierEntity)const aiProviderRepo = repoFactory<AIProviderSchema>(AIProviderEntity)const MAX_LIVE_TIERS = 50+const MAX_REPLACEMENT_HOPS = 3+const TIER_REMOVED_MESSAGE = 'This tier was removed. Pick a new model for this step.'export const platformModelTierService = {async listSummaries({ platformId }: { platformId: PlatformId }): Promise<PlatformModelTierSummary[]> {@@ -136,6 +138,28 @@ export const platformModelTierService = {}},+ async getForRun({ platformId, id }: { platformId: PlatformId, id: string }): Promise<TierForRun> {+ const tier = await followReplacements({ platformId, id })+ const configIds = unique(tier.entries.map((entry) => entry.configId))+ const keys = await aiProviderRepo().findBy({ platformId, id: In(configIds) })+ const keyById = new Map(keys.map((key) => [key.id, key]))+ const runnable = tier.entries.flatMap((entry) => {+ const key = keyById.get(entry.configId)+ if (isNil(key) || key.provider === AIProviderName.ACTIVEPIECES || !scopeAllows({ modelScope: key.modelScope, modelIds: key.modelIds, modelId: entry.modelId })) {+ return []+ }+ return [{ modelId: entry.modelId, key }]+ })+ if (runnable.length === 0) {+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: `No model in tier "${tier.name}" can run` } })+ }+ const healthyFirst = [+ ...runnable.filter((entry) => entry.key.status === 'active'),+ ...runnable.filter((entry) => entry.key.status !== 'active'),+ ]+ return { tier, entries: healthyFirst }+ },+async assertKeyScopeKeepsTiers({ manager, platformId, configId, modelScope, modelIds }: AssertKeyScopeParams): Promise<void> {await lockPlatform({ manager, platformId })const key = await aiProviderRepo(manager).findOneBy({ platformId, id: configId })@@ -161,6 +185,24 @@ async function lockPlatform({ manager, platformId }: { manager: EntityManager, p}}+async function followReplacements({ platformId, id }: { platformId: PlatformId, id: string }): Promise<PlatformModelTier> {+ let currentId = id+ for (let hop = 0; hop <= MAX_REPLACEMENT_HOPS; hop++) {+ const tier = await tierRepo().findOne({ where: { platformId, id: currentId }, withDeleted: true })+ if (isNil(tier)) {+ throw new ActivepiecesError({ code: ErrorCode.ENTITY_NOT_FOUND, params: { entityId: currentId, entityType: 'platform_model_tier' } })+ }+ if (isNil(tier.deleted)) {+ return tier+ }+ if (isNil(tier.replacedBy)) {+ break+ }+ currentId = tier.replacedBy+ }+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: TIER_REMOVED_MESSAGE } })+}+async function listLive({ platformId, manager }: { platformId: PlatformId, manager?: EntityManager }): Promise<PlatformModelTier[]> {return tierRepo(manager).find({ where: { platformId }, order: { position: 'ASC', created: 'ASC' }, take: MAX_LIVE_TIERS })}@@ -251,6 +293,11 @@ function toSummary({ tier, providerByConfigId }: { tier: PlatformModelTier, prov}}+export type TierForRun = {+ tier: PlatformModelTier+ entries: { modelId: string, key: AIProviderSchema }[]+}+type AssertKeyScopeParams = {manager: EntityManagerplatformId: PlatformIddiff --git a/packages/server/api/src/app/ai/providers/ai-provider.ts b/packages/server/api/src/app/ai/providers/ai-provider.tsindex ee08f3d453c..7a7e1fee8fe 100644--- a/packages/server/api/src/app/ai/providers/ai-provider.ts+++ b/packages/server/api/src/app/ai/providers/ai-provider.ts@@ -6,6 +6,7 @@ export const MODEL_LIST_TIMEOUT_MS = 15_000export type AIProviderStrategy<T extends AIProviderAuthConfig, C extends AIProviderConfig> = {name: stringmodelIdsAreCustomerNamed?: boolean+ validationSkipsModelEndpoint?: booleanlistModels(authConfig: T, config: C): Promise<AIProviderModel[]>validateConnection(authConfig: T, config: C, log: FastifyBaseLogger): Promise<void>}diff --git a/packages/server/api/src/app/ai/providers/openai-compatible-gateway-provider.ts b/packages/server/api/src/app/ai/providers/openai-compatible-gateway-provider.tsindex 195d2849408..6589a0bd83c 100644--- a/packages/server/api/src/app/ai/providers/openai-compatible-gateway-provider.ts+++ b/packages/server/api/src/app/ai/providers/openai-compatible-gateway-provider.ts@@ -4,6 +4,7 @@ import { AIProviderStrategy } from './ai-provider'export const openAICompatibleProvider: AIProviderStrategy<OpenAICompatibleProviderAuthConfig, OpenAICompatibleProviderConfig> = {name: 'OpenAI Compatible',+ validationSkipsModelEndpoint: true,async validateConnection(authConfig: OpenAICompatibleProviderAuthConfig, providerConfig: OpenAICompatibleProviderConfig, _log: FastifyBaseLogger): Promise<void> {assertUsableBaseUrl({ baseUrl: providerConfig.baseUrl })assertUsableHeader({ name: providerConfig.apiKeyHeader, value: authConfig.apiKey, field: 'The API key header' })diff --git a/packages/server/api/src/app/ai/providers/vertex-provider.ts b/packages/server/api/src/app/ai/providers/vertex-provider.tsindex f7a8f55b560..0f412482818 100644--- a/packages/server/api/src/app/ai/providers/vertex-provider.ts+++ b/packages/server/api/src/app/ai/providers/vertex-provider.ts@@ -5,6 +5,7 @@ import { AIProviderStrategy } from './ai-provider'export const vertexProvider: AIProviderStrategy<VertexProviderAuthConfig, VertexProviderConfig> = {name: 'Google Vertex AI',+ validationSkipsModelEndpoint: true,async validateConnection(authConfig: VertexProviderAuthConfig,diff --git a/packages/server/api/src/app/workers/rpc/worker-rpc-service.ts b/packages/server/api/src/app/workers/rpc/worker-rpc-service.tsindex bf6ba67b42f..baace04372a 100644--- a/packages/server/api/src/app/workers/rpc/worker-rpc-service.ts+++ b/packages/server/api/src/app/workers/rpc/worker-rpc-service.ts@@ -404,6 +404,12 @@ export function createHandlers(log: FastifyBaseLogger, assignment: WorkerGroupAsasync resolveAiProvider(input) {return aiRpcHandlers(log).resolveAiProvider(input)},+ async resolveAiModelCandidates(input) {+ return aiRpcHandlers(log).resolveAiModelCandidates(input)+ },+ async reportAiKeyOutcome(input) {+ return aiRpcHandlers(log).reportAiKeyOutcome(input)+ },async saveFlowStepFile(input) {return aiRpcHandlers(log).saveFlowStepFile(input)},diff --git a/packages/server/api/test/integration/ce/ai-provider/ai-model-candidates.test.ts b/packages/server/api/test/integration/ce/ai-provider/ai-model-candidates.test.tsnew file mode 100644index 00000000000..395c62047ec--- /dev/null+++ b/packages/server/api/test/integration/ce/ai-provider/ai-model-candidates.test.ts@@ -0,0 +1,238 @@+import { AIProviderName, apId } from '@activepieces/core-utils'+import { AiStepAction, PlatformModelTier, PrincipalType } from '@activepieces/shared'+import { FastifyInstance } from 'fastify'+import { StatusCodes } from 'http-status-codes'+import { vi } from 'vitest'+import { aiRpcHandlers } from '../../../../src/app/ai/ai-rpc-handlers'+import { databaseConnection } from '../../../../src/app/database/database-connection'+import { generateMockToken } from '../../../helpers/auth'+import { mockAndSaveAIProvider } from '../../../helpers/mocks'+import { createTestContext, TestContext } from '../../../helpers/test-context'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++const { enqueue, mockSendRequest } = vi.hoisted(() => ({ enqueue: vi.fn(), mockSendRequest: vi.fn() }))++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const original = await importOriginal<typeof import('@activepieces/pieces-common')>()+ return {+ ...original,+ httpClient: { ...original.httpClient, sendRequest: mockSendRequest },+ }+})++vi.mock('../../../../src/app/ai/ai-execution', () => ({+ aiExecution: () => ({ serverId: () => 'server-1', enqueue, waitForAnswer: vi.fn() }),+}))++let app: FastifyInstance | null = null+let ctx: TestContext++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++beforeEach(async () => {+ ctx = await createTestContext(app!)+ enqueue.mockReset().mockResolvedValue(undefined)+ mockSendRequest.mockReset()+})++describe('tier candidates', () => {+ it('lets a tier run a key that is scoped away from the project, while a specific pick of it still fails', async () => {+ const scopedAway = await seedKey({ testCtx: ctx, projectScope: 'selected', projectIds: [] })+ const tier = await createTier({ testCtx: ctx, name: 'Expert', entries: [{ configId: scopedAway.id, modelId: 'gpt-4o' }] })++ const { tierName, candidates } = await rpc().resolveAiModelCandidates({ projectId: ctx.project.id, platformId: ctx.platform.id, modelTierId: tier.id })+ const specificPick = rpc().resolveAiProvider({ projectId: ctx.project.id, platformId: ctx.platform.id, provider: AIProviderName.CUSTOM, providerConfigId: scopedAway.id })++ expect(tierName).toBe('Expert')+ expect(candidates).toEqual([expect.objectContaining({ providerConfigId: scopedAway.id, modelId: 'gpt-4o', provider: AIProviderName.CUSTOM, status: 'active' })])+ await expect(specificPick).rejects.toThrow()+ })++ it('tries healthy keys first and keeps the tier order inside each group', async () => {+ const down = await seedKey({ testCtx: ctx })+ const up = await seedKey({ testCtx: ctx })+ await databaseConnection().getRepository('ai_provider').update({ id: down.id }, { status: 'unreachable' })+ const tier = await createTier({ testCtx: ctx, entries: [+ { configId: down.id, modelId: 'main' },+ { configId: up.id, modelId: 'first-fallback' },+ { configId: up.id, modelId: 'second-fallback' },+ ] })++ const { candidates } = await rpc().resolveAiModelCandidates({ projectId: ctx.project.id, platformId: ctx.platform.id, modelTierId: tier.id })++ expect(candidates.map((candidate) => candidate.modelId)).toEqual(['first-fallback', 'second-fallback', 'main'])+ })++ it('skips an entry whose key cannot be decrypted and keeps the rest', async () => {+ const broken = await seedKey({ testCtx: ctx })+ const working = await seedKey({ testCtx: ctx })+ await databaseConnection().getRepository('ai_provider').update({ id: broken.id }, { auth: { iv: 'bad', data: 'bad' } })+ const tier = await createTier({ testCtx: ctx, entries: [{ configId: broken.id, modelId: 'main' }, { configId: working.id, modelId: 'backup' }] })++ const { candidates } = await rpc().resolveAiModelCandidates({ projectId: ctx.project.id, platformId: ctx.platform.id, modelTierId: tier.id })++ expect(candidates.map((candidate) => candidate.modelId)).toEqual(['backup'])+ })++ it('follows a deleted tier to its replacement', async () => {+ const key = await seedKey({ testCtx: ctx })+ const old = await createTier({ testCtx: ctx, name: 'Old', entries: [{ configId: key.id, modelId: 'old-model' }] })+ const replacement = await createTier({ testCtx: ctx, name: 'New', entries: [{ configId: key.id, modelId: 'new-model' }] })+ await ctx.delete(`${TIERS}/${old.id}`, { replacedBy: replacement.id })++ const { tierName, candidates } = await rpc().resolveAiModelCandidates({ projectId: ctx.project.id, platformId: ctx.platform.id, modelTierId: old.id })++ expect(tierName).toBe('New')+ expect(candidates.map((candidate) => candidate.modelId)).toEqual(['new-model'])+ })++ it('fails a tier that was removed without a replacement', async () => {+ const key = await seedKey({ testCtx: ctx })+ const tier = await createTier({ testCtx: ctx, entries: [{ configId: key.id, modelId: 'gpt-4o' }] })+ const removed = await ctx.delete(`${TIERS}/${tier.id}`)+ expect(removed.statusCode).toBe(StatusCodes.NO_CONTENT)++ await expect(rpc().resolveAiModelCandidates({ projectId: ctx.project.id, platformId: ctx.platform.id, modelTierId: tier.id }))+ .rejects.toMatchObject({ error: { code: 'VALIDATION', params: { message: 'This tier was removed. Pick a new model for this step.' } } })+ })++ it('never resolves another platform\'s tier', async () => {+ const otherCtx = await createTestContext(app!)+ const foreignKey = await seedKey({ testCtx: otherCtx })+ const foreignTier = await createTier({ testCtx: otherCtx, entries: [{ configId: foreignKey.id, modelId: 'gpt-4o' }] })++ await expect(rpc().resolveAiModelCandidates({ projectId: ctx.project.id, platformId: ctx.platform.id, modelTierId: foreignTier.id }))+ .rejects.toThrow()+ await expect(rpc().resolveAiModelCandidates({ projectId: ctx.project.id, platformId: otherCtx.platform.id, modelTierId: foreignTier.id }))+ .rejects.toThrow()+ })+})++describe('reported key outcomes', () => {+ it('re-checks the key instead of trusting a reported success, so a forged report cannot mark a key healthy', async () => {+ const key = await mockAndSaveAIProvider({ platformId: ctx.platform.id, provider: AIProviderName.AZURE, config: { resourceName: `forged-${apId()}` } })+ await databaseConnection().getRepository('ai_provider').update({ id: key.id }, { status: 'unreachable' })+ mockSendRequest.mockRejectedValue(Object.assign(new Error('Request failed with status code 401'), { response: { status: 401, body: { error: 'invalid key' } } }))++ await rpc().reportAiKeyOutcome({ platformId: ctx.platform.id, providerConfigId: key.id, signal: { statusCode: 200 } })++ await vi.waitFor(async () => expect(await statusOf(key.id)).toBe('rejected'))+ expect(mockSendRequest).toHaveBeenCalled()+ })++ it('records a reported outage on a custom endpoint, since its check never reaches the model', async () => {+ const key = await seedKey({ testCtx: ctx })++ await rpc().reportAiKeyOutcome({ platformId: ctx.platform.id, providerConfigId: key.id, signal: { statusCode: 503 } })++ await vi.waitFor(async () => expect(await statusOf(key.id)).toBe('unreachable'))+ expect(mockSendRequest).not.toHaveBeenCalled()+ })++ it('does nothing when the report matches what the key already says', async () => {+ const key = await seedKey({ testCtx: ctx })++ await rpc().reportAiKeyOutcome({ platformId: ctx.platform.id, providerConfigId: key.id, signal: { statusCode: 200 } })++ expect(mockSendRequest).not.toHaveBeenCalled()+ expect(await statusOf(key.id)).toBe('active')+ })++ it('never touches another platform\'s key', async () => {+ const otherCtx = await createTestContext(app!)+ const foreignKey = await seedKey({ testCtx: otherCtx })++ await rpc().reportAiKeyOutcome({ platformId: ctx.platform.id, providerConfigId: foreignKey.id, signal: { statusCode: 401 } })++ expect(mockSendRequest).not.toHaveBeenCalled()+ expect(await statusOf(foreignKey.id)).toBe('active')+ })+})++describe('POST /v1/ai/execute with a tier', () => {+ it('enqueues the tier and the first model the worker will try', async () => {+ const key = await seedKey({ testCtx: ctx, projectScope: 'selected', projectIds: [] })+ const tier = await createTier({ testCtx: ctx, entries: [{ configId: key.id, modelId: 'gpt-4o' }] })++ const response = await executeAiStep({ body: { action: AiStepAction.ASK_AI, modelTierId: tier.id } })++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(enqueue.mock.calls[0][0]).toMatchObject({ modelTierId: tier.id, provider: AIProviderName.CUSTOM, providerConfigId: key.id, modelId: 'gpt-4o' })+ })++ it('refuses a tier on an image step', async () => {+ const key = await seedKey({ testCtx: ctx })+ const tier = await createTier({ testCtx: ctx, entries: [{ configId: key.id, modelId: 'gpt-4o' }] })++ const response = await executeAiStep({ body: { action: AiStepAction.GENERATE_IMAGE, modelTierId: tier.id } })++ expect(response.statusCode).not.toBe(StatusCodes.OK)+ expect(enqueue).not.toHaveBeenCalled()+ })++ it('returns not found for another platform\'s tier', async () => {+ const otherCtx = await createTestContext(app!)+ const foreignKey = await seedKey({ testCtx: otherCtx })+ const foreignTier = await createTier({ testCtx: otherCtx, entries: [{ configId: foreignKey.id, modelId: 'gpt-4o' }] })++ const response = await executeAiStep({ body: { action: AiStepAction.ASK_AI, modelTierId: foreignTier.id } })++ expect(response.statusCode).toBe(StatusCodes.NOT_FOUND)+ expect(enqueue).not.toHaveBeenCalled()+ })++ it('refuses a body with neither a tier nor a model', async () => {+ const response = await executeAiStep({ body: { action: AiStepAction.ASK_AI } })++ expect(response.statusCode).not.toBe(StatusCodes.OK)+ expect(enqueue).not.toHaveBeenCalled()+ })+})++async function statusOf(id: string): Promise<string> {+ const row = await databaseConnection().getRepository('ai_provider').findOneByOrFail({ id })+ return row.status+}++function rpc(): ReturnType<typeof aiRpcHandlers> {+ return aiRpcHandlers(app!.log)+}++async function seedKey({ testCtx, projectScope, projectIds }: { testCtx: TestContext, projectScope?: 'all' | 'selected', projectIds?: string[] }): Promise<{ id: string }> {+ return mockAndSaveAIProvider({+ platformId: testCtx.platform.id,+ provider: AIProviderName.CUSTOM,+ config: { baseUrl: 'https://api.example.com/v1', apiKeyHeader: 'Authorization', models: [] },+ ...(projectScope ? { projectScope } : {}),+ ...(projectIds ? { projectIds } : {}),+ })+}++async function createTier({ testCtx, name, entries }: { testCtx: TestContext, name?: string, entries: { configId: string, modelId: string }[] }): Promise<PlatformModelTier> {+ const response = await testCtx.post(TIERS, { name: name ?? 'Fast', emoji: '⚡', description: null, entries })+ expect(response.statusCode).toBe(StatusCodes.OK)+ return response.json()+}++async function executeAiStep({ body }: { body: Record<string, unknown> }) {+ const engineToken = await generateMockToken({+ type: PrincipalType.ENGINE,+ id: apId(),+ projectId: ctx.project.id,+ platform: { id: ctx.platform.id },+ })+ return app!.inject({+ method: 'POST',+ url: '/api/v1/ai/execute',+ headers: { authorization: `Bearer ${engineToken}` },+ body: { flowId: apId(), flowRunId: apId(), waitpointId: apId(), prompt: 'hello', ...body },+ })+}++const TIERS = '/v1/platform-model-tiers'diff --git a/packages/server/utils/package.json b/packages/server/utils/package.jsonindex 6501f95f801..814afb4e281 100644--- a/packages/server/utils/package.json+++ b/packages/server/utils/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/server-utils",- "version": "0.3.0",+ "version": "0.3.1","type": "commonjs","main": "./dist/src/index.js","typings": "./dist/src/index.d.ts",diff --git a/packages/server/utils/src/ai-provider-signal.ts b/packages/server/utils/src/ai-provider-signal.tsnew file mode 100644index 00000000000..fb6ee2cafc7--- /dev/null+++ b/packages/server/utils/src/ai-provider-signal.ts@@ -0,0 +1,41 @@+import { isNil, ProviderOutcomeSignal, toProviderOutcomeSignal } from '@activepieces/core-utils'+import { APICallError, RetryError } from 'ai'++function fromError(error: unknown): ProviderOutcomeSignal {+ const root = innermostError(error)+ if (APICallError.isInstance(root)) {+ return {+ ...(isNil(root.statusCode) ? {} : { statusCode: root.statusCode }),+ ...(isNil(root.responseBody) ? {} : { body: root.responseBody }),+ message: root.message,+ retryable: root.isRetryable,+ fromProvider: true,+ }+ }+ return { ...toProviderOutcomeSignal(root), fromProvider: false }+}++function innermostError(error: unknown): unknown {+ let current = error+ for (let depth = 0; depth < MAX_CAUSE_DEPTH; depth++) {+ if (RetryError.isInstance(current) && !isNil(current.lastError)) {+ current = current.lastError+ continue+ }+ if (APICallError.isInstance(current)) {+ return current+ }+ const cause = current instanceof Error ? current.cause : undefined+ if (isNil(cause)) {+ return current+ }+ current = cause+ }+ return current+}++const MAX_CAUSE_DEPTH = 5++export const aiProviderSignal = {+ fromError,+}diff --git a/packages/server/utils/src/index.ts b/packages/server/utils/src/index.tsindex 461d31e558d..35df74803bc 100644--- a/packages/server/utils/src/index.ts+++ b/packages/server/utils/src/index.ts@@ -33,6 +33,7 @@ export { activepiecesAiCost } from './activepieces-ai-cost'export { aiUsageReportOf } from './ai-usage-report'export { aiCostReporter } from './ai-cost-reporter'export { aiProviderKeyHealth } from './ai-provider-key-health'+export { aiProviderSignal } from './ai-provider-signal'export type { KeyHealthObservation } from './ai-provider-key-health'export { agentAiUtils } from './agent-ai-utils'export type { ContentPartLike } from './agent-ai-utils'diff --git a/packages/server/utils/test/ai-provider-signal.test.ts b/packages/server/utils/test/ai-provider-signal.test.tsnew file mode 100644index 00000000000..d2682642c7e--- /dev/null+++ b/packages/server/utils/test/ai-provider-signal.test.ts@@ -0,0 +1,47 @@+import { APICallError, RetryError } from 'ai'+import { describe, expect, it } from 'vitest'+import { aiProviderSignal } from '../src/ai-provider-signal'++function rateLimited(): APICallError {+ return new APICallError({+ message: 'Rate limit reached',+ url: 'https://api.openai.com/v1/chat/completions',+ requestBodyValues: {},+ statusCode: 429,+ responseBody: '{"error":"rate_limit"}',+ isRetryable: true,+ })+}++describe('aiProviderSignal.fromError', () => {+ it('reads the provider status out of a retry error', () => {+ const error = new RetryError({ message: 'Failed after 2 attempts', reason: 'maxRetriesExceeded', errors: [rateLimited(), rateLimited()] })+ expect(aiProviderSignal.fromError(error)).toEqual({+ statusCode: 429,+ body: '{"error":"rate_limit"}',+ message: 'Rate limit reached',+ retryable: true,+ fromProvider: true,+ })+ })++ it('looks through a wrapping error to the provider failure', () => {+ const error = new Error('Failed to extract structured data: rate limited', { cause: rateLimited() })+ expect(aiProviderSignal.fromError(error)).toMatchObject({ statusCode: 429, fromProvider: true })+ })++ it('keeps a network failure retryable even without a status', () => {+ const error = new APICallError({+ message: 'Cannot connect to API: connect ECONNREFUSED 10.0.0.1:443',+ url: 'https://llm.internal/v1',+ requestBodyValues: {},+ isRetryable: true,+ })+ expect(aiProviderSignal.fromError(error)).toMatchObject({ retryable: true, fromProvider: true })+ expect(aiProviderSignal.fromError(error).statusCode).toBeUndefined()+ })++ it('marks our own errors as not coming from the provider', () => {+ expect(aiProviderSignal.fromError(new Error('Unable to classify the text into the provided categories.'))).toMatchObject({ fromProvider: false })+ })+})diff --git a/packages/server/worker/src/lib/execute/jobs/ai/execute-ai.ts b/packages/server/worker/src/lib/execute/jobs/ai/execute-ai.tsindex 9422cc58859..bc3dca3df66 100644--- a/packages/server/worker/src/lib/execute/jobs/ai/execute-ai.ts+++ b/packages/server/worker/src/lib/execute/jobs/ai/execute-ai.ts@@ -7,6 +7,7 @@ import { resolveAiFiles } from './ai-files'import { extractStructuredData } from './extract-structured-data'import { generateImageStep } from './generate-image'import { routeStep } from './route'+import { CandidateRun, runWithFallback } from './run-with-fallback'export const executeAiJob: JobHandler<ExecuteAiJobData, JobResult> = {jobType: WorkerJobType.EXECUTE_AI,@@ -52,38 +53,75 @@ async function waitBeforeRetry(attempt: number): Promise<void> {}async function callTheModel({ ctx, data }: { ctx: JobContext, data: ExecuteAiJobData }): Promise<unknown> {- const resolved = await ctx.apiClient.resolveAiProvider({- projectId: data.projectId,- platformId: data.platformId,- provider: data.provider,- ...spreadIfDefined('providerConfigId', data.providerConfigId),- })const flowStep = flowStepMetadata(data)const billing = billingFor(data)switch (data.action) {- case AiStepAction.EXTRACT_STRUCTURED_DATA:- return { answer: await extractStructuredData({ data, resolved, flowStep, billing, files: await resolveAiFiles({ ctx, data }) }) }+ case AiStepAction.EXTRACT_STRUCTURED_DATA: {+ const files = await resolveAiFiles({ ctx, data })+ return { answer: await withModel({ ctx, data, attempt: ({ candidate, maxRetries }) => extractStructuredData({ data, resolved: candidate, modelId: candidate.modelId, flowStep, billing, files, maxRetries }) }) }+ }case AiStepAction.GENERATE_IMAGE:- return { answer: await generateImageStep({ ctx, data, resolved, flowStep, billing, inputImages: await resolveAiFiles({ ctx, data }) }) }+ return { answer: await generateImageStep({ ctx, data, resolved: await resolveSpecificModel({ ctx, data }), flowStep, billing, inputImages: await resolveAiFiles({ ctx, data }) }) }case AiStepAction.ROUTE:- return routeStep({ data, resolved, billing })+ return routeStep({ data, resolved: await resolveSpecificModel({ ctx, data }), billing })case AiStepAction.ASK_AI:case AiStepAction.SUMMARIZE_TEXT:case AiStepAction.CLASSIFY_TEXT:- return runTextStep({ data, resolved, flowStep, billing })+ return withModel({ ctx, data, attempt: ({ candidate, maxRetries, onStepFinish }) => runTextStep({ data, resolved: candidate, modelId: candidate.modelId, flowStep, billing, maxRetries, onStepFinish }) })}}-async function runTextStep({ data, resolved, flowStep, billing }: { data: ExecuteAiJobData, resolved: ResolveAiProviderResponse, flowStep: FlowStepMetadata, billing: ActivepiecesAiBilling }): Promise<unknown> {+async function withModel<T>({ ctx, data, attempt }: { ctx: JobContext, data: ExecuteAiJobData, attempt: (run: CandidateRun) => Promise<T> }): Promise<T> {+ if (isNil(data.modelTierId)) {+ const resolved = await resolveSpecificModel({ ctx, data })+ return attempt({ candidate: { ...resolved, modelId: data.modelId, status: 'active' }, maxRetries: undefined, onStepFinish: () => undefined })+ }+ const { tierName, candidates } = await ctx.apiClient.resolveAiModelCandidates({+ projectId: data.projectId,+ platformId: data.platformId,+ modelTierId: data.modelTierId,+ })+ return runWithFallback({+ candidates,+ tierName,+ log: ctx.log,+ attempt,+ report: async ({ candidate, signal }) => {+ const { error } = await tryCatch(() => ctx.apiClient.reportAiKeyOutcome({ platformId: data.platformId, providerConfigId: candidate.providerConfigId, signal }))+ if (!isNil(error)) {+ ctx.log.warn({ error, aiProvider: { id: candidate.providerConfigId } }, '[executeAiJob] Could not report the key outcome')+ }+ },+ })+}++async function resolveSpecificModel({ ctx, data }: { ctx: JobContext, data: ExecuteAiJobData }): Promise<ResolveAiProviderResponse> {+ return ctx.apiClient.resolveAiProvider({+ projectId: data.projectId,+ platformId: data.platformId,+ provider: data.provider,+ ...spreadIfDefined('providerConfigId', data.providerConfigId),+ })+}++async function runTextStep({ data, resolved, modelId, flowStep, billing, maxRetries, onStepFinish }: {+ data: ExecuteAiJobData+ resolved: ResolveAiProviderResponse+ modelId: string+ flowStep: FlowStepMetadata+ billing: ActivepiecesAiBilling+ maxRetries: number | undefined+ onStepFinish: () => void+}): Promise<unknown> {const credentials = resolvedconst { provider } = credentialsconst webSearchEnabled = data.webSearch?.enabled ?? falseconst webSearchOptions = data.webSearch?.options- const { provider: effectiveProvider } = getEffectiveProviderAndModel({ provider, model: data.modelId })- const tools = aiUtils.buildWebSearchToolsOrThrow({ provider, model: data.modelId, webSearchEnabled, options: webSearchOptions })+ const { provider: effectiveProvider } = getEffectiveProviderAndModel({ provider, model: modelId })+ const tools = aiUtils.buildWebSearchToolsOrThrow({ provider, model: modelId, webSearchEnabled, options: webSearchOptions })const model = aiUtils.createModel({credentials,- modelId: data.modelId,+ modelId,flowStep,billing,openaiResponsesModel: webSearchEnabled && (effectiveProvider ?? provider) === AIProviderName.OPENAI,@@ -95,6 +133,8 @@ async function runTextStep({ data, resolved, flowStep, billing }: { data: Executmodel,messages: buildMessages(data),tools,+ onStepFinish,+ ...spreadIfDefined('maxRetries', maxRetries),...spreadIfDefined('maxOutputTokens', data.maxOutputTokens),...spreadIfDefined('temperature', data.temperature),...spreadIfDefined('providerOptions', reasoningEffortFor({ action: data.action, provider })),diff --git a/packages/server/worker/src/lib/execute/jobs/ai/extract-structured-data.ts b/packages/server/worker/src/lib/execute/jobs/ai/extract-structured-data.tsindex 56537cc43ac..2cd4de7c88b 100644--- a/packages/server/worker/src/lib/execute/jobs/ai/extract-structured-data.ts+++ b/packages/server/worker/src/lib/execute/jobs/ai/extract-structured-data.ts@@ -4,16 +4,18 @@ import { ExtractStructuredDataJobData, ResolveAiProviderResponse } from '@activeimport { generateText, jsonSchema, ModelMessage, tool, UserModelMessage } from 'ai'import { ResolvedAiFile } from './ai-files'-export async function extractStructuredData({ data, resolved, flowStep, billing, files }: {+export async function extractStructuredData({ data, resolved, modelId, flowStep, billing, files, maxRetries }: {data: ExtractStructuredDataJobDataresolved: ResolveAiProviderResponse+ modelId: string+ maxRetries?: numberflowStep: FlowStepMetadatabilling: ActivepiecesAiBillingfiles: ResolvedAiFile[]}): Promise<unknown> {const model = aiUtils.createModel({credentials: resolved,- modelId: data.modelId,+ modelId,flowStep,billing,})@@ -27,6 +29,7 @@ export async function extractStructuredData({ data, resolved, flowStep, billing,try {const result = await generateText({model,+ ...spreadIfDefined('maxRetries', maxRetries),...spreadIfDefined('maxOutputTokens', data.maxOutputTokens),tools: { extractData: extractionTool },toolChoice: 'required',@@ -39,7 +42,7 @@ export async function extractStructuredData({ data, resolved, flowStep, billing,return restoreFieldNames({ extracted: toolCalls[0].input, sanitizedNameMap })}catch (error) {- throw new Error(`Failed to extract structured data: ${error instanceof Error ? error.message : 'Unknown error'}`)+ throw new Error(`Failed to extract structured data: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error })}}diff --git a/packages/server/worker/src/lib/execute/jobs/ai/run-with-fallback.ts b/packages/server/worker/src/lib/execute/jobs/ai/run-with-fallback.tsnew file mode 100644index 00000000000..b9785eb3656--- /dev/null+++ b/packages/server/worker/src/lib/execute/jobs/ai/run-with-fallback.ts@@ -0,0 +1,66 @@+import { isFallbackWorthy, ProviderOutcomeSignal } from '@activepieces/core-utils'+import { aiProviderSignal, ApLogger } from '@activepieces/server-utils'+import { AiModelCandidate } from '@activepieces/shared'++export async function runWithFallback<T>({ candidates, tierName, log, report, attempt }: {+ candidates: AiModelCandidate[]+ tierName: string+ log: ApLogger+ report: (outcome: { candidate: AiModelCandidate, signal: ProviderOutcomeSignal }) => Promise<void>+ attempt: (run: CandidateRun) => Promise<T>+}): Promise<T> {+ let lastError: unknown+ for (const [index, candidate] of candidates.entries()) {+ const isLast = index === candidates.length - 1+ let stepFinished = false+ const outcome = await settle(() => attempt({+ candidate,+ maxRetries: isLast ? undefined : RETRIES_BEFORE_FALLBACK,+ onStepFinish: () => {+ stepFinished = true+ },+ }))+ if (outcome.ok) {+ if (candidate.status !== 'active') {+ await report({ candidate, signal: { statusCode: 200 } })+ }+ if (index > 0) {+ log.info({ platformTier: { name: tierName }, candidateIndex: index, model: { id: candidate.modelId } }, '[runWithFallback] A fallback model answered')+ }+ return outcome.value+ }+ const error = outcome.error+ lastError = error+ const signal = aiProviderSignal.fromError(error)+ if (signal.fromProvider === true) {+ await report({ candidate, signal })+ }+ if (stepFinished || !isFallbackWorthy(signal) || candidates.length === 1) {+ throw error+ }+ if (!isLast) {+ log.warn({ platformTier: { name: tierName }, candidateIndex: index, model: { id: candidate.modelId }, statusCode: signal.statusCode }, '[runWithFallback] Model failed, trying the next one in the tier')+ }+ }+ const modelIds = candidates.map((candidate) => candidate.modelId).join(', ')+ throw new Error(`All ${candidates.length} models in tier ${tierName} failed (${modelIds}). Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`)+}++async function settle<T>(run: () => Promise<T>): Promise<Settled<T>> {+ try {+ return { ok: true, value: await run() }+ }+ catch (error) {+ return { ok: false, error }+ }+}++const RETRIES_BEFORE_FALLBACK = 1++type Settled<T> = { ok: true, value: T } | { ok: false, error: unknown }++export type CandidateRun = {+ candidate: AiModelCandidate+ maxRetries: number | undefined+ onStepFinish: () => void+}diff --git a/packages/server/worker/test/lib/execute/jobs/ai/flow-step-routing.test.ts b/packages/server/worker/test/lib/execute/jobs/ai/flow-step-routing.test.tsindex 58604370526..b4120f53949 100644--- a/packages/server/worker/test/lib/execute/jobs/ai/flow-step-routing.test.ts+++ b/packages/server/worker/test/lib/execute/jobs/ai/flow-step-routing.test.ts@@ -71,6 +71,7 @@ describe('flowStep reaches every model built on the worker', () => {schema: { mode: 'simple', fields: [{ name: 'total', type: 'number', isRequired: true }] },}),resolved: RESOLVED,+ modelId: 'mistral-large-latest',flowStep: FLOW_STEP,files: [],})diff --git a/packages/server/worker/test/lib/execute/jobs/ai/tier-fallback.test.ts b/packages/server/worker/test/lib/execute/jobs/ai/tier-fallback.test.tsnew file mode 100644index 00000000000..de99059dc93--- /dev/null+++ b/packages/server/worker/test/lib/execute/jobs/ai/tier-fallback.test.ts@@ -0,0 +1,153 @@+import { AIProviderName } from '@activepieces/core-utils'+import { AiModelCandidate, AiStepAction, ExecuteAiJobData, ReportAiKeyOutcomeRequest } from '@activepieces/shared'+import { APICallError } from 'ai'+import { beforeEach, describe, expect, it, vi } from 'vitest'++const generateCalls: { modelId: string, maxRetries: number | undefined }[] = []+const failuresByModel = new Map<string, () => unknown>()++vi.mock('@activepieces/server-utils', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ aiUtils: {+ createModel: (args: Record<string, unknown>) => ({ modelId: args['modelId'] }),+ buildWebSearchToolsOrThrow: () => ({}),+ },+}))++vi.mock('ai', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ generateText: async ({ model, maxRetries, onStepFinish }: { model: { modelId: string }, maxRetries?: number, onStepFinish?: () => void }) => {+ generateCalls.push({ modelId: model.modelId, maxRetries })+ const failure = failuresByModel.get(model.modelId)+ if (failure !== undefined) {+ const thrown = failure()+ if (thrown === STEP_THEN_FAIL) {+ onStepFinish?.()+ throw providerError(429)+ }+ throw thrown+ }+ return { text: 'positive', toolCalls: [{ input: { total: 42 } }], response: { body: {} } }+ },+}))++const { executeAiJob } = await import('../../../../../src/lib/execute/jobs/ai/execute-ai')++const STEP_THEN_FAIL = Symbol('step-then-fail')++function providerError(statusCode: number, responseBody = '{"error":"x"}'): APICallError {+ return new APICallError({ message: `HTTP ${statusCode}`, url: 'https://llm.example/v1', requestBodyValues: {}, statusCode, responseBody, isRetryable: statusCode >= 429 })+}++function candidate(modelId: string, status: AiModelCandidate['status'] = 'active'): AiModelCandidate {+ return { provider: AIProviderName.OPENAI, providerConfigId: `key-${modelId}`, auth: { apiKey: 'k' }, config: {}, modelId, status }+}++function tierJob(overrides: Partial<ExecuteAiJobData> = {}): ExecuteAiJobData {+ return {+ requestId: 'request-1',+ projectId: 'project-1',+ platformId: 'platform-1',+ flowId: 'flow-1',+ flowRunId: 'run-1',+ action: AiStepAction.CLASSIFY_TEXT,+ text: 'great product',+ categories: ['positive', 'negative'],+ provider: AIProviderName.OPENAI,+ modelId: 'main',+ modelTierId: 'tier-1',+ ...overrides,+ } as ExecuteAiJobData+}++function contextWith(candidates: AiModelCandidate[]): { ctx: Parameters<typeof executeAiJob.execute>[0], reports: ReportAiKeyOutcomeRequest[] } {+ const reports: ReportAiKeyOutcomeRequest[] = []+ const ctx = {+ apiClient: {+ resolveAiModelCandidates: async () => ({ tierName: 'Expert', candidates }),+ reportAiKeyOutcome: async (input: ReportAiKeyOutcomeRequest) => {+ reports.push(input)+ },+ resolveAiProvider: async () => {+ throw new Error('a tier step must not resolve a specific key')+ },+ },+ log: { info: () => undefined, warn: () => undefined, error: () => undefined },+ } as unknown as Parameters<typeof executeAiJob.execute>[0]+ return { ctx, reports }+}++async function run(candidates: AiModelCandidate[], overrides: Partial<ExecuteAiJobData> = {}): Promise<{ response: unknown, reports: ReportAiKeyOutcomeRequest[] }> {+ const { ctx, reports } = contextWith(candidates)+ const result = await executeAiJob.execute(ctx, tierJob(overrides))+ return { response: 'response' in result ? result.response : undefined, reports }+}++describe('a tier step falls back on provider failures', () => {+ beforeEach(() => {+ generateCalls.length = 0+ failuresByModel.clear()+ })++ it('answers from the next model when the main one is rate limited', async () => {+ failuresByModel.set('main', () => providerError(429))+ const { response, reports } = await run([candidate('main'), candidate('backup')])++ expect(response).toEqual({ output: { answer: 'positive' } })+ expect(generateCalls).toEqual([{ modelId: 'main', maxRetries: 1 }, { modelId: 'backup', maxRetries: undefined }])+ expect(reports).toEqual([expect.objectContaining({ providerConfigId: 'key-main', signal: expect.objectContaining({ statusCode: 429 }) })])+ })++ it('stops on a bad request, since every model would get the same one', async () => {+ failuresByModel.set('main', () => providerError(400))+ const { response } = await run([candidate('main'), candidate('backup')])++ expect(response).toEqual({ failure: 'HTTP 400' })+ expect(generateCalls.map((call) => call.modelId)).toEqual(['main'])+ })++ it('stops on its own errors and never reports them against the key', async () => {+ failuresByModel.set('main', () => new Error('Unable to classify the text into the provided categories.'))+ const { response, reports } = await run([candidate('main'), candidate('backup')])++ expect(response).toEqual({ failure: 'Unable to classify the text into the provided categories.' })+ expect(generateCalls.map((call) => call.modelId)).toEqual(['main'])+ expect(reports).toEqual([])+ })++ it('names the tier and every model when all of them fail, never the keys', async () => {+ failuresByModel.set('main', () => providerError(503))+ failuresByModel.set('backup', () => providerError(429))+ const { response } = await run([candidate('main'), candidate('backup')])++ expect(response).toEqual({ failure: 'All 2 models in tier Expert failed (main, backup). Last error: HTTP 429' })+ })++ it('does not fall back once a web search step already ran', async () => {+ failuresByModel.set('main', () => STEP_THEN_FAIL)+ const { response } = await run([candidate('main'), candidate('backup')], { action: AiStepAction.ASK_AI, prompt: 'news?' })++ expect(response).toEqual({ failure: 'HTTP 429' })+ expect(generateCalls.map((call) => call.modelId)).toEqual(['main'])+ })++ it('reports a success only for a key that was not healthy', async () => {+ const { reports } = await run([candidate('main', 'unreachable'), candidate('backup')])+ expect(reports).toEqual([{ platformId: 'platform-1', providerConfigId: 'key-main', signal: { statusCode: 200 } }])++ const healthy = await run([candidate('main')])+ expect(healthy.reports).toEqual([])+ })++ it('keeps the provider status through the extract wrapper', async () => {+ failuresByModel.set('main', () => providerError(503))+ const { response } = await run([candidate('main'), candidate('backup')], {+ action: AiStepAction.EXTRACT_STRUCTURED_DATA,+ text: 'total 42',+ schema: { mode: 'simple', fields: [{ name: 'total', type: 'number', isRequired: true }] },+ })++ expect(response).toEqual({ output: { answer: { total: 42 } } })+ expect(generateCalls.map((call) => call.modelId)).toEqual(['main', 'backup'])+ })+})