Elffuss BraidHub

kikocis/continue public

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
Changesetd04f16ee25ad2d27bcb09dbdd06567f7920e7ff163ba00ade1562c15d17c2bba
AuthorDallin Romney <dallinromney@gmail.com> · 2025-09-24 12:57 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-24 12:57 -07:00
Parents78ceb4f611b1

Browse the files at this changeset

15 files changed

modified core/llm/constants.ts +2 −0
@@ -2,6 +2,7 @@
22 const DEFAULT_CONTEXT_LENGTH = 32_768;
33 const DEFAULT_TEMPERATURE = 0.5;
44 const DEFAULT_PRUNING_LENGTH = 128000;
5+const DEFAULT_REASONING_TOKENS = 2048;
56
67 const DEFAULT_ARGS = {
78 maxTokens: DEFAULT_MAX_TOKENS,
@@ -31,5 +32,6 @@
3132 DEFAULT_MAX_CHUNK_SIZE,
3233 DEFAULT_MAX_TOKENS,
3334 DEFAULT_PRUNING_LENGTH,
35+ DEFAULT_REASONING_TOKENS,
3436 PROXY_URL,
3537 };
modified core/llm/index.ts +8 −7
@@ -65,7 +65,6 @@
6565 toCompleteBody,
6666 toFimBody,
6767 } from "./openaiTypeConverters.js";
68-
6968 export class LLMError extends Error {
7069 constructor(
7170 message: string,
@@ -558,12 +557,14 @@
558557 private _formatChatMessage(msg: ChatMessage): string {
559558 let contentToShow = renderChatMessage(msg);
560559 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");
567568 }
568569
569570 return `<${msg.role}>\n${contentToShow}\n\n`;
modified core/llm/llm-pre-fetch.vitest.ts +4 −0
@@ -58,6 +58,10 @@
5858 describe("LLM Pre-fetch", () => {
5959 beforeEach(() => {
6060 vi.resetAllMocks();
61+ // Mock getAnthropicHeaders to return fake headers
62+ vi.mocked(openAiAdapters.getAnthropicHeaders).mockReturnValue({
63+ fake: "headers",
64+ });
6165 // Log to verify the mock is properly set up
6266 console.log("Mock setup:", openAiAdapters);
6367 });
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";
113 import { streamSse } from "@continuedev/fetch";
14+import {
15+ addCacheControlToLastTwoUserMessages,
16+ getAnthropicErrorMessage,
17+ getAnthropicHeaders,
18+ getAnthropicMediaTypeFromDataUrl,
19+} from "@continuedev/openai-adapters";
220 import {
321 ChatMessage,
422 CompletionOptions,
523 LLMOptions,
24+ MessageContent,
25+ Tool,
26+ ToolCallDelta,
627 Usage,
728 } from "../../index.js";
829 import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
930 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
31+import { DEFAULT_REASONING_TOKENS } from "../constants.js";
1032 import { BaseLLM } from "../index.js";
1133
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-
2834 class Anthropic extends BaseLLM {
2935 static providerName = "anthropic";
3036 static defaultOptions: Partial<LLMOptions> = {
@@ -36,8 +42,21 @@
3642 apiBase: "https://api.anthropic.com/v1/",
3743 };
3844
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"> {
4160 const finalOptions = {
4261 top_k: options.topK,
4362 top_p: options.topP,
@@ -46,20 +65,17 @@
4665 model: options.model === "claude-2" ? "claude-2.1" : options.model,
4766 stop_sequences: options.stop?.filter((x) => x.trim() !== ""),
4867 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),
5469 thinking: options.reasoning
5570 ? {
56- type: "enabled",
57- budget_tokens: options.reasoningBudgetTokens,
71+ type: "enabled" as const,
72+ budget_tokens:
73+ options.reasoningBudgetTokens ?? DEFAULT_REASONING_TOKENS,
5874 }
5975 : undefined,
6076 tool_choice: options.toolChoice
6177 ? {
62- type: "tool",
78+ type: "tool" as const,
6379 name: options.toolChoice.function.name,
6480 }
6581 : undefined,
@@ -68,138 +84,146 @@
6884 return finalOptions;
6985 }
7086
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+ ];
7897 }
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+ });
80114 }
81115
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) {
84122 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 [
87138 {
88139 type: "tool_result",
89140 tool_use_id: message.toolCallId,
90141 content: renderChatMessage(message) || undefined,
91142 },
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+ }
97155 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+ ];
106163 }
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 [];
141186 }
187+ }
142188
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));
155219 }
220+ flushCurrentMessage();
156221
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+ }
181225
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;
203227 }
204228
205229 protected async *_streamComplete(
@@ -224,12 +248,7 @@
224248 if (!response.ok) {
225249 const json = await response.json();
226250 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));
233252 }
234253 throw new Error(
235254 `Anthropic API sent back ${response.status}: ${JSON.stringify(json)}`,
@@ -237,17 +256,17 @@
237256 }
238257
239258 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
242261 ? {
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,
246265 }
247266 : {};
248267 yield {
249268 role: "assistant",
250- content: data.content[0].text,
269+ content: json.content[0].text,
251270 ...(Object.keys(cost).length > 0 ? { cost } : {}),
252271 };
253272 return;
@@ -264,51 +283,59 @@
264283 },
265284 };
266285
267- for await (const value of streamSse(response)) {
286+ for await (const event of streamSse(response)) {
268287 // https://docs.anthropic.com/en/api/messages-streaming#event-types
269- switch (value.type) {
288+ const rawEvent = event as RawMessageStreamEvent;
289+ switch (event.type) {
270290 case "message_start":
271291 // 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;
273294 usage.promptTokensDetails!.cachedTokens =
274- value.message.usage.cache_read_input_tokens;
295+ startEvent.message.usage.cache_read_input_tokens ?? undefined;
275296 usage.promptTokensDetails!.cacheWriteTokens =
276- value.message.usage.cache_creation_input_tokens;
297+ startEvent.message.usage.cache_creation_input_tokens ?? undefined;
277298 break;
278299 case "message_delta":
279300 // 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;
282304 }
283305 break;
284306 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;
288311 }
289312 // handle redacted thinking
290- if (value.content_block.type === "redacted_thinking") {
313+ if (blockStartEvent.content_block.type === "redacted_thinking") {
291314 yield {
292315 role: "thinking",
293316 content: "",
294- redactedThinking: value.content_block.data,
317+ redactedThinking: blockStartEvent.content_block.data,
295318 };
296319 }
297320 break;
298321 case "content_block_delta":
299322 // 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) {
301325 case "text_delta":
302- yield { role: "assistant", content: value.delta.text };
326+ yield { role: "assistant", content: blockDeltaEvent.delta.text };
303327 break;
304328 case "thinking_delta":
305- yield { role: "thinking", content: value.delta.thinking };
329+ yield {
330+ role: "thinking",
331+ content: blockDeltaEvent.delta.thinking,
332+ };
306333 break;
307334 case "signature_delta":
308335 yield {
309336 role: "thinking",
310337 content: "",
311- signature: value.delta.signature,
338+ signature: blockDeltaEvent.delta.signature,
312339 };
313340 break;
314341 case "input_json_delta":
@@ -324,7 +351,7 @@
324351 type: "function",
325352 function: {
326353 name: lastToolUseName,
327- arguments: value.delta.partial_json,
354+ arguments: blockDeltaEvent.delta.partial_json,
328355 },
329356 },
330357 ],
@@ -365,32 +392,35 @@
365392 const shouldCacheSystemMessage = !!(
366393 this.cacheBehavior?.cacheSystemMessage && systemMessage
367394 );
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+ };
368419
369- const msgs = this.convertMessages(messages);
370420 const response = await this.fetch(new URL("messages", this.apiBase), {
371421 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),
394424 signal,
395425 });
396426
modified core/llm/llms/VertexAI.ts +9 −2
@@ -223,6 +223,10 @@
223223 const shouldCacheSystemMessage = !!(
224224 this.cacheBehavior?.cacheSystemMessage && systemMessage
225225 );
226+ const shouldCachePrompt = !!(
227+ this.cacheBehavior?.cacheConversation ??
228+ this.completionOptions.promptCaching
229+ );
226230
227231 // <code>/v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict
228232
@@ -234,13 +238,16 @@
234238 const response = await this.fetch(apiURL, {
235239 method: "POST",
236240 headers: {
237- ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
241+ ...(shouldCacheSystemMessage || shouldCachePrompt
238242 ? { "anthropic-beta": "prompt-caching-2024-07-31" }
239243 : {}),
240244 },
241245 body: JSON.stringify({
242246 ...this._anthropicConvertArgs(options),
243- messages: this.anthropicInstance.convertMessages(messages),
247+ messages: this.anthropicInstance.convertMessages(
248+ messages,
249+ shouldCachePrompt,
250+ ),
244251 system: shouldCacheSystemMessage
245252 ? [
246253 {
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 @@
5454 "vitest": "^3.1.4"
5555 },
5656 "dependencies": {
57+ "@anthropic-ai/sdk": "^0.62.0",
5758 "@aws-sdk/client-bedrock-runtime": "^3.779.0",
5859 "@aws-sdk/client-sagemaker-runtime": "^3.777.0",
5960 "@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 @@
1212 "author": "Nate Sesti and Ty Dunn",
1313 "license": "Apache-2.0",
1414 "dependencies": {
15+ "@anthropic-ai/sdk": "^0.62.0",
1516 "@aws-sdk/client-bedrock-runtime": "^3.842.0",
1617 "@aws-sdk/credential-providers": "^3.840.0",
1718 "@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";
113 import { streamSse } from "@continuedev/fetch";
214 import { OpenAI } from "openai/index";
315 import {
416 ChatCompletion,
517 ChatCompletionChunk,
18+ ChatCompletionContentPartRefusal,
19+ ChatCompletionContentPartText,
620 ChatCompletionCreateParamsNonStreaming,
721 ChatCompletionCreateParamsStreaming,
822 Completion,
@@ -24,6 +38,12 @@
2438 CACHING_STRATEGIES,
2539 CachingStrategyName,
2640 } from "./AnthropicCachingStrategies.js";
41+import {
42+ getAnthropicHeaders,
43+ getAnthropicMediaTypeFromDataUrl,
44+ openAiToolChoiceToAnthropicToolChoice,
45+ openaiToolToAnthropicTool,
46+} from "./AnthropicUtils.js";
2747 import {
2848 BaseLlmApi,
2949 CreateRerankResponse,
@@ -59,11 +79,12 @@
5979 if (model.includes("haiku")) {
6080 return 8192;
6181 }
62-
6382 return 32_000;
6483 }
6584
66- public _convertToCleanAnthropicBody(oaiBody: ChatCompletionCreateParams) {
85+ public _convertToCleanAnthropicBody(
86+ oaiBody: ChatCompletionCreateParams,
87+ ): MessageCreateParams {
6788 let stop = undefined;
6889 if (oaiBody.stop && Array.isArray(oaiBody.stop)) {
6990 stop = oaiBody.stop.filter((x) => x.trim() !== "");
@@ -75,145 +96,198 @@
7596 (msg) => msg.role === "system",
7697 )?.content;
7798
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 = {
79127 messages: this._convertMessages(
80128 oaiBody.messages.filter((msg) => msg.role !== "system"),
81129 ),
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,
92141 max_tokens: oaiBody.max_tokens ?? this.maxTokensForModel(oaiBody.model), // max_tokens is required
93142 model: oaiBody.model,
94143 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),
119147 };
120148
121149 return anthropicBody;
122150 }
123151
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({
147210 type: "text",
148- text: message.content,
211+ text,
149212 });
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- );
157213 }
158214 }
215+ }
216+ }
217+ return blocks;
218+ }
159219
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 = [];
182274 }
275+ };
183276
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;
186285 }
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;
217291 }
218292
219293 async chatCompletionNonStream(
@@ -224,13 +298,7 @@
224298 new URL("messages", this.apiBase),
225299 {
226300 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(),
234302 body: JSON.stringify(this._convertBody(body)),
235303 signal,
236304 },
@@ -240,7 +308,7 @@
240308 return EMPTY_CHAT_COMPLETION;
241309 }
242310
243- const completion = (await response.json()) as any;
311+ const completion = await response.json();
244312
245313 const usage: Record<string, number> | undefined = completion.usage;
246314 return {
@@ -281,30 +349,36 @@
281349 prompt_tokens: 0,
282350 total_tokens: 0,
283351 };
284- for await (const value of streamSse(response as any)) {
352+ for await (const event of streamSse(response)) {
285353 // https://docs.anthropic.com/en/api/messages-streaming#event-types
286- switch (value.type) {
354+ const rawEvent = event as RawMessageStreamEvent;
355+ switch (rawEvent.type) {
287356 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;
291361 }
292362 break;
293363 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;
295366 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,
297369 };
298370 break;
299371 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;
301374 break;
302375 case "content_block_delta":
303376 // 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) {
305379 case "text_delta":
306380 yield chatChunk({
307- content: value.delta.text,
381+ content: blockDeltaEvent.delta.text,
308382 model,
309383 });
310384 break;
@@ -322,7 +396,7 @@
322396 index: 0,
323397 function: {
324398 name: lastToolUseName,
325- arguments: value.delta.partial_json,
399+ arguments: blockDeltaEvent.delta.partial_json,
326400 },
327401 },
328402 ],
@@ -352,25 +426,24 @@
352426 async *chatCompletionStream(
353427 body: ChatCompletionCreateParamsStreaming,
354428 signal: AbortSignal,
355- ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
356- body.messages;
429+ ): AsyncGenerator<ChatCompletionChunk> {
357430 const response = await customFetch(this.config.requestOptions)(
358431 new URL("messages", this.apiBase),
359432 {
360433 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(),
368435 body: JSON.stringify(this._convertBody(body)),
369436 signal,
370437 },
371438 );
372439 yield* this.handleStreamResponse(response, body.model);
373440 }
441+
442+ private getHeaders(): Record<string, string> {
443+ const enableCaching = this.config?.cachingStrategy !== "none";
444+ return getAnthropicHeaders(this.config.apiKey, enableCaching);
445+ }
446+
374447 async completionNonStream(
375448 body: CompletionCreateParamsNonStreaming,
376449 signal: AbortSignal,
@@ -380,13 +453,13 @@
380453 async *completionStream(
381454 body: CompletionCreateParamsStreaming,
382455 signal: AbortSignal,
383- ): AsyncGenerator<Completion, any, unknown> {
456+ ): AsyncGenerator<Completion> {
384457 throw new Error("Method not implemented.");
385458 }
386459 async *fimStream(
387460 body: FimCreateParamsStreaming,
388461 signal: AbortSignal,
389- ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
462+ ): AsyncGenerator<ChatCompletionChunk> {
390463 throw new Error("Method not implemented.");
391464 }
392465
modified packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts +277 −133
@@ -1,24 +1,42 @@
1+import { MessageCreateParams, ToolUnion } from "@anthropic-ai/sdk/resources";
12 import {
23 CACHING_STRATEGIES,
3- CachingStrategy,
44 CachingStrategyName,
55 getAvailableStrategies,
66 getStrategyDescription,
77 } from "./AnthropicCachingStrategies.js";
88
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+
922 describe("AnthropicCachingStrategies", () => {
1023 describe("noCachingStrategy", () => {
1124 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+ };
1330 const result = CACHING_STRATEGIES.none(body);
1431 expect(result).toBe(body);
1532 });
1633
1734 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,
2240 };
2341 const result = CACHING_STRATEGIES.none(body);
2442 expect(result).toBe(body);
@@ -27,24 +45,37 @@
2745
2846 describe("systemOnlyStrategy", () => {
2947 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,
3355 };
3456
3557 const result = CACHING_STRATEGIES.systemOnly(body);
3658
3759 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+ },
4070 ]);
4171 expect(result.messages).toEqual(body.messages);
4272 });
4373
4474 it("should return body unchanged if system is not an array", () => {
45- const body = {
75+ const body: MessageCreateParams = {
4676 system: "string system message",
47- messages: [{ content: "user message" }],
77+ messages: [{ role: "user", content: "user message" }],
78+ ...body_params,
4879 };
4980
5081 const result = CACHING_STRATEGIES.systemOnly(body);
@@ -52,8 +83,9 @@
5283 });
5384
5485 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,
5789 };
5890
5991 const result = CACHING_STRATEGIES.systemOnly(body);
@@ -61,25 +93,42 @@
6193 });
6294
6395 it("should not add more than 5 cached messages", () => {
64- const body = {
96+ const body: MessageCreateParams = {
6597 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" },
71103 ],
72- messages: [{ content: "user message" }],
104+ messages: [{ role: "user", content: "user message" }],
105+ ...body_params,
73106 };
74107
75108 const result = CACHING_STRATEGIES.systemOnly(body);
76109
77110 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" },
83132 ]);
84133 expect(result.messages).toEqual(body.messages);
85134 });
@@ -87,82 +136,116 @@
87136
88137 describe("systemAndToolsStrategy", () => {
89138 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,
94144 };
95145
96146 const result = CACHING_STRATEGIES.systemAndTools(body);
97147
98148 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+ },
100154 ]);
101155 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+ },
104169 ]);
105170 expect(result.messages).toEqual(body.messages);
106171 });
107172
108173 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,
112178 };
113179
114180 const result = CACHING_STRATEGIES.systemAndTools(body);
115181
116182 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+ },
118190 ]);
119191 expect(result.messages).toEqual(body.messages);
120192 });
121193
122194 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,
126199 };
127200
128201 const result = CACHING_STRATEGIES.systemAndTools(body);
129202
130203 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+ },
132209 ]);
133210 expect(result.messages).toEqual(body.messages);
134211 });
135212
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-
147213 it("should add only 4 cache controls in total to both system and tools", () => {
148- const body = {
214+ const body: MessageCreateParams = {
149215 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" },
154220 ],
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,
157224 };
158225
159226 const result = CACHING_STRATEGIES.systemAndTools(body);
160227
161228 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+ },
166249 ]);
167250 expect(result.tools).toEqual(body.tools);
168251 expect(result.messages).toEqual(body.messages);
@@ -171,32 +254,45 @@
171254
172255 describe("optimizedStrategy", () => {
173256 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,
178262 };
179263
180264 const result = CACHING_STRATEGIES.optimized(body);
181265
182266 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+ },
184272 ]);
185273 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+ },
187281 ]);
188282 });
189283
190284 it("should cache large string messages (>500 tokens)", () => {
191285 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,
194289 };
195290
196291 const result = CACHING_STRATEGIES.optimized(body);
197292
198293 expect(result.messages).toEqual([
199294 {
295+ role: "user",
200296 content: [
201297 {
202298 type: "text",
@@ -210,30 +306,42 @@
210306
211307 it("should not cache small string messages (<500 tokens)", () => {
212308 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,
215312 };
216313
217314 const result = CACHING_STRATEGIES.optimized(body);
218315
219- expect(result.messages).toEqual([{ content: smallContent }]);
316+ expect(result.messages).toEqual([
317+ { role: "user", content: smallContent },
318+ ]);
220319 });
221320
222321 it("should cache large text items in array content but only once per message", () => {
223322 const largeText = "a".repeat(2100); // ~525 tokens
224323 const anotherLargeText = "b".repeat(2100); // Also ~525 tokens
225324 const smallText = "a".repeat(100); // ~25 tokens
226- const body = {
325+ const body: MessageCreateParams = {
227326 messages: [
228327 {
328+ role: "user",
229329 content: [
230330 { type: "text", text: largeText },
231331 { type: "text", text: anotherLargeText },
232332 { 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+ },
234341 ],
235342 },
236343 ],
344+ ...body_params,
237345 };
238346
239347 const result = CACHING_STRATEGIES.optimized(body);
@@ -241,6 +349,7 @@
241349 // Only the first large text item should get cache_control
242350 expect(result.messages).toEqual([
243351 {
352+ role: "user",
244353 content: [
245354 {
246355 type: "text",
@@ -249,40 +358,78 @@
249358 },
250359 { type: "text", text: anotherLargeText },
251360 { 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+ },
253369 ],
254370 },
255371 ]);
256372 });
257373
258374 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")],
262381 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) },
266385 {
386+ role: "user",
267387 content: [
268388 { 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+ },
270397 ],
271398 },
272399 ],
400+ ...body_params,
273401 };
274402
275403 const result = CACHING_STRATEGIES.optimized(body);
276404
277405 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+ },
280416 ]);
281417 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+ },
283425 ]);
284- expect(result.messages[0]).toEqual({ content: "small content" });
426+ expect(result.messages[0]).toEqual({
427+ role: "user",
428+ content: "small content",
429+ });
430+
285431 expect(result.messages[1]).toEqual({
432+ role: "user",
286433 content: [
287434 {
288435 type: "text",
@@ -296,31 +443,50 @@
296443 });
297444
298445 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")],
302449 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
305452 {
453+ role: "user",
306454 content: [
307455 { 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+ },
309464 ],
310465 },
311466 ],
467+ ...body_params,
312468 };
313469
314470 const result = CACHING_STRATEGIES.optimized(body);
315471
316472 expect(result.system).toEqual([
317- { text: "system", cache_control: { type: "ephemeral" } },
473+ { type: "text", text: "system", cache_control: { type: "ephemeral" } },
318474 ]);
319475 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+ },
321483 ]);
322- expect(result.messages[0]).toEqual({ content: "small content" });
484+ expect(result.messages[0]).toEqual({
485+ role: "user",
486+ content: "small content",
487+ });
323488 expect(result.messages[1]).toEqual({
489+ role: "user",
324490 content: [
325491 {
326492 type: "text",
@@ -337,30 +503,17 @@
337503 });
338504
339505 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,
356510 };
357511
358512 const result = CACHING_STRATEGIES.optimized(body);
359513
360514 expect(result.system).toEqual([
361- { text: "system", cache_control: { type: "ephemeral" } },
515+ { type: "text", text: "system", cache_control: { type: "ephemeral" } },
362516 ]);
363- expect(result.messages).toBe("not an array");
364517 });
365518 });
366519
@@ -370,8 +523,14 @@
370523 const smallContent = "a".repeat(100); // ~25 tokens
371524 const largeContent = "a".repeat(2100); // ~525 tokens
372525
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+ };
375534
376535 const resultSmall = CACHING_STRATEGIES.optimized(bodySmall);
377536 const resultLarge = CACHING_STRATEGIES.optimized(bodyLarge);
@@ -429,21 +588,6 @@
429588 });
430589 });
431590 });
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-
447591 describe("CachingStrategyName type", () => {
448592 it("should work with valid strategy names", () => {
449593 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+
13 const MAX_CACHING_MESSAGES = 4;
24
35 // 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;
59
610 // Utility function to estimate token count
711 const estimateTokenCount = (text: string): number => Math.ceil(text.length / 4);
812
9-// Strategy 1: No Caching (Baseline)
13+// Strategy 1: No Caching
1014 const noCachingStrategy: CachingStrategy = (body) => body;
1115
12-// Strategy 2: System Messages Only (Current Implementation)
16+// Strategy 2: System Messages Only
1317 const systemOnlyStrategy: CachingStrategy = (body) => {
1418 let availableCacheMessages = MAX_CACHING_MESSAGES;
1519 if (body.system && Array.isArray(body.system)) {
1620 return {
1721 ...body,
18- system: body.system.map((item: any) => {
22+ system: body.system.map((item) => {
1923 if (availableCacheMessages > 0) {
2024 availableCacheMessages -= 1;
2125 return {
@@ -37,7 +41,7 @@
3741
3842 // Cache system messages
3943 if (result.system && Array.isArray(result.system)) {
40- result.system = result.system.map((item: any) => {
44+ result.system = result.system.map((item) => {
4145 if (availableCacheMessages > 0) {
4246 availableCacheMessages -= 1;
4347 return {
@@ -51,8 +55,8 @@
5155
5256 // Cache tool definitions
5357 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) {
5660 availableCacheMessages -= 1;
5761 return {
5862 ...tool,
@@ -73,7 +77,7 @@
7377
7478 // Always cache system messages
7579 if (result.system && Array.isArray(result.system)) {
76- result.system = result.system.map((item: any) => {
80+ result.system = result.system.map((item) => {
7781 if (availableCacheMessages > 0) {
7882 availableCacheMessages -= 1;
7983 return {
@@ -87,8 +91,8 @@
8791
8892 // Cache tool definitions
8993 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) {
9296 availableCacheMessages -= 1;
9397 return {
9498 ...tool,
@@ -101,7 +105,7 @@
101105
102106 // Cache large messages (>500 tokens)
103107 if (result.messages && Array.isArray(result.messages)) {
104- result.messages = result.messages.map((message: any) => {
108+ result.messages = result.messages.map((message) => {
105109 if (message.content && typeof message.content === "string") {
106110 const tokens = estimateTokenCount(message.content);
107111 if (tokens > 500 && availableCacheMessages > 0) {
@@ -112,7 +116,7 @@
112116 {
113117 type: "text",
114118 text: message.content,
115- cache_control: { type: "ephemeral" },
119+ cache_control: { type: "ephemeral" as const },
116120 },
117121 ],
118122 };
@@ -120,7 +124,7 @@
120124 } else if (message.content && Array.isArray(message.content)) {
121125 // Only add one cache control per message with array content
122126 let addedCacheControl = false;
123- const updatedContent = message.content.map((item: any) => {
127+ const updatedContent = message.content.map((item) => {
124128 if (item.type === "text" && item.text) {
125129 const tokens = estimateTokenCount(item.text);
126130 if (
@@ -132,7 +136,7 @@
132136 addedCacheControl = true;
133137 return {
134138 ...item,
135- cache_control: { type: "ephemeral" },
139+ cache_control: { type: "ephemeral" as const },
136140 };
137141 }
138142 }
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 @@
177177 // export
178178 export type { BaseLlmApi } from "./apis/base.js";
179179 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 @@
5050 "x-api-key": "test-api-key",
5151 },
5252 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+ ],
5464 system: undefined,
5565 model: "claude-3-5-sonnet-20241022",
5666 max_tokens: 32000,
@@ -104,7 +114,17 @@
104114 "x-api-key": "test-api-key",
105115 },
106116 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+ ],
108128 system: undefined,
109129 model: "claude-3-5-sonnet-20241022",
110130 max_tokens: 32000,
@@ -159,7 +179,17 @@
159179 "x-api-key": "test-api-key",
160180 },
161181 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+ ],
163193 system: [
164194 {
165195 type: "text",