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

fix(agents): agents on Bedrock work with non-Claude models like Amazon Nova (#15737)

Hazem Adel130286ce9e5c
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
index 22379ffb3bd..8327dd29d30 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
@@ -1,5 +1,5 @@
import { AIProviderName, ErrorCode, formatPieceError, isNil, isObject, isProviderBillingError, isTransientProviderError, spreadIfDefined, tryCatch, tryCatchSync } from '@activepieces/core-utils'
-import { agentAiUtils, ContentPartLike } from '@activepieces/server-utils'
+import { agentAiUtils, ContentPartLike, modelCatalog } from '@activepieces/server-utils'
import { AgentPhase, AgentRunSource, agentToolClassification, agentToolPhases, aiProviderUtils, apErrorOf, PersistedAgentPart } from '@activepieces/shared'
import { APICallError, generateText, isLoopFinished, isStepCount, LanguageModel, LanguageModelUsage, ModelMessage, NoSuchToolError, RetryError, StepResultPerformance, StopCondition, streamText, ToolExecutionOptions, ToolSet } from 'ai'
@@ -74,10 +74,12 @@ export async function runAgentTurn({ model, fastModel, provider, systemPrompt, m
let lastFinishReason = ''
let budgetExceeded = false
+ const maxOutputTokens = await affordableOutputTokens({ provider, modelIds: [modelId, fastModelId], thinkingBudget: tier.thinkingBudget })
+
const runStreamAttempt = (attemptMessages: ModelMessage[]): ReturnType<typeof streamText> => streamText({
model,
maxRetries: 3,
- maxOutputTokens: tier.thinkingBudget + MAX_RESPONSE_OUTPUT_TOKENS,
+ maxOutputTokens,
abortSignal,
instructions: agentAiUtils.buildSystemPromptWithCaching({ systemPrompt, provider }),
messages: agentAiUtils.stripThinkingBlocks(attemptMessages, provider),
@@ -385,6 +387,17 @@ export function looksEmptyResultText(text: string): boolean {
return /"found"\s*:\s*false|\bempty result\b|no results matched|"result"\s*:\s*\[\s*\]|"results"\s*:\s*\[\s*\]/i.test(text)
}
+export async function affordableOutputTokens({ provider, modelIds, thinkingBudget }: { provider: AIProviderName, modelIds: (string | undefined)[], thinkingBudget: number }): Promise<number> {
+ const catalog = await modelCatalog.load()
+ const ceilings = modelIds.map((modelId) => isNil(modelId) ? undefined : catalog.lookup({ provider, modelId })?.maxOutputTokens)
+ return clampOutputTokens({ thinkingBudget, ceilings })
+}
+
+export function clampOutputTokens({ thinkingBudget, ceilings }: { thinkingBudget: number, ceilings: (number | undefined)[] }): number {
+ const known = ceilings.filter((ceiling) => !isNil(ceiling))
+ return Math.min(thinkingBudget + MAX_RESPONSE_OUTPUT_TOKENS, ...known)
+}
+
function runawayTokenCeiling(provider: AIProviderName): number {
return aiProviderUtils.getMaxContextTokens({ provider }) * RUNAWAY_TURN_CONTEXT_MULTIPLE
}
diff --git a/packages/server/worker/src/lib/worker.ts b/packages/server/worker/src/lib/worker.ts
index 001030a3d51..ae2cf31557d 100644
--- a/packages/server/worker/src/lib/worker.ts
+++ b/packages/server/worker/src/lib/worker.ts
@@ -2,7 +2,7 @@ import { createServer } from 'http'
import os from 'os'
import { ActivepiecesError, isNil, spreadIfDefined, tryCatch, tryCatchSync } from '@activepieces/core-utils'
import { ACTION_RUN_CACHE_ACTIVE_WINDOW_MS, ACTION_RUN_CACHE_FIRST_SWEEP_DELAY_MS, ACTION_RUN_CACHE_SWEEP_INTERVAL_MS, actionRunCache, cacheUtils, createResolver, createSandboxRuntime, Runtime } from '@activepieces/sandbox'
-import { aiCostReporter, createLogger, systemUsage, wideEvent } from '@activepieces/server-utils'
+import { aiCostReporter, createLogger, modelCatalog, systemUsage, wideEvent } from '@activepieces/server-utils'
import { ApEdition, ApiToWorkerContract, ConsumeJobRequest, createNotifyServer, createRpcClient, EngineResponseStatus, ExecutionMode, JobData, LONG_RUNNING_RPC_METHODS, SandboxInformation, WebsocketServerEvent, WorkerJobType, WorkerMachineHealthcheckRequest, WorkerProps, WorkerSettingsResponse, WorkerToApiContract } from '@activepieces/shared'
import { nanoid } from 'nanoid'
import { io, Socket } from 'socket.io-client'
@@ -61,6 +61,7 @@ let cacheSweepFirstRunTimeout: NodeJS.Timeout | null = null
export const worker = {
async start({ apiUrl, socketUrl, workerToken, withHealthServer = false }: WorkerStartParams): Promise<void> {
versionChecker.assertReleaseReadable()
+ modelCatalog.load().catch(() => undefined)
const workerGroupId = system.get(WorkerSystemProp.WORKER_GROUP_ID)
const projectWorker = system.getBoolean(WorkerSystemProp.PROJECT_WORKER) ?? true
socket = io(socketUrl.url, {
diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/output-token-ceiling.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/output-token-ceiling.test.ts
new file mode 100644
index 00000000000..110d145c881
--- /dev/null
+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/output-token-ceiling.test.ts
@@ -0,0 +1,63 @@
+import { AIProviderName } from '@activepieces/core-utils'
+import { describe, expect, it, vi } from 'vitest'
+
+const { mockLoad } = vi.hoisted(() => ({ mockLoad: vi.fn() }))
+
+vi.mock('@activepieces/server-utils', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ modelCatalog: { load: mockLoad },
+}))
+
+const { affordableOutputTokens } = await import('../../../../../../src/lib/execute/jobs/ee/agent/run-agent-turn')
+
+const catalogOf = (byId: Record<string, number>) => ({
+ lookup: ({ modelId }: { modelId: string }) => {
+ const stripped = modelId.replace(/^(us|eu|apac|global)\./, '')
+ const maxOutputTokens = byId[stripped]
+ return maxOutputTokens === undefined ? undefined : { maxOutputTokens }
+ },
+})
+
+describe('affordableOutputTokens', () => {
+ const SMART_TIER_THINKING = 10_000
+
+ it('reads through a region-prefixed Bedrock id, which is how the picker spells them', async () => {
+ mockLoad.mockResolvedValue(catalogOf({ 'amazon.nova-pro-v1:0': 10_000 }))
+
+ await expect(affordableOutputTokens({
+ provider: AIProviderName.BEDROCK,
+ modelIds: ['eu.amazon.nova-pro-v1:0'],
+ thinkingBudget: SMART_TIER_THINKING,
+ })).resolves.toBe(10_000)
+ })
+
+ it('keeps the turn inside the smaller ceiling when the fast round runs a different model', async () => {
+ mockLoad.mockResolvedValue(catalogOf({ 'amazon.nova-pro-v1:0': 10_000, 'amazon.nova-micro-v1:0': 5_000 }))
+
+ await expect(affordableOutputTokens({
+ provider: AIProviderName.BEDROCK,
+ modelIds: ['eu.amazon.nova-pro-v1:0', 'eu.amazon.nova-micro-v1:0'],
+ thinkingBudget: SMART_TIER_THINKING,
+ })).resolves.toBe(5_000)
+ })
+
+ it('leaves the budget alone for a model the catalog has never heard of', async () => {
+ mockLoad.mockResolvedValue(catalogOf({}))
+
+ await expect(affordableOutputTokens({
+ provider: AIProviderName.BEDROCK,
+ modelIds: ['eu.some.brand-new-model-v9:0'],
+ thinkingBudget: SMART_TIER_THINKING,
+ })).resolves.toBe(42_000)
+ })
+
+ it('does not shrink a turn because the catalog was unreachable', async () => {
+ mockLoad.mockResolvedValue({ lookup: () => undefined })
+
+ await expect(affordableOutputTokens({
+ provider: AIProviderName.BEDROCK,
+ modelIds: ['eu.amazon.nova-pro-v1:0', undefined],
+ thinkingBudget: SMART_TIER_THINKING,
+ })).resolves.toBe(42_000)
+ })
+})
diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-guards.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-guards.test.ts
index 287dff8c87e..0b439cf03cd 100644
--- a/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-guards.test.ts
+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-guards.test.ts
@@ -3,7 +3,7 @@ import { AgentRunSource } from '@activepieces/shared'
import { APICallError, RetryError } from 'ai'
import { describe, expect, it } from 'vitest'
-import { classifyAgentRunError, firstStepUsesFastModel, isTransientFailureText, jsonInputFrom, looksEmptyResultText } from '../../../../../../src/lib/execute/jobs/ee/agent/run-agent-turn'
+import { clampOutputTokens, classifyAgentRunError, firstStepUsesFastModel, isTransientFailureText, jsonInputFrom, looksEmptyResultText } from '../../../../../../src/lib/execute/jobs/ee/agent/run-agent-turn'
function apiError({ statusCode, message, responseBody }: { statusCode: number, message: string, responseBody?: string }): APICallError {
return new APICallError({ message, url: 'https://provider.test/v1/chat', requestBodyValues: {}, statusCode, responseBody })
@@ -202,3 +202,23 @@ describe('jsonInputFrom', () => {
}
})
})
+
+describe('clampOutputTokens', () => {
+ const SMART_TIER_THINKING = 10_000
+
+ it('asks for the full budget when no model declares a ceiling', () => {
+ expect(clampOutputTokens({ thinkingBudget: SMART_TIER_THINKING, ceilings: [undefined, undefined] })).toBe(42_000)
+ })
+
+ it('never asks a model for more than it accepts', () => {
+ expect(clampOutputTokens({ thinkingBudget: SMART_TIER_THINKING, ceilings: [10_000] })).toBe(10_000)
+ })
+
+ it('respects the smaller ceiling when the turn spans two models', () => {
+ expect(clampOutputTokens({ thinkingBudget: SMART_TIER_THINKING, ceilings: [64_000, 8_192] })).toBe(8_192)
+ })
+
+ it('leaves a generous ceiling alone rather than raising the ask to meet it', () => {
+ expect(clampOutputTokens({ thinkingBudget: SMART_TIER_THINKING, ceilings: [200_000] })).toBe(42_000)
+ })
+})