Elffuss BraidHub

kikocis/continue public

a36aa2a5e5e6 · 9.5 KiBRawPermalink
1import { streamSse } from "@continuedev/fetch";
2import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
3import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
4import { renderChatMessage, stripImages } from "../../util/messageContent.js";
5import { BaseLLM } from "../index.js";
6
7class Anthropic extends BaseLLM {
8 static providerName = "anthropic";
9 static defaultOptions: Partial<LLMOptions> = {
10 model: "claude-3-5-sonnet-latest",
11 completionOptions: {
12 model: "claude-3-5-sonnet-latest",
13 maxTokens: 8192,
14 },
15 apiBase: "https://api.anthropic.com/v1/",
16 };
17
18 public convertArgs(options: CompletionOptions) {
19 // should be public for use within VertexAI
20 const finalOptions = {
21 top_k: options.topK,
22 top_p: options.topP,
23 temperature: options.temperature,
24 max_tokens: options.maxTokens ?? 2048,
25 model: options.model === "claude-2" ? "claude-2.1" : options.model,
26 stop_sequences: options.stop?.filter((x) => x.trim() !== ""),
27 stream: options.stream ?? true,
28 tools: options.tools?.map((tool) => ({
29 name: tool.function.name,
30 description: tool.function.description,
31 input_schema: tool.function.parameters,
32 })),
33 thinking: options.reasoning
34 ? {
35 type: "enabled",
36 budget_tokens: options.reasoningBudgetTokens,
37 }
38 : undefined,
39 tool_choice: options.toolChoice
40 ? {
41 type: "tool",
42 name: options.toolChoice.function.name,
43 }
44 : undefined,
45 };
46
47 return finalOptions;
48 }
49
50 private convertMessage(message: ChatMessage, addCaching: boolean): any {
51 if (message.role === "tool") {
52 return {
53 role: "user",
54 content: [
55 {
56 type: "tool_result",
57 tool_use_id: message.toolCallId,
58 content: renderChatMessage(message) || undefined,
59 },
60 ],
61 };
62 } else if (message.role === "assistant" && message.toolCalls) {
63 return {
64 role: "assistant",
65 content: message.toolCalls.map((toolCall) => ({
66 type: "tool_use",
67 id: toolCall.id,
68 name: toolCall.function?.name,
69 input: safeParseToolCallArgs(toolCall),
70 })),
71 };
72 } else if (message.role === "thinking" && !message.redactedThinking) {
73 return {
74 role: "assistant",
75 content: [
76 {
77 type: "thinking",
78 thinking: message.content,
79 signature: message.signature,
80 },
81 ],
82 };
83 } else if (message.role === "thinking" && message.redactedThinking) {
84 return {
85 role: "assistant",
86 content: [
87 {
88 type: "redacted_thinking",
89 data: message.redactedThinking,
90 },
91 ],
92 };
93 }
94
95 if (typeof message.content === "string") {
96 var chatMessage = {
97 role: message.role,
98 content: [
99 {
100 type: "text",
101 text: message.content,
102 ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}),
103 },
104 ],
105 };
106 return chatMessage;
107 }
108
109 return {
110 role: message.role,
111 content: message.content.map((part, contentIdx) => {
112 if (part.type === "text") {
113 const newpart = {
114 ...part,
115 // If multiple text parts, only add cache_control to the last one
116 ...(addCaching && contentIdx === message.content.length - 1
117 ? { cache_control: { type: "ephemeral" } }
118 : {}),
119 };
120 return newpart;
121 }
122 return {
123 type: "image",
124 source: {
125 type: "base64",
126 media_type: "image/jpeg",
127 data: part.imageUrl?.url.split(",")[1],
128 },
129 };
130 }),
131 };
132 }
133
134 public convertMessages(msgs: ChatMessage[]): any[] {
135 // should be public for use within VertexAI
136 const filteredmessages = msgs.filter(
137 (m) => m.role !== "system" && !!m.content,
138 );
139 const lastTwoUserMsgIndices = filteredmessages
140 .map((msg, index) => (msg.role === "user" ? index : -1))
141 .filter((index) => index !== -1)
142 .slice(-2);
143
144 const messages = filteredmessages.map((message, filteredMsgIdx) => {
145 // Add cache_control parameter to the last two user messages
146 // The second-to-last because it retrieves potentially already cached contents,
147 // The last one because we want it cached for later retrieval.
148 // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
149 const addCaching =
150 this.cacheBehavior?.cacheConversation &&
151 lastTwoUserMsgIndices.includes(filteredMsgIdx);
152
153 const chatMessage = this.convertMessage(message, !!addCaching);
154 return chatMessage;
155 });
156 return messages;
157 }
158
159 protected async *_streamComplete(
160 prompt: string,
161 signal: AbortSignal,
162 options: CompletionOptions,
163 ): AsyncGenerator<string> {
164 const messages = [{ role: "user" as const, content: prompt }];
165 for await (const update of this._streamChat(messages, signal, options)) {
166 yield renderChatMessage(update);
167 }
168 }
169
170 protected async *_streamChat(
171 messages: ChatMessage[],
172 signal: AbortSignal,
173 options: CompletionOptions,
174 ): AsyncGenerator<ChatMessage> {
175 if (!this.apiKey || this.apiKey === "") {
176 throw new Error(
177 "Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
178 );
179 }
180
181 const systemMessage = stripImages(
182 messages.filter((m) => m.role === "system")[0]?.content ?? "",
183 );
184 const shouldCacheSystemMessage = !!(
185 this.cacheBehavior?.cacheSystemMessage && systemMessage
186 );
187
188 const msgs = this.convertMessages(messages);
189 const response = await this.fetch(new URL("messages", this.apiBase), {
190 method: "POST",
191 headers: {
192 "Content-Type": "application/json",
193 Accept: "application/json",
194 "anthropic-version": "2023-06-01",
195 "x-api-key": this.apiKey as string,
196 ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
197 ? { "anthropic-beta": "prompt-caching-2024-07-31" }
198 : {}),
199 },
200 body: JSON.stringify({
201 ...this.convertArgs(options),
202 messages: msgs,
203 system: shouldCacheSystemMessage
204 ? [
205 {
206 type: "text",
207 text: systemMessage,
208 cache_control: { type: "ephemeral" },
209 },
210 ]
211 : systemMessage,
212 }),
213 signal,
214 });
215
216 if (response.status === 499) {
217 return; // Aborted by user
218 }
219
220 if (!response.ok) {
221 const json = await response.json();
222 if (json.type === "error") {
223 if (json.error?.type === "overloaded_error") {
224 throw new Error(
225 "The Anthropic API is currently overloaded. Please check their status page: https://status.anthropic.com/#past-incidents",
226 );
227 }
228 throw new Error(json.message);
229 }
230 throw new Error(
231 `Anthropic API sent back ${response.status}: ${JSON.stringify(json)}`,
232 );
233 }
234
235 if (options.stream === false) {
236 const data = await response.json();
237 yield { role: "assistant", content: data.content[0].text };
238 return;
239 }
240
241 let lastToolUseId: string | undefined;
242 let lastToolUseName: string | undefined;
243 for await (const value of streamSse(response)) {
244 // https://docs.anthropic.com/en/api/messages-streaming#event-types
245 switch (value.type) {
246 case "content_block_start":
247 if (value.content_block.type === "tool_use") {
248 lastToolUseId = value.content_block.id;
249 lastToolUseName = value.content_block.name;
250 }
251 // handle redacted thinking
252 if (value.content_block.type === "redacted_thinking") {
253 console.log("redacted thinking", value.content_block.data);
254 yield {
255 role: "thinking",
256 content: "",
257 redactedThinking: value.content_block.data,
258 };
259 }
260 break;
261 case "content_block_delta":
262 // https://docs.anthropic.com/en/api/messages-streaming#delta-types
263 switch (value.delta.type) {
264 case "text_delta":
265 yield { role: "assistant", content: value.delta.text };
266 break;
267 case "thinking_delta":
268 yield { role: "thinking", content: value.delta.thinking };
269 break;
270 case "signature_delta":
271 yield {
272 role: "thinking",
273 content: "",
274 signature: value.delta.signature,
275 };
276 break;
277 case "input_json_delta":
278 if (!lastToolUseId || !lastToolUseName) {
279 throw new Error("No tool use found");
280 }
281 yield {
282 role: "assistant",
283 content: "",
284 toolCalls: [
285 {
286 id: lastToolUseId,
287 type: "function",
288 function: {
289 name: lastToolUseName,
290 arguments: value.delta.partial_json,
291 },
292 },
293 ],
294 };
295 break;
296 }
297 break;
298 case "content_block_stop":
299 lastToolUseId = undefined;
300 lastToolUseName = undefined;
301 break;
302 default:
303 break;
304 }
305 }
306 }
307}
308
309export default Anthropic;