Changesets · Branches · Tags · Compare
| Changeset | d04f16ee25ad2d27bcb09dbdd06567f7920e7ff163ba00ade1562c15d17c2bba |
|---|---|
| Author | Dallin Romney <dallinromney@gmail.com> · 2025-09-24 12:57 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-09-24 12:57 -07:00 |
| Parents | 78ceb4f611b1 |
15 files changed
modified core/llm/constants.ts +2 −0
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | const DEFAULT_CONTEXT_LENGTH = 32_768; |
| 3 | 3 | const DEFAULT_TEMPERATURE = 0.5; |
| 4 | 4 | const DEFAULT_PRUNING_LENGTH = 128000; |
| 5 | +const DEFAULT_REASONING_TOKENS = 2048; | |
| 5 | 6 | |
| 6 | 7 | const DEFAULT_ARGS = { |
| 7 | 8 | maxTokens: DEFAULT_MAX_TOKENS, |
| @@ -31,5 +32,6 @@ | ||
| 31 | 32 | DEFAULT_MAX_CHUNK_SIZE, |
| 32 | 33 | DEFAULT_MAX_TOKENS, |
| 33 | 34 | DEFAULT_PRUNING_LENGTH, |
| 35 | + DEFAULT_REASONING_TOKENS, | |
| 34 | 36 | PROXY_URL, |
| 35 | 37 | }; |
modified core/llm/index.ts +8 −7
| @@ -65,7 +65,6 @@ | ||
| 65 | 65 | toCompleteBody, |
| 66 | 66 | toFimBody, |
| 67 | 67 | } from "./openaiTypeConverters.js"; |
| 68 | - | |
| 69 | 68 | export class LLMError extends Error { |
| 70 | 69 | constructor( |
| 71 | 70 | message: string, |
| @@ -558,12 +557,14 @@ | ||
| 558 | 557 | private _formatChatMessage(msg: ChatMessage): string { |
| 559 | 558 | let contentToShow = renderChatMessage(msg); |
| 560 | 559 | if (msg.role === "assistant" && msg.toolCalls?.length) { |
| 561 | - contentToShow += msg.toolCalls | |
| 562 | - ?.map( | |
| 563 | - (toolCall) => | |
| 564 | - `${toolCall.function?.name}(${toolCall.function?.arguments})`, | |
| 565 | - ) | |
| 566 | - .join("\n"); | |
| 560 | + contentToShow += | |
| 561 | + "\n" + | |
| 562 | + msg.toolCalls | |
| 563 | + ?.map( | |
| 564 | + (toolCall) => | |
| 565 | + `${toolCall.function?.name}(${toolCall.function?.arguments})`, | |
| 566 | + ) | |
| 567 | + .join("\n"); | |
| 567 | 568 | } |
| 568 | 569 | |
| 569 | 570 | return `<${msg.role}>\n${contentToShow}\n\n`; |
modified core/llm/llm-pre-fetch.vitest.ts +4 −0
| @@ -58,6 +58,10 @@ | ||
| 58 | 58 | describe("LLM Pre-fetch", () => { |
| 59 | 59 | beforeEach(() => { |
| 60 | 60 | vi.resetAllMocks(); |
| 61 | + // Mock getAnthropicHeaders to return fake headers | |
| 62 | + vi.mocked(openAiAdapters.getAnthropicHeaders).mockReturnValue({ | |
| 63 | + fake: "headers", | |
| 64 | + }); | |
| 61 | 65 | // Log to verify the mock is properly set up |
| 62 | 66 | console.log("Mock setup:", openAiAdapters); |
| 63 | 67 | }); |
modified core/llm/llms/Anthropic.ts +224 −194
| @@ -1,30 +1,36 @@ | ||
| 1 | +import { | |
| 2 | + Tool as AnthropicTool, | |
| 3 | + ContentBlockParam, | |
| 4 | + MessageCreateParams, | |
| 5 | + MessageParam, | |
| 6 | + RawContentBlockDeltaEvent, | |
| 7 | + RawContentBlockStartEvent, | |
| 8 | + RawMessageDeltaEvent, | |
| 9 | + RawMessageStartEvent, | |
| 10 | + RawMessageStreamEvent, | |
| 11 | + ToolUseBlock, | |
| 12 | +} from "@anthropic-ai/sdk/resources/messages.mjs"; | |
| 1 | 13 | import { streamSse } from "@continuedev/fetch"; |
| 14 | +import { | |
| 15 | + addCacheControlToLastTwoUserMessages, | |
| 16 | + getAnthropicErrorMessage, | |
| 17 | + getAnthropicHeaders, | |
| 18 | + getAnthropicMediaTypeFromDataUrl, | |
| 19 | +} from "@continuedev/openai-adapters"; | |
| 2 | 20 | import { |
| 3 | 21 | ChatMessage, |
| 4 | 22 | CompletionOptions, |
| 5 | 23 | LLMOptions, |
| 24 | + MessageContent, | |
| 25 | + Tool, | |
| 26 | + ToolCallDelta, | |
| 6 | 27 | Usage, |
| 7 | 28 | } from "../../index.js"; |
| 8 | 29 | import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; |
| 9 | 30 | import { renderChatMessage, stripImages } from "../../util/messageContent.js"; |
| 31 | +import { DEFAULT_REASONING_TOKENS } from "../constants.js"; | |
| 10 | 32 | import { BaseLLM } from "../index.js"; |
| 11 | 33 | |
| 12 | -const errorMessages = { | |
| 13 | - invalid_request_error: | |
| 14 | - "There was an issue with the format or content of your request.", | |
| 15 | - authentication_error: "There's an issue with your API key.", | |
| 16 | - permission_error: | |
| 17 | - "Your API key does not have permission to use the specified resource.", | |
| 18 | - not_found_error: "The requested resource was not found.", | |
| 19 | - request_too_large: | |
| 20 | - "Request exceeds the maximum allowed number of bytes (32 MB limit).", | |
| 21 | - rate_limit_error: "Your account has hit a rate limit.", | |
| 22 | - api_error: | |
| 23 | - "An unexpected error has occurred internal to Anthropic's systems.", | |
| 24 | - overloaded_error: | |
| 25 | - "Anthropic's API is temporarily overloaded. Please check their status page: https://status.anthropic.com/#past-incidents", | |
| 26 | -}; | |
| 27 | - | |
| 28 | 34 | class Anthropic extends BaseLLM { |
| 29 | 35 | static providerName = "anthropic"; |
| 30 | 36 | static defaultOptions: Partial<LLMOptions> = { |
| @@ -36,8 +42,21 @@ | ||
| 36 | 42 | apiBase: "https://api.anthropic.com/v1/", |
| 37 | 43 | }; |
| 38 | 44 | |
| 39 | - public convertArgs(options: CompletionOptions) { | |
| 40 | - // should be public for use within VertexAI | |
| 45 | + private convertToolToAnthropicTool(tool: Tool): AnthropicTool { | |
| 46 | + return { | |
| 47 | + name: tool.function.name, | |
| 48 | + description: tool.function.description, | |
| 49 | + input_schema: (tool.function.parameters as AnthropicTool.InputSchema) ?? { | |
| 50 | + // TODO unsafe tool.function.parameters casting | |
| 51 | + type: "object", | |
| 52 | + }, | |
| 53 | + }; | |
| 54 | + } | |
| 55 | + | |
| 56 | + // Public for use within VertexAI | |
| 57 | + public convertArgs( | |
| 58 | + options: CompletionOptions, | |
| 59 | + ): Omit<MessageCreateParams, "messages"> { | |
| 41 | 60 | const finalOptions = { |
| 42 | 61 | top_k: options.topK, |
| 43 | 62 | top_p: options.topP, |
| @@ -46,20 +65,17 @@ | ||
| 46 | 65 | model: options.model === "claude-2" ? "claude-2.1" : options.model, |
| 47 | 66 | stop_sequences: options.stop?.filter((x) => x.trim() !== ""), |
| 48 | 67 | stream: options.stream ?? true, |
| 49 | - tools: options.tools?.map((tool) => ({ | |
| 50 | - name: tool.function.name, | |
| 51 | - description: tool.function.description, | |
| 52 | - input_schema: tool.function.parameters, | |
| 53 | - })), | |
| 68 | + tools: options.tools?.map(this.convertToolToAnthropicTool), | |
| 54 | 69 | thinking: options.reasoning |
| 55 | 70 | ? { |
| 56 | - type: "enabled", | |
| 57 | - budget_tokens: options.reasoningBudgetTokens, | |
| 71 | + type: "enabled" as const, | |
| 72 | + budget_tokens: | |
| 73 | + options.reasoningBudgetTokens ?? DEFAULT_REASONING_TOKENS, | |
| 58 | 74 | } |
| 59 | 75 | : undefined, |
| 60 | 76 | tool_choice: options.toolChoice |
| 61 | 77 | ? { |
| 62 | - type: "tool", | |
| 78 | + type: "tool" as const, | |
| 63 | 79 | name: options.toolChoice.function.name, |
| 64 | 80 | } |
| 65 | 81 | : undefined, |
| @@ -68,138 +84,146 @@ | ||
| 68 | 84 | return finalOptions; |
| 69 | 85 | } |
| 70 | 86 | |
| 71 | - private buildTextPart(text: string, addCaching: boolean) { | |
| 72 | - const part: any = { | |
| 73 | - type: "text", | |
| 74 | - text, | |
| 75 | - }; | |
| 76 | - if (addCaching) { | |
| 77 | - part.cache_control = { type: "ephemeral" }; | |
| 87 | + private convertMessageContentToBlocks( | |
| 88 | + content: MessageContent, | |
| 89 | + ): ContentBlockParam[] { | |
| 90 | + if (typeof content === "string") { | |
| 91 | + return [ | |
| 92 | + { | |
| 93 | + type: "text", | |
| 94 | + text: content, | |
| 95 | + }, | |
| 96 | + ]; | |
| 78 | 97 | } |
| 79 | - return part; | |
| 98 | + return content.map((part) => { | |
| 99 | + if (part.type === "text") { | |
| 100 | + return { | |
| 101 | + type: "text", | |
| 102 | + text: part.text, | |
| 103 | + }; | |
| 104 | + } | |
| 105 | + return { | |
| 106 | + type: "image", | |
| 107 | + source: { | |
| 108 | + type: "base64", | |
| 109 | + media_type: getAnthropicMediaTypeFromDataUrl(part.imageUrl.url), | |
| 110 | + data: part.imageUrl.url.split(",")[1], | |
| 111 | + }, | |
| 112 | + }; | |
| 113 | + }); | |
| 80 | 114 | } |
| 81 | 115 | |
| 82 | - private convertMessage(message: ChatMessage, addCaching: boolean): any { | |
| 83 | - if (message.role === "tool") { | |
| 116 | + private convertToolCallsToBlocks( | |
| 117 | + toolCall: ToolCallDelta, | |
| 118 | + ): ToolUseBlock | undefined { | |
| 119 | + const toolCallId = toolCall.id; | |
| 120 | + const toolName = toolCall.function?.name; | |
| 121 | + if (toolCallId && toolName) { | |
| 84 | 122 | return { |
| 85 | - role: "user", | |
| 86 | - content: [ | |
| 123 | + type: "tool_use", | |
| 124 | + id: toolCallId, | |
| 125 | + name: toolName, | |
| 126 | + input: safeParseToolCallArgs(toolCall), | |
| 127 | + }; | |
| 128 | + } | |
| 129 | + } | |
| 130 | + | |
| 131 | + private getContentBlocksFromChatMessage( | |
| 132 | + message: ChatMessage, | |
| 133 | + ): ContentBlockParam[] { | |
| 134 | + switch (message.role) { | |
| 135 | + // One tool message = one tool_result block | |
| 136 | + case "tool": | |
| 137 | + return [ | |
| 87 | 138 | { |
| 88 | 139 | type: "tool_result", |
| 89 | 140 | tool_use_id: message.toolCallId, |
| 90 | 141 | content: renderChatMessage(message) || undefined, |
| 91 | 142 | }, |
| 92 | - ], | |
| 93 | - }; | |
| 94 | - } else if (message.role === "assistant" && message.toolCalls) { | |
| 95 | - const parts: any[] = []; | |
| 96 | - if (message.content) { | |
| 143 | + ]; | |
| 144 | + case "user": | |
| 145 | + return this.convertMessageContentToBlocks(message.content); | |
| 146 | + case "thinking": | |
| 147 | + if (message.redactedThinking) { | |
| 148 | + return [ | |
| 149 | + { | |
| 150 | + type: "redacted_thinking", | |
| 151 | + data: message.redactedThinking, | |
| 152 | + }, | |
| 153 | + ]; | |
| 154 | + } | |
| 97 | 155 | if (typeof message.content === "string") { |
| 98 | - parts.push(this.buildTextPart(message.content, addCaching)); | |
| 99 | - } else if (message.content.length > 0) { | |
| 100 | - const textContent = message.content.filter((p) => p.type === "text"); | |
| 101 | - const textParts = textContent.map((part, idx) => { | |
| 102 | - const cache = idx === textContent.length - 1 && addCaching; | |
| 103 | - return this.buildTextPart(part.text, cache); | |
| 104 | - }); | |
| 105 | - parts.push(...textParts); | |
| 156 | + return [ | |
| 157 | + { | |
| 158 | + type: "thinking", | |
| 159 | + thinking: message.content, | |
| 160 | + signature: message.signature ?? "", // TODO - unsafe signature | |
| 161 | + }, | |
| 162 | + ]; | |
| 106 | 163 | } |
| 107 | - } | |
| 108 | - parts.push( | |
| 109 | - ...message.toolCalls.map((toolCall) => ({ | |
| 110 | - type: "tool_use", | |
| 111 | - id: toolCall.id, | |
| 112 | - name: toolCall.function?.name, | |
| 113 | - input: safeParseToolCallArgs(toolCall), | |
| 114 | - })), | |
| 115 | - ); | |
| 116 | - return { | |
| 117 | - role: "assistant", | |
| 118 | - content: parts, | |
| 119 | - }; | |
| 120 | - } else if (message.role === "thinking" && !message.redactedThinking) { | |
| 121 | - return { | |
| 122 | - role: "assistant", | |
| 123 | - content: [ | |
| 124 | - { | |
| 125 | - type: "thinking", | |
| 126 | - thinking: message.content, | |
| 127 | - signature: message.signature, | |
| 128 | - }, | |
| 129 | - ], | |
| 130 | - }; | |
| 131 | - } else if (message.role === "thinking" && message.redactedThinking) { | |
| 132 | - return { | |
| 133 | - role: "assistant", | |
| 134 | - content: [ | |
| 135 | - { | |
| 136 | - type: "redacted_thinking", | |
| 137 | - data: message.redactedThinking, | |
| 138 | - }, | |
| 139 | - ], | |
| 140 | - }; | |
| 164 | + const textParts = message.content.filter((p) => p.type === "text"); | |
| 165 | + return textParts.map((part) => ({ | |
| 166 | + type: "thinking", | |
| 167 | + thinking: part.text, | |
| 168 | + signature: message.signature ?? "", // TODO - unsafe signature | |
| 169 | + })); | |
| 170 | + case "assistant": | |
| 171 | + const blocks: ContentBlockParam[] = this.convertMessageContentToBlocks( | |
| 172 | + message.content, | |
| 173 | + ); | |
| 174 | + // If any tool calls are present, always put them last | |
| 175 | + // Loses order vs what was originally sent, but they typically come last | |
| 176 | + for (const toolCall of message.toolCalls ?? []) { | |
| 177 | + const block = this.convertToolCallsToBlocks(toolCall); | |
| 178 | + if (block) { | |
| 179 | + blocks.push(block); | |
| 180 | + } | |
| 181 | + } | |
| 182 | + return blocks; | |
| 183 | + // system, etc. | |
| 184 | + default: | |
| 185 | + return []; | |
| 141 | 186 | } |
| 187 | + } | |
| 142 | 188 | |
| 143 | - if (typeof message.content === "string") { | |
| 144 | - var chatMessage = { | |
| 145 | - role: message.role, | |
| 146 | - content: [ | |
| 147 | - { | |
| 148 | - type: "text", | |
| 149 | - text: message.content, | |
| 150 | - ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}), | |
| 151 | - }, | |
| 152 | - ], | |
| 153 | - }; | |
| 154 | - return chatMessage; | |
| 189 | + public convertMessages( | |
| 190 | + msgs: ChatMessage[], | |
| 191 | + cachePrompt: boolean, | |
| 192 | + ): MessageParam[] { | |
| 193 | + const nonSystemMessages = msgs.filter((m) => m.role !== "system"); | |
| 194 | + | |
| 195 | + const convertedMessages: MessageParam[] = []; | |
| 196 | + let currentRole: "user" | "assistant" | undefined = undefined; | |
| 197 | + let currentParts: ContentBlockParam[] = []; | |
| 198 | + | |
| 199 | + const flushCurrentMessage = () => { | |
| 200 | + if (currentRole && currentParts.length > 0) { | |
| 201 | + convertedMessages.push({ | |
| 202 | + role: currentRole, | |
| 203 | + content: currentParts, | |
| 204 | + }); | |
| 205 | + currentParts = []; | |
| 206 | + } | |
| 207 | + }; | |
| 208 | + | |
| 209 | + for (const message of nonSystemMessages) { | |
| 210 | + const newRole = | |
| 211 | + message.role === "user" || message.role === "tool" | |
| 212 | + ? "user" | |
| 213 | + : "assistant"; | |
| 214 | + if (currentRole !== newRole) { | |
| 215 | + flushCurrentMessage(); | |
| 216 | + currentRole = newRole; | |
| 217 | + } | |
| 218 | + currentParts.push(...this.getContentBlocksFromChatMessage(message)); | |
| 155 | 219 | } |
| 220 | + flushCurrentMessage(); | |
| 156 | 221 | |
| 157 | - return { | |
| 158 | - role: message.role, | |
| 159 | - content: message.content.map((part, contentIdx) => { | |
| 160 | - if (part.type === "text") { | |
| 161 | - const newpart = { | |
| 162 | - ...part, | |
| 163 | - // If multiple text parts, only add cache_control to the last one | |
| 164 | - ...(addCaching && contentIdx === message.content.length - 1 | |
| 165 | - ? { cache_control: { type: "ephemeral" } } | |
| 166 | - : {}), | |
| 167 | - }; | |
| 168 | - return newpart; | |
| 169 | - } | |
| 170 | - return { | |
| 171 | - type: "image", | |
| 172 | - source: { | |
| 173 | - type: "base64", | |
| 174 | - media_type: "image/jpeg", | |
| 175 | - data: part.imageUrl?.url.split(",")[1], | |
| 176 | - }, | |
| 177 | - }; | |
| 178 | - }), | |
| 179 | - }; | |
| 180 | - } | |
| 222 | + if (cachePrompt) { | |
| 223 | + addCacheControlToLastTwoUserMessages(convertedMessages); | |
| 224 | + } | |
| 181 | 225 | |
| 182 | - public convertMessages(msgs: ChatMessage[]): any[] { | |
| 183 | - // should be public for use within VertexAI | |
| 184 | - const filteredmessages = msgs.filter((m) => m.role !== "system"); | |
| 185 | - const lastTwoUserMsgIndices = filteredmessages | |
| 186 | - .map((msg, index) => (msg.role === "user" ? index : -1)) | |
| 187 | - .filter((index) => index !== -1) | |
| 188 | - .slice(-2); | |
| 189 | - | |
| 190 | - const messages = filteredmessages.map((message, filteredMsgIdx) => { | |
| 191 | - // Add cache_control parameter to the last two user messages | |
| 192 | - // The second-to-last because it retrieves potentially already cached contents, | |
| 193 | - // The last one because we want it cached for later retrieval. | |
| 194 | - // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching | |
| 195 | - const addCaching = | |
| 196 | - this.cacheBehavior?.cacheConversation && | |
| 197 | - lastTwoUserMsgIndices.includes(filteredMsgIdx); | |
| 198 | - | |
| 199 | - const chatMessage = this.convertMessage(message, !!addCaching); | |
| 200 | - return chatMessage; | |
| 201 | - }); | |
| 202 | - return messages; | |
| 226 | + return convertedMessages; | |
| 203 | 227 | } |
| 204 | 228 | |
| 205 | 229 | protected async *_streamComplete( |
| @@ -224,12 +248,7 @@ | ||
| 224 | 248 | if (!response.ok) { |
| 225 | 249 | const json = await response.json(); |
| 226 | 250 | if (json.type === "error") { |
| 227 | - if (json.error?.type in errorMessages) { | |
| 228 | - throw new Error( | |
| 229 | - errorMessages[json.error.type as keyof typeof errorMessages], | |
| 230 | - ); | |
| 231 | - } | |
| 232 | - throw new Error(json.message); | |
| 251 | + throw new Error(getAnthropicErrorMessage(json)); | |
| 233 | 252 | } |
| 234 | 253 | throw new Error( |
| 235 | 254 | `Anthropic API sent back ${response.status}: ${JSON.stringify(json)}`, |
| @@ -237,17 +256,17 @@ | ||
| 237 | 256 | } |
| 238 | 257 | |
| 239 | 258 | if (stream === false) { |
| 240 | - const data = await response.json(); | |
| 241 | - const cost = data.usage | |
| 259 | + const json = await response.json(); | |
| 260 | + const cost = json.usage | |
| 242 | 261 | ? { |
| 243 | - inputTokens: data.usage.input_tokens, | |
| 244 | - outputTokens: data.usage.output_tokens, | |
| 245 | - totalTokens: data.usage.input_tokens + data.usage.output_tokens, | |
| 262 | + inputTokens: json.usage.input_tokens, | |
| 263 | + outputTokens: json.usage.output_tokens, | |
| 264 | + totalTokens: json.usage.input_tokens + json.usage.output_tokens, | |
| 246 | 265 | } |
| 247 | 266 | : {}; |
| 248 | 267 | yield { |
| 249 | 268 | role: "assistant", |
| 250 | - content: data.content[0].text, | |
| 269 | + content: json.content[0].text, | |
| 251 | 270 | ...(Object.keys(cost).length > 0 ? { cost } : {}), |
| 252 | 271 | }; |
| 253 | 272 | return; |
| @@ -264,51 +283,59 @@ | ||
| 264 | 283 | }, |
| 265 | 284 | }; |
| 266 | 285 | |
| 267 | - for await (const value of streamSse(response)) { | |
| 286 | + for await (const event of streamSse(response)) { | |
| 268 | 287 | // https://docs.anthropic.com/en/api/messages-streaming#event-types |
| 269 | - switch (value.type) { | |
| 288 | + const rawEvent = event as RawMessageStreamEvent; | |
| 289 | + switch (event.type) { | |
| 270 | 290 | case "message_start": |
| 271 | 291 | // Capture initial usage information |
| 272 | - usage.promptTokens = value.message.usage.input_tokens; | |
| 292 | + const startEvent = rawEvent as RawMessageStartEvent; | |
| 293 | + usage.promptTokens = startEvent.message.usage.input_tokens; | |
| 273 | 294 | usage.promptTokensDetails!.cachedTokens = |
| 274 | - value.message.usage.cache_read_input_tokens; | |
| 295 | + startEvent.message.usage.cache_read_input_tokens ?? undefined; | |
| 275 | 296 | usage.promptTokensDetails!.cacheWriteTokens = |
| 276 | - value.message.usage.cache_creation_input_tokens; | |
| 297 | + startEvent.message.usage.cache_creation_input_tokens ?? undefined; | |
| 277 | 298 | break; |
| 278 | 299 | case "message_delta": |
| 279 | 300 | // Update usage information during streaming |
| 280 | - if (value.usage) { | |
| 281 | - usage.completionTokens = value.usage.output_tokens; | |
| 301 | + const deltaEvent = rawEvent as RawMessageDeltaEvent; | |
| 302 | + if (deltaEvent.usage) { | |
| 303 | + usage.completionTokens = deltaEvent.usage.output_tokens; | |
| 282 | 304 | } |
| 283 | 305 | break; |
| 284 | 306 | case "content_block_start": |
| 285 | - if (value.content_block.type === "tool_use") { | |
| 286 | - lastToolUseId = value.content_block.id; | |
| 287 | - lastToolUseName = value.content_block.name; | |
| 307 | + const blockStartEvent = rawEvent as RawContentBlockStartEvent; | |
| 308 | + if (blockStartEvent.content_block.type === "tool_use") { | |
| 309 | + lastToolUseId = blockStartEvent.content_block.id; | |
| 310 | + lastToolUseName = blockStartEvent.content_block.name; | |
| 288 | 311 | } |
| 289 | 312 | // handle redacted thinking |
| 290 | - if (value.content_block.type === "redacted_thinking") { | |
| 313 | + if (blockStartEvent.content_block.type === "redacted_thinking") { | |
| 291 | 314 | yield { |
| 292 | 315 | role: "thinking", |
| 293 | 316 | content: "", |
| 294 | - redactedThinking: value.content_block.data, | |
| 317 | + redactedThinking: blockStartEvent.content_block.data, | |
| 295 | 318 | }; |
| 296 | 319 | } |
| 297 | 320 | break; |
| 298 | 321 | case "content_block_delta": |
| 299 | 322 | // https://docs.anthropic.com/en/api/messages-streaming#delta-types |
| 300 | - switch (value.delta.type) { | |
| 323 | + const blockDeltaEvent = rawEvent as RawContentBlockDeltaEvent; | |
| 324 | + switch (blockDeltaEvent.delta.type) { | |
| 301 | 325 | case "text_delta": |
| 302 | - yield { role: "assistant", content: value.delta.text }; | |
| 326 | + yield { role: "assistant", content: blockDeltaEvent.delta.text }; | |
| 303 | 327 | break; |
| 304 | 328 | case "thinking_delta": |
| 305 | - yield { role: "thinking", content: value.delta.thinking }; | |
| 329 | + yield { | |
| 330 | + role: "thinking", | |
| 331 | + content: blockDeltaEvent.delta.thinking, | |
| 332 | + }; | |
| 306 | 333 | break; |
| 307 | 334 | case "signature_delta": |
| 308 | 335 | yield { |
| 309 | 336 | role: "thinking", |
| 310 | 337 | content: "", |
| 311 | - signature: value.delta.signature, | |
| 338 | + signature: blockDeltaEvent.delta.signature, | |
| 312 | 339 | }; |
| 313 | 340 | break; |
| 314 | 341 | case "input_json_delta": |
| @@ -324,7 +351,7 @@ | ||
| 324 | 351 | type: "function", |
| 325 | 352 | function: { |
| 326 | 353 | name: lastToolUseName, |
| 327 | - arguments: value.delta.partial_json, | |
| 354 | + arguments: blockDeltaEvent.delta.partial_json, | |
| 328 | 355 | }, |
| 329 | 356 | }, |
| 330 | 357 | ], |
| @@ -365,32 +392,35 @@ | ||
| 365 | 392 | const shouldCacheSystemMessage = !!( |
| 366 | 393 | this.cacheBehavior?.cacheSystemMessage && systemMessage |
| 367 | 394 | ); |
| 395 | + const shouldCachePrompt = !!( | |
| 396 | + this.cacheBehavior?.cacheConversation || | |
| 397 | + this.completionOptions.promptCaching | |
| 398 | + ); | |
| 399 | + | |
| 400 | + const msgs = this.convertMessages(messages, shouldCachePrompt); | |
| 401 | + const headers = getAnthropicHeaders( | |
| 402 | + this.apiKey, | |
| 403 | + shouldCacheSystemMessage || shouldCachePrompt, | |
| 404 | + ); | |
| 405 | + | |
| 406 | + const body: MessageCreateParams = { | |
| 407 | + ...this.convertArgs(options), | |
| 408 | + messages: msgs, | |
| 409 | + system: shouldCacheSystemMessage | |
| 410 | + ? [ | |
| 411 | + { | |
| 412 | + type: "text", | |
| 413 | + text: systemMessage, | |
| 414 | + cache_control: { type: "ephemeral" }, | |
| 415 | + }, | |
| 416 | + ] | |
| 417 | + : systemMessage, | |
| 418 | + }; | |
| 368 | 419 | |
| 369 | - const msgs = this.convertMessages(messages); | |
| 370 | 420 | const response = await this.fetch(new URL("messages", this.apiBase), { |
| 371 | 421 | method: "POST", |
| 372 | - headers: { | |
| 373 | - "Content-Type": "application/json", | |
| 374 | - Accept: "application/json", | |
| 375 | - "anthropic-version": "2023-06-01", | |
| 376 | - "x-api-key": this.apiKey as string, | |
| 377 | - ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation | |
| 378 | - ? { "anthropic-beta": "prompt-caching-2024-07-31" } | |
| 379 | - : {}), | |
| 380 | - }, | |
| 381 | - body: JSON.stringify({ | |
| 382 | - ...this.convertArgs(options), | |
| 383 | - messages: msgs, | |
| 384 | - system: shouldCacheSystemMessage | |
| 385 | - ? [ | |
| 386 | - { | |
| 387 | - type: "text", | |
| 388 | - text: systemMessage, | |
| 389 | - cache_control: { type: "ephemeral" }, | |
| 390 | - }, | |
| 391 | - ] | |
| 392 | - : systemMessage, | |
| 393 | - }), | |
| 422 | + headers, | |
| 423 | + body: JSON.stringify(body), | |
| 394 | 424 | signal, |
| 395 | 425 | }); |
| 396 | 426 |
modified core/llm/llms/VertexAI.ts +9 −2
| @@ -223,6 +223,10 @@ | ||
| 223 | 223 | const shouldCacheSystemMessage = !!( |
| 224 | 224 | this.cacheBehavior?.cacheSystemMessage && systemMessage |
| 225 | 225 | ); |
| 226 | + const shouldCachePrompt = !!( | |
| 227 | + this.cacheBehavior?.cacheConversation ?? | |
| 228 | + this.completionOptions.promptCaching | |
| 229 | + ); | |
| 226 | 230 | |
| 227 | 231 | // <code>/v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict |
| 228 | 232 | |
| @@ -234,13 +238,16 @@ | ||
| 234 | 238 | const response = await this.fetch(apiURL, { |
| 235 | 239 | method: "POST", |
| 236 | 240 | headers: { |
| 237 | - ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation | |
| 241 | + ...(shouldCacheSystemMessage || shouldCachePrompt | |
| 238 | 242 | ? { "anthropic-beta": "prompt-caching-2024-07-31" } |
| 239 | 243 | : {}), |
| 240 | 244 | }, |
| 241 | 245 | body: JSON.stringify({ |
| 242 | 246 | ...this._anthropicConvertArgs(options), |
| 243 | - messages: this.anthropicInstance.convertMessages(messages), | |
| 247 | + messages: this.anthropicInstance.convertMessages( | |
| 248 | + messages, | |
| 249 | + shouldCachePrompt, | |
| 250 | + ), | |
| 244 | 251 | system: shouldCacheSystemMessage |
| 245 | 252 | ? [ |
| 246 | 253 | { |
modified core/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified core/package.json +1 −0
| @@ -54,6 +54,7 @@ | ||
| 54 | 54 | "vitest": "^3.1.4" |
| 55 | 55 | }, |
| 56 | 56 | "dependencies": { |
| 57 | + "@anthropic-ai/sdk": "^0.62.0", | |
| 57 | 58 | "@aws-sdk/client-bedrock-runtime": "^3.779.0", |
| 58 | 59 | "@aws-sdk/client-sagemaker-runtime": "^3.777.0", |
| 59 | 60 | "@aws-sdk/credential-providers": "^3.778.0", |
modified packages/openai-adapters/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified packages/openai-adapters/package.json +1 −0
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | "author": "Nate Sesti and Ty Dunn", |
| 13 | 13 | "license": "Apache-2.0", |
| 14 | 14 | "dependencies": { |
| 15 | + "@anthropic-ai/sdk": "^0.62.0", | |
| 15 | 16 | "@aws-sdk/client-bedrock-runtime": "^3.842.0", |
| 16 | 17 | "@aws-sdk/credential-providers": "^3.840.0", |
| 17 | 18 | "@continuedev/config-types": "^1.0.14", |
modified packages/openai-adapters/src/apis/Anthropic.ts +225 −152
| @@ -1,8 +1,22 @@ | ||
| 1 | +import { | |
| 2 | + ContentBlockParam, | |
| 3 | + MessageCreateParams, | |
| 4 | + MessageParam, | |
| 5 | + RawContentBlockDeltaEvent, | |
| 6 | + RawContentBlockStartEvent, | |
| 7 | + RawMessageDeltaEvent, | |
| 8 | + RawMessageStartEvent, | |
| 9 | + RawMessageStreamEvent, | |
| 10 | + Tool, | |
| 11 | + ToolUseBlock, | |
| 12 | +} from "@anthropic-ai/sdk/resources"; | |
| 1 | 13 | import { streamSse } from "@continuedev/fetch"; |
| 2 | 14 | import { OpenAI } from "openai/index"; |
| 3 | 15 | import { |
| 4 | 16 | ChatCompletion, |
| 5 | 17 | ChatCompletionChunk, |
| 18 | + ChatCompletionContentPartRefusal, | |
| 19 | + ChatCompletionContentPartText, | |
| 6 | 20 | ChatCompletionCreateParamsNonStreaming, |
| 7 | 21 | ChatCompletionCreateParamsStreaming, |
| 8 | 22 | Completion, |
| @@ -24,6 +38,12 @@ | ||
| 24 | 38 | CACHING_STRATEGIES, |
| 25 | 39 | CachingStrategyName, |
| 26 | 40 | } from "./AnthropicCachingStrategies.js"; |
| 41 | +import { | |
| 42 | + getAnthropicHeaders, | |
| 43 | + getAnthropicMediaTypeFromDataUrl, | |
| 44 | + openAiToolChoiceToAnthropicToolChoice, | |
| 45 | + openaiToolToAnthropicTool, | |
| 46 | +} from "./AnthropicUtils.js"; | |
| 27 | 47 | import { |
| 28 | 48 | BaseLlmApi, |
| 29 | 49 | CreateRerankResponse, |
| @@ -59,11 +79,12 @@ | ||
| 59 | 79 | if (model.includes("haiku")) { |
| 60 | 80 | return 8192; |
| 61 | 81 | } |
| 62 | - | |
| 63 | 82 | return 32_000; |
| 64 | 83 | } |
| 65 | 84 | |
| 66 | - public _convertToCleanAnthropicBody(oaiBody: ChatCompletionCreateParams) { | |
| 85 | + public _convertToCleanAnthropicBody( | |
| 86 | + oaiBody: ChatCompletionCreateParams, | |
| 87 | + ): MessageCreateParams { | |
| 67 | 88 | let stop = undefined; |
| 68 | 89 | if (oaiBody.stop && Array.isArray(oaiBody.stop)) { |
| 69 | 90 | stop = oaiBody.stop.filter((x) => x.trim() !== ""); |
| @@ -75,145 +96,198 @@ | ||
| 75 | 96 | (msg) => msg.role === "system", |
| 76 | 97 | )?.content; |
| 77 | 98 | |
| 78 | - const anthropicBody = { | |
| 99 | + // TODO support custom tools | |
| 100 | + const functionTools = oaiBody.tools?.filter((t) => t.type === "function"); | |
| 101 | + let tools: Tool[] | undefined = undefined; | |
| 102 | + | |
| 103 | + if ( | |
| 104 | + oaiBody.tool_choice !== "none" && | |
| 105 | + functionTools && | |
| 106 | + functionTools.length > 0 | |
| 107 | + ) { | |
| 108 | + if ( | |
| 109 | + typeof oaiBody.tool_choice !== "string" && | |
| 110 | + oaiBody.tool_choice?.type === "allowed_tools" | |
| 111 | + ) { | |
| 112 | + const allowedToolNames = new Set( | |
| 113 | + oaiBody.tool_choice?.allowed_tools.tools.map( | |
| 114 | + (tool) => tool["name"], | |
| 115 | + ) ?? [], | |
| 116 | + ); | |
| 117 | + const allowedTools = functionTools.filter((t) => | |
| 118 | + allowedToolNames.has(t.function.name), | |
| 119 | + ); | |
| 120 | + tools = allowedTools.map(openaiToolToAnthropicTool); | |
| 121 | + } else { | |
| 122 | + tools = functionTools.map(openaiToolToAnthropicTool); | |
| 123 | + } | |
| 124 | + } | |
| 125 | + | |
| 126 | + const anthropicBody: MessageCreateParams = { | |
| 79 | 127 | messages: this._convertMessages( |
| 80 | 128 | oaiBody.messages.filter((msg) => msg.role !== "system"), |
| 81 | 129 | ), |
| 82 | - system: systemMessage | |
| 83 | - ? [ | |
| 84 | - { | |
| 85 | - type: "text", | |
| 86 | - text: systemMessage, | |
| 87 | - }, | |
| 88 | - ] | |
| 89 | - : systemMessage, | |
| 90 | - top_p: oaiBody.top_p, | |
| 91 | - temperature: oaiBody.temperature, | |
| 130 | + system: | |
| 131 | + typeof systemMessage === "string" | |
| 132 | + ? [ | |
| 133 | + { | |
| 134 | + type: "text", | |
| 135 | + text: systemMessage, | |
| 136 | + }, | |
| 137 | + ] | |
| 138 | + : systemMessage, | |
| 139 | + top_p: oaiBody.top_p ?? undefined, | |
| 140 | + temperature: oaiBody.temperature ?? undefined, | |
| 92 | 141 | max_tokens: oaiBody.max_tokens ?? this.maxTokensForModel(oaiBody.model), // max_tokens is required |
| 93 | 142 | model: oaiBody.model, |
| 94 | 143 | stop_sequences: stop, |
| 95 | - stream: oaiBody.stream, | |
| 96 | - tools: oaiBody.tools?.map((tool) => { | |
| 97 | - // Type guard for function tools | |
| 98 | - if (tool.type === "function" && "function" in tool) { | |
| 99 | - return { | |
| 100 | - name: tool.function.name, | |
| 101 | - description: tool.function.description, | |
| 102 | - input_schema: tool.function.parameters, | |
| 103 | - }; | |
| 104 | - } else { | |
| 105 | - throw new Error(`Unsupported tool type in Anthropic: ${tool.type}`); | |
| 106 | - } | |
| 107 | - }), | |
| 108 | - tool_choice: oaiBody.tool_choice | |
| 109 | - ? { | |
| 110 | - type: "tool", | |
| 111 | - name: | |
| 112 | - typeof oaiBody.tool_choice === "string" | |
| 113 | - ? oaiBody.tool_choice | |
| 114 | - : oaiBody.tool_choice && "function" in oaiBody.tool_choice | |
| 115 | - ? oaiBody.tool_choice.function.name | |
| 116 | - : undefined, | |
| 117 | - } | |
| 118 | - : undefined, | |
| 144 | + stream: oaiBody.stream ?? undefined, | |
| 145 | + tools, | |
| 146 | + tool_choice: openAiToolChoiceToAnthropicToolChoice(oaiBody.tool_choice), | |
| 119 | 147 | }; |
| 120 | 148 | |
| 121 | 149 | return anthropicBody; |
| 122 | 150 | } |
| 123 | 151 | |
| 124 | - private _convertMessages( | |
| 125 | - msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], | |
| 126 | - ): any[] { | |
| 127 | - const messages = msgs.map((message) => { | |
| 128 | - if (message.role === "tool") { | |
| 129 | - return { | |
| 130 | - role: "user", | |
| 131 | - content: [ | |
| 132 | - { | |
| 133 | - type: "tool_result", | |
| 134 | - tool_use_id: message.tool_call_id, | |
| 135 | - content: | |
| 136 | - typeof message.content === "string" | |
| 137 | - ? message.content | |
| 138 | - : message.content.map((part) => part.text).join(""), | |
| 139 | - }, | |
| 140 | - ], | |
| 141 | - }; | |
| 142 | - } else if (message.role === "assistant" && message.tool_calls) { | |
| 143 | - const parts: any[] = []; | |
| 144 | - if (message.content) { | |
| 145 | - if (typeof message.content === "string") { | |
| 146 | - parts.push({ | |
| 152 | + private convertToolCallsToBlocks( | |
| 153 | + toolCall: OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall, | |
| 154 | + ): ToolUseBlock | undefined { | |
| 155 | + const toolCallId = toolCall.id; | |
| 156 | + const toolName = toolCall.function?.name; | |
| 157 | + if (toolCallId && toolName) { | |
| 158 | + return { | |
| 159 | + type: "tool_use", | |
| 160 | + id: toolCallId, | |
| 161 | + name: toolName, | |
| 162 | + input: safeParseArgs( | |
| 163 | + toolCall.function.arguments, | |
| 164 | + `${toolName} ${toolCallId}`, | |
| 165 | + ), | |
| 166 | + }; | |
| 167 | + } | |
| 168 | + } | |
| 169 | + | |
| 170 | + // 1. ignores empty content | |
| 171 | + // 2. converts string content to text parts | |
| 172 | + // 3. converts text and refusal parts to text blocks | |
| 173 | + // 4. converts image parts to image blocks | |
| 174 | + private convertMessageContentToBlocks( | |
| 175 | + content: | |
| 176 | + | string | |
| 177 | + | OpenAI.Chat.Completions.ChatCompletionContentPart[] | |
| 178 | + | (ChatCompletionContentPartText | ChatCompletionContentPartRefusal)[], | |
| 179 | + ): ContentBlockParam[] { | |
| 180 | + const blocks: ContentBlockParam[] = []; | |
| 181 | + if (typeof content === "string") { | |
| 182 | + if (content) { | |
| 183 | + blocks.push({ | |
| 184 | + type: "text", | |
| 185 | + text: content, | |
| 186 | + }); | |
| 187 | + } | |
| 188 | + } else { | |
| 189 | + const supportedParts = content.filter( | |
| 190 | + (p) => | |
| 191 | + p.type === "text" || p.type === "image_url" || p.type === "refusal", | |
| 192 | + ); | |
| 193 | + for (const part of supportedParts) { | |
| 194 | + if (part.type === "image_url") { | |
| 195 | + const dataUrl = part.image_url.url; | |
| 196 | + if (dataUrl?.startsWith("data:")) { | |
| 197 | + blocks.push({ | |
| 198 | + type: "image", | |
| 199 | + source: { | |
| 200 | + type: "base64", | |
| 201 | + media_type: getAnthropicMediaTypeFromDataUrl(dataUrl), | |
| 202 | + data: dataUrl.split(",")[1], | |
| 203 | + }, | |
| 204 | + }); | |
| 205 | + } | |
| 206 | + } else { | |
| 207 | + const text = part.type === "text" ? part.text : part.refusal; | |
| 208 | + if (text) { | |
| 209 | + blocks.push({ | |
| 147 | 210 | type: "text", |
| 148 | - text: message.content, | |
| 211 | + text, | |
| 149 | 212 | }); |
| 150 | - } else if (message.content.length > 0) { | |
| 151 | - parts.push( | |
| 152 | - message.content.map((c) => ({ | |
| 153 | - type: "text", | |
| 154 | - text: c.type === "text" ? c.text : c.refusal, | |
| 155 | - })), | |
| 156 | - ); | |
| 157 | 213 | } |
| 158 | 214 | } |
| 215 | + } | |
| 216 | + } | |
| 217 | + return blocks; | |
| 218 | + } | |
| 159 | 219 | |
| 160 | - parts.push( | |
| 161 | - ...message.tool_calls.map((toolCall) => { | |
| 162 | - // Type guard for function tool calls | |
| 163 | - if (toolCall.type === "function" && "function" in toolCall) { | |
| 164 | - return { | |
| 165 | - type: "tool_use", | |
| 166 | - id: toolCall.id, | |
| 167 | - name: toolCall.function?.name, | |
| 168 | - input: safeParseArgs( | |
| 169 | - toolCall.function?.arguments, | |
| 170 | - `${toolCall.function?.name} ${toolCall.id}`, | |
| 171 | - ), | |
| 172 | - }; | |
| 173 | - } else { | |
| 174 | - throw new Error(`Unsupported tool call type: ${toolCall.type}`); | |
| 175 | - } | |
| 176 | - }), | |
| 177 | - ); | |
| 178 | - return { | |
| 179 | - role: "assistant", | |
| 180 | - content: parts, | |
| 181 | - }; | |
| 220 | + private getContentBlocksFromChatMessage( | |
| 221 | + message: OpenAI.Chat.Completions.ChatCompletionMessageParam, | |
| 222 | + ): ContentBlockParam[] { | |
| 223 | + switch (message.role) { | |
| 224 | + // One tool message = one tool_result block | |
| 225 | + case "tool": | |
| 226 | + return [ | |
| 227 | + { | |
| 228 | + type: "tool_result", | |
| 229 | + tool_use_id: message.tool_call_id, | |
| 230 | + content: message.content, | |
| 231 | + }, | |
| 232 | + ]; | |
| 233 | + case "user": | |
| 234 | + return this.convertMessageContentToBlocks(message.content); | |
| 235 | + case "assistant": | |
| 236 | + const blocks: ContentBlockParam[] = message.content | |
| 237 | + ? this.convertMessageContentToBlocks(message.content) | |
| 238 | + : []; | |
| 239 | + // If any tool calls are present, always put them last | |
| 240 | + // Loses order vs what was originally sent, but they typically come last | |
| 241 | + for (const toolCall of message.tool_calls ?? []) { | |
| 242 | + if (toolCall.type !== "function") { | |
| 243 | + // TODO support custom tool calls | |
| 244 | + continue; | |
| 245 | + } | |
| 246 | + const block = this.convertToolCallsToBlocks(toolCall); | |
| 247 | + if (block) { | |
| 248 | + blocks.push(block); | |
| 249 | + } | |
| 250 | + } | |
| 251 | + return blocks; | |
| 252 | + // system, etc. | |
| 253 | + default: | |
| 254 | + return []; | |
| 255 | + } | |
| 256 | + } | |
| 257 | + | |
| 258 | + private _convertMessages( | |
| 259 | + msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], | |
| 260 | + ): MessageParam[] { | |
| 261 | + const nonSystemMessages = msgs.filter((m) => m.role !== "system"); | |
| 262 | + | |
| 263 | + const convertedMessages: MessageParam[] = []; | |
| 264 | + let currentRole: "user" | "assistant" | undefined = undefined; | |
| 265 | + let currentParts: ContentBlockParam[] = []; | |
| 266 | + | |
| 267 | + const flushCurrentMessage = () => { | |
| 268 | + if (currentRole && currentParts.length > 0) { | |
| 269 | + convertedMessages.push({ | |
| 270 | + role: currentRole, | |
| 271 | + content: currentParts, | |
| 272 | + }); | |
| 273 | + currentParts = []; | |
| 182 | 274 | } |
| 275 | + }; | |
| 183 | 276 | |
| 184 | - if (!Array.isArray(message.content)) { | |
| 185 | - return message; | |
| 277 | + for (const message of nonSystemMessages) { | |
| 278 | + const newRole = | |
| 279 | + message.role === "user" || message.role === "tool" | |
| 280 | + ? "user" | |
| 281 | + : "assistant"; | |
| 282 | + if (currentRole !== newRole) { | |
| 283 | + flushCurrentMessage(); | |
| 284 | + currentRole = newRole; | |
| 186 | 285 | } |
| 187 | - return { | |
| 188 | - ...message, | |
| 189 | - content: message.content | |
| 190 | - .map((part) => { | |
| 191 | - if (part.type === "text") { | |
| 192 | - if ((part.text?.trim() ?? "") === "") { | |
| 193 | - return null; | |
| 194 | - } | |
| 195 | - return part; | |
| 196 | - } | |
| 197 | - const dataUrl = | |
| 198 | - (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage) | |
| 199 | - ?.image_url?.url || ""; | |
| 200 | - // Extract media type from data URL (ex. "data:image/png;base64,..." -> "image/png") | |
| 201 | - const mediaTypeMatch = dataUrl.match(/^data:([^;]+);base64,/); | |
| 202 | - const mediaType = mediaTypeMatch ? mediaTypeMatch[1] : "image/jpeg"; | |
| 203 | - | |
| 204 | - return { | |
| 205 | - type: "image", | |
| 206 | - source: { | |
| 207 | - type: "base64", | |
| 208 | - media_type: mediaType, | |
| 209 | - data: dataUrl.split(",")[1], | |
| 210 | - }, | |
| 211 | - }; | |
| 212 | - }) | |
| 213 | - .filter((x) => x !== null), | |
| 214 | - }; | |
| 215 | - }); | |
| 216 | - return messages; | |
| 286 | + currentParts.push(...this.getContentBlocksFromChatMessage(message)); | |
| 287 | + } | |
| 288 | + flushCurrentMessage(); | |
| 289 | + | |
| 290 | + return convertedMessages; | |
| 217 | 291 | } |
| 218 | 292 | |
| 219 | 293 | async chatCompletionNonStream( |
| @@ -224,13 +298,7 @@ | ||
| 224 | 298 | new URL("messages", this.apiBase), |
| 225 | 299 | { |
| 226 | 300 | method: "POST", |
| 227 | - headers: { | |
| 228 | - "Content-Type": "application/json", | |
| 229 | - Accept: "application/json", | |
| 230 | - "anthropic-version": "2023-06-01", | |
| 231 | - "anthropic-beta": "prompt-caching-2024-07-31", | |
| 232 | - "x-api-key": this.config.apiKey, | |
| 233 | - }, | |
| 301 | + headers: this.getHeaders(), | |
| 234 | 302 | body: JSON.stringify(this._convertBody(body)), |
| 235 | 303 | signal, |
| 236 | 304 | }, |
| @@ -240,7 +308,7 @@ | ||
| 240 | 308 | return EMPTY_CHAT_COMPLETION; |
| 241 | 309 | } |
| 242 | 310 | |
| 243 | - const completion = (await response.json()) as any; | |
| 311 | + const completion = await response.json(); | |
| 244 | 312 | |
| 245 | 313 | const usage: Record<string, number> | undefined = completion.usage; |
| 246 | 314 | return { |
| @@ -281,30 +349,36 @@ | ||
| 281 | 349 | prompt_tokens: 0, |
| 282 | 350 | total_tokens: 0, |
| 283 | 351 | }; |
| 284 | - for await (const value of streamSse(response as any)) { | |
| 352 | + for await (const event of streamSse(response)) { | |
| 285 | 353 | // https://docs.anthropic.com/en/api/messages-streaming#event-types |
| 286 | - switch (value.type) { | |
| 354 | + const rawEvent = event as RawMessageStreamEvent; | |
| 355 | + switch (rawEvent.type) { | |
| 287 | 356 | case "content_block_start": |
| 288 | - if (value.content_block.type === "tool_use") { | |
| 289 | - lastToolUseId = value.content_block.id; | |
| 290 | - lastToolUseName = value.content_block.name; | |
| 357 | + const blockStartEvent = rawEvent as RawContentBlockStartEvent; | |
| 358 | + if (blockStartEvent.content_block.type === "tool_use") { | |
| 359 | + lastToolUseId = blockStartEvent.content_block.id; | |
| 360 | + lastToolUseName = blockStartEvent.content_block.name; | |
| 291 | 361 | } |
| 292 | 362 | break; |
| 293 | 363 | case "message_start": |
| 294 | - usage.prompt_tokens = value.message.usage?.input_tokens ?? 0; | |
| 364 | + const startEvent = rawEvent as RawMessageStartEvent; | |
| 365 | + usage.prompt_tokens = startEvent.message.usage?.input_tokens ?? 0; | |
| 295 | 366 | usage.prompt_tokens_details = { |
| 296 | - cached_tokens: value.message.usage?.cache_read_input_tokens ?? 0, | |
| 367 | + cached_tokens: | |
| 368 | + startEvent.message.usage?.cache_read_input_tokens ?? 0, | |
| 297 | 369 | }; |
| 298 | 370 | break; |
| 299 | 371 | case "message_delta": |
| 300 | - usage.completion_tokens = value.usage?.output_tokens ?? 0; | |
| 372 | + const deltaEvent = rawEvent as RawMessageDeltaEvent; | |
| 373 | + usage.completion_tokens = deltaEvent.usage?.output_tokens ?? 0; | |
| 301 | 374 | break; |
| 302 | 375 | case "content_block_delta": |
| 303 | 376 | // https://docs.anthropic.com/en/api/messages-streaming#delta-types |
| 304 | - switch (value.delta.type) { | |
| 377 | + const blockDeltaEvent = rawEvent as RawContentBlockDeltaEvent; | |
| 378 | + switch (blockDeltaEvent.delta.type) { | |
| 305 | 379 | case "text_delta": |
| 306 | 380 | yield chatChunk({ |
| 307 | - content: value.delta.text, | |
| 381 | + content: blockDeltaEvent.delta.text, | |
| 308 | 382 | model, |
| 309 | 383 | }); |
| 310 | 384 | break; |
| @@ -322,7 +396,7 @@ | ||
| 322 | 396 | index: 0, |
| 323 | 397 | function: { |
| 324 | 398 | name: lastToolUseName, |
| 325 | - arguments: value.delta.partial_json, | |
| 399 | + arguments: blockDeltaEvent.delta.partial_json, | |
| 326 | 400 | }, |
| 327 | 401 | }, |
| 328 | 402 | ], |
| @@ -352,25 +426,24 @@ | ||
| 352 | 426 | async *chatCompletionStream( |
| 353 | 427 | body: ChatCompletionCreateParamsStreaming, |
| 354 | 428 | signal: AbortSignal, |
| 355 | - ): AsyncGenerator<ChatCompletionChunk, any, unknown> { | |
| 356 | - body.messages; | |
| 429 | + ): AsyncGenerator<ChatCompletionChunk> { | |
| 357 | 430 | const response = await customFetch(this.config.requestOptions)( |
| 358 | 431 | new URL("messages", this.apiBase), |
| 359 | 432 | { |
| 360 | 433 | method: "POST", |
| 361 | - headers: { | |
| 362 | - "Content-Type": "application/json", | |
| 363 | - Accept: "application/json", | |
| 364 | - "anthropic-version": "2023-06-01", | |
| 365 | - "anthropic-beta": "prompt-caching-2024-07-31", | |
| 366 | - "x-api-key": this.config.apiKey, | |
| 367 | - }, | |
| 434 | + headers: this.getHeaders(), | |
| 368 | 435 | body: JSON.stringify(this._convertBody(body)), |
| 369 | 436 | signal, |
| 370 | 437 | }, |
| 371 | 438 | ); |
| 372 | 439 | yield* this.handleStreamResponse(response, body.model); |
| 373 | 440 | } |
| 441 | + | |
| 442 | + private getHeaders(): Record<string, string> { | |
| 443 | + const enableCaching = this.config?.cachingStrategy !== "none"; | |
| 444 | + return getAnthropicHeaders(this.config.apiKey, enableCaching); | |
| 445 | + } | |
| 446 | + | |
| 374 | 447 | async completionNonStream( |
| 375 | 448 | body: CompletionCreateParamsNonStreaming, |
| 376 | 449 | signal: AbortSignal, |
| @@ -380,13 +453,13 @@ | ||
| 380 | 453 | async *completionStream( |
| 381 | 454 | body: CompletionCreateParamsStreaming, |
| 382 | 455 | signal: AbortSignal, |
| 383 | - ): AsyncGenerator<Completion, any, unknown> { | |
| 456 | + ): AsyncGenerator<Completion> { | |
| 384 | 457 | throw new Error("Method not implemented."); |
| 385 | 458 | } |
| 386 | 459 | async *fimStream( |
| 387 | 460 | body: FimCreateParamsStreaming, |
| 388 | 461 | signal: AbortSignal, |
| 389 | - ): AsyncGenerator<ChatCompletionChunk, any, unknown> { | |
| 462 | + ): AsyncGenerator<ChatCompletionChunk> { | |
| 390 | 463 | throw new Error("Method not implemented."); |
| 391 | 464 | } |
| 392 | 465 |
modified packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts +277 −133
| @@ -1,24 +1,42 @@ | ||
| 1 | +import { MessageCreateParams, ToolUnion } from "@anthropic-ai/sdk/resources"; | |
| 1 | 2 | import { |
| 2 | 3 | CACHING_STRATEGIES, |
| 3 | - CachingStrategy, | |
| 4 | 4 | CachingStrategyName, |
| 5 | 5 | getAvailableStrategies, |
| 6 | 6 | getStrategyDescription, |
| 7 | 7 | } from "./AnthropicCachingStrategies.js"; |
| 8 | 8 | |
| 9 | +const body_params = { | |
| 10 | + model: "claude", | |
| 11 | + stream: true, | |
| 12 | + max_tokens: 8192, | |
| 13 | +}; | |
| 14 | + | |
| 15 | +const makeTool = (name: string): ToolUnion => ({ | |
| 16 | + name, | |
| 17 | + input_schema: { | |
| 18 | + type: "object", | |
| 19 | + }, | |
| 20 | +}); | |
| 21 | + | |
| 9 | 22 | describe("AnthropicCachingStrategies", () => { |
| 10 | 23 | describe("noCachingStrategy", () => { |
| 11 | 24 | it("should return the body unchanged", () => { |
| 12 | - const body = { system: "test", messages: [] }; | |
| 25 | + const body: MessageCreateParams = { | |
| 26 | + system: "test", | |
| 27 | + messages: [], | |
| 28 | + ...body_params, | |
| 29 | + }; | |
| 13 | 30 | const result = CACHING_STRATEGIES.none(body); |
| 14 | 31 | expect(result).toBe(body); |
| 15 | 32 | }); |
| 16 | 33 | |
| 17 | 34 | it("should not modify complex objects", () => { |
| 18 | - const body = { | |
| 19 | - system: [{ text: "test" }], | |
| 20 | - tools: [{ name: "test" }], | |
| 21 | - messages: [{ content: "test" }], | |
| 35 | + const body: MessageCreateParams = { | |
| 36 | + system: [{ type: "text", text: "test" }], | |
| 37 | + tools: [makeTool("test")], | |
| 38 | + messages: [{ role: "user", content: "test" }], | |
| 39 | + ...body_params, | |
| 22 | 40 | }; |
| 23 | 41 | const result = CACHING_STRATEGIES.none(body); |
| 24 | 42 | expect(result).toBe(body); |
| @@ -27,24 +45,37 @@ | ||
| 27 | 45 | |
| 28 | 46 | describe("systemOnlyStrategy", () => { |
| 29 | 47 | it("should add cache_control to system messages array", () => { |
| 30 | - const body = { | |
| 31 | - system: [{ text: "system message 1" }, { text: "system message 2" }], | |
| 32 | - messages: [{ content: "user message" }], | |
| 48 | + const body: MessageCreateParams = { | |
| 49 | + system: [ | |
| 50 | + { type: "text", text: "system message 1" }, | |
| 51 | + { type: "text", text: "system message 2" }, | |
| 52 | + ], | |
| 53 | + messages: [{ role: "user", content: "user message" }], | |
| 54 | + ...body_params, | |
| 33 | 55 | }; |
| 34 | 56 | |
| 35 | 57 | const result = CACHING_STRATEGIES.systemOnly(body); |
| 36 | 58 | |
| 37 | 59 | expect(result.system).toEqual([ |
| 38 | - { text: "system message 1", cache_control: { type: "ephemeral" } }, | |
| 39 | - { text: "system message 2", cache_control: { type: "ephemeral" } }, | |
| 60 | + { | |
| 61 | + type: "text", | |
| 62 | + text: "system message 1", | |
| 63 | + cache_control: { type: "ephemeral" }, | |
| 64 | + }, | |
| 65 | + { | |
| 66 | + type: "text", | |
| 67 | + text: "system message 2", | |
| 68 | + cache_control: { type: "ephemeral" }, | |
| 69 | + }, | |
| 40 | 70 | ]); |
| 41 | 71 | expect(result.messages).toEqual(body.messages); |
| 42 | 72 | }); |
| 43 | 73 | |
| 44 | 74 | it("should return body unchanged if system is not an array", () => { |
| 45 | - const body = { | |
| 75 | + const body: MessageCreateParams = { | |
| 46 | 76 | system: "string system message", |
| 47 | - messages: [{ content: "user message" }], | |
| 77 | + messages: [{ role: "user", content: "user message" }], | |
| 78 | + ...body_params, | |
| 48 | 79 | }; |
| 49 | 80 | |
| 50 | 81 | const result = CACHING_STRATEGIES.systemOnly(body); |
| @@ -52,8 +83,9 @@ | ||
| 52 | 83 | }); |
| 53 | 84 | |
| 54 | 85 | it("should return body unchanged if system is undefined", () => { |
| 55 | - const body = { | |
| 56 | - messages: [{ content: "user message" }], | |
| 86 | + const body: MessageCreateParams = { | |
| 87 | + messages: [{ role: "user", content: "user message" }], | |
| 88 | + ...body_params, | |
| 57 | 89 | }; |
| 58 | 90 | |
| 59 | 91 | const result = CACHING_STRATEGIES.systemOnly(body); |
| @@ -61,25 +93,42 @@ | ||
| 61 | 93 | }); |
| 62 | 94 | |
| 63 | 95 | it("should not add more than 5 cached messages", () => { |
| 64 | - const body = { | |
| 96 | + const body: MessageCreateParams = { | |
| 65 | 97 | system: [ |
| 66 | - { text: "system message 1" }, | |
| 67 | - { text: "system message 2" }, | |
| 68 | - { text: "system message 3" }, | |
| 69 | - { text: "system message 4" }, | |
| 70 | - { text: "system message 5" }, | |
| 98 | + { type: "text", text: "system message 1" }, | |
| 99 | + { type: "text", text: "system message 2" }, | |
| 100 | + { type: "text", text: "system message 3" }, | |
| 101 | + { type: "text", text: "system message 4" }, | |
| 102 | + { type: "text", text: "system message 5" }, | |
| 71 | 103 | ], |
| 72 | - messages: [{ content: "user message" }], | |
| 104 | + messages: [{ role: "user", content: "user message" }], | |
| 105 | + ...body_params, | |
| 73 | 106 | }; |
| 74 | 107 | |
| 75 | 108 | const result = CACHING_STRATEGIES.systemOnly(body); |
| 76 | 109 | |
| 77 | 110 | expect(result.system).toEqual([ |
| 78 | - { text: "system message 1", cache_control: { type: "ephemeral" } }, | |
| 79 | - { text: "system message 2", cache_control: { type: "ephemeral" } }, | |
| 80 | - { text: "system message 3", cache_control: { type: "ephemeral" } }, | |
| 81 | - { text: "system message 4", cache_control: { type: "ephemeral" } }, | |
| 82 | - { text: "system message 5" }, | |
| 111 | + { | |
| 112 | + type: "text", | |
| 113 | + text: "system message 1", | |
| 114 | + cache_control: { type: "ephemeral" }, | |
| 115 | + }, | |
| 116 | + { | |
| 117 | + type: "text", | |
| 118 | + text: "system message 2", | |
| 119 | + cache_control: { type: "ephemeral" }, | |
| 120 | + }, | |
| 121 | + { | |
| 122 | + type: "text", | |
| 123 | + text: "system message 3", | |
| 124 | + cache_control: { type: "ephemeral" }, | |
| 125 | + }, | |
| 126 | + { | |
| 127 | + type: "text", | |
| 128 | + text: "system message 4", | |
| 129 | + cache_control: { type: "ephemeral" }, | |
| 130 | + }, | |
| 131 | + { type: "text", text: "system message 5" }, | |
| 83 | 132 | ]); |
| 84 | 133 | expect(result.messages).toEqual(body.messages); |
| 85 | 134 | }); |
| @@ -87,82 +136,116 @@ | ||
| 87 | 136 | |
| 88 | 137 | describe("systemAndToolsStrategy", () => { |
| 89 | 138 | it("should add cache_control to both system and tools", () => { |
| 90 | - const body = { | |
| 91 | - system: [{ text: "system message" }], | |
| 92 | - tools: [{ name: "tool1" }, { name: "tool2" }], | |
| 93 | - messages: [{ content: "user message" }], | |
| 139 | + const body: MessageCreateParams = { | |
| 140 | + system: [{ type: "text", text: "system message" }], | |
| 141 | + tools: [makeTool("tool1"), makeTool("tool2")], | |
| 142 | + messages: [{ role: "user", content: "user message" }], | |
| 143 | + ...body_params, | |
| 94 | 144 | }; |
| 95 | 145 | |
| 96 | 146 | const result = CACHING_STRATEGIES.systemAndTools(body); |
| 97 | 147 | |
| 98 | 148 | expect(result.system).toEqual([ |
| 99 | - { text: "system message", cache_control: { type: "ephemeral" } }, | |
| 149 | + { | |
| 150 | + type: "text", | |
| 151 | + text: "system message", | |
| 152 | + cache_control: { type: "ephemeral" }, | |
| 153 | + }, | |
| 100 | 154 | ]); |
| 101 | 155 | expect(result.tools).toEqual([ |
| 102 | - { name: "tool1" }, | |
| 103 | - { name: "tool2", cache_control: { type: "ephemeral" } }, | |
| 156 | + { | |
| 157 | + name: "tool1", | |
| 158 | + input_schema: { | |
| 159 | + type: "object", | |
| 160 | + }, | |
| 161 | + }, | |
| 162 | + { | |
| 163 | + name: "tool2", | |
| 164 | + input_schema: { | |
| 165 | + type: "object", | |
| 166 | + }, | |
| 167 | + cache_control: { type: "ephemeral" }, | |
| 168 | + }, | |
| 104 | 169 | ]); |
| 105 | 170 | expect(result.messages).toEqual(body.messages); |
| 106 | 171 | }); |
| 107 | 172 | |
| 108 | 173 | it("should handle missing system messages", () => { |
| 109 | - const body = { | |
| 110 | - tools: [{ name: "tool1" }], | |
| 111 | - messages: [{ content: "user message" }], | |
| 174 | + const body: MessageCreateParams = { | |
| 175 | + tools: [makeTool("tool1")], | |
| 176 | + messages: [{ role: "user", content: "user message" }], | |
| 177 | + ...body_params, | |
| 112 | 178 | }; |
| 113 | 179 | |
| 114 | 180 | const result = CACHING_STRATEGIES.systemAndTools(body); |
| 115 | 181 | |
| 116 | 182 | expect(result.tools).toEqual([ |
| 117 | - { name: "tool1", cache_control: { type: "ephemeral" } }, | |
| 183 | + { | |
| 184 | + name: "tool1", | |
| 185 | + input_schema: { | |
| 186 | + type: "object", | |
| 187 | + }, | |
| 188 | + cache_control: { type: "ephemeral" }, | |
| 189 | + }, | |
| 118 | 190 | ]); |
| 119 | 191 | expect(result.messages).toEqual(body.messages); |
| 120 | 192 | }); |
| 121 | 193 | |
| 122 | 194 | it("should handle missing tools", () => { |
| 123 | - const body = { | |
| 124 | - system: [{ text: "system message" }], | |
| 125 | - messages: [{ content: "user message" }], | |
| 195 | + const body: MessageCreateParams = { | |
| 196 | + system: [{ type: "text", text: "system message" }], | |
| 197 | + messages: [{ role: "user", content: "user message" }], | |
| 198 | + ...body_params, | |
| 126 | 199 | }; |
| 127 | 200 | |
| 128 | 201 | const result = CACHING_STRATEGIES.systemAndTools(body); |
| 129 | 202 | |
| 130 | 203 | expect(result.system).toEqual([ |
| 131 | - { text: "system message", cache_control: { type: "ephemeral" } }, | |
| 204 | + { | |
| 205 | + type: "text", | |
| 206 | + text: "system message", | |
| 207 | + cache_control: { type: "ephemeral" }, | |
| 208 | + }, | |
| 132 | 209 | ]); |
| 133 | 210 | expect(result.messages).toEqual(body.messages); |
| 134 | 211 | }); |
| 135 | 212 | |
| 136 | - it("should handle non-array system and tools", () => { | |
| 137 | - const body = { | |
| 138 | - system: "string system", | |
| 139 | - tools: "string tools", | |
| 140 | - messages: [{ content: "user message" }], | |
| 141 | - }; | |
| 142 | - | |
| 143 | - const result = CACHING_STRATEGIES.systemAndTools(body); | |
| 144 | - expect(result).toEqual(body); | |
| 145 | - }); | |
| 146 | - | |
| 147 | 213 | it("should add only 4 cache controls in total to both system and tools", () => { |
| 148 | - const body = { | |
| 214 | + const body: MessageCreateParams = { | |
| 149 | 215 | system: [ |
| 150 | - { text: "system message 1" }, | |
| 151 | - { text: "system message 2" }, | |
| 152 | - { text: "system message 3" }, | |
| 153 | - { text: "system message 4" }, | |
| 216 | + { type: "text", text: "system message 1" }, | |
| 217 | + { type: "text", text: "system message 2" }, | |
| 218 | + { type: "text", text: "system message 3" }, | |
| 219 | + { type: "text", text: "system message 4" }, | |
| 154 | 220 | ], |
| 155 | - tools: [{ name: "tool1" }, { name: "tool2" }], | |
| 156 | - messages: [{ content: "user message" }], | |
| 221 | + tools: [makeTool("tool1"), makeTool("tool2")], | |
| 222 | + messages: [{ role: "user", content: "user message" }], | |
| 223 | + ...body_params, | |
| 157 | 224 | }; |
| 158 | 225 | |
| 159 | 226 | const result = CACHING_STRATEGIES.systemAndTools(body); |
| 160 | 227 | |
| 161 | 228 | expect(result.system).toEqual([ |
| 162 | - { text: "system message 1", cache_control: { type: "ephemeral" } }, | |
| 163 | - { text: "system message 2", cache_control: { type: "ephemeral" } }, | |
| 164 | - { text: "system message 3", cache_control: { type: "ephemeral" } }, | |
| 165 | - { text: "system message 4", cache_control: { type: "ephemeral" } }, | |
| 229 | + { | |
| 230 | + type: "text", | |
| 231 | + text: "system message 1", | |
| 232 | + cache_control: { type: "ephemeral" }, | |
| 233 | + }, | |
| 234 | + { | |
| 235 | + type: "text", | |
| 236 | + text: "system message 2", | |
| 237 | + cache_control: { type: "ephemeral" }, | |
| 238 | + }, | |
| 239 | + { | |
| 240 | + type: "text", | |
| 241 | + text: "system message 3", | |
| 242 | + cache_control: { type: "ephemeral" }, | |
| 243 | + }, | |
| 244 | + { | |
| 245 | + type: "text", | |
| 246 | + text: "system message 4", | |
| 247 | + cache_control: { type: "ephemeral" }, | |
| 248 | + }, | |
| 166 | 249 | ]); |
| 167 | 250 | expect(result.tools).toEqual(body.tools); |
| 168 | 251 | expect(result.messages).toEqual(body.messages); |
| @@ -171,32 +254,45 @@ | ||
| 171 | 254 | |
| 172 | 255 | describe("optimizedStrategy", () => { |
| 173 | 256 | it("should cache system messages and tools", () => { |
| 174 | - const body = { | |
| 175 | - system: [{ text: "system message" }], | |
| 176 | - tools: [{ name: "tool1" }], | |
| 177 | - messages: [{ content: "short message" }], | |
| 257 | + const body: MessageCreateParams = { | |
| 258 | + system: [{ type: "text", text: "system message" }], | |
| 259 | + tools: [makeTool("tool1")], | |
| 260 | + messages: [{ role: "user", content: "short message" }], | |
| 261 | + ...body_params, | |
| 178 | 262 | }; |
| 179 | 263 | |
| 180 | 264 | const result = CACHING_STRATEGIES.optimized(body); |
| 181 | 265 | |
| 182 | 266 | expect(result.system).toEqual([ |
| 183 | - { text: "system message", cache_control: { type: "ephemeral" } }, | |
| 267 | + { | |
| 268 | + type: "text", | |
| 269 | + text: "system message", | |
| 270 | + cache_control: { type: "ephemeral" }, | |
| 271 | + }, | |
| 184 | 272 | ]); |
| 185 | 273 | expect(result.tools).toEqual([ |
| 186 | - { name: "tool1", cache_control: { type: "ephemeral" } }, | |
| 274 | + { | |
| 275 | + name: "tool1", | |
| 276 | + input_schema: { | |
| 277 | + type: "object", | |
| 278 | + }, | |
| 279 | + cache_control: { type: "ephemeral" }, | |
| 280 | + }, | |
| 187 | 281 | ]); |
| 188 | 282 | }); |
| 189 | 283 | |
| 190 | 284 | it("should cache large string messages (>500 tokens)", () => { |
| 191 | 285 | const largeContent = "a".repeat(2100); // ~525 tokens |
| 192 | - const body = { | |
| 193 | - messages: [{ content: largeContent }], | |
| 286 | + const body: MessageCreateParams = { | |
| 287 | + messages: [{ role: "user", content: largeContent }], | |
| 288 | + ...body_params, | |
| 194 | 289 | }; |
| 195 | 290 | |
| 196 | 291 | const result = CACHING_STRATEGIES.optimized(body); |
| 197 | 292 | |
| 198 | 293 | expect(result.messages).toEqual([ |
| 199 | 294 | { |
| 295 | + role: "user", | |
| 200 | 296 | content: [ |
| 201 | 297 | { |
| 202 | 298 | type: "text", |
| @@ -210,30 +306,42 @@ | ||
| 210 | 306 | |
| 211 | 307 | it("should not cache small string messages (<500 tokens)", () => { |
| 212 | 308 | const smallContent = "a".repeat(100); // ~25 tokens |
| 213 | - const body = { | |
| 214 | - messages: [{ content: smallContent }], | |
| 309 | + const body: MessageCreateParams = { | |
| 310 | + messages: [{ role: "user", content: smallContent }], | |
| 311 | + ...body_params, | |
| 215 | 312 | }; |
| 216 | 313 | |
| 217 | 314 | const result = CACHING_STRATEGIES.optimized(body); |
| 218 | 315 | |
| 219 | - expect(result.messages).toEqual([{ content: smallContent }]); | |
| 316 | + expect(result.messages).toEqual([ | |
| 317 | + { role: "user", content: smallContent }, | |
| 318 | + ]); | |
| 220 | 319 | }); |
| 221 | 320 | |
| 222 | 321 | it("should cache large text items in array content but only once per message", () => { |
| 223 | 322 | const largeText = "a".repeat(2100); // ~525 tokens |
| 224 | 323 | const anotherLargeText = "b".repeat(2100); // Also ~525 tokens |
| 225 | 324 | const smallText = "a".repeat(100); // ~25 tokens |
| 226 | - const body = { | |
| 325 | + const body: MessageCreateParams = { | |
| 227 | 326 | messages: [ |
| 228 | 327 | { |
| 328 | + role: "user", | |
| 229 | 329 | content: [ |
| 230 | 330 | { type: "text", text: largeText }, |
| 231 | 331 | { type: "text", text: anotherLargeText }, |
| 232 | 332 | { type: "text", text: smallText }, |
| 233 | - { type: "image", data: "image_data" }, | |
| 333 | + { | |
| 334 | + type: "image", | |
| 335 | + source: { | |
| 336 | + data: "image_data", | |
| 337 | + media_type: "image/jpeg", | |
| 338 | + type: "base64", | |
| 339 | + }, | |
| 340 | + }, | |
| 234 | 341 | ], |
| 235 | 342 | }, |
| 236 | 343 | ], |
| 344 | + ...body_params, | |
| 237 | 345 | }; |
| 238 | 346 | |
| 239 | 347 | const result = CACHING_STRATEGIES.optimized(body); |
| @@ -241,6 +349,7 @@ | ||
| 241 | 349 | // Only the first large text item should get cache_control |
| 242 | 350 | expect(result.messages).toEqual([ |
| 243 | 351 | { |
| 352 | + role: "user", | |
| 244 | 353 | content: [ |
| 245 | 354 | { |
| 246 | 355 | type: "text", |
| @@ -249,40 +358,78 @@ | ||
| 249 | 358 | }, |
| 250 | 359 | { type: "text", text: anotherLargeText }, |
| 251 | 360 | { type: "text", text: smallText }, |
| 252 | - { type: "image", data: "image_data" }, | |
| 361 | + { | |
| 362 | + type: "image", | |
| 363 | + source: { | |
| 364 | + data: "image_data", | |
| 365 | + media_type: "image/jpeg", | |
| 366 | + type: "base64", | |
| 367 | + }, | |
| 368 | + }, | |
| 253 | 369 | ], |
| 254 | 370 | }, |
| 255 | 371 | ]); |
| 256 | 372 | }); |
| 257 | 373 | |
| 258 | 374 | it("should add maximum 4 cache control blocks", () => { |
| 259 | - const body = { | |
| 260 | - system: [{ text: "system message 1" }, { text: "system message 2" }], | |
| 261 | - tools: [{ name: "tool" }], | |
| 375 | + const body: MessageCreateParams = { | |
| 376 | + system: [ | |
| 377 | + { type: "text", text: "system message 1" }, | |
| 378 | + { type: "text", text: "system message 2" }, | |
| 379 | + ], | |
| 380 | + tools: [makeTool("tool")], | |
| 262 | 381 | messages: [ |
| 263 | - { content: "small content" }, | |
| 264 | - { content: "a".repeat(2100) }, | |
| 265 | - { content: "b".repeat(2100) }, | |
| 382 | + { role: "user", content: "small content" }, | |
| 383 | + { role: "user", content: "a".repeat(2100) }, | |
| 384 | + { role: "user", content: "b".repeat(2100) }, | |
| 266 | 385 | { |
| 386 | + role: "user", | |
| 267 | 387 | content: [ |
| 268 | 388 | { type: "text", text: "c".repeat(2100) }, |
| 269 | - { type: "image", data: "image" }, | |
| 389 | + { | |
| 390 | + type: "image", | |
| 391 | + source: { | |
| 392 | + data: "image_data", | |
| 393 | + media_type: "image/jpeg", | |
| 394 | + type: "base64", | |
| 395 | + }, | |
| 396 | + }, | |
| 270 | 397 | ], |
| 271 | 398 | }, |
| 272 | 399 | ], |
| 400 | + ...body_params, | |
| 273 | 401 | }; |
| 274 | 402 | |
| 275 | 403 | const result = CACHING_STRATEGIES.optimized(body); |
| 276 | 404 | |
| 277 | 405 | expect(result.system).toEqual([ |
| 278 | - { text: "system message 1", cache_control: { type: "ephemeral" } }, | |
| 279 | - { text: "system message 2", cache_control: { type: "ephemeral" } }, | |
| 406 | + { | |
| 407 | + type: "text", | |
| 408 | + text: "system message 1", | |
| 409 | + cache_control: { type: "ephemeral" }, | |
| 410 | + }, | |
| 411 | + { | |
| 412 | + type: "text", | |
| 413 | + text: "system message 2", | |
| 414 | + cache_control: { type: "ephemeral" }, | |
| 415 | + }, | |
| 280 | 416 | ]); |
| 281 | 417 | expect(result.tools).toEqual([ |
| 282 | - { name: "tool", cache_control: { type: "ephemeral" } }, | |
| 418 | + { | |
| 419 | + name: "tool", | |
| 420 | + input_schema: { | |
| 421 | + type: "object", | |
| 422 | + }, | |
| 423 | + cache_control: { type: "ephemeral" }, | |
| 424 | + }, | |
| 283 | 425 | ]); |
| 284 | - expect(result.messages[0]).toEqual({ content: "small content" }); | |
| 426 | + expect(result.messages[0]).toEqual({ | |
| 427 | + role: "user", | |
| 428 | + content: "small content", | |
| 429 | + }); | |
| 430 | + | |
| 285 | 431 | expect(result.messages[1]).toEqual({ |
| 432 | + role: "user", | |
| 286 | 433 | content: [ |
| 287 | 434 | { |
| 288 | 435 | type: "text", |
| @@ -296,31 +443,50 @@ | ||
| 296 | 443 | }); |
| 297 | 444 | |
| 298 | 445 | it("should handle complex message structure", () => { |
| 299 | - const body = { | |
| 300 | - system: [{ text: "system" }], | |
| 301 | - tools: [{ name: "tool" }], | |
| 446 | + const body: MessageCreateParams = { | |
| 447 | + system: [{ type: "text", text: "system" }], | |
| 448 | + tools: [makeTool("tool")], | |
| 302 | 449 | messages: [ |
| 303 | - { content: "small content" }, | |
| 304 | - { content: "a".repeat(2100) }, // large content | |
| 450 | + { role: "user", content: "small content" }, | |
| 451 | + { role: "user", content: "a".repeat(2100) }, // large content | |
| 305 | 452 | { |
| 453 | + role: "user", | |
| 306 | 454 | content: [ |
| 307 | 455 | { type: "text", text: "a".repeat(2100) }, // large text |
| 308 | - { type: "image", data: "image" }, | |
| 456 | + { | |
| 457 | + type: "image", | |
| 458 | + source: { | |
| 459 | + data: "image_data", | |
| 460 | + media_type: "image/jpeg", | |
| 461 | + type: "base64", | |
| 462 | + }, | |
| 463 | + }, | |
| 309 | 464 | ], |
| 310 | 465 | }, |
| 311 | 466 | ], |
| 467 | + ...body_params, | |
| 312 | 468 | }; |
| 313 | 469 | |
| 314 | 470 | const result = CACHING_STRATEGIES.optimized(body); |
| 315 | 471 | |
| 316 | 472 | expect(result.system).toEqual([ |
| 317 | - { text: "system", cache_control: { type: "ephemeral" } }, | |
| 473 | + { type: "text", text: "system", cache_control: { type: "ephemeral" } }, | |
| 318 | 474 | ]); |
| 319 | 475 | expect(result.tools).toEqual([ |
| 320 | - { name: "tool", cache_control: { type: "ephemeral" } }, | |
| 476 | + { | |
| 477 | + name: "tool", | |
| 478 | + input_schema: { | |
| 479 | + type: "object", | |
| 480 | + }, | |
| 481 | + cache_control: { type: "ephemeral" }, | |
| 482 | + }, | |
| 321 | 483 | ]); |
| 322 | - expect(result.messages[0]).toEqual({ content: "small content" }); | |
| 484 | + expect(result.messages[0]).toEqual({ | |
| 485 | + role: "user", | |
| 486 | + content: "small content", | |
| 487 | + }); | |
| 323 | 488 | expect(result.messages[1]).toEqual({ |
| 489 | + role: "user", | |
| 324 | 490 | content: [ |
| 325 | 491 | { |
| 326 | 492 | type: "text", |
| @@ -337,30 +503,17 @@ | ||
| 337 | 503 | }); |
| 338 | 504 | |
| 339 | 505 | it("should handle empty or missing messages", () => { |
| 340 | - const body = { | |
| 341 | - system: [{ text: "system" }], | |
| 342 | - }; | |
| 343 | - | |
| 344 | - const result = CACHING_STRATEGIES.optimized(body); | |
| 345 | - | |
| 346 | - expect(result.system).toEqual([ | |
| 347 | - { text: "system", cache_control: { type: "ephemeral" } }, | |
| 348 | - ]); | |
| 349 | - expect(result.messages).toBeUndefined(); | |
| 350 | - }); | |
| 351 | - | |
| 352 | - it("should handle non-array messages", () => { | |
| 353 | - const body = { | |
| 354 | - system: [{ text: "system" }], | |
| 355 | - messages: "not an array", | |
| 506 | + const body: MessageCreateParams = { | |
| 507 | + system: [{ type: "text", text: "system" }], | |
| 508 | + messages: [], | |
| 509 | + ...body_params, | |
| 356 | 510 | }; |
| 357 | 511 | |
| 358 | 512 | const result = CACHING_STRATEGIES.optimized(body); |
| 359 | 513 | |
| 360 | 514 | expect(result.system).toEqual([ |
| 361 | - { text: "system", cache_control: { type: "ephemeral" } }, | |
| 515 | + { type: "text", text: "system", cache_control: { type: "ephemeral" } }, | |
| 362 | 516 | ]); |
| 363 | - expect(result.messages).toBe("not an array"); | |
| 364 | 517 | }); |
| 365 | 518 | }); |
| 366 | 519 | |
| @@ -370,8 +523,14 @@ | ||
| 370 | 523 | const smallContent = "a".repeat(100); // ~25 tokens |
| 371 | 524 | const largeContent = "a".repeat(2100); // ~525 tokens |
| 372 | 525 | |
| 373 | - const bodySmall = { messages: [{ content: smallContent }] }; | |
| 374 | - const bodyLarge = { messages: [{ content: largeContent }] }; | |
| 526 | + const bodySmall: MessageCreateParams = { | |
| 527 | + messages: [{ role: "user", content: smallContent }], | |
| 528 | + ...body_params, | |
| 529 | + }; | |
| 530 | + const bodyLarge: MessageCreateParams = { | |
| 531 | + messages: [{ role: "user", content: largeContent }], | |
| 532 | + ...body_params, | |
| 533 | + }; | |
| 375 | 534 | |
| 376 | 535 | const resultSmall = CACHING_STRATEGIES.optimized(bodySmall); |
| 377 | 536 | const resultLarge = CACHING_STRATEGIES.optimized(bodyLarge); |
| @@ -429,21 +588,6 @@ | ||
| 429 | 588 | }); |
| 430 | 589 | }); |
| 431 | 590 | }); |
| 432 | - | |
| 433 | - describe("CachingStrategy type", () => { | |
| 434 | - it("should accept valid caching strategy functions", () => { | |
| 435 | - const customStrategy: CachingStrategy = (body) => ({ | |
| 436 | - ...body, | |
| 437 | - custom: true, | |
| 438 | - }); | |
| 439 | - | |
| 440 | - const input = { test: "value" }; | |
| 441 | - const result = customStrategy(input); | |
| 442 | - | |
| 443 | - expect(result).toEqual({ test: "value", custom: true }); | |
| 444 | - }); | |
| 445 | - }); | |
| 446 | - | |
| 447 | 591 | describe("CachingStrategyName type", () => { |
| 448 | 592 | it("should work with valid strategy names", () => { |
| 449 | 593 | const strategyNames: CachingStrategyName[] = [ |
modified packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts +18 −14
| @@ -1,21 +1,25 @@ | ||
| 1 | +import { MessageCreateParams } from "@anthropic-ai/sdk/resources"; | |
| 2 | + | |
| 1 | 3 | const MAX_CACHING_MESSAGES = 4; |
| 2 | 4 | |
| 3 | 5 | // Caching strategy type - transforms a clean Anthropic body by adding cache_control |
| 4 | -export type CachingStrategy = (anthropicBody: any) => any; | |
| 6 | +export type CachingStrategy = ( | |
| 7 | + anthropicBody: MessageCreateParams, | |
| 8 | +) => MessageCreateParams; | |
| 5 | 9 | |
| 6 | 10 | // Utility function to estimate token count |
| 7 | 11 | const estimateTokenCount = (text: string): number => Math.ceil(text.length / 4); |
| 8 | 12 | |
| 9 | -// Strategy 1: No Caching (Baseline) | |
| 13 | +// Strategy 1: No Caching | |
| 10 | 14 | const noCachingStrategy: CachingStrategy = (body) => body; |
| 11 | 15 | |
| 12 | -// Strategy 2: System Messages Only (Current Implementation) | |
| 16 | +// Strategy 2: System Messages Only | |
| 13 | 17 | const systemOnlyStrategy: CachingStrategy = (body) => { |
| 14 | 18 | let availableCacheMessages = MAX_CACHING_MESSAGES; |
| 15 | 19 | if (body.system && Array.isArray(body.system)) { |
| 16 | 20 | return { |
| 17 | 21 | ...body, |
| 18 | - system: body.system.map((item: any) => { | |
| 22 | + system: body.system.map((item) => { | |
| 19 | 23 | if (availableCacheMessages > 0) { |
| 20 | 24 | availableCacheMessages -= 1; |
| 21 | 25 | return { |
| @@ -37,7 +41,7 @@ | ||
| 37 | 41 | |
| 38 | 42 | // Cache system messages |
| 39 | 43 | if (result.system && Array.isArray(result.system)) { |
| 40 | - result.system = result.system.map((item: any) => { | |
| 44 | + result.system = result.system.map((item) => { | |
| 41 | 45 | if (availableCacheMessages > 0) { |
| 42 | 46 | availableCacheMessages -= 1; |
| 43 | 47 | return { |
| @@ -51,8 +55,8 @@ | ||
| 51 | 55 | |
| 52 | 56 | // Cache tool definitions |
| 53 | 57 | if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) { |
| 54 | - result.tools = result.tools.map((tool: any, index: number) => { | |
| 55 | - if (index === result.tools.length - 1 && availableCacheMessages > 0) { | |
| 58 | + result.tools = result.tools.map((tool, index: number) => { | |
| 59 | + if (index === result.tools!.length - 1 && availableCacheMessages > 0) { | |
| 56 | 60 | availableCacheMessages -= 1; |
| 57 | 61 | return { |
| 58 | 62 | ...tool, |
| @@ -73,7 +77,7 @@ | ||
| 73 | 77 | |
| 74 | 78 | // Always cache system messages |
| 75 | 79 | if (result.system && Array.isArray(result.system)) { |
| 76 | - result.system = result.system.map((item: any) => { | |
| 80 | + result.system = result.system.map((item) => { | |
| 77 | 81 | if (availableCacheMessages > 0) { |
| 78 | 82 | availableCacheMessages -= 1; |
| 79 | 83 | return { |
| @@ -87,8 +91,8 @@ | ||
| 87 | 91 | |
| 88 | 92 | // Cache tool definitions |
| 89 | 93 | if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) { |
| 90 | - result.tools = result.tools.map((tool: any, index: number) => { | |
| 91 | - if (index === result.tools.length - 1 && availableCacheMessages > 0) { | |
| 94 | + result.tools = result.tools.map((tool, index: number) => { | |
| 95 | + if (index === result.tools!.length - 1 && availableCacheMessages > 0) { | |
| 92 | 96 | availableCacheMessages -= 1; |
| 93 | 97 | return { |
| 94 | 98 | ...tool, |
| @@ -101,7 +105,7 @@ | ||
| 101 | 105 | |
| 102 | 106 | // Cache large messages (>500 tokens) |
| 103 | 107 | if (result.messages && Array.isArray(result.messages)) { |
| 104 | - result.messages = result.messages.map((message: any) => { | |
| 108 | + result.messages = result.messages.map((message) => { | |
| 105 | 109 | if (message.content && typeof message.content === "string") { |
| 106 | 110 | const tokens = estimateTokenCount(message.content); |
| 107 | 111 | if (tokens > 500 && availableCacheMessages > 0) { |
| @@ -112,7 +116,7 @@ | ||
| 112 | 116 | { |
| 113 | 117 | type: "text", |
| 114 | 118 | text: message.content, |
| 115 | - cache_control: { type: "ephemeral" }, | |
| 119 | + cache_control: { type: "ephemeral" as const }, | |
| 116 | 120 | }, |
| 117 | 121 | ], |
| 118 | 122 | }; |
| @@ -120,7 +124,7 @@ | ||
| 120 | 124 | } else if (message.content && Array.isArray(message.content)) { |
| 121 | 125 | // Only add one cache control per message with array content |
| 122 | 126 | let addedCacheControl = false; |
| 123 | - const updatedContent = message.content.map((item: any) => { | |
| 127 | + const updatedContent = message.content.map((item) => { | |
| 124 | 128 | if (item.type === "text" && item.text) { |
| 125 | 129 | const tokens = estimateTokenCount(item.text); |
| 126 | 130 | if ( |
| @@ -132,7 +136,7 @@ | ||
| 132 | 136 | addedCacheControl = true; |
| 133 | 137 | return { |
| 134 | 138 | ...item, |
| 135 | - cache_control: { type: "ephemeral" }, | |
| 139 | + cache_control: { type: "ephemeral" as const }, | |
| 136 | 140 | }; |
| 137 | 141 | } |
| 138 | 142 | } |
added packages/openai-adapters/src/apis/AnthropicUtils.ts +139 −0
| @@ -0,0 +1,139 @@ | ||
| 1 | +import { | |
| 2 | + Base64ImageSource, | |
| 3 | + ErrorResponse, | |
| 4 | + MessageParam, | |
| 5 | + Tool, | |
| 6 | + ToolChoice, | |
| 7 | +} from "@anthropic-ai/sdk/resources"; | |
| 8 | +import { | |
| 9 | + ChatCompletionTool, | |
| 10 | + ChatCompletionToolChoiceOption, | |
| 11 | +} from "openai/resources"; | |
| 12 | + | |
| 13 | +export function getAnthropicErrorMessage(response: ErrorResponse): string { | |
| 14 | + switch (response.error.type) { | |
| 15 | + case "api_error": | |
| 16 | + return "An unexpected error has occurred internal to Anthropic's systems."; | |
| 17 | + case "invalid_request_error": | |
| 18 | + return "There was an issue with the format or content of your request."; | |
| 19 | + case "authentication_error": | |
| 20 | + return "There's an issue with your API key."; | |
| 21 | + case "permission_error": | |
| 22 | + return "Your API key does not have permission to use the specified resource."; | |
| 23 | + case "not_found_error": | |
| 24 | + return "The requested resource was not found."; | |
| 25 | + case "rate_limit_error": | |
| 26 | + return "Your account has hit a rate limit."; | |
| 27 | + case "overloaded_error": | |
| 28 | + return "Anthropic's API is temporarily overloaded. Please check their status page: https://status.anthropic.com/#past-incidents"; | |
| 29 | + case "timeout_error": | |
| 30 | + return "Anthropic API timed out. Please check their status page: https://status.anthropic.com/#past-incidents"; | |
| 31 | + case "billing_error": | |
| 32 | + default: | |
| 33 | + return response.error.message; | |
| 34 | + } | |
| 35 | +} | |
| 36 | + | |
| 37 | +export function getAnthropicHeaders( | |
| 38 | + apiKey: string, | |
| 39 | + enableCaching: boolean, | |
| 40 | +): Record<string, string> { | |
| 41 | + const headers: Record<string, string> = { | |
| 42 | + "Content-Type": "application/json", | |
| 43 | + Accept: "application/json", | |
| 44 | + "anthropic-version": "2023-06-01", | |
| 45 | + "x-api-key": apiKey, | |
| 46 | + }; | |
| 47 | + | |
| 48 | + if (enableCaching) { | |
| 49 | + headers["anthropic-beta"] = "prompt-caching-2024-07-31"; | |
| 50 | + } | |
| 51 | + return headers; | |
| 52 | +} | |
| 53 | + | |
| 54 | +export function addCacheControlToLastTwoUserMessages(messages: MessageParam[]) { | |
| 55 | + let userMessages = 0; | |
| 56 | + for (let i = messages.length - 1; i >= 0; i--) { | |
| 57 | + const msg = messages[i]; | |
| 58 | + if (msg.role === "user") { | |
| 59 | + userMessages++; | |
| 60 | + if (typeof msg.content === "string") { | |
| 61 | + continue; | |
| 62 | + } | |
| 63 | + for (let j = msg.content.length - 1; j >= 0; j--) { | |
| 64 | + const part = msg.content[j]; | |
| 65 | + if (part.type === "text") { | |
| 66 | + part.cache_control = { type: "ephemeral" }; | |
| 67 | + break; | |
| 68 | + } | |
| 69 | + } | |
| 70 | + if (userMessages >= 2) { | |
| 71 | + break; | |
| 72 | + } | |
| 73 | + } | |
| 74 | + } | |
| 75 | +} | |
| 76 | + | |
| 77 | +export function openAiToolChoiceToAnthropicToolChoice( | |
| 78 | + toolChoice: ChatCompletionToolChoiceOption | undefined, | |
| 79 | +): ToolChoice | undefined { | |
| 80 | + if (!toolChoice) { | |
| 81 | + return undefined; | |
| 82 | + } | |
| 83 | + switch (toolChoice) { | |
| 84 | + case "none": | |
| 85 | + // "none" is handled by excluding tools | |
| 86 | + return undefined; | |
| 87 | + case "required": | |
| 88 | + return { | |
| 89 | + type: "any", | |
| 90 | + }; | |
| 91 | + case "auto": | |
| 92 | + return { | |
| 93 | + type: "auto", | |
| 94 | + }; | |
| 95 | + default: | |
| 96 | + switch (toolChoice.type) { | |
| 97 | + case "allowed_tools": | |
| 98 | + // Filtering of tools is handled elsewhere | |
| 99 | + return { | |
| 100 | + type: toolChoice.allowed_tools.mode === "auto" ? "auto" : "any", | |
| 101 | + }; | |
| 102 | + case "custom": | |
| 103 | + return undefined; // TODO not supported yet | |
| 104 | + case "function": | |
| 105 | + return { | |
| 106 | + type: "tool", | |
| 107 | + name: toolChoice.function.name, | |
| 108 | + }; | |
| 109 | + } | |
| 110 | + } | |
| 111 | +} | |
| 112 | + | |
| 113 | +export function openaiToolToAnthropicTool(tool: ChatCompletionTool): Tool { | |
| 114 | + if (tool.type === "function" && "function" in tool) { | |
| 115 | + return { | |
| 116 | + name: tool.function.name, | |
| 117 | + description: tool.function.description, | |
| 118 | + input_schema: tool.function.parameters as Tool.InputSchema, // TODO unsafe cast, may be differences between openai tool schema and anthropic tool schema, | |
| 119 | + }; | |
| 120 | + } else { | |
| 121 | + throw new Error(`Unsupported tool type in Anthropic: ${tool.type}`); | |
| 122 | + } | |
| 123 | +} | |
| 124 | + | |
| 125 | +// Extract media type from data URL (ex. "data:image/png;base64,..." -> "image/png") | |
| 126 | +export function getAnthropicMediaTypeFromDataUrl( | |
| 127 | + dataUrl: string, | |
| 128 | +): Base64ImageSource["media_type"] { | |
| 129 | + const match = dataUrl.match(/^data:([^;]+);base64,/); | |
| 130 | + if (match) { | |
| 131 | + switch (match[1]) { | |
| 132 | + case "image/png": | |
| 133 | + case "image/gif": | |
| 134 | + case "image/webp": | |
| 135 | + return match[1]; | |
| 136 | + } | |
| 137 | + } | |
| 138 | + return "image/jpeg"; | |
| 139 | +} |
modified packages/openai-adapters/src/index.ts +7 −0
| @@ -177,3 +177,10 @@ | ||
| 177 | 177 | // export |
| 178 | 178 | export type { BaseLlmApi } from "./apis/base.js"; |
| 179 | 179 | export type { LLMConfig } from "./types.js"; |
| 180 | + | |
| 181 | +export { | |
| 182 | + addCacheControlToLastTwoUserMessages, | |
| 183 | + getAnthropicErrorMessage, | |
| 184 | + getAnthropicHeaders, | |
| 185 | + getAnthropicMediaTypeFromDataUrl, | |
| 186 | +} from "./apis/AnthropicUtils.js"; |
modified packages/openai-adapters/src/test/anthropic-adapter.vitest.ts +33 −3
| @@ -50,7 +50,17 @@ | ||
| 50 | 50 | "x-api-key": "test-api-key", |
| 51 | 51 | }, |
| 52 | 52 | body: { |
| 53 | - messages: [{ role: "user", content: "hello" }], | |
| 53 | + messages: [ | |
| 54 | + { | |
| 55 | + role: "user", | |
| 56 | + content: [ | |
| 57 | + { | |
| 58 | + type: "text", | |
| 59 | + text: "hello", | |
| 60 | + }, | |
| 61 | + ], | |
| 62 | + }, | |
| 63 | + ], | |
| 54 | 64 | system: undefined, |
| 55 | 65 | model: "claude-3-5-sonnet-20241022", |
| 56 | 66 | max_tokens: 32000, |
| @@ -104,7 +114,17 @@ | ||
| 104 | 114 | "x-api-key": "test-api-key", |
| 105 | 115 | }, |
| 106 | 116 | body: { |
| 107 | - messages: [{ role: "user", content: "hello" }], | |
| 117 | + messages: [ | |
| 118 | + { | |
| 119 | + role: "user", | |
| 120 | + content: [ | |
| 121 | + { | |
| 122 | + type: "text", | |
| 123 | + text: "hello", | |
| 124 | + }, | |
| 125 | + ], | |
| 126 | + }, | |
| 127 | + ], | |
| 108 | 128 | system: undefined, |
| 109 | 129 | model: "claude-3-5-sonnet-20241022", |
| 110 | 130 | max_tokens: 32000, |
| @@ -159,7 +179,17 @@ | ||
| 159 | 179 | "x-api-key": "test-api-key", |
| 160 | 180 | }, |
| 161 | 181 | body: { |
| 162 | - messages: [{ role: "user", content: "hello" }], | |
| 182 | + messages: [ | |
| 183 | + { | |
| 184 | + role: "user", | |
| 185 | + content: [ | |
| 186 | + { | |
| 187 | + type: "text", | |
| 188 | + text: "hello", | |
| 189 | + }, | |
| 190 | + ], | |
| 191 | + }, | |
| 192 | + ], | |
| 163 | 193 | system: [ |
| 164 | 194 | { |
| 165 | 195 | type: "text", |