Elffuss BraidHub

kikocis/continue public

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