Elffuss BraidHub

kikocis/continue public

87f75892af56 · 24.0 KiBRawPermalink
1import {
2 BedrockRuntimeClient,
3 ContentBlock,
4 ConversationRole,
5 ConverseStreamCommand,
6 ConverseStreamCommandOutput,
7 ImageFormat,
8 InvokeModelCommand,
9 Message,
10 ToolConfiguration,
11} from "@aws-sdk/client-bedrock-runtime";
12import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
13
14import type { CompletionOptions } from "../../index.js";
15import { ChatMessage, Chunk, LLMOptions, MessageContent } from "../../index.js";
16import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
17import { renderChatMessage, stripImages } from "../../util/messageContent.js";
18import { BaseLLM } from "../index.js";
19import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
20import { getSecureID } from "../utils/getSecureID.js";
21import { withLLMRetry } from "../utils/retry.js";
22
23interface ModelConfig {
24 formatPayload: (text: string) => any;
25 extractEmbeddings: (responseBody: any) => number[][];
26}
27
28/**
29 * Interface for tool use state tracking
30 */
31interface ToolUseState {
32 toolUseId: string;
33 name: string;
34 input: string;
35}
36
37/**
38 * Interface for prompt caching metrics
39 */
40interface PromptCachingMetrics {
41 cacheReadInputTokens: number;
42 cacheWriteInputTokens: number;
43}
44
45class Bedrock extends BaseLLM {
46 static providerName = "bedrock";
47 static defaultOptions: Partial<LLMOptions> = {
48 region: "us-east-1",
49 model: "anthropic.claude-3-sonnet-20240229-v1:0",
50 profile: "bedrock",
51 };
52
53 private _currentToolResponse: Partial<ToolUseState> | null = null;
54 private _promptCachingMetrics: PromptCachingMetrics = {
55 cacheReadInputTokens: 0,
56 cacheWriteInputTokens: 0,
57 };
58
59 public requestOptions: {
60 region?: string;
61 credentials?: any;
62 headers?: Record<string, string>;
63 };
64
65 constructor(options: LLMOptions) {
66 super(options);
67 if (!options.apiBase) {
68 this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
69 }
70
71 this.requestOptions = {
72 region: options.region,
73 headers: {},
74 };
75 }
76
77 protected async *_streamComplete(
78 prompt: string,
79 signal: AbortSignal,
80 options: CompletionOptions,
81 ): AsyncGenerator<string> {
82 const messages = [{ role: "user" as const, content: prompt }];
83 for await (const update of this._streamChat(messages, signal, options)) {
84 yield renderChatMessage(update);
85 }
86 }
87
88 @withLLMRetry()
89 protected async *_streamChat(
90 messages: ChatMessage[],
91 signal: AbortSignal,
92 options: CompletionOptions,
93 ): AsyncGenerator<ChatMessage> {
94 const credentials = await this._getCredentials();
95 const client = new BedrockRuntimeClient({
96 region: this.region,
97 endpoint: this.apiBase,
98 credentials: {
99 accessKeyId: credentials.accessKeyId,
100 secretAccessKey: credentials.secretAccessKey,
101 sessionToken: credentials.sessionToken || "",
102 },
103 });
104
105 let config_headers =
106 this.requestOptions && this.requestOptions.headers
107 ? this.requestOptions.headers
108 : {};
109 // AWS SigV4 requires strict canonicalization of headers.
110 // DO NOT USE "_" in your header name. It will return an error like below.
111 // "The request signature we calculated does not match the signature you provided."
112
113 client.middlewareStack.add(
114 (next) => async (args: any) => {
115 args.request.headers = {
116 ...args.request.headers,
117 ...config_headers,
118 };
119 return next(args);
120 },
121 {
122 step: "build",
123 },
124 );
125
126 const input = this._generateConverseInput(messages, {
127 ...options,
128 stream: true,
129 });
130 const command = new ConverseStreamCommand(input);
131
132 const response = (await client.send(command, {
133 abortSignal: signal,
134 })) as ConverseStreamCommandOutput;
135
136 if (!response?.stream) {
137 throw new Error("No stream received from Bedrock API");
138 }
139
140 // Reset cache metrics for new request
141 this._promptCachingMetrics = {
142 cacheReadInputTokens: 0,
143 cacheWriteInputTokens: 0,
144 };
145
146 try {
147 for await (const chunk of response.stream) {
148 if (chunk.metadata?.usage) {
149 console.log(`${JSON.stringify(chunk.metadata.usage)}`);
150 }
151
152 if (chunk.contentBlockDelta?.delta) {
153 const delta: any = chunk.contentBlockDelta.delta;
154
155 // Handle text content
156 if (chunk.contentBlockDelta.delta.text) {
157 yield {
158 role: "assistant",
159 content: chunk.contentBlockDelta.delta.text,
160 };
161 continue;
162 }
163
164 // Handle text content
165 if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) {
166 yield {
167 role: "thinking",
168 content: (chunk.contentBlockDelta.delta as any).reasoningContent
169 .text,
170 };
171 continue;
172 }
173
174 // Handle signature for thinking
175 if (delta.reasoningContent?.signature) {
176 yield {
177 role: "thinking",
178 content: "",
179 signature: delta.reasoningContent.signature,
180 };
181 continue;
182 }
183
184 // Handle redacted thinking
185 if (delta.redactedReasoning?.data) {
186 yield {
187 role: "thinking",
188 content: "",
189 redactedThinking: delta.redactedReasoning.data,
190 };
191 continue;
192 }
193
194 if (
195 chunk.contentBlockDelta.delta.toolUse?.input &&
196 this._currentToolResponse
197 ) {
198 // Append the new input to the existing string
199 if (this._currentToolResponse.input === undefined) {
200 this._currentToolResponse.input = "";
201 }
202 this._currentToolResponse.input +=
203 chunk.contentBlockDelta.delta.toolUse.input;
204 continue;
205 }
206 }
207
208 if (chunk.contentBlockStart?.start) {
209 const start: any = chunk.contentBlockStart.start;
210 if (start.redactedReasoning) {
211 yield {
212 role: "thinking",
213 content: "",
214 redactedThinking: start.redactedReasoning.data,
215 };
216 continue;
217 }
218
219 const toolUse = chunk.contentBlockStart.start.toolUse;
220 if (toolUse?.toolUseId && toolUse?.name) {
221 this._currentToolResponse = {
222 toolUseId: toolUse.toolUseId,
223 name: toolUse.name,
224 input: "",
225 };
226 }
227 continue;
228 }
229
230 if (chunk.contentBlockStop) {
231 if (this._currentToolResponse) {
232 yield {
233 role: "assistant",
234 content: "",
235 toolCalls: [
236 {
237 id: this._currentToolResponse.toolUseId,
238 type: "function",
239 function: {
240 name: this._currentToolResponse.name,
241 arguments: this._currentToolResponse.input,
242 },
243 },
244 ],
245 };
246 this._currentToolResponse = null;
247 }
248 continue;
249 }
250 }
251 } catch (error: unknown) {
252 // Clean up state and let the original error bubble up to the retry decorator
253 this._currentToolResponse = null;
254 throw error;
255 }
256 }
257
258 /**
259 * Generates the input payload for the Bedrock Converse API
260 * @param messages - Array of chat messages
261 * @param options - Completion options
262 * @returns Formatted input payload for the API
263 */
264 private _generateConverseInput(
265 messages: ChatMessage[],
266 options: CompletionOptions,
267 ): any {
268 const systemMessage = stripImages(
269 messages.find((m) => m.role === "system")?.content ?? "",
270 );
271
272 // Prompt and system message caching settings
273 const shouldCacheSystemMessage =
274 (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
275 this.completionOptions.promptCaching;
276 const enablePromptCaching =
277 shouldCacheSystemMessage ||
278 this.cacheBehavior?.cacheConversation ||
279 this.completionOptions.promptCaching;
280
281 if (enablePromptCaching) {
282 this.requestOptions.headers = {
283 ...this.requestOptions.headers,
284 "x-amzn-bedrock-enablepromptcaching": "true",
285 };
286 }
287
288 // First get tools
289 const supportsTools =
290 (this.capabilities?.tools ||
291 PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
292 false;
293
294 let toolConfig: undefined | ToolConfiguration = undefined;
295 const availableTools = new Set<string>();
296 if (supportsTools && options.tools && options.tools.length > 0) {
297 toolConfig = {
298 tools: options.tools.map((tool) => ({
299 toolSpec: {
300 name: tool.function.name,
301 description: tool.function.description,
302 inputSchema: {
303 json: tool.function.parameters,
304 },
305 },
306 })),
307 } as ToolConfiguration;
308 const shouldCacheToolsConfig = this.completionOptions.promptCaching;
309 if (shouldCacheToolsConfig) {
310 toolConfig.tools!.push({ cachePoint: { type: "default" } });
311 }
312 options.tools.forEach((tool) => {
313 availableTools.add(tool.function.name);
314 });
315 }
316
317 const convertedMessages = this._convertMessages(messages, availableTools);
318
319 return {
320 modelId: options.model,
321 system: systemMessage
322 ? shouldCacheSystemMessage
323 ? [{ text: systemMessage }, { cachePoint: { type: "default" } }]
324 : [{ text: systemMessage }]
325 : undefined,
326 toolConfig: toolConfig,
327 messages: convertedMessages,
328 inferenceConfig: {
329 maxTokens: options.maxTokens,
330 temperature: options.temperature,
331 topP: options.topP,
332 // TODO: The current approach selects the first 4 items from the list to comply with Bedrock's requirement
333 // of having at most 4 stop sequences, as per the AWS documentation:
334 // https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_InferenceConfiguration.html
335 // However, it might be better to implement a strategy that dynamically selects the most appropriate stop sequences
336 // based on the context.
337 // TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback.
338 // For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes),
339 // providing meaningful error messages to improve the user experience.
340 stopSequences: options.stop
341 ?.filter((stop) => stop.trim() !== "")
342 .slice(0, 4),
343 },
344 additionalModelRequestFields: {
345 thinking: options.reasoning
346 ? {
347 type: "enabled",
348 budget_tokens: options.reasoningBudgetTokens,
349 }
350 : undefined,
351 },
352 };
353 }
354
355 /*
356 Converts the messages to the format expected by the Bedrock API.
357
358 */
359 private _convertMessages(
360 messages: ChatMessage[],
361 availableTools: Set<string>,
362 ): Message[] {
363 let currentRole: "user" | "assistant" = "user";
364 let currentBlocks: ContentBlock[] = [];
365
366 const converted: Message[] = [];
367 const pushCurrentMessage = () => {
368 if (currentBlocks.length === 0 && converted.length > 1) {
369 throw new Error(
370 `Bedrock: no content in ${currentRole} message before conversational turn change`,
371 );
372 }
373 if (currentBlocks.length > 0) {
374 converted.push({
375 role: currentRole,
376 content: currentBlocks,
377 });
378 }
379 currentBlocks = [];
380 };
381
382 const nonSystemMessages = messages.filter((m) => m.role !== "system");
383 const hasAddedToolCallIds = new Set<string>();
384
385 for (let idx = 0; idx < nonSystemMessages.length; idx++) {
386 const message = nonSystemMessages[idx];
387
388 if (message.role === "user" || message.role === "tool") {
389 // Detect conversational turn change
390 if (currentRole !== ConversationRole.USER) {
391 pushCurrentMessage();
392 currentRole = ConversationRole.USER;
393 }
394
395 // USER messages:
396 // Non-empty user message content is converted to "text" and "image" blocks
397 // If ANY user message part is cached, we add a single cache point block when we push the message
398 if (message.role === "user") {
399 const trimmedContent =
400 typeof message.content === "string"
401 ? message.content.trim()
402 : message.content;
403 if (trimmedContent) {
404 currentBlocks.push(
405 ...this._convertMessageContentToBlocks(trimmedContent),
406 );
407 }
408 }
409 // TOOL messages:
410 // Tool messages are represented by "toolResult" blocks
411 // toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig)
412 // If it doesn't, we convert it to a text block
413 else if (message.role === "tool") {
414 const trimmedContent = message.content.trim() || "No tool output";
415 if (hasAddedToolCallIds.has(message.toolCallId)) {
416 currentBlocks.push({
417 toolResult: {
418 toolUseId: message.toolCallId,
419 content: [
420 {
421 text: trimmedContent,
422 },
423 ],
424 },
425 });
426 } else {
427 currentBlocks.push({
428 text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`,
429 });
430 }
431 }
432 } else if (message.role === "assistant" || message.role === "thinking") {
433 // Detect conversational turn change
434 if (currentRole !== ConversationRole.ASSISTANT) {
435 pushCurrentMessage();
436 currentRole = ConversationRole.ASSISTANT;
437 }
438
439 // ASSISTANT messages:
440 // Non-empty assistant message content is converted to "text" and "image" blocks
441 if (message.role === "assistant") {
442 const trimmedContent =
443 typeof message.content === "string"
444 ? message.content.trim()
445 : message.content;
446 if (trimmedContent) {
447 currentBlocks.push(
448 ...this._convertMessageContentToBlocks(trimmedContent),
449 );
450 }
451 // TOOL CALLS:
452 // Tool calls are represented by "toolUse" blocks
453 // Each tool call must have an id and a function name
454 // The function name must match one of the available tools
455 // Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools)
456 if (message.toolCalls) {
457 for (const toolCall of message.toolCalls) {
458 if (toolCall.id && toolCall.function?.name) {
459 if (availableTools.has(toolCall.function.name)) {
460 currentBlocks.push({
461 toolUse: {
462 toolUseId: toolCall.id,
463 name: toolCall.function.name,
464 input: safeParseToolCallArgs(toolCall),
465 },
466 });
467 hasAddedToolCallIds.add(toolCall.id);
468 } else {
469 const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`;
470 currentBlocks.push({
471 text: toolCallText,
472 });
473 }
474 } else {
475 console.warn(
476 `Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`,
477 );
478 continue;
479 }
480 }
481 }
482 } else if (message.role === "thinking") {
483 // THINKING:
484 // Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content
485 if (message.redactedThinking) {
486 const block: ContentBlock.ReasoningContentMember = {
487 reasoningContent: {
488 redactedContent: new Uint8Array(
489 Buffer.from(message.redactedThinking),
490 ),
491 },
492 };
493 currentBlocks.push(block);
494 } else {
495 const block: ContentBlock.ReasoningContentMember = {
496 reasoningContent: {
497 reasoningText: {
498 text: (message.content as string) || "",
499 signature: message.signature,
500 },
501 },
502 };
503 currentBlocks.push(block);
504 }
505 }
506 }
507 }
508 if (currentBlocks.length > 0) {
509 pushCurrentMessage();
510 }
511
512 // If caching is enabled, we add cache_control parameter to the last two user messages
513 // The second-to-last because it retrieves potentially already cached contents,
514 // The last one because we want it cached for later retrieval.
515 // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
516 if (
517 this.cacheBehavior?.cacheConversation ||
518 this.completionOptions.promptCaching
519 ) {
520 this._addCachingToLastTwoUserMessages(converted);
521 }
522
523 return converted;
524 }
525
526 private _addCachingToLastTwoUserMessages(converted: Message[]) {
527 let numCached = 0;
528 for (let i = converted.length - 1; i >= 0; i--) {
529 const message = converted[i];
530 if (message.role === "user") {
531 message.content?.forEach((block) => {
532 if (block.text) {
533 block.text += getSecureID();
534 }
535 });
536 message.content?.push({ cachePoint: { type: "default" } });
537 numCached++;
538 }
539 if (numCached === 2) {
540 break;
541 }
542 }
543 }
544
545 // Converts Continue message content (string/parts) to Bedrock ContentBlock format.
546 // Unsupported/problematic image formats are skipped with a warning.
547 private _convertMessageContentToBlocks(
548 content: MessageContent,
549 ): ContentBlock[] {
550 const blocks: ContentBlock[] = [];
551 if (typeof content === "string") {
552 blocks.push({ text: content });
553 } else {
554 for (const part of content) {
555 if (part.type === "text") {
556 blocks.push({ text: part.text });
557 } else if (part.type === "imageUrl" && part.imageUrl) {
558 try {
559 const [mimeType, base64Data] = part.imageUrl.url.split(",");
560 const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
561 if (
562 format === ImageFormat.JPEG ||
563 format === ImageFormat.PNG ||
564 format === ImageFormat.WEBP ||
565 format === ImageFormat.GIF
566 ) {
567 blocks.push({
568 image: {
569 format,
570 source: {
571 bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
572 },
573 },
574 });
575 } else {
576 console.warn(
577 `Bedrock: skipping unsupported image part format: ${format}`,
578 part,
579 );
580 }
581 } catch (error) {
582 console.warn("Bedrock: failed to process image part", error, part);
583 }
584 }
585 }
586 }
587 return blocks;
588 }
589
590 private async _getCredentials() {
591 if (this.accessKeyId && this.secretAccessKey) {
592 return {
593 accessKeyId: this.accessKeyId,
594 secretAccessKey: this.secretAccessKey,
595 };
596 }
597 const profile = this.profile ?? "bedrock";
598 try {
599 return await fromNodeProviderChain({
600 profile: profile,
601 ignoreCache: true,
602 })();
603 } catch (e) {
604 console.warn(
605 `AWS profile with name ${profile} not found in ~/.aws/credentials, using default profile`,
606 );
607 }
608 return await fromNodeProviderChain()();
609 }
610
611 // EMBED //
612 async _embed(chunks: string[]): Promise<number[][]> {
613 const credentials = await this._getCredentials();
614 const client = new BedrockRuntimeClient({
615 region: this.region,
616 credentials: {
617 accessKeyId: credentials.accessKeyId,
618 secretAccessKey: credentials.secretAccessKey,
619 sessionToken: credentials.sessionToken || "",
620 },
621 });
622
623 return (
624 await Promise.all(
625 chunks.map(async (chunk) => {
626 const input = this._generateInvokeModelCommandInput(chunk);
627 const command = new InvokeModelCommand(input);
628 const response = await client.send(command);
629 if (response.body) {
630 const decoder = new TextDecoder();
631 const decoded = decoder.decode(response.body);
632 try {
633 const responseBody = JSON.parse(decoded);
634 return this._extractEmbeddings(responseBody);
635 } catch (e) {
636 console.error(`Error parsing response body from:\n${decoded}`, e);
637 }
638 }
639 return [];
640 }),
641 )
642 ).flat();
643 }
644
645 private _generateInvokeModelCommandInput(text: string): any {
646 const modelConfig = this._getModelConfig();
647 const payload = modelConfig.formatPayload(text);
648
649 return {
650 body: JSON.stringify(payload),
651 modelId: this.model,
652 accept: "*/*",
653 contentType: "application/json",
654 };
655 }
656
657 private _extractEmbeddings(responseBody: any): number[][] {
658 const modelConfig = this._getModelConfig();
659 return modelConfig.extractEmbeddings(responseBody);
660 }
661
662 private _getModelConfig() {
663 const modelConfigs: { [key: string]: ModelConfig } = {
664 cohere: {
665 formatPayload: (text: string) => ({
666 texts: [text],
667 input_type: "search_document",
668 truncate: "END",
669 }),
670 extractEmbeddings: (responseBody: any) => responseBody.embeddings || [],
671 },
672 "amazon.titan-embed": {
673 formatPayload: (text: string) => ({
674 inputText: text,
675 }),
676 extractEmbeddings: (responseBody: any) =>
677 responseBody.embedding ? [responseBody.embedding] : [],
678 },
679 };
680
681 const modelPrefix = Object.keys(modelConfigs).find((prefix) =>
682 this.model!.startsWith(prefix),
683 );
684 if (!modelPrefix) {
685 throw new Error(`Unsupported model: ${this.model}`);
686 }
687 return modelConfigs[modelPrefix];
688 }
689
690 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
691 if (!query || !chunks.length) {
692 throw new Error("Query and chunks must not be empty");
693 }
694
695 try {
696 const credentials = await this._getCredentials();
697 const client = new BedrockRuntimeClient({
698 region: this.region,
699 credentials: {
700 accessKeyId: credentials.accessKeyId,
701 secretAccessKey: credentials.secretAccessKey,
702 sessionToken: credentials.sessionToken || "",
703 },
704 });
705
706 // Base payload for both models
707 const payload: any = {
708 query: query,
709 documents: chunks.map((chunk) => chunk.content),
710 top_n: chunks.length,
711 };
712
713 // Add api_version for Cohere model
714 if (this.model.startsWith("cohere.rerank")) {
715 payload.api_version = 2;
716 }
717
718 const input = {
719 body: JSON.stringify(payload),
720 modelId: this.model,
721 accept: "*/*",
722 contentType: "application/json",
723 };
724
725 const command = new InvokeModelCommand(input);
726 const response = await client.send(command);
727
728 if (!response.body) {
729 throw new Error("Empty response received from Bedrock");
730 }
731
732 const decoder = new TextDecoder();
733 const decoded = decoder.decode(response.body);
734 try {
735 const responseBody = JSON.parse(decoded);
736 // Sort results by index to maintain original order
737 return responseBody.results
738 .sort((a: any, b: any) => a.index - b.index)
739 .map((result: any) => result.relevance_score);
740 } catch (e) {
741 throw new Error(
742 `Error parsing JSON from Bedrock response body:\n${decoded}, ${JSON.stringify(e)}`,
743 );
744 }
745 } catch (error: unknown) {
746 if (error instanceof Error) {
747 if ("code" in error) {
748 // AWS SDK specific errors
749 throw new Error(
750 `AWS Bedrock rerank error (${(error as any).code}): ${error.message}`,
751 );
752 }
753 throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
754 }
755 throw new Error(
756 "Error in BedrockReranker.rerank: Unknown error occurred",
757 );
758 }
759 }
760}
761
762export default Bedrock;