Elffuss BraidHub

kikocis/continue public

main · 12.5 KiBRawPermalink
1import {
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";
13import { streamSse } from "@continuedev/fetch";
14import {
15 addCacheControlToLastTwoUserMessages,
16 getAnthropicErrorMessage,
17 getAnthropicHeaders,
18 getAnthropicMediaTypeFromDataUrl,
19} from "@continuedev/openai-adapters";
20import {
21 ChatMessage,
22 CompletionOptions,
23 LLMOptions,
24 MessageContent,
25 Tool,
26 ToolCallDelta,
27 Usage,
28} from "../../index.js";
29import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
30import { renderChatMessage, stripImages } from "../../util/messageContent.js";
31import { DEFAULT_REASONING_TOKENS } from "../constants.js";
32import { BaseLLM } from "../index.js";
33
34class Anthropic extends BaseLLM {
35 static providerName = "anthropic";
36 static defaultOptions: Partial<LLMOptions> = {
37 model: "claude-3-5-sonnet-latest",
38 completionOptions: {
39 model: "claude-3-5-sonnet-latest",
40 maxTokens: 8192,
41 },
42 apiBase: "https://api.anthropic.com/v1/",
43 };
44
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"> {
60 const finalOptions = {
61 top_k: options.topK,
62 top_p: options.topP,
63 temperature: options.temperature,
64 max_tokens: options.maxTokens ?? 2048,
65 model: options.model === "claude-2" ? "claude-2.1" : options.model,
66 stop_sequences: options.stop?.filter((x) => x.trim() !== ""),
67 stream: options.stream ?? true,
68 tools: options.tools?.map(this.convertToolToAnthropicTool),
69 thinking: options.reasoning
70 ? {
71 type: "enabled" as const,
72 budget_tokens:
73 options.reasoningBudgetTokens ?? DEFAULT_REASONING_TOKENS,
74 }
75 : undefined,
76 tool_choice: options.toolChoice
77 ? {
78 type: "tool" as const,
79 name: options.toolChoice.function.name,
80 }
81 : undefined,
82 };
83
84 return finalOptions;
85 }
86
87 private convertMessageContentToBlocks(
88 content: MessageContent,
89 ): ContentBlockParam[] {
90 if (typeof content === "string") {
91 return [
92 {
93 type: "text",
94 text: content,
95 },
96 ];
97 }
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 });
114 }
115
116 private convertToolCallsToBlocks(
117 toolCall: ToolCallDelta,
118 ): ToolUseBlock | undefined {
119 const toolCallId = toolCall.id;
120 const toolName = toolCall.function?.name;
121 if (toolCallId && toolName) {
122 return {
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 [
138 {
139 type: "tool_result",
140 tool_use_id: message.toolCallId,
141 content: renderChatMessage(message) || undefined,
142 },
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 }
155 if (typeof message.content === "string") {
156 return [
157 {
158 type: "thinking",
159 thinking: message.content,
160 signature: message.signature ?? "", // TODO - unsafe signature
161 },
162 ];
163 }
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 [];
186 }
187 }
188
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));
219 }
220 flushCurrentMessage();
221
222 if (cachePrompt) {
223 addCacheControlToLastTwoUserMessages(convertedMessages);
224 }
225
226 return convertedMessages;
227 }
228
229 protected async *_streamComplete(
230 prompt: string,
231 signal: AbortSignal,
232 options: CompletionOptions,
233 ): AsyncGenerator<string> {
234 const messages = [{ role: "user" as const, content: prompt }];
235 for await (const update of this._streamChat(messages, signal, options)) {
236 yield renderChatMessage(update);
237 }
238 }
239
240 async *handleResponse(
241 response: any,
242 stream: boolean | undefined,
243 ): AsyncGenerator<ChatMessage> {
244 if (response.status === 499) {
245 return; // Aborted by user
246 }
247
248 if (!response.ok) {
249 const json = await response.json();
250 if (json.type === "error") {
251 throw new Error(getAnthropicErrorMessage(json));
252 }
253 throw new Error(
254 `Anthropic API sent back ${response.status}: ${JSON.stringify(json)}`,
255 );
256 }
257
258 if (stream === false) {
259 const json = await response.json();
260 const cost = json.usage
261 ? {
262 inputTokens: json.usage.input_tokens,
263 outputTokens: json.usage.output_tokens,
264 totalTokens: json.usage.input_tokens + json.usage.output_tokens,
265 }
266 : {};
267 yield {
268 role: "assistant",
269 content: json.content[0].text,
270 ...(Object.keys(cost).length > 0 ? { cost } : {}),
271 };
272 return;
273 }
274
275 let lastToolUseId: string | undefined;
276 let lastToolUseName: string | undefined;
277 let usage: Usage = {
278 promptTokens: 0,
279 completionTokens: 0,
280 promptTokensDetails: {
281 cachedTokens: 0,
282 cacheWriteTokens: 0,
283 },
284 };
285
286 for await (const event of streamSse(response)) {
287 // https://docs.anthropic.com/en/api/messages-streaming#event-types
288 const rawEvent = event as RawMessageStreamEvent;
289 switch (event.type) {
290 case "message_start":
291 // Capture initial usage information
292 const startEvent = rawEvent as RawMessageStartEvent;
293 usage.promptTokens = startEvent.message.usage.input_tokens;
294 usage.promptTokensDetails!.cachedTokens =
295 startEvent.message.usage.cache_read_input_tokens ?? undefined;
296 usage.promptTokensDetails!.cacheWriteTokens =
297 startEvent.message.usage.cache_creation_input_tokens ?? undefined;
298 break;
299 case "message_delta":
300 // Update usage information during streaming
301 const deltaEvent = rawEvent as RawMessageDeltaEvent;
302 if (deltaEvent.usage) {
303 usage.completionTokens = deltaEvent.usage.output_tokens;
304 }
305 break;
306 case "content_block_start":
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;
311 }
312 // handle redacted thinking
313 if (blockStartEvent.content_block.type === "redacted_thinking") {
314 yield {
315 role: "thinking",
316 content: "",
317 redactedThinking: blockStartEvent.content_block.data,
318 };
319 }
320 break;
321 case "content_block_delta":
322 // https://docs.anthropic.com/en/api/messages-streaming#delta-types
323 const blockDeltaEvent = rawEvent as RawContentBlockDeltaEvent;
324 switch (blockDeltaEvent.delta.type) {
325 case "text_delta":
326 yield { role: "assistant", content: blockDeltaEvent.delta.text };
327 break;
328 case "thinking_delta":
329 yield {
330 role: "thinking",
331 content: blockDeltaEvent.delta.thinking,
332 };
333 break;
334 case "signature_delta":
335 yield {
336 role: "thinking",
337 content: "",
338 signature: blockDeltaEvent.delta.signature,
339 };
340 break;
341 case "input_json_delta":
342 if (!lastToolUseId || !lastToolUseName) {
343 throw new Error("No tool use found");
344 }
345 yield {
346 role: "assistant",
347 content: "",
348 toolCalls: [
349 {
350 id: lastToolUseId,
351 type: "function",
352 function: {
353 name: lastToolUseName,
354 arguments: blockDeltaEvent.delta.partial_json,
355 },
356 },
357 ],
358 };
359 break;
360 }
361 break;
362 case "content_block_stop":
363 lastToolUseId = undefined;
364 lastToolUseName = undefined;
365 break;
366 default:
367 break;
368 }
369 }
370
371 yield {
372 role: "assistant",
373 content: "",
374 usage,
375 };
376 }
377
378 protected async *_streamChat(
379 messages: ChatMessage[],
380 signal: AbortSignal,
381 options: CompletionOptions,
382 ): AsyncGenerator<ChatMessage> {
383 if (!this.apiKey || this.apiKey === "") {
384 throw new Error(
385 "Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
386 );
387 }
388
389 const systemMessage = stripImages(
390 messages.filter((m) => m.role === "system")[0]?.content ?? "",
391 );
392 const shouldCacheSystemMessage = !!(
393 this.cacheBehavior?.cacheSystemMessage && systemMessage
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 };
419
420 const response = await this.fetch(new URL("messages", this.apiBase), {
421 method: "POST",
422 headers,
423 body: JSON.stringify(body),
424 signal,
425 });
426
427 yield* this.handleResponse(response, options.stream);
428 }
429}
430
431export default Anthropic;