From 2a77e6de6064d9e217bfdfc7e4fb860e70e11c8e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 24 Sep 2025 12:57:10 -0700 Subject: [PATCH] feat: clean up anthropic messaging (#7799) * fix: include message content when tool calls present * chore: use buildTextPart more * fix: HOTFIX text parts for anthropic openai adapter * fix: anthropic types * fix: response.json assumption for anthropic * fix: test mocks * fix: address cubic feedback * fix: anthopric tests * fix: prettier --- core/llm/constants.ts | 2 + core/llm/index.ts | 15 +- core/llm/llm-pre-fetch.vitest.ts | 4 + core/llm/llms/Anthropic.ts | 418 ++++++++++-------- core/llm/llms/VertexAI.ts | 11 +- core/package-lock.json | 11 + core/package.json | 1 + packages/openai-adapters/package-lock.json | 11 + packages/openai-adapters/package.json | 1 + .../openai-adapters/src/apis/Anthropic.ts | 379 +++++++++------- .../apis/AnthropicCachingStrategies.test.ts | 410 +++++++++++------ .../src/apis/AnthropicCachingStrategies.ts | 32 +- .../src/apis/AnthropicUtils.ts | 139 ++++++ packages/openai-adapters/src/index.ts | 7 + .../src/test/anthropic-adapter.vitest.ts | 36 +- 15 files changed, 971 insertions(+), 506 deletions(-) create mode 100644 packages/openai-adapters/src/apis/AnthropicUtils.ts diff --git a/core/llm/constants.ts b/core/llm/constants.ts index c368e0d5a..2c59579dd 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -2,6 +2,7 @@ const DEFAULT_MAX_TOKENS = 4096; const DEFAULT_CONTEXT_LENGTH = 32_768; const DEFAULT_TEMPERATURE = 0.5; const DEFAULT_PRUNING_LENGTH = 128000; +const DEFAULT_REASONING_TOKENS = 2048; const DEFAULT_ARGS = { maxTokens: DEFAULT_MAX_TOKENS, @@ -31,5 +32,6 @@ export { DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, DEFAULT_PRUNING_LENGTH, + DEFAULT_REASONING_TOKENS, PROXY_URL, }; diff --git a/core/llm/index.ts b/core/llm/index.ts index 751a537ea..a634fc5d6 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -65,7 +65,6 @@ import { toCompleteBody, toFimBody, } from "./openaiTypeConverters.js"; - export class LLMError extends Error { constructor( message: string, @@ -558,12 +557,14 @@ export abstract class BaseLLM implements ILLM { private _formatChatMessage(msg: ChatMessage): string { let contentToShow = renderChatMessage(msg); if (msg.role === "assistant" && msg.toolCalls?.length) { - contentToShow += msg.toolCalls - ?.map( - (toolCall) => - `${toolCall.function?.name}(${toolCall.function?.arguments})`, - ) - .join("\n"); + contentToShow += + "\n" + + msg.toolCalls + ?.map( + (toolCall) => + `${toolCall.function?.name}(${toolCall.function?.arguments})`, + ) + .join("\n"); } return `<${msg.role}>\n${contentToShow}\n\n`; diff --git a/core/llm/llm-pre-fetch.vitest.ts b/core/llm/llm-pre-fetch.vitest.ts index f6c271870..026b47c5c 100644 --- a/core/llm/llm-pre-fetch.vitest.ts +++ b/core/llm/llm-pre-fetch.vitest.ts @@ -58,6 +58,10 @@ const messagesWithInvalidToolCallArgs: ChatMessage[] = [ describe("LLM Pre-fetch", () => { beforeEach(() => { vi.resetAllMocks(); + // Mock getAnthropicHeaders to return fake headers + vi.mocked(openAiAdapters.getAnthropicHeaders).mockReturnValue({ + fake: "headers", + }); // Log to verify the mock is properly set up console.log("Mock setup:", openAiAdapters); }); diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index fdaac3290..62d963b99 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -1,30 +1,36 @@ +import { + Tool as AnthropicTool, + ContentBlockParam, + MessageCreateParams, + MessageParam, + RawContentBlockDeltaEvent, + RawContentBlockStartEvent, + RawMessageDeltaEvent, + RawMessageStartEvent, + RawMessageStreamEvent, + ToolUseBlock, +} from "@anthropic-ai/sdk/resources/messages.mjs"; import { streamSse } from "@continuedev/fetch"; +import { + addCacheControlToLastTwoUserMessages, + getAnthropicErrorMessage, + getAnthropicHeaders, + getAnthropicMediaTypeFromDataUrl, +} from "@continuedev/openai-adapters"; import { ChatMessage, CompletionOptions, LLMOptions, + MessageContent, + Tool, + ToolCallDelta, Usage, } from "../../index.js"; import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; +import { DEFAULT_REASONING_TOKENS } from "../constants.js"; import { BaseLLM } from "../index.js"; -const errorMessages = { - invalid_request_error: - "There was an issue with the format or content of your request.", - authentication_error: "There's an issue with your API key.", - permission_error: - "Your API key does not have permission to use the specified resource.", - not_found_error: "The requested resource was not found.", - request_too_large: - "Request exceeds the maximum allowed number of bytes (32 MB limit).", - rate_limit_error: "Your account has hit a rate limit.", - api_error: - "An unexpected error has occurred internal to Anthropic's systems.", - overloaded_error: - "Anthropic's API is temporarily overloaded. Please check their status page: https://status.anthropic.com/#past-incidents", -}; - class Anthropic extends BaseLLM { static providerName = "anthropic"; static defaultOptions: Partial = { @@ -36,8 +42,21 @@ class Anthropic extends BaseLLM { apiBase: "https://api.anthropic.com/v1/", }; - public convertArgs(options: CompletionOptions) { - // should be public for use within VertexAI + private convertToolToAnthropicTool(tool: Tool): AnthropicTool { + return { + name: tool.function.name, + description: tool.function.description, + input_schema: (tool.function.parameters as AnthropicTool.InputSchema) ?? { + // TODO unsafe tool.function.parameters casting + type: "object", + }, + }; + } + + // Public for use within VertexAI + public convertArgs( + options: CompletionOptions, + ): Omit { const finalOptions = { top_k: options.topK, top_p: options.topP, @@ -46,20 +65,17 @@ class Anthropic extends BaseLLM { model: options.model === "claude-2" ? "claude-2.1" : options.model, stop_sequences: options.stop?.filter((x) => x.trim() !== ""), stream: options.stream ?? true, - tools: options.tools?.map((tool) => ({ - name: tool.function.name, - description: tool.function.description, - input_schema: tool.function.parameters, - })), + tools: options.tools?.map(this.convertToolToAnthropicTool), thinking: options.reasoning ? { - type: "enabled", - budget_tokens: options.reasoningBudgetTokens, + type: "enabled" as const, + budget_tokens: + options.reasoningBudgetTokens ?? DEFAULT_REASONING_TOKENS, } : undefined, tool_choice: options.toolChoice ? { - type: "tool", + type: "tool" as const, name: options.toolChoice.function.name, } : undefined, @@ -68,138 +84,146 @@ class Anthropic extends BaseLLM { return finalOptions; } - private buildTextPart(text: string, addCaching: boolean) { - const part: any = { - type: "text", - text, - }; - if (addCaching) { - part.cache_control = { type: "ephemeral" }; + private convertMessageContentToBlocks( + content: MessageContent, + ): ContentBlockParam[] { + if (typeof content === "string") { + return [ + { + type: "text", + text: content, + }, + ]; } - return part; + return content.map((part) => { + if (part.type === "text") { + return { + type: "text", + text: part.text, + }; + } + return { + type: "image", + source: { + type: "base64", + media_type: getAnthropicMediaTypeFromDataUrl(part.imageUrl.url), + data: part.imageUrl.url.split(",")[1], + }, + }; + }); } - private convertMessage(message: ChatMessage, addCaching: boolean): any { - if (message.role === "tool") { + private convertToolCallsToBlocks( + toolCall: ToolCallDelta, + ): ToolUseBlock | undefined { + const toolCallId = toolCall.id; + const toolName = toolCall.function?.name; + if (toolCallId && toolName) { return { - role: "user", - content: [ + type: "tool_use", + id: toolCallId, + name: toolName, + input: safeParseToolCallArgs(toolCall), + }; + } + } + + private getContentBlocksFromChatMessage( + message: ChatMessage, + ): ContentBlockParam[] { + switch (message.role) { + // One tool message = one tool_result block + case "tool": + return [ { type: "tool_result", tool_use_id: message.toolCallId, content: renderChatMessage(message) || undefined, }, - ], - }; - } else if (message.role === "assistant" && message.toolCalls) { - const parts: any[] = []; - if (message.content) { + ]; + case "user": + return this.convertMessageContentToBlocks(message.content); + case "thinking": + if (message.redactedThinking) { + return [ + { + type: "redacted_thinking", + data: message.redactedThinking, + }, + ]; + } if (typeof message.content === "string") { - parts.push(this.buildTextPart(message.content, addCaching)); - } else if (message.content.length > 0) { - const textContent = message.content.filter((p) => p.type === "text"); - const textParts = textContent.map((part, idx) => { - const cache = idx === textContent.length - 1 && addCaching; - return this.buildTextPart(part.text, cache); - }); - parts.push(...textParts); + return [ + { + type: "thinking", + thinking: message.content, + signature: message.signature ?? "", // TODO - unsafe signature + }, + ]; } - } - parts.push( - ...message.toolCalls.map((toolCall) => ({ - type: "tool_use", - id: toolCall.id, - name: toolCall.function?.name, - input: safeParseToolCallArgs(toolCall), - })), - ); - return { - role: "assistant", - content: parts, - }; - } else if (message.role === "thinking" && !message.redactedThinking) { - return { - role: "assistant", - content: [ - { - type: "thinking", - thinking: message.content, - signature: message.signature, - }, - ], - }; - } else if (message.role === "thinking" && message.redactedThinking) { - return { - role: "assistant", - content: [ - { - type: "redacted_thinking", - data: message.redactedThinking, - }, - ], - }; - } - - if (typeof message.content === "string") { - var chatMessage = { - role: message.role, - content: [ - { - type: "text", - text: message.content, - ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}), - }, - ], - }; - return chatMessage; - } - - return { - role: message.role, - content: message.content.map((part, contentIdx) => { - if (part.type === "text") { - const newpart = { - ...part, - // If multiple text parts, only add cache_control to the last one - ...(addCaching && contentIdx === message.content.length - 1 - ? { cache_control: { type: "ephemeral" } } - : {}), - }; - return newpart; + const textParts = message.content.filter((p) => p.type === "text"); + return textParts.map((part) => ({ + type: "thinking", + thinking: part.text, + signature: message.signature ?? "", // TODO - unsafe signature + })); + case "assistant": + const blocks: ContentBlockParam[] = this.convertMessageContentToBlocks( + message.content, + ); + // If any tool calls are present, always put them last + // Loses order vs what was originally sent, but they typically come last + for (const toolCall of message.toolCalls ?? []) { + const block = this.convertToolCallsToBlocks(toolCall); + if (block) { + blocks.push(block); + } } - return { - type: "image", - source: { - type: "base64", - media_type: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - }), - }; + return blocks; + // system, etc. + default: + return []; + } } - public convertMessages(msgs: ChatMessage[]): any[] { - // should be public for use within VertexAI - const filteredmessages = msgs.filter((m) => m.role !== "system"); - const lastTwoUserMsgIndices = filteredmessages - .map((msg, index) => (msg.role === "user" ? index : -1)) - .filter((index) => index !== -1) - .slice(-2); + public convertMessages( + msgs: ChatMessage[], + cachePrompt: boolean, + ): MessageParam[] { + const nonSystemMessages = msgs.filter((m) => m.role !== "system"); - const messages = filteredmessages.map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching - const addCaching = - this.cacheBehavior?.cacheConversation && - lastTwoUserMsgIndices.includes(filteredMsgIdx); + const convertedMessages: MessageParam[] = []; + let currentRole: "user" | "assistant" | undefined = undefined; + let currentParts: ContentBlockParam[] = []; - const chatMessage = this.convertMessage(message, !!addCaching); - return chatMessage; - }); - return messages; + const flushCurrentMessage = () => { + if (currentRole && currentParts.length > 0) { + convertedMessages.push({ + role: currentRole, + content: currentParts, + }); + currentParts = []; + } + }; + + for (const message of nonSystemMessages) { + const newRole = + message.role === "user" || message.role === "tool" + ? "user" + : "assistant"; + if (currentRole !== newRole) { + flushCurrentMessage(); + currentRole = newRole; + } + currentParts.push(...this.getContentBlocksFromChatMessage(message)); + } + flushCurrentMessage(); + + if (cachePrompt) { + addCacheControlToLastTwoUserMessages(convertedMessages); + } + + return convertedMessages; } protected async *_streamComplete( @@ -224,12 +248,7 @@ class Anthropic extends BaseLLM { if (!response.ok) { const json = await response.json(); if (json.type === "error") { - if (json.error?.type in errorMessages) { - throw new Error( - errorMessages[json.error.type as keyof typeof errorMessages], - ); - } - throw new Error(json.message); + throw new Error(getAnthropicErrorMessage(json)); } throw new Error( `Anthropic API sent back ${response.status}: ${JSON.stringify(json)}`, @@ -237,17 +256,17 @@ class Anthropic extends BaseLLM { } if (stream === false) { - const data = await response.json(); - const cost = data.usage + const json = await response.json(); + const cost = json.usage ? { - inputTokens: data.usage.input_tokens, - outputTokens: data.usage.output_tokens, - totalTokens: data.usage.input_tokens + data.usage.output_tokens, + inputTokens: json.usage.input_tokens, + outputTokens: json.usage.output_tokens, + totalTokens: json.usage.input_tokens + json.usage.output_tokens, } : {}; yield { role: "assistant", - content: data.content[0].text, + content: json.content[0].text, ...(Object.keys(cost).length > 0 ? { cost } : {}), }; return; @@ -264,51 +283,59 @@ class Anthropic extends BaseLLM { }, }; - for await (const value of streamSse(response)) { + for await (const event of streamSse(response)) { // https://docs.anthropic.com/en/api/messages-streaming#event-types - switch (value.type) { + const rawEvent = event as RawMessageStreamEvent; + switch (event.type) { case "message_start": // Capture initial usage information - usage.promptTokens = value.message.usage.input_tokens; + const startEvent = rawEvent as RawMessageStartEvent; + usage.promptTokens = startEvent.message.usage.input_tokens; usage.promptTokensDetails!.cachedTokens = - value.message.usage.cache_read_input_tokens; + startEvent.message.usage.cache_read_input_tokens ?? undefined; usage.promptTokensDetails!.cacheWriteTokens = - value.message.usage.cache_creation_input_tokens; + startEvent.message.usage.cache_creation_input_tokens ?? undefined; break; case "message_delta": // Update usage information during streaming - if (value.usage) { - usage.completionTokens = value.usage.output_tokens; + const deltaEvent = rawEvent as RawMessageDeltaEvent; + if (deltaEvent.usage) { + usage.completionTokens = deltaEvent.usage.output_tokens; } break; case "content_block_start": - if (value.content_block.type === "tool_use") { - lastToolUseId = value.content_block.id; - lastToolUseName = value.content_block.name; + const blockStartEvent = rawEvent as RawContentBlockStartEvent; + if (blockStartEvent.content_block.type === "tool_use") { + lastToolUseId = blockStartEvent.content_block.id; + lastToolUseName = blockStartEvent.content_block.name; } // handle redacted thinking - if (value.content_block.type === "redacted_thinking") { + if (blockStartEvent.content_block.type === "redacted_thinking") { yield { role: "thinking", content: "", - redactedThinking: value.content_block.data, + redactedThinking: blockStartEvent.content_block.data, }; } break; case "content_block_delta": // https://docs.anthropic.com/en/api/messages-streaming#delta-types - switch (value.delta.type) { + const blockDeltaEvent = rawEvent as RawContentBlockDeltaEvent; + switch (blockDeltaEvent.delta.type) { case "text_delta": - yield { role: "assistant", content: value.delta.text }; + yield { role: "assistant", content: blockDeltaEvent.delta.text }; break; case "thinking_delta": - yield { role: "thinking", content: value.delta.thinking }; + yield { + role: "thinking", + content: blockDeltaEvent.delta.thinking, + }; break; case "signature_delta": yield { role: "thinking", content: "", - signature: value.delta.signature, + signature: blockDeltaEvent.delta.signature, }; break; case "input_json_delta": @@ -324,7 +351,7 @@ class Anthropic extends BaseLLM { type: "function", function: { name: lastToolUseName, - arguments: value.delta.partial_json, + arguments: blockDeltaEvent.delta.partial_json, }, }, ], @@ -365,32 +392,35 @@ class Anthropic extends BaseLLM { const shouldCacheSystemMessage = !!( this.cacheBehavior?.cacheSystemMessage && systemMessage ); + const shouldCachePrompt = !!( + this.cacheBehavior?.cacheConversation || + this.completionOptions.promptCaching + ); + + const msgs = this.convertMessages(messages, shouldCachePrompt); + const headers = getAnthropicHeaders( + this.apiKey, + shouldCacheSystemMessage || shouldCachePrompt, + ); + + const body: MessageCreateParams = { + ...this.convertArgs(options), + messages: msgs, + system: shouldCacheSystemMessage + ? [ + { + type: "text", + text: systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] + : systemMessage, + }; - const msgs = this.convertMessages(messages); const response = await this.fetch(new URL("messages", this.apiBase), { method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - "anthropic-version": "2023-06-01", - "x-api-key": this.apiKey as string, - ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation - ? { "anthropic-beta": "prompt-caching-2024-07-31" } - : {}), - }, - body: JSON.stringify({ - ...this.convertArgs(options), - messages: msgs, - system: shouldCacheSystemMessage - ? [ - { - type: "text", - text: systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] - : systemMessage, - }), + headers, + body: JSON.stringify(body), signal, }); diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index cb828bedb..258bccc3d 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -223,6 +223,10 @@ class VertexAI extends BaseLLM { const shouldCacheSystemMessage = !!( this.cacheBehavior?.cacheSystemMessage && systemMessage ); + const shouldCachePrompt = !!( + this.cacheBehavior?.cacheConversation ?? + this.completionOptions.promptCaching + ); // /v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict @@ -234,13 +238,16 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", headers: { - ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation + ...(shouldCacheSystemMessage || shouldCachePrompt ? { "anthropic-beta": "prompt-caching-2024-07-31" } : {}), }, body: JSON.stringify({ ...this._anthropicConvertArgs(options), - messages: this.anthropicInstance.convertMessages(messages), + messages: this.anthropicInstance.convertMessages( + messages, + shouldCachePrompt, + ), system: shouldCacheSystemMessage ? [ { diff --git a/core/package-lock.json b/core/package-lock.json index 180a40903..109605f18 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -9,6 +9,7 @@ "version": "1.1.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.779.0", "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", @@ -218,6 +219,7 @@ "version": "1.15.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.14", @@ -297,6 +299,15 @@ "node": ">=6.0.0" } }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.62.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.62.0.tgz", + "integrity": "sha512-gT2VFKX0gSp7KJNlav/vzRFjJOPYDZxCJRx7MYUc+fqURc5aS6OI/UJeD2KytJkjsIWv0OOwH1ePc1S5QE2GZw==", + "license": "MIT", + "bin": { + "anthropic-ai-sdk": "bin/cli" + } + }, "node_modules/@apache-arrow/ts": { "version": "14.0.2", "resolved": "https://registry.npmjs.org/@apache-arrow/ts/-/ts-14.0.2.tgz", diff --git a/core/package.json b/core/package.json index db53c661a..f20ba384b 100644 --- a/core/package.json +++ b/core/package.json @@ -54,6 +54,7 @@ "vitest": "^3.1.4" }, "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.779.0", "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 77ab666f1..2f38ada3e 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -9,6 +9,7 @@ "version": "1.15.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.14", @@ -40,6 +41,15 @@ "vitest": "^3.2.4" } }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.62.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.62.0.tgz", + "integrity": "sha512-gT2VFKX0gSp7KJNlav/vzRFjJOPYDZxCJRx7MYUc+fqURc5aS6OI/UJeD2KytJkjsIWv0OOwH1ePc1S5QE2GZw==", + "license": "MIT", + "bin": { + "anthropic-ai-sdk": "bin/cli" + } + }, "node_modules/@aws-crypto/crc32": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", @@ -15179,6 +15189,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz", "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", "dev": true, + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index c2b11cd4a..49dbcc1f2 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -12,6 +12,7 @@ "author": "Nate Sesti and Ty Dunn", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sdk": "^0.62.0", "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.14", diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index 27c0c6f86..b2663896f 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -1,8 +1,22 @@ +import { + ContentBlockParam, + MessageCreateParams, + MessageParam, + RawContentBlockDeltaEvent, + RawContentBlockStartEvent, + RawMessageDeltaEvent, + RawMessageStartEvent, + RawMessageStreamEvent, + Tool, + ToolUseBlock, +} from "@anthropic-ai/sdk/resources"; import { streamSse } from "@continuedev/fetch"; import { OpenAI } from "openai/index"; import { ChatCompletion, ChatCompletionChunk, + ChatCompletionContentPartRefusal, + ChatCompletionContentPartText, ChatCompletionCreateParamsNonStreaming, ChatCompletionCreateParamsStreaming, Completion, @@ -24,6 +38,12 @@ import { CACHING_STRATEGIES, CachingStrategyName, } from "./AnthropicCachingStrategies.js"; +import { + getAnthropicHeaders, + getAnthropicMediaTypeFromDataUrl, + openAiToolChoiceToAnthropicToolChoice, + openaiToolToAnthropicTool, +} from "./AnthropicUtils.js"; import { BaseLlmApi, CreateRerankResponse, @@ -59,11 +79,12 @@ export class AnthropicApi implements BaseLlmApi { if (model.includes("haiku")) { return 8192; } - return 32_000; } - public _convertToCleanAnthropicBody(oaiBody: ChatCompletionCreateParams) { + public _convertToCleanAnthropicBody( + oaiBody: ChatCompletionCreateParams, + ): MessageCreateParams { let stop = undefined; if (oaiBody.stop && Array.isArray(oaiBody.stop)) { stop = oaiBody.stop.filter((x) => x.trim() !== ""); @@ -75,145 +96,198 @@ export class AnthropicApi implements BaseLlmApi { (msg) => msg.role === "system", )?.content; - const anthropicBody = { + // TODO support custom tools + const functionTools = oaiBody.tools?.filter((t) => t.type === "function"); + let tools: Tool[] | undefined = undefined; + + if ( + oaiBody.tool_choice !== "none" && + functionTools && + functionTools.length > 0 + ) { + if ( + typeof oaiBody.tool_choice !== "string" && + oaiBody.tool_choice?.type === "allowed_tools" + ) { + const allowedToolNames = new Set( + oaiBody.tool_choice?.allowed_tools.tools.map( + (tool) => tool["name"], + ) ?? [], + ); + const allowedTools = functionTools.filter((t) => + allowedToolNames.has(t.function.name), + ); + tools = allowedTools.map(openaiToolToAnthropicTool); + } else { + tools = functionTools.map(openaiToolToAnthropicTool); + } + } + + const anthropicBody: MessageCreateParams = { messages: this._convertMessages( oaiBody.messages.filter((msg) => msg.role !== "system"), ), - system: systemMessage - ? [ - { - type: "text", - text: systemMessage, - }, - ] - : systemMessage, - top_p: oaiBody.top_p, - temperature: oaiBody.temperature, + system: + typeof systemMessage === "string" + ? [ + { + type: "text", + text: systemMessage, + }, + ] + : systemMessage, + top_p: oaiBody.top_p ?? undefined, + temperature: oaiBody.temperature ?? undefined, max_tokens: oaiBody.max_tokens ?? this.maxTokensForModel(oaiBody.model), // max_tokens is required model: oaiBody.model, stop_sequences: stop, - stream: oaiBody.stream, - tools: oaiBody.tools?.map((tool) => { - // Type guard for function tools - if (tool.type === "function" && "function" in tool) { - return { - name: tool.function.name, - description: tool.function.description, - input_schema: tool.function.parameters, - }; - } else { - throw new Error(`Unsupported tool type in Anthropic: ${tool.type}`); - } - }), - tool_choice: oaiBody.tool_choice - ? { - type: "tool", - name: - typeof oaiBody.tool_choice === "string" - ? oaiBody.tool_choice - : oaiBody.tool_choice && "function" in oaiBody.tool_choice - ? oaiBody.tool_choice.function.name - : undefined, - } - : undefined, + stream: oaiBody.stream ?? undefined, + tools, + tool_choice: openAiToolChoiceToAnthropicToolChoice(oaiBody.tool_choice), }; return anthropicBody; } - private _convertMessages( - msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], - ): any[] { - const messages = msgs.map((message) => { - if (message.role === "tool") { - return { - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: message.tool_call_id, - content: - typeof message.content === "string" - ? message.content - : message.content.map((part) => part.text).join(""), - }, - ], - }; - } else if (message.role === "assistant" && message.tool_calls) { - const parts: any[] = []; - if (message.content) { - if (typeof message.content === "string") { - parts.push({ - type: "text", - text: message.content, - }); - } else if (message.content.length > 0) { - parts.push( - message.content.map((c) => ({ - type: "text", - text: c.type === "text" ? c.text : c.refusal, - })), - ); - } - } - - parts.push( - ...message.tool_calls.map((toolCall) => { - // Type guard for function tool calls - if (toolCall.type === "function" && "function" in toolCall) { - return { - type: "tool_use", - id: toolCall.id, - name: toolCall.function?.name, - input: safeParseArgs( - toolCall.function?.arguments, - `${toolCall.function?.name} ${toolCall.id}`, - ), - }; - } else { - throw new Error(`Unsupported tool call type: ${toolCall.type}`); - } - }), - ); - return { - role: "assistant", - content: parts, - }; - } - - if (!Array.isArray(message.content)) { - return message; - } + private convertToolCallsToBlocks( + toolCall: OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall, + ): ToolUseBlock | undefined { + const toolCallId = toolCall.id; + const toolName = toolCall.function?.name; + if (toolCallId && toolName) { return { - ...message, - content: message.content - .map((part) => { - if (part.type === "text") { - if ((part.text?.trim() ?? "") === "") { - return null; - } - return part; - } - const dataUrl = - (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage) - ?.image_url?.url || ""; - // Extract media type from data URL (ex. "data:image/png;base64,..." -> "image/png") - const mediaTypeMatch = dataUrl.match(/^data:([^;]+);base64,/); - const mediaType = mediaTypeMatch ? mediaTypeMatch[1] : "image/jpeg"; + type: "tool_use", + id: toolCallId, + name: toolName, + input: safeParseArgs( + toolCall.function.arguments, + `${toolName} ${toolCallId}`, + ), + }; + } + } - return { + // 1. ignores empty content + // 2. converts string content to text parts + // 3. converts text and refusal parts to text blocks + // 4. converts image parts to image blocks + private convertMessageContentToBlocks( + content: + | string + | OpenAI.Chat.Completions.ChatCompletionContentPart[] + | (ChatCompletionContentPartText | ChatCompletionContentPartRefusal)[], + ): ContentBlockParam[] { + const blocks: ContentBlockParam[] = []; + if (typeof content === "string") { + if (content) { + blocks.push({ + type: "text", + text: content, + }); + } + } else { + const supportedParts = content.filter( + (p) => + p.type === "text" || p.type === "image_url" || p.type === "refusal", + ); + for (const part of supportedParts) { + if (part.type === "image_url") { + const dataUrl = part.image_url.url; + if (dataUrl?.startsWith("data:")) { + blocks.push({ type: "image", source: { type: "base64", - media_type: mediaType, + media_type: getAnthropicMediaTypeFromDataUrl(dataUrl), data: dataUrl.split(",")[1], }, - }; - }) - .filter((x) => x !== null), - }; - }); - return messages; + }); + } + } else { + const text = part.type === "text" ? part.text : part.refusal; + if (text) { + blocks.push({ + type: "text", + text, + }); + } + } + } + } + return blocks; + } + + private getContentBlocksFromChatMessage( + message: OpenAI.Chat.Completions.ChatCompletionMessageParam, + ): ContentBlockParam[] { + switch (message.role) { + // One tool message = one tool_result block + case "tool": + return [ + { + type: "tool_result", + tool_use_id: message.tool_call_id, + content: message.content, + }, + ]; + case "user": + return this.convertMessageContentToBlocks(message.content); + case "assistant": + const blocks: ContentBlockParam[] = message.content + ? this.convertMessageContentToBlocks(message.content) + : []; + // If any tool calls are present, always put them last + // Loses order vs what was originally sent, but they typically come last + for (const toolCall of message.tool_calls ?? []) { + if (toolCall.type !== "function") { + // TODO support custom tool calls + continue; + } + const block = this.convertToolCallsToBlocks(toolCall); + if (block) { + blocks.push(block); + } + } + return blocks; + // system, etc. + default: + return []; + } + } + + private _convertMessages( + msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], + ): MessageParam[] { + const nonSystemMessages = msgs.filter((m) => m.role !== "system"); + + const convertedMessages: MessageParam[] = []; + let currentRole: "user" | "assistant" | undefined = undefined; + let currentParts: ContentBlockParam[] = []; + + const flushCurrentMessage = () => { + if (currentRole && currentParts.length > 0) { + convertedMessages.push({ + role: currentRole, + content: currentParts, + }); + currentParts = []; + } + }; + + for (const message of nonSystemMessages) { + const newRole = + message.role === "user" || message.role === "tool" + ? "user" + : "assistant"; + if (currentRole !== newRole) { + flushCurrentMessage(); + currentRole = newRole; + } + currentParts.push(...this.getContentBlocksFromChatMessage(message)); + } + flushCurrentMessage(); + + return convertedMessages; } async chatCompletionNonStream( @@ -224,13 +298,7 @@ export class AnthropicApi implements BaseLlmApi { new URL("messages", this.apiBase), { method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - "anthropic-version": "2023-06-01", - "anthropic-beta": "prompt-caching-2024-07-31", - "x-api-key": this.config.apiKey, - }, + headers: this.getHeaders(), body: JSON.stringify(this._convertBody(body)), signal, }, @@ -240,7 +308,7 @@ export class AnthropicApi implements BaseLlmApi { return EMPTY_CHAT_COMPLETION; } - const completion = (await response.json()) as any; + const completion = await response.json(); const usage: Record | undefined = completion.usage; return { @@ -281,30 +349,36 @@ export class AnthropicApi implements BaseLlmApi { prompt_tokens: 0, total_tokens: 0, }; - for await (const value of streamSse(response as any)) { + for await (const event of streamSse(response)) { // https://docs.anthropic.com/en/api/messages-streaming#event-types - switch (value.type) { + const rawEvent = event as RawMessageStreamEvent; + switch (rawEvent.type) { case "content_block_start": - if (value.content_block.type === "tool_use") { - lastToolUseId = value.content_block.id; - lastToolUseName = value.content_block.name; + const blockStartEvent = rawEvent as RawContentBlockStartEvent; + if (blockStartEvent.content_block.type === "tool_use") { + lastToolUseId = blockStartEvent.content_block.id; + lastToolUseName = blockStartEvent.content_block.name; } break; case "message_start": - usage.prompt_tokens = value.message.usage?.input_tokens ?? 0; + const startEvent = rawEvent as RawMessageStartEvent; + usage.prompt_tokens = startEvent.message.usage?.input_tokens ?? 0; usage.prompt_tokens_details = { - cached_tokens: value.message.usage?.cache_read_input_tokens ?? 0, + cached_tokens: + startEvent.message.usage?.cache_read_input_tokens ?? 0, }; break; case "message_delta": - usage.completion_tokens = value.usage?.output_tokens ?? 0; + const deltaEvent = rawEvent as RawMessageDeltaEvent; + usage.completion_tokens = deltaEvent.usage?.output_tokens ?? 0; break; case "content_block_delta": // https://docs.anthropic.com/en/api/messages-streaming#delta-types - switch (value.delta.type) { + const blockDeltaEvent = rawEvent as RawContentBlockDeltaEvent; + switch (blockDeltaEvent.delta.type) { case "text_delta": yield chatChunk({ - content: value.delta.text, + content: blockDeltaEvent.delta.text, model, }); break; @@ -322,7 +396,7 @@ export class AnthropicApi implements BaseLlmApi { index: 0, function: { name: lastToolUseName, - arguments: value.delta.partial_json, + arguments: blockDeltaEvent.delta.partial_json, }, }, ], @@ -352,25 +426,24 @@ export class AnthropicApi implements BaseLlmApi { async *chatCompletionStream( body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, - ): AsyncGenerator { - body.messages; + ): AsyncGenerator { const response = await customFetch(this.config.requestOptions)( new URL("messages", this.apiBase), { method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - "anthropic-version": "2023-06-01", - "anthropic-beta": "prompt-caching-2024-07-31", - "x-api-key": this.config.apiKey, - }, + headers: this.getHeaders(), body: JSON.stringify(this._convertBody(body)), signal, }, ); yield* this.handleStreamResponse(response, body.model); } + + private getHeaders(): Record { + const enableCaching = this.config?.cachingStrategy !== "none"; + return getAnthropicHeaders(this.config.apiKey, enableCaching); + } + async completionNonStream( body: CompletionCreateParamsNonStreaming, signal: AbortSignal, @@ -380,13 +453,13 @@ export class AnthropicApi implements BaseLlmApi { async *completionStream( body: CompletionCreateParamsStreaming, signal: AbortSignal, - ): AsyncGenerator { + ): AsyncGenerator { throw new Error("Method not implemented."); } async *fimStream( body: FimCreateParamsStreaming, signal: AbortSignal, - ): AsyncGenerator { + ): AsyncGenerator { throw new Error("Method not implemented."); } diff --git a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts index db7a975e5..263c1f2d2 100644 --- a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts +++ b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts @@ -1,24 +1,42 @@ +import { MessageCreateParams, ToolUnion } from "@anthropic-ai/sdk/resources"; import { CACHING_STRATEGIES, - CachingStrategy, CachingStrategyName, getAvailableStrategies, getStrategyDescription, } from "./AnthropicCachingStrategies.js"; +const body_params = { + model: "claude", + stream: true, + max_tokens: 8192, +}; + +const makeTool = (name: string): ToolUnion => ({ + name, + input_schema: { + type: "object", + }, +}); + describe("AnthropicCachingStrategies", () => { describe("noCachingStrategy", () => { it("should return the body unchanged", () => { - const body = { system: "test", messages: [] }; + const body: MessageCreateParams = { + system: "test", + messages: [], + ...body_params, + }; const result = CACHING_STRATEGIES.none(body); expect(result).toBe(body); }); it("should not modify complex objects", () => { - const body = { - system: [{ text: "test" }], - tools: [{ name: "test" }], - messages: [{ content: "test" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "test" }], + tools: [makeTool("test")], + messages: [{ role: "user", content: "test" }], + ...body_params, }; const result = CACHING_STRATEGIES.none(body); expect(result).toBe(body); @@ -27,24 +45,37 @@ describe("AnthropicCachingStrategies", () => { describe("systemOnlyStrategy", () => { it("should add cache_control to system messages array", () => { - const body = { - system: [{ text: "system message 1" }, { text: "system message 2" }], - messages: [{ content: "user message" }], + const body: MessageCreateParams = { + system: [ + { type: "text", text: "system message 1" }, + { type: "text", text: "system message 2" }, + ], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemOnly(body); expect(result.system).toEqual([ - { text: "system message 1", cache_control: { type: "ephemeral" } }, - { text: "system message 2", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message 1", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 2", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.messages).toEqual(body.messages); }); it("should return body unchanged if system is not an array", () => { - const body = { + const body: MessageCreateParams = { system: "string system message", - messages: [{ content: "user message" }], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemOnly(body); @@ -52,8 +83,9 @@ describe("AnthropicCachingStrategies", () => { }); it("should return body unchanged if system is undefined", () => { - const body = { - messages: [{ content: "user message" }], + const body: MessageCreateParams = { + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemOnly(body); @@ -61,25 +93,42 @@ describe("AnthropicCachingStrategies", () => { }); it("should not add more than 5 cached messages", () => { - const body = { + const body: MessageCreateParams = { system: [ - { text: "system message 1" }, - { text: "system message 2" }, - { text: "system message 3" }, - { text: "system message 4" }, - { text: "system message 5" }, + { type: "text", text: "system message 1" }, + { type: "text", text: "system message 2" }, + { type: "text", text: "system message 3" }, + { type: "text", text: "system message 4" }, + { type: "text", text: "system message 5" }, ], - messages: [{ content: "user message" }], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemOnly(body); expect(result.system).toEqual([ - { text: "system message 1", cache_control: { type: "ephemeral" } }, - { text: "system message 2", cache_control: { type: "ephemeral" } }, - { text: "system message 3", cache_control: { type: "ephemeral" } }, - { text: "system message 4", cache_control: { type: "ephemeral" } }, - { text: "system message 5" }, + { + type: "text", + text: "system message 1", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 2", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 3", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 4", + cache_control: { type: "ephemeral" }, + }, + { type: "text", text: "system message 5" }, ]); expect(result.messages).toEqual(body.messages); }); @@ -87,82 +136,116 @@ describe("AnthropicCachingStrategies", () => { describe("systemAndToolsStrategy", () => { it("should add cache_control to both system and tools", () => { - const body = { - system: [{ text: "system message" }], - tools: [{ name: "tool1" }, { name: "tool2" }], - messages: [{ content: "user message" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "system message" }], + tools: [makeTool("tool1"), makeTool("tool2")], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemAndTools(body); expect(result.system).toEqual([ - { text: "system message", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.tools).toEqual([ - { name: "tool1" }, - { name: "tool2", cache_control: { type: "ephemeral" } }, + { + name: "tool1", + input_schema: { + type: "object", + }, + }, + { + name: "tool2", + input_schema: { + type: "object", + }, + cache_control: { type: "ephemeral" }, + }, ]); expect(result.messages).toEqual(body.messages); }); it("should handle missing system messages", () => { - const body = { - tools: [{ name: "tool1" }], - messages: [{ content: "user message" }], + const body: MessageCreateParams = { + tools: [makeTool("tool1")], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemAndTools(body); expect(result.tools).toEqual([ - { name: "tool1", cache_control: { type: "ephemeral" } }, + { + name: "tool1", + input_schema: { + type: "object", + }, + cache_control: { type: "ephemeral" }, + }, ]); expect(result.messages).toEqual(body.messages); }); it("should handle missing tools", () => { - const body = { - system: [{ text: "system message" }], - messages: [{ content: "user message" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "system message" }], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemAndTools(body); expect(result.system).toEqual([ - { text: "system message", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.messages).toEqual(body.messages); }); - it("should handle non-array system and tools", () => { - const body = { - system: "string system", - tools: "string tools", - messages: [{ content: "user message" }], - }; - - const result = CACHING_STRATEGIES.systemAndTools(body); - expect(result).toEqual(body); - }); - it("should add only 4 cache controls in total to both system and tools", () => { - const body = { + const body: MessageCreateParams = { system: [ - { text: "system message 1" }, - { text: "system message 2" }, - { text: "system message 3" }, - { text: "system message 4" }, + { type: "text", text: "system message 1" }, + { type: "text", text: "system message 2" }, + { type: "text", text: "system message 3" }, + { type: "text", text: "system message 4" }, ], - tools: [{ name: "tool1" }, { name: "tool2" }], - messages: [{ content: "user message" }], + tools: [makeTool("tool1"), makeTool("tool2")], + messages: [{ role: "user", content: "user message" }], + ...body_params, }; const result = CACHING_STRATEGIES.systemAndTools(body); expect(result.system).toEqual([ - { text: "system message 1", cache_control: { type: "ephemeral" } }, - { text: "system message 2", cache_control: { type: "ephemeral" } }, - { text: "system message 3", cache_control: { type: "ephemeral" } }, - { text: "system message 4", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message 1", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 2", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 3", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 4", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.tools).toEqual(body.tools); expect(result.messages).toEqual(body.messages); @@ -171,32 +254,45 @@ describe("AnthropicCachingStrategies", () => { describe("optimizedStrategy", () => { it("should cache system messages and tools", () => { - const body = { - system: [{ text: "system message" }], - tools: [{ name: "tool1" }], - messages: [{ content: "short message" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "system message" }], + tools: [makeTool("tool1")], + messages: [{ role: "user", content: "short message" }], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); expect(result.system).toEqual([ - { text: "system message", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.tools).toEqual([ - { name: "tool1", cache_control: { type: "ephemeral" } }, + { + name: "tool1", + input_schema: { + type: "object", + }, + cache_control: { type: "ephemeral" }, + }, ]); }); it("should cache large string messages (>500 tokens)", () => { const largeContent = "a".repeat(2100); // ~525 tokens - const body = { - messages: [{ content: largeContent }], + const body: MessageCreateParams = { + messages: [{ role: "user", content: largeContent }], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); expect(result.messages).toEqual([ { + role: "user", content: [ { type: "text", @@ -210,30 +306,42 @@ describe("AnthropicCachingStrategies", () => { it("should not cache small string messages (<500 tokens)", () => { const smallContent = "a".repeat(100); // ~25 tokens - const body = { - messages: [{ content: smallContent }], + const body: MessageCreateParams = { + messages: [{ role: "user", content: smallContent }], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); - expect(result.messages).toEqual([{ content: smallContent }]); + expect(result.messages).toEqual([ + { role: "user", content: smallContent }, + ]); }); it("should cache large text items in array content but only once per message", () => { const largeText = "a".repeat(2100); // ~525 tokens const anotherLargeText = "b".repeat(2100); // Also ~525 tokens const smallText = "a".repeat(100); // ~25 tokens - const body = { + const body: MessageCreateParams = { messages: [ { + role: "user", content: [ { type: "text", text: largeText }, { type: "text", text: anotherLargeText }, { type: "text", text: smallText }, - { type: "image", data: "image_data" }, + { + type: "image", + source: { + data: "image_data", + media_type: "image/jpeg", + type: "base64", + }, + }, ], }, ], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); @@ -241,6 +349,7 @@ describe("AnthropicCachingStrategies", () => { // Only the first large text item should get cache_control expect(result.messages).toEqual([ { + role: "user", content: [ { type: "text", @@ -249,40 +358,78 @@ describe("AnthropicCachingStrategies", () => { }, { type: "text", text: anotherLargeText }, { type: "text", text: smallText }, - { type: "image", data: "image_data" }, + { + type: "image", + source: { + data: "image_data", + media_type: "image/jpeg", + type: "base64", + }, + }, ], }, ]); }); it("should add maximum 4 cache control blocks", () => { - const body = { - system: [{ text: "system message 1" }, { text: "system message 2" }], - tools: [{ name: "tool" }], + const body: MessageCreateParams = { + system: [ + { type: "text", text: "system message 1" }, + { type: "text", text: "system message 2" }, + ], + tools: [makeTool("tool")], messages: [ - { content: "small content" }, - { content: "a".repeat(2100) }, - { content: "b".repeat(2100) }, + { role: "user", content: "small content" }, + { role: "user", content: "a".repeat(2100) }, + { role: "user", content: "b".repeat(2100) }, { + role: "user", content: [ { type: "text", text: "c".repeat(2100) }, - { type: "image", data: "image" }, + { + type: "image", + source: { + data: "image_data", + media_type: "image/jpeg", + type: "base64", + }, + }, ], }, ], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); expect(result.system).toEqual([ - { text: "system message 1", cache_control: { type: "ephemeral" } }, - { text: "system message 2", cache_control: { type: "ephemeral" } }, + { + type: "text", + text: "system message 1", + cache_control: { type: "ephemeral" }, + }, + { + type: "text", + text: "system message 2", + cache_control: { type: "ephemeral" }, + }, ]); expect(result.tools).toEqual([ - { name: "tool", cache_control: { type: "ephemeral" } }, + { + name: "tool", + input_schema: { + type: "object", + }, + cache_control: { type: "ephemeral" }, + }, ]); - expect(result.messages[0]).toEqual({ content: "small content" }); + expect(result.messages[0]).toEqual({ + role: "user", + content: "small content", + }); + expect(result.messages[1]).toEqual({ + role: "user", content: [ { type: "text", @@ -296,31 +443,50 @@ describe("AnthropicCachingStrategies", () => { }); it("should handle complex message structure", () => { - const body = { - system: [{ text: "system" }], - tools: [{ name: "tool" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "system" }], + tools: [makeTool("tool")], messages: [ - { content: "small content" }, - { content: "a".repeat(2100) }, // large content + { role: "user", content: "small content" }, + { role: "user", content: "a".repeat(2100) }, // large content { + role: "user", content: [ { type: "text", text: "a".repeat(2100) }, // large text - { type: "image", data: "image" }, + { + type: "image", + source: { + data: "image_data", + media_type: "image/jpeg", + type: "base64", + }, + }, ], }, ], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); expect(result.system).toEqual([ - { text: "system", cache_control: { type: "ephemeral" } }, + { type: "text", text: "system", cache_control: { type: "ephemeral" } }, ]); expect(result.tools).toEqual([ - { name: "tool", cache_control: { type: "ephemeral" } }, + { + name: "tool", + input_schema: { + type: "object", + }, + cache_control: { type: "ephemeral" }, + }, ]); - expect(result.messages[0]).toEqual({ content: "small content" }); + expect(result.messages[0]).toEqual({ + role: "user", + content: "small content", + }); expect(result.messages[1]).toEqual({ + role: "user", content: [ { type: "text", @@ -337,30 +503,17 @@ describe("AnthropicCachingStrategies", () => { }); it("should handle empty or missing messages", () => { - const body = { - system: [{ text: "system" }], + const body: MessageCreateParams = { + system: [{ type: "text", text: "system" }], + messages: [], + ...body_params, }; const result = CACHING_STRATEGIES.optimized(body); expect(result.system).toEqual([ - { text: "system", cache_control: { type: "ephemeral" } }, + { type: "text", text: "system", cache_control: { type: "ephemeral" } }, ]); - expect(result.messages).toBeUndefined(); - }); - - it("should handle non-array messages", () => { - const body = { - system: [{ text: "system" }], - messages: "not an array", - }; - - const result = CACHING_STRATEGIES.optimized(body); - - expect(result.system).toEqual([ - { text: "system", cache_control: { type: "ephemeral" } }, - ]); - expect(result.messages).toBe("not an array"); }); }); @@ -370,8 +523,14 @@ describe("AnthropicCachingStrategies", () => { const smallContent = "a".repeat(100); // ~25 tokens const largeContent = "a".repeat(2100); // ~525 tokens - const bodySmall = { messages: [{ content: smallContent }] }; - const bodyLarge = { messages: [{ content: largeContent }] }; + const bodySmall: MessageCreateParams = { + messages: [{ role: "user", content: smallContent }], + ...body_params, + }; + const bodyLarge: MessageCreateParams = { + messages: [{ role: "user", content: largeContent }], + ...body_params, + }; const resultSmall = CACHING_STRATEGIES.optimized(bodySmall); const resultLarge = CACHING_STRATEGIES.optimized(bodyLarge); @@ -429,21 +588,6 @@ describe("AnthropicCachingStrategies", () => { }); }); }); - - describe("CachingStrategy type", () => { - it("should accept valid caching strategy functions", () => { - const customStrategy: CachingStrategy = (body) => ({ - ...body, - custom: true, - }); - - const input = { test: "value" }; - const result = customStrategy(input); - - expect(result).toEqual({ test: "value", custom: true }); - }); - }); - describe("CachingStrategyName type", () => { it("should work with valid strategy names", () => { const strategyNames: CachingStrategyName[] = [ diff --git a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts index 4b4ac49d0..b9a690d0d 100644 --- a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts +++ b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts @@ -1,21 +1,25 @@ +import { MessageCreateParams } from "@anthropic-ai/sdk/resources"; + const MAX_CACHING_MESSAGES = 4; // Caching strategy type - transforms a clean Anthropic body by adding cache_control -export type CachingStrategy = (anthropicBody: any) => any; +export type CachingStrategy = ( + anthropicBody: MessageCreateParams, +) => MessageCreateParams; // Utility function to estimate token count const estimateTokenCount = (text: string): number => Math.ceil(text.length / 4); -// Strategy 1: No Caching (Baseline) +// Strategy 1: No Caching const noCachingStrategy: CachingStrategy = (body) => body; -// Strategy 2: System Messages Only (Current Implementation) +// Strategy 2: System Messages Only const systemOnlyStrategy: CachingStrategy = (body) => { let availableCacheMessages = MAX_CACHING_MESSAGES; if (body.system && Array.isArray(body.system)) { return { ...body, - system: body.system.map((item: any) => { + system: body.system.map((item) => { if (availableCacheMessages > 0) { availableCacheMessages -= 1; return { @@ -37,7 +41,7 @@ const systemAndToolsStrategy: CachingStrategy = (body) => { // Cache system messages if (result.system && Array.isArray(result.system)) { - result.system = result.system.map((item: any) => { + result.system = result.system.map((item) => { if (availableCacheMessages > 0) { availableCacheMessages -= 1; return { @@ -51,8 +55,8 @@ const systemAndToolsStrategy: CachingStrategy = (body) => { // Cache tool definitions if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) { - result.tools = result.tools.map((tool: any, index: number) => { - if (index === result.tools.length - 1 && availableCacheMessages > 0) { + result.tools = result.tools.map((tool, index: number) => { + if (index === result.tools!.length - 1 && availableCacheMessages > 0) { availableCacheMessages -= 1; return { ...tool, @@ -73,7 +77,7 @@ const optimizedStrategy: CachingStrategy = (body) => { // Always cache system messages if (result.system && Array.isArray(result.system)) { - result.system = result.system.map((item: any) => { + result.system = result.system.map((item) => { if (availableCacheMessages > 0) { availableCacheMessages -= 1; return { @@ -87,8 +91,8 @@ const optimizedStrategy: CachingStrategy = (body) => { // Cache tool definitions if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) { - result.tools = result.tools.map((tool: any, index: number) => { - if (index === result.tools.length - 1 && availableCacheMessages > 0) { + result.tools = result.tools.map((tool, index: number) => { + if (index === result.tools!.length - 1 && availableCacheMessages > 0) { availableCacheMessages -= 1; return { ...tool, @@ -101,7 +105,7 @@ const optimizedStrategy: CachingStrategy = (body) => { // Cache large messages (>500 tokens) if (result.messages && Array.isArray(result.messages)) { - result.messages = result.messages.map((message: any) => { + result.messages = result.messages.map((message) => { if (message.content && typeof message.content === "string") { const tokens = estimateTokenCount(message.content); if (tokens > 500 && availableCacheMessages > 0) { @@ -112,7 +116,7 @@ const optimizedStrategy: CachingStrategy = (body) => { { type: "text", text: message.content, - cache_control: { type: "ephemeral" }, + cache_control: { type: "ephemeral" as const }, }, ], }; @@ -120,7 +124,7 @@ const optimizedStrategy: CachingStrategy = (body) => { } else if (message.content && Array.isArray(message.content)) { // Only add one cache control per message with array content let addedCacheControl = false; - const updatedContent = message.content.map((item: any) => { + const updatedContent = message.content.map((item) => { if (item.type === "text" && item.text) { const tokens = estimateTokenCount(item.text); if ( @@ -132,7 +136,7 @@ const optimizedStrategy: CachingStrategy = (body) => { addedCacheControl = true; return { ...item, - cache_control: { type: "ephemeral" }, + cache_control: { type: "ephemeral" as const }, }; } } diff --git a/packages/openai-adapters/src/apis/AnthropicUtils.ts b/packages/openai-adapters/src/apis/AnthropicUtils.ts new file mode 100644 index 000000000..cc0df5ee0 --- /dev/null +++ b/packages/openai-adapters/src/apis/AnthropicUtils.ts @@ -0,0 +1,139 @@ +import { + Base64ImageSource, + ErrorResponse, + MessageParam, + Tool, + ToolChoice, +} from "@anthropic-ai/sdk/resources"; +import { + ChatCompletionTool, + ChatCompletionToolChoiceOption, +} from "openai/resources"; + +export function getAnthropicErrorMessage(response: ErrorResponse): string { + switch (response.error.type) { + case "api_error": + return "An unexpected error has occurred internal to Anthropic's systems."; + case "invalid_request_error": + return "There was an issue with the format or content of your request."; + case "authentication_error": + return "There's an issue with your API key."; + case "permission_error": + return "Your API key does not have permission to use the specified resource."; + case "not_found_error": + return "The requested resource was not found."; + case "rate_limit_error": + return "Your account has hit a rate limit."; + case "overloaded_error": + return "Anthropic's API is temporarily overloaded. Please check their status page: https://status.anthropic.com/#past-incidents"; + case "timeout_error": + return "Anthropic API timed out. Please check their status page: https://status.anthropic.com/#past-incidents"; + case "billing_error": + default: + return response.error.message; + } +} + +export function getAnthropicHeaders( + apiKey: string, + enableCaching: boolean, +): Record { + const headers: Record = { + "Content-Type": "application/json", + Accept: "application/json", + "anthropic-version": "2023-06-01", + "x-api-key": apiKey, + }; + + if (enableCaching) { + headers["anthropic-beta"] = "prompt-caching-2024-07-31"; + } + return headers; +} + +export function addCacheControlToLastTwoUserMessages(messages: MessageParam[]) { + let userMessages = 0; + for (let i = messages.length - 1; i >= 0; i--) { + const msg = messages[i]; + if (msg.role === "user") { + userMessages++; + if (typeof msg.content === "string") { + continue; + } + for (let j = msg.content.length - 1; j >= 0; j--) { + const part = msg.content[j]; + if (part.type === "text") { + part.cache_control = { type: "ephemeral" }; + break; + } + } + if (userMessages >= 2) { + break; + } + } + } +} + +export function openAiToolChoiceToAnthropicToolChoice( + toolChoice: ChatCompletionToolChoiceOption | undefined, +): ToolChoice | undefined { + if (!toolChoice) { + return undefined; + } + switch (toolChoice) { + case "none": + // "none" is handled by excluding tools + return undefined; + case "required": + return { + type: "any", + }; + case "auto": + return { + type: "auto", + }; + default: + switch (toolChoice.type) { + case "allowed_tools": + // Filtering of tools is handled elsewhere + return { + type: toolChoice.allowed_tools.mode === "auto" ? "auto" : "any", + }; + case "custom": + return undefined; // TODO not supported yet + case "function": + return { + type: "tool", + name: toolChoice.function.name, + }; + } + } +} + +export function openaiToolToAnthropicTool(tool: ChatCompletionTool): Tool { + if (tool.type === "function" && "function" in tool) { + return { + name: tool.function.name, + description: tool.function.description, + input_schema: tool.function.parameters as Tool.InputSchema, // TODO unsafe cast, may be differences between openai tool schema and anthropic tool schema, + }; + } else { + throw new Error(`Unsupported tool type in Anthropic: ${tool.type}`); + } +} + +// Extract media type from data URL (ex. "data:image/png;base64,..." -> "image/png") +export function getAnthropicMediaTypeFromDataUrl( + dataUrl: string, +): Base64ImageSource["media_type"] { + const match = dataUrl.match(/^data:([^;]+);base64,/); + if (match) { + switch (match[1]) { + case "image/png": + case "image/gif": + case "image/webp": + return match[1]; + } + } + return "image/jpeg"; +} diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index a8b85a4aa..ff4722e89 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -177,3 +177,10 @@ export { // export export type { BaseLlmApi } from "./apis/base.js"; export type { LLMConfig } from "./types.js"; + +export { + addCacheControlToLastTwoUserMessages, + getAnthropicErrorMessage, + getAnthropicHeaders, + getAnthropicMediaTypeFromDataUrl, +} from "./apis/AnthropicUtils.js"; diff --git a/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts b/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts index 6e875efe0..859bcab02 100644 --- a/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts +++ b/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts @@ -50,7 +50,17 @@ describe("Anthropic Adapter Tests", () => { "x-api-key": "test-api-key", }, body: { - messages: [{ role: "user", content: "hello" }], + messages: [ + { + role: "user", + content: [ + { + type: "text", + text: "hello", + }, + ], + }, + ], system: undefined, model: "claude-3-5-sonnet-20241022", max_tokens: 32000, @@ -104,7 +114,17 @@ describe("Anthropic Adapter Tests", () => { "x-api-key": "test-api-key", }, body: { - messages: [{ role: "user", content: "hello" }], + messages: [ + { + role: "user", + content: [ + { + type: "text", + text: "hello", + }, + ], + }, + ], system: undefined, model: "claude-3-5-sonnet-20241022", max_tokens: 32000, @@ -159,7 +179,17 @@ describe("Anthropic Adapter Tests", () => { "x-api-key": "test-api-key", }, body: { - messages: [{ role: "user", content: "hello" }], + messages: [ + { + role: "user", + content: [ + { + type: "text", + text: "hello", + }, + ], + }, + ], system: [ { type: "text",