import Anthropic from '@anthropic-ai/sdk'; import { AgentCompletion, completePrompt, PromptCompletionArgs, RequestError, isMultimodalContent, ToolHandler } from './types'; export interface AnthropicArgs { apiKey: string; model: string; baseURL?: string; temperature?: number; maxRetries?: number; } /** * Build the messages array and system content for an Anthropic API request. * Pure function — no SDK dependency. */ export function buildAnthropicRequest(args: PromptCompletionArgs, defaultTemp: number): { messages: { role: string; content: string | Anthropic.ContentBlockParam[] }[]; system: string | Anthropic.TextBlockParam[] | undefined; temperature: number; outputConfig?: Anthropic.OutputConfig; tools?: Anthropic.Tool[]; } { const reqTemp = args.temperature ?? defaultTemp; const messages: { role: string; content: string | Anthropic.ContentBlockParam[] }[] = []; if (args.history) { for (const msg of args.history) { messages.push({ role: msg.role, content: msg.content }); } } // Build user content — multimodal when ContentBlock[] is provided const promptContent = args.prompt.content; let userContent: string | Anthropic.ContentBlockParam[]; if (isMultimodalContent(promptContent)) { userContent = promptContent.map(block => { if (block.type === 'text') { return { type: 'text' as const, text: block.text }; } return { type: 'image' as const, source: { type: 'base64' as const, media_type: block.mediaType as 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp', data: block.data }, }; }); } else { userContent = promptContent; } // Claude 4.6+ rejects assistant-message prefill ("This model does not support // assistant message prefill. The conversation must end with a user message."). // The chainOfThought parser already extracts JSON via indexOf('{')/lastIndexOf('}'), // and the system prompt instructs the model to emit JSON, so no prefill is needed. messages.push({ role: 'user', content: userContent }); let system = args.system?.content; if (args.jsonSchema) { const schemaInstruction = `\n\nYou must return valid JSON conforming to this schema:\n${JSON.stringify(args.jsonSchema)}`; system = system ? system + schemaInstruction : schemaInstruction; } // Wrap system content with cache_control for prompt caching const finalSystem: string | Anthropic.TextBlockParam[] | undefined = (system && args.cacheSystem) ? [{ type: 'text' as const, text: system, cache_control: { type: 'ephemeral' as const } }] : system; // Structured output config for constrained decoding const outputConfig: Anthropic.OutputConfig | undefined = args.outputSchema ? { format: { type: 'json_schema', schema: args.outputSchema } } : undefined; // Tool definitions const tools: Anthropic.Tool[] | undefined = args.tools && args.tools.length > 0 ? args.tools.map(t => ({ name: t.name, description: t.description, input_schema: t.input_schema as Anthropic.Tool.InputSchema, })) : undefined; return { messages, system: finalSystem, temperature: reqTemp, outputConfig, tools }; } interface PendingToolUse { id: string; name: string; partialJson: string; } /** * Stream a single Anthropic request, accumulating text deltas and any tool_use * blocks the model emits. Returns both the text buffer and the tool_use blocks * (if any) so the caller can decide whether to loop on tool results. */ async function streamOnce( client: Anthropic, params: Anthropic.MessageCreateParamsStreaming ): Promise<{ text: string; toolUses: PendingToolUse[]; stopReason: Anthropic.StopReason | null }> { const stream = await client.messages.create(params); // Track content blocks by stream index. Tool_use blocks get their partial_json // routed to their own buffer; text + structured-output input_json_deltas go to text. const textByIndex = new Map(); const toolByIndex = new Map(); let stopReason: Anthropic.StopReason | null = null; for await (const event of stream) { if (event.type === 'content_block_start') { const block = event.content_block; if (block.type === 'tool_use') { toolByIndex.set(event.index, { id: block.id, name: block.name, partialJson: '' }); } else if (block.type === 'text') { textByIndex.set(event.index, ''); } } else if (event.type === 'content_block_delta') { if (event.delta.type === 'text_delta') { textByIndex.set(event.index, (textByIndex.get(event.index) ?? '') + event.delta.text); } else if (event.delta.type === 'input_json_delta') { const tool = toolByIndex.get(event.index); if (tool) { tool.partialJson += event.delta.partial_json; } else { // Structured output streams JSON as input_json_delta into a text block — // accumulate into the text buffer so parseBuilderResponse sees the JSON. textByIndex.set(event.index, (textByIndex.get(event.index) ?? '') + event.delta.partial_json); } } } else if (event.type === 'message_delta') { if (event.delta.stop_reason) stopReason = event.delta.stop_reason; } } const text = Array.from(textByIndex.entries()) .sort(([a], [b]) => a - b) .map(([, v]) => v) .join(''); const toolUses = Array.from(toolByIndex.values()); return { text, toolUses, stopReason }; } export function anthropic(args: AnthropicArgs): completePrompt { const { apiKey, model, baseURL, temperature = 0.0, maxRetries } = args; const client = new Anthropic({ apiKey, baseURL, maxRetries }); return async (completionArgs: PromptCompletionArgs): Promise> => { const { messages, system: systemContent, temperature: reqTemp, outputConfig, tools } = buildAnthropicRequest(completionArgs, temperature); const hasTools = !!(tools && tools.length > 0); const maxIterations = completionArgs.maxToolIterations ?? 3; const toolHandlers = completionArgs.toolHandlers ?? {}; try { // Mutable copy of messages — extended each tool-use iteration. const turnMessages: Anthropic.MessageParam[] = messages as Anthropic.MessageParam[]; let lastText = ''; for (let iteration = 0; iteration < maxIterations; iteration++) { const params: Anthropic.MessageCreateParamsStreaming = { model, max_tokens: 32768, temperature: reqTemp, system: systemContent, messages: turnMessages, stream: true, ...(outputConfig && { output_config: outputConfig }), ...(hasTools && { tools }), }; const { text, toolUses, stopReason } = await streamOnce(client, params); lastText = text; // Terminal turn: no tool_use blocks OR model stopped for a non-tool reason. if (!hasTools || toolUses.length === 0 || stopReason !== 'tool_use') { return { completed: true, value: lastText }; } // Tool-use turn: notify, execute handlers in parallel, append results, loop. if (completionArgs.onToolCall) { completionArgs.onToolCall(toolUses.map(t => t.name)); } const toolResults: Anthropic.ToolResultBlockParam[] = await Promise.all( toolUses.map(async (t): Promise => { const handler: ToolHandler | undefined = toolHandlers[t.name]; if (!handler) { return { type: 'tool_result', tool_use_id: t.id, content: `Error: no handler registered for tool "${t.name}"`, is_error: true }; } let input: Record = {}; try { if (t.partialJson.trim()) input = JSON.parse(t.partialJson); } catch (err) { return { type: 'tool_result', tool_use_id: t.id, content: `Error parsing tool input: ${(err as Error).message}`, is_error: true }; } try { const output = await handler(input); return { type: 'tool_result', tool_use_id: t.id, content: output }; } catch (err) { return { type: 'tool_result', tool_use_id: t.id, content: `Error: ${(err as Error).message}`, is_error: true }; } }) ); // Append the assistant's tool_use turn and our tool_result reply. const assistantBlocks: Anthropic.ContentBlockParam[] = []; if (text.trim()) assistantBlocks.push({ type: 'text', text }); for (const t of toolUses) { let parsedInput: unknown = {}; try { if (t.partialJson.trim()) parsedInput = JSON.parse(t.partialJson); } catch { /* empty input */ } assistantBlocks.push({ type: 'tool_use', id: t.id, name: t.name, input: parsedInput }); } turnMessages.push({ role: 'assistant', content: assistantBlocks }); turnMessages.push({ role: 'user', content: toolResults }); } // Iteration budget exhausted. return { completed: false, error: new Error(`Tool-use loop exceeded ${maxIterations} iterations`) }; } catch (err: unknown) { let error: Error; if (err instanceof Anthropic.APIError && (err as any).status !== undefined) { error = new RequestError(err.message, (err as any).status, err.name); } else { error = err as Error; } return { completed: false, error }; } }; }