Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"deploy:staging": "wrangler deploy --env staging"
},
"dependencies": {
"@ai-sdk/openai-compatible": "2.0.87",
"@aws-sdk/client-s3": "catalog:",
"@aws-sdk/s3-request-presigner": "catalog:",
"@cloudflare/containers": "0.3.7",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
* locking, or handle captured async prerequisites; they are given inputs and
* return outputs.
*/
import type { Env } from '../../env';
import { expectJsonRecord } from '../../lib/runtime-validation';
import type { OpenAIMessage } from './payload-size';
import type { AnthropicToolDef, CollectedToolCall, MessageRow, SamSseEvent } from './types';
Expand Down Expand Up @@ -219,10 +218,4 @@ export function toOpenAIMessages(rows: MessageRow[]): OpenAIMessage[] {
return messages;
}

export function buildAnthropicGatewayUrl(env: Env): string {
const gatewayId = env.AI_GATEWAY_ID;
if (gatewayId) {
return `https://gateway.ai.cloudflare.com/v1/${env.CF_ACCOUNT_ID}/${gatewayId}/anthropic/v1/messages`;
}
return 'https://api.anthropic.com/v1/messages';
}
export { buildAnthropicGatewayUrl } from '../../services/ai-proxy-shared';
56 changes: 34 additions & 22 deletions apps/api/src/durable-objects/sam-session/agent-loop-llm.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
/**
* The model call for one agent-loop turn, split out of agent-loop.ts (rule 18).
*
* Route by model prefix: claude-* to Anthropic (translated at the boundary), @cf/* and @hf/* to
* Workers AI, both through AI Gateway.
* Route order: an admin-configured OpenAI-compatible endpoint when one is set
* (services/llm-chat-target.ts), else by model prefix: claude-* to Anthropic (translated at the
* boundary), @cf/* and @hf/* to Workers AI through AI Gateway or the REST API.
*/
import { SAM_ANTHROPIC_VERSION, type SamConfig } from '@simple-agent-manager/shared';

import type { Env } from '../../env';
import { getCredentialEncryptionKey } from '../../lib/secrets';
import { buildWorkersAIGatewayUrl } from '../../services/ai-proxy-shared';
import {
type ChatCompletionsTarget,
chatTargetHeaders,
fetchChatTarget,
LlmUnavailableError,
resolveCloudflareWorkersAiTarget,
} from '../../services/llm-chat-target';
import { aiGatewayOnlyHeaders } from '../../services/platform-capabilities';
import { getPlatformAgentCredential } from '../../services/platform-credentials';
import {
buildAnthropicGatewayUrl,
Expand Down Expand Up @@ -43,7 +51,7 @@ export async function callLLM(
userId: string,
conversationId: string,
baseSystemPrompt: string,
tools: AnthropicToolDef[]
{ tools, endpoint }: { tools: AnthropicToolDef[]; endpoint: ChatCompletionsTarget | null }
): Promise<Response> {
const model = config.model;
const systemPrompt = config.systemPromptAppend
Expand All @@ -65,7 +73,17 @@ export async function callLLM(
const timer = setTimeout(() => controller.abort(), timeoutMs);

try {
if (isAnthropicModel(model)) {
if (endpoint) {
return await callOpenAIChatLLM(
endpoint,
systemPrompt,
messages,
openAITools,
aigMetadata,
config.maxTokens,
controller.signal
);
} else if (isAnthropicModel(model)) {
return await callAnthropicLLM(
env,
model,
Expand All @@ -78,9 +96,10 @@ export async function callLLM(
tools
);
} else if (isWorkersAIModel(model)) {
return await callWorkersAILLM(
env,
model,
const target = resolveCloudflareWorkersAiTarget(env, model);
if (!target) throw new LlmUnavailableError('agent');
return await callOpenAIChatLLM(
target,
systemPrompt,
messages,
openAITools,
Expand Down Expand Up @@ -150,7 +169,7 @@ async function callAnthropicLLM(
'x-api-key': apiKey,
'anthropic-version': SAM_ANTHROPIC_VERSION,
'content-type': 'application/json',
'cf-aig-metadata': aigMetadata,
...aiGatewayOnlyHeaders(env, { 'cf-aig-metadata': aigMetadata }),
},
body: JSON.stringify({
model,
Expand All @@ -163,31 +182,24 @@ async function callAnthropicLLM(
});
}

/** Call Workers AI via AI Gateway (OpenAI-compatible). */
async function callWorkersAILLM(
env: Env,
model: string,
/** Call an OpenAI-format chat completions target (Workers AI or an OpenAI-compatible endpoint). */
function callOpenAIChatLLM(
target: ChatCompletionsTarget,
systemPrompt: string,
messages: OpenAIMessage[],
openAITools: OpenAITool[],
aigMetadata: string,
maxTokens: number,
signal: AbortSignal
): Promise<Response> {
const url = buildWorkersAIGatewayUrl(env);

const fullMessages: OpenAIMessage[] = [{ role: 'system', content: systemPrompt }, ...messages];

return fetch(url, {
return fetchChatTarget(target, {
method: 'POST',
signal,
headers: {
Authorization: `Bearer ${env.CF_API_TOKEN}`,
'Content-Type': 'application/json',
'cf-aig-metadata': aigMetadata,
},
headers: chatTargetHeaders(target, { 'cf-aig-metadata': aigMetadata }),
body: JSON.stringify({
model,
model: target.model,
max_tokens: maxTokens,
messages: fullMessages,
tools: openAITools.length > 0 ? openAITools : undefined,
Expand Down
28 changes: 24 additions & 4 deletions apps/api/src/durable-objects/sam-session/agent-loop.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { estimateInputTokensFromMessages } from '@simple-agent-manager/ai-proxy';
/**
* Agent loop — unified OpenAI-format code path routed through AI Gateway.
*
Expand All @@ -21,6 +22,7 @@ import { log } from '../../lib/logger';
import { expectJsonRecord } from '../../lib/runtime-validation';
import { checkAiUsageGate } from '../../services/ai-token-budget';
import { attachTokenUsageAccounting } from '../../services/ai-token-usage-accounting';
import { LlmUnavailableError, resolveOpenAICompatibleTarget } from '../../services/llm-chat-target';
import {
encodeSseEvent,
isAnthropicModel,
Expand Down Expand Up @@ -58,7 +60,7 @@ export async function runAgentLoop(
conversationId: string,
historyRows: MessageRow[],
userMessage: string,
config: SamConfig,
baseConfig: SamConfig,
env: Env,
userId: string,
writer: WritableStreamDefaultWriter<Uint8Array>,
Expand All @@ -82,6 +84,16 @@ export async function runAgentLoop(
];

const systemPrompt = options?.systemPrompt ?? SAM_SYSTEM_PROMPT;
let endpoint;
try {
endpoint = await resolveOpenAICompatibleTarget(env, 'agent', baseConfig.model);
} catch (err) {
if (!(err instanceof LlmUnavailableError)) throw err;
await writer.write(encodeSseEvent({ type: 'error', message: err.message }));
await writer.write(encodeSseEvent({ type: 'done' }));
return;
}
const config = endpoint ? { ...baseConfig, model: endpoint.model } : baseConfig;
const tools = options?.tools ?? [];
const executeToolFn =
options?.executeTool ?? (async () => ({ error: 'No tool executor configured' }));
Expand All @@ -91,7 +103,7 @@ export async function runAgentLoop(
searchMessages,
...options?.toolContextExtras,
};
const useAnthropicParser = isAnthropicModel(config.model);
const useAnthropicParser = !endpoint && isAnthropicModel(config.model);
const tokenUsageFormat = useAnthropicParser ? ('anthropic' as const) : ('openai' as const);

// Workers AI models have smaller context windows, so use a tighter budget
Expand Down Expand Up @@ -146,12 +158,20 @@ export async function runAgentLoop(
userId,
conversationId,
systemPrompt,
tools
{ tools, endpoint }
);
response = await attachTokenUsageAccounting(response, {
env,
userId,
format: tokenUsageFormat,
estimateMissingUsage: endpoint !== null,
fallbackInputTokens: endpoint
? estimateInputTokensFromMessages([
{ role: 'system', content: systemPrompt },
...llmMessages,
])
: undefined,
costModelId: endpoint ? undefined : config.model,
executionCtx,
});
} catch (fetchErr) {
Expand Down Expand Up @@ -183,7 +203,7 @@ export async function runAgentLoop(
const errorText = await response.text().catch(() => 'Unknown error');
log.error('sam.llm_error', {
status: response.status,
body: errorText.slice(0, 500),
body: endpoint ? '[external endpoint body omitted]' : errorText.slice(0, 500),
model: config.model,
});
await writer.write(
Expand Down
9 changes: 7 additions & 2 deletions apps/api/src/durable-objects/sam-session/operator/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ export async function runOperatorAgent(options: {
metadata: JSON.stringify({ source: config.aigSource, userId, turnId: turn.id }),
sessionAffinity: `sam-${turn.conversation_id}`,
});
const customEndpoint =
typeof model === 'object' &&
model !== null &&
'provider' in model &&
String(model.provider).startsWith('sam-openai-compatible');
assertCurrent();
let toolAttempted = false;
let inferenceFailed = false;
Expand Down Expand Up @@ -128,7 +133,7 @@ export async function runOperatorAgent(options: {
maxSteps: config.maxTurns - startedSteps,
...(correcting ? { instructions: `${instructions}\n${GROUNDING_CORRECTION}` } : {}),
modelSettings: { maxOutputTokens: config.maxTokens, maxRetries: 0 },
providerOptions: operatorProviderOptions(config.model),
providerOptions: operatorProviderOptions(customEndpoint ? '' : config.model),
// Same scheduling as generate(): a tool starts after its step, behind prepareStep's gates.
eagerToolExecution: false,
onChunk: (chunk) => {
Expand Down Expand Up @@ -158,7 +163,7 @@ export async function runOperatorAgent(options: {
if (step.finishReason === 'error') inferenceFailed = true;
if (step.toolCalls.length > 0) toolAttempted = true;
live?.stepFinished(step.toolCalls.length > 0);
await recordOperatorStepUsage(env, userId, config, catalogModel, step);
await recordOperatorStepUsage(env, userId, config, catalogModel, step, customEndpoint);
},
});
const full = await output.getFullOutput();
Expand Down
Loading
Loading