Elffuss BraidHub

kikocis/continue public

f433400a74a4 · 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 (this.cacheBehavior?.cacheConversation) {
517 this._addCachingToLastTwoUserMessages(converted);
518 }
519
520 return converted;
521 }
522
523 private _addCachingToLastTwoUserMessages(converted: Message[]) {
524 let numCached = 0;
525 for (let i = converted.length - 1; i >= 0; i--) {
526 const message = converted[i];
527 if (message.role === "user") {
528 message.content?.forEach((block) => {
529 if (block.text) {
530 block.text += getSecureID();
531 }
532 });
533 message.content?.push({ cachePoint: { type: "default" } });
534 numCached++;
535 }
536 if (numCached === 2) {
537 break;
538 }
539 }
540 }
541
542 // Converts Continue message content (string/parts) to Bedrock ContentBlock format.
543 // Unsupported/problematic image formats are skipped with a warning.
544 private _convertMessageContentToBlocks(
545 content: MessageContent,
546 ): ContentBlock[] {
547 const blocks: ContentBlock[] = [];
548 if (typeof content === "string") {
549 blocks.push({ text: content });
550 } else {
551 for (const part of content) {
552 if (part.type === "text") {
553 blocks.push({ text: part.text });
554 } else if (part.type === "imageUrl" && part.imageUrl) {
555 try {
556 const [mimeType, base64Data] = part.imageUrl.url.split(",");
557 const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
558 if (
559 format === ImageFormat.JPEG ||
560 format === ImageFormat.PNG ||
561 format === ImageFormat.WEBP ||
562 format === ImageFormat.GIF
563 ) {
564 blocks.push({
565 image: {
566 format,
567 source: {
568 bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
569 },
570 },
571 });
572 } else {
573 console.warn(
574 `Bedrock: skipping unsupported image part format: ${format}`,
575 part,
576 );
577 }
578 } catch (error) {
579 console.warn("Bedrock: failed to process image part", error, part);
580 }
581 }
582 }
583 }
584 return blocks;
585 }
586
587 private async _getCredentials() {
588 if (this.accessKeyId && this.secretAccessKey) {
589 return {
590 accessKeyId: this.accessKeyId,
591 secretAccessKey: this.secretAccessKey,
592 };
593 }
594 const profile = this.profile ?? "bedrock";
595 try {
596 return await fromNodeProviderChain({
597 profile: profile,
598 ignoreCache: true,
599 })();
600 } catch (e) {
601 console.warn(
602 `AWS profile with name ${profile} not found in ~/.aws/credentials, using default profile`,
603 );
604 }
605 return await fromNodeProviderChain()();
606 }
607
608 // EMBED //
609 async _embed(chunks: string[]): Promise<number[][]> {
610 const credentials = await this._getCredentials();
611 const client = new BedrockRuntimeClient({
612 region: this.region,
613 credentials: {
614 accessKeyId: credentials.accessKeyId,
615 secretAccessKey: credentials.secretAccessKey,
616 sessionToken: credentials.sessionToken || "",
617 },
618 });
619
620 return (
621 await Promise.all(
622 chunks.map(async (chunk) => {
623 const input = this._generateInvokeModelCommandInput(chunk);
624 const command = new InvokeModelCommand(input);
625 const response = await client.send(command);
626 if (response.body) {
627 const decoder = new TextDecoder();
628 const decoded = decoder.decode(response.body);
629 try {
630 const responseBody = JSON.parse(decoded);
631 return this._extractEmbeddings(responseBody);
632 } catch (e) {
633 console.error(`Error parsing response body from:\n${decoded}`, e);
634 }
635 }
636 return [];
637 }),
638 )
639 ).flat();
640 }
641
642 private _generateInvokeModelCommandInput(text: string): any {
643 const modelConfig = this._getModelConfig();
644 const payload = modelConfig.formatPayload(text);
645
646 return {
647 body: JSON.stringify(payload),
648 modelId: this.model,
649 accept: "*/*",
650 contentType: "application/json",
651 };
652 }
653
654 private _extractEmbeddings(responseBody: any): number[][] {
655 const modelConfig = this._getModelConfig();
656 return modelConfig.extractEmbeddings(responseBody);
657 }
658
659 private _getModelConfig() {
660 const modelConfigs: { [key: string]: ModelConfig } = {
661 cohere: {
662 formatPayload: (text: string) => ({
663 texts: [text],
664 input_type: "search_document",
665 truncate: "END",
666 }),
667 extractEmbeddings: (responseBody: any) => responseBody.embeddings || [],
668 },
669 "amazon.titan-embed": {
670 formatPayload: (text: string) => ({
671 inputText: text,
672 }),
673 extractEmbeddings: (responseBody: any) =>
674 responseBody.embedding ? [responseBody.embedding] : [],
675 },
676 };
677
678 const modelPrefix = Object.keys(modelConfigs).find((prefix) =>
679 this.model!.startsWith(prefix),
680 );
681 if (!modelPrefix) {
682 throw new Error(`Unsupported model: ${this.model}`);
683 }
684 return modelConfigs[modelPrefix];
685 }
686
687 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
688 if (!query || !chunks.length) {
689 throw new Error("Query and chunks must not be empty");
690 }
691
692 try {
693 const credentials = await this._getCredentials();
694 const client = new BedrockRuntimeClient({
695 region: this.region,
696 credentials: {
697 accessKeyId: credentials.accessKeyId,
698 secretAccessKey: credentials.secretAccessKey,
699 sessionToken: credentials.sessionToken || "",
700 },
701 });
702
703 // Base payload for both models
704 const payload: any = {
705 query: query,
706 documents: chunks.map((chunk) => chunk.content),
707 top_n: chunks.length,
708 };
709
710 // Add api_version for Cohere model
711 if (this.model.startsWith("cohere.rerank")) {
712 payload.api_version = 2;
713 }
714
715 const input = {
716 body: JSON.stringify(payload),
717 modelId: this.model,
718 accept: "*/*",
719 contentType: "application/json",
720 };
721
722 const command = new InvokeModelCommand(input);
723 const response = await client.send(command);
724
725 if (!response.body) {
726 throw new Error("Empty response received from Bedrock");
727 }
728
729 const decoder = new TextDecoder();
730 const decoded = decoder.decode(response.body);
731 try {
732 const responseBody = JSON.parse(decoded);
733 // Sort results by index to maintain original order
734 return responseBody.results
735 .sort((a: any, b: any) => a.index - b.index)
736 .map((result: any) => result.relevance_score);
737 } catch (e) {
738 throw new Error(
739 `Error parsing JSON from Bedrock response body:\n${decoded}, ${JSON.stringify(e)}`,
740 );
741 }
742 } catch (error: unknown) {
743 if (error instanceof Error) {
744 if ("code" in error) {
745 // AWS SDK specific errors
746 throw new Error(
747 `AWS Bedrock rerank error (${(error as any).code}): ${error.message}`,
748 );
749 }
750 throw new Error(`Error in BedrockReranker.rerank: ${error.message}`);
751 }
752 throw new Error(
753 "Error in BedrockReranker.rerank: Unknown error occurred",
754 );
755 }
756 }
757}
758
759export default Bedrock;