import type * as plugins from './plugins.js'; import { AnthropicMessagesError } from './errors.js'; import type { IAnthropicMessagesMessage, IAnthropicMessagesUsage, TAnthropicMessagesStopReason, TAnthropicMessagesStreamEvent, } from './interfaces.js'; import type { ToolNames } from './request.js'; import { mergeReasoningMetadata, type ThinkingSignatures } from './signature.js'; /** * Anthropic counts input tokens without the ones read from or written to the cache. A cache count the model did not * state is `null`, as Anthropic's own usage may give it, never 0: no cache use and an unknown one are not the same. * `input_tokens` then holds whatever of the unknown count the model's input total includes. */ export const toAnthropicUsage = (usageArg: plugins.LanguageModelV4Usage | undefined): IAnthropicMessagesUsage => { const cacheRead = usageArg?.inputTokens.cacheRead ?? null; const cacheWrite = usageArg?.inputTokens.cacheWrite ?? null; return { input_tokens: usageArg?.inputTokens.noCache ?? Math.max(0, (usageArg?.inputTokens.total ?? 0) - (cacheRead ?? 0) - (cacheWrite ?? 0)), output_tokens: usageArg?.outputTokens.total ?? 0, cache_creation_input_tokens: cacheWrite, cache_read_input_tokens: cacheRead, }; }; const streamFailure = (messageArg: string): AnthropicMessagesError => new AnthropicMessagesError(500, 'api_error', messageArg); export interface IAnthropicMessagesStreamTranslatorOptions { messageId: string; modelId: string; thinking: false | { display: 'summarized' | 'omitted' }; signatures: ThinkingSignatures; signatureScope: string; toolNames: ToolNames; } interface IOpenBlock { kind: 'text' | 'thinking'; partId: string; index: number; metadata?: plugins.SharedV4ProviderMetadata; } /** * Turns the stream of one model call into the event sequence of an Anthropic message: `message_start`, * content blocks that each open, change and close before the next one opens, then `message_delta` with the * stop reason and usage, and `message_stop`. A part it cannot state faithfully throws, and the caller ends * the stream with an error event. */ export class AnthropicMessagesStreamTranslator { private nextIndex = 0; private open: IOpenBlock | undefined; private readonly skippedReasoning = new Set(); private hasToolUse = false; private finished = false; public usage: plugins.LanguageModelV4Usage | undefined; constructor(private readonly options: IAnthropicMessagesStreamTranslatorOptions) {} public get isFinished(): boolean { return this.finished; } public start(): TAnthropicMessagesStreamEvent { return { type: 'message_start', message: { id: this.options.messageId, type: 'message', role: 'assistant', model: this.options.modelId, content: [], stop_reason: null, stop_sequence: null, usage: toAnthropicUsage(undefined), }, }; } public async push(partArg: plugins.LanguageModelV4StreamPart): Promise { if (this.finished) throw streamFailure('The model sent output after it finished.'); switch (partArg.type) { case 'stream-start': case 'response-metadata': case 'raw': case 'tool-input-start': case 'tool-input-delta': case 'tool-input-end': // Tool input is sent whole with its tool call, which carries the complete, parsed arguments. return []; case 'text-start': return [...this.close(), this.openBlock({ kind: 'text', partId: partArg.id }, { type: 'text', text: '' })]; case 'text-delta': return [{ type: 'content_block_delta', index: this.requireOpen('text', partArg.id).index, delta: { type: 'text_delta', text: partArg.delta }, }]; case 'text-end': this.requireOpen('text', partArg.id); return this.close(); case 'reasoning-start': if (this.options.thinking === false) { this.skippedReasoning.add(partArg.id); return []; } return [ ...this.close(), this.openBlock( { kind: 'thinking', partId: partArg.id, metadata: partArg.providerMetadata }, { type: 'thinking', thinking: '', signature: '' }, ), ]; case 'reasoning-delta': { if (this.skippedReasoning.has(partArg.id)) return []; const block = this.requireOpen('thinking', partArg.id); if (this.options.thinking !== false && this.options.thinking.display === 'omitted') return []; return [{ type: 'content_block_delta', index: block.index, delta: { type: 'thinking_delta', thinking: partArg.delta } }]; } case 'reasoning-end': { if (this.skippedReasoning.delete(partArg.id)) return []; const block = this.requireOpen('thinking', partArg.id); const signature = await this.options.signatures.sign( this.options.signatureScope, mergeReasoningMetadata(block.metadata, partArg.providerMetadata), ); this.open = undefined; return [ { type: 'content_block_delta', index: block.index, delta: { type: 'signature_delta', signature } }, { type: 'content_block_stop', index: block.index }, ]; } case 'tool-call': { if (partArg.providerExecuted) throw streamFailure('The model ran a provider tool, which this service cannot state.'); const name = this.options.toolNames.received(partArg.toolName); if (name === undefined) throw streamFailure(`The model called "${partArg.toolName}", a tool the request did not offer.`); const inputJson = partArg.input.trim() === '' ? '{}' : partArg.input; let input: unknown; try { input = JSON.parse(inputJson); } catch { throw streamFailure(`The model called "${name}" with arguments that are not JSON.`); } if (typeof input !== 'object' || input === null || Array.isArray(input)) { throw streamFailure(`The model called "${name}" with arguments that are not a JSON object.`); } this.hasToolUse = true; const events = this.close(); const index = this.nextIndex++; events.push( { type: 'content_block_start', index, content_block: { type: 'tool_use', id: partArg.toolCallId, name, input: {} } }, { type: 'content_block_delta', index, delta: { type: 'input_json_delta', partial_json: JSON.stringify(input) } }, { type: 'content_block_stop', index }, ); return events; } case 'finish': { const events = this.close(); this.finished = true; this.usage = partArg.usage; events.push( { type: 'message_delta', delta: { stop_reason: this.stopReason(partArg.finishReason), stop_sequence: null }, usage: toAnthropicUsage(partArg.usage), }, { type: 'message_stop' }, ); return events; } case 'error': throw partArg.error; default: throw streamFailure(`The model produced "${partArg.type}" output, which this service cannot state.`); } } private stopReason(reasonArg: plugins.LanguageModelV4FinishReason): TAnthropicMessagesStopReason { switch (reasonArg.unified) { case 'stop': return this.hasToolUse ? 'tool_use' : 'end_turn'; case 'tool-calls': return 'tool_use'; case 'length': return 'max_tokens'; case 'content-filter': return 'refusal'; default: throw streamFailure(`The model stopped for a reason this service cannot state (${reasonArg.raw ?? reasonArg.unified}).`); } } private openBlock( blockArg: Omit, contentArg: Extract['content_block'], ): TAnthropicMessagesStreamEvent { const index = this.nextIndex++; this.open = { ...blockArg, index }; return { type: 'content_block_start', index, content_block: contentArg }; } private requireOpen(kindArg: IOpenBlock['kind'], partIdArg: string): IOpenBlock { if (this.open?.kind !== kindArg || this.open.partId !== partIdArg) { throw streamFailure('The model interleaved its output parts, which the message stream cannot state.'); } return this.open; } /** Closes an open text block before the next block; reasoning is closed only by its own end, with its signature. */ private close(): TAnthropicMessagesStreamEvent[] { if (!this.open) return []; const index = this.open.index; if (this.open.kind === 'thinking') { throw streamFailure('The model moved on before its reasoning ended.'); } this.open = undefined; return [{ type: 'content_block_stop', index }]; } } /** Builds the complete message a non-streaming request answers with from the events of its stream. */ export class AnthropicMessagesAccumulator { private message: IAnthropicMessagesMessage | undefined; public apply(eventArg: TAnthropicMessagesStreamEvent): void { switch (eventArg.type) { case 'message_start': this.message = structuredClone(eventArg.message); return; case 'content_block_start': this.require().content[eventArg.index] = structuredClone(eventArg.content_block); return; case 'content_block_delta': { const block = this.require().content[eventArg.index]; const delta = eventArg.delta; if (block.type === 'text' && delta.type === 'text_delta') block.text += delta.text; else if (block.type === 'thinking' && delta.type === 'thinking_delta') block.thinking += delta.thinking; else if (block.type === 'thinking' && delta.type === 'signature_delta') block.signature = delta.signature; else if (block.type === 'tool_use' && delta.type === 'input_json_delta') block.input = JSON.parse(delta.partial_json); else throw streamFailure('A content delta does not match its block.'); return; } case 'message_delta': this.require().stop_reason = eventArg.delta.stop_reason; this.require().stop_sequence = eventArg.delta.stop_sequence; this.require().usage = eventArg.usage; return; default: return; } } public result(): IAnthropicMessagesMessage { return this.require(); } private require(): IAnthropicMessagesMessage { if (!this.message) throw streamFailure('The message has not started.'); return this.message; } } export const encodeServerSentEvent = (eventArg: TAnthropicMessagesStreamEvent): string => `event: ${eventArg.type}\ndata: ${JSON.stringify(eventArg)}\n\n`;