Elffuss BraidHub

kikocis/continue public

bedrock message conversions
Changeset693d0df2720692ca634a1cbeed2d54af29d3e7daf945c0d7769493b7cabbe3e4
AuthorDallin Romney <dallinromney@gmail.com> · 2025-07-01 17:31 -07:00
CommitterDallin Romney <dallinromney@gmail.com> · 2025-07-01 17:31 -07:00
Parents3c39a014374a

Browse the files at this changeset

1 file changed

modified core/llm/llms/Bedrock.ts +182 −149
@@ -1,8 +1,10 @@
11 import {
22 BedrockRuntimeClient,
33 ContentBlock,
4+ ConversationRole,
45 ConverseStreamCommand,
56 ConverseStreamCommandOutput,
7+ ImageFormat,
68 InvokeModelCommand,
79 Message,
810 ToolConfiguration,
@@ -14,6 +16,7 @@
1416 Chunk,
1517 CompletionOptions,
1618 LLMOptions,
19+ MessageContent,
1720 } from "../../index.js";
1821 import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
1922 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
@@ -289,8 +292,8 @@
289292 const systemMessage = stripImages(
290293 messages.find((m) => m.role === "system")?.content ?? "",
291294 );
292- const convertedMessages = this._convertMessages(messages);
293295
296+ // Prompt and system message caching settings
294297 const shouldCacheSystemMessage =
295298 (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
296299 this.completionOptions.promptCaching;
@@ -298,9 +301,7 @@
298301 shouldCacheSystemMessage ||
299302 this.cacheBehavior?.cacheConversation ||
300303 this.completionOptions.promptCaching;
301- const shouldCacheToolsConfig = this.completionOptions.promptCaching;
302304
303- // Add header for prompt caching
304305 if (enablePromptCaching) {
305306 this.requestOptions.headers = {
306307 ...this.requestOptions.headers,
@@ -308,30 +309,37 @@
308309 };
309310 }
310311
312+ // First get tools
311313 const supportsTools =
312314 (this.capabilities?.tools ||
313315 PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
314316 false;
315317
316- let toolConfig =
317- supportsTools && options.tools
318- ? ({
319- tools: options.tools.map((tool) => ({
320- toolSpec: {
321- name: tool.function.name,
322- description: tool.function.description,
323- inputSchema: {
324- json: tool.function.parameters,
325- },
326- },
327- })),
328- } as ToolConfiguration)
329- : undefined;
330-
331- if (toolConfig?.tools && shouldCacheToolsConfig) {
332- toolConfig.tools.push({ cachePoint: { type: "default" } });
318+ let toolConfig: undefined | ToolConfiguration = undefined;
319+ const availableTools = new Set<string>();
320+ if (supportsTools && options.tools && options.tools.length > 0) {
321+ toolConfig = {
322+ tools: options.tools.map((tool) => ({
323+ toolSpec: {
324+ name: tool.function.name,
325+ description: tool.function.description,
326+ inputSchema: {
327+ json: tool.function.parameters,
328+ },
329+ },
330+ })),
331+ } as ToolConfiguration;
332+ const shouldCacheToolsConfig = this.completionOptions.promptCaching;
333+ if (shouldCacheToolsConfig) {
334+ toolConfig.tools!.push({ cachePoint: { type: "default" } });
335+ }
336+ options.tools.forEach((tool) => {
337+ availableTools.add(tool.function.name);
338+ });
333339 }
334340
341+ const convertedMessages = this._convertMessages(messages, availableTools);
342+
335343 return {
336344 modelId: options.model,
337345 system: systemMessage
@@ -368,25 +376,75 @@
368376 };
369377 }
370378
371- private _convertMessage(
372- message: ChatMessage,
373- addCaching: boolean = false,
374- ): Message | null {
375- // Handle system messages explicitly
376- if (message.role === "system") {
377- return null;
379+ private _convertMessages(
380+ messages: ChatMessage[],
381+ availableTools: Set<string>,
382+ ): Message[] {
383+ const nonSystemMessages = messages.filter((m) => m.role !== "system");
384+
385+ const lastTwoUserMsgIndices: number[] = [];
386+ for (let i = nonSystemMessages.length - 1; i >= 0; i--) {
387+ if (nonSystemMessages[i].role === "user") {
388+ lastTwoUserMsgIndices.push(i);
389+ if (lastTwoUserMsgIndices.length === 2) {
390+ break;
391+ }
392+ }
378393 }
379394
380- const cachePoint = addCaching
381- ? { cachePoint: { type: "default" } }
382- : undefined;
383-
384- // Tool response handling
385- if (message.role === "tool") {
386- return {
387- role: "user",
388- content: [
389- {
395+ let currentRole: "user" | "assistant" = "user";
396+ let currentBlocks: ContentBlock[] = [];
397+ let addCachePoint = false;
398+
399+ const converted: Message[] = [];
400+ const pushCurrentMessage = () => {
401+ if (currentBlocks.length === 0 && converted.length > 1) {
402+ throw new Error(
403+ `Bedrock: no content in ${currentRole} message before conversational turn change`,
404+ );
405+ }
406+ if (currentBlocks.length > 0) {
407+ if (addCachePoint) {
408+ currentBlocks.push({ cachePoint: { type: "default" } });
409+ }
410+ converted.push({
411+ role: currentRole,
412+ content: currentBlocks,
413+ });
414+ }
415+ // Change roles and reset
416+ currentBlocks = [];
417+ addCachePoint = false;
418+ };
419+
420+ for (let idx = 0; idx < nonSystemMessages.length; idx++) {
421+ const message = nonSystemMessages[idx];
422+ if (message.role === "user" || message.role === "tool") {
423+ pushCurrentMessage();
424+ currentRole = ConversationRole.USER;
425+
426+ if (message.role === "user") {
427+ if (message.content) {
428+ // Add cache_control parameter to the last two user messages
429+ // The second-to-last because it retrieves potentially already cached contents,
430+ // The last one because we want it cached for later retrieval.
431+ // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
432+ const messageIsCached = !!(
433+ this.cacheBehavior?.cacheConversation &&
434+ lastTwoUserMsgIndices.includes(idx)
435+ );
436+ if (messageIsCached) {
437+ addCachePoint = true;
438+ }
439+ currentBlocks.push(
440+ ...this._convertMessageContentToBlocks(
441+ message.content,
442+ messageIsCached,
443+ ),
444+ );
445+ }
446+ } else if (message.role === "tool") {
447+ currentBlocks.push({
390448 toolResult: {
391449 toolUseId: message.toolCallId,
392450 content: [
@@ -395,140 +453,115 @@
395453 },
396454 ],
397455 },
398- },
399- ],
400- };
401- }
402-
403- // Tool calls handling
404- if (message.role === "assistant" && message.toolCalls) {
405- return {
406- role: "assistant",
407- content: message.toolCalls.map((toolCall) => ({
408- toolUse: {
409- toolUseId: toolCall.id,
410- name: toolCall.function?.name,
411- input: safeParseToolCallArgs(toolCall),
412- },
413- })),
414- };
415- }
416-
417- if (message.role === "thinking") {
418- if (message.redactedThinking) {
419- const content: ContentBlock.ReasoningContentMember = {
420- reasoningContent: {
421- redactedContent: new Uint8Array(
422- Buffer.from(message.redactedThinking),
423- ),
424- },
425- };
426- return {
427- role: "assistant",
428- content: [content],
429- };
456+ });
457+ }
430458 } else {
431- const content: ContentBlock.ReasoningContentMember = {
432- reasoningContent: {
433- reasoningText: {
434- text: (message.content as string) || "",
435- signature: message.signature,
436- },
437- },
438- };
439- return {
440- role: "assistant",
441- content: [content],
442- };
459+ pushCurrentMessage();
460+ currentRole = ConversationRole.ASSISTANT;
461+
462+ if (message.role === "assistant") {
463+ if (message.content) {
464+ currentBlocks.push(
465+ ...this._convertMessageContentToBlocks(message.content, false),
466+ );
467+ }
468+ if (message.toolCalls) {
469+ for (const toolCall of message.toolCalls) {
470+ if (availableTools.has(toolCall.function?.name || "")) {
471+ currentBlocks.push({
472+ toolUse: {
473+ toolUseId: toolCall.id,
474+ name: toolCall.function?.name,
475+ input: safeParseToolCallArgs(toolCall),
476+ },
477+ });
478+ } else {
479+ console.warn(
480+ `Tool ${toolCall.function?.name} is not available for this model.`,
481+ );
482+ }
483+ }
484+ }
485+ } else if (message.role === "thinking") {
486+ if (message.redactedThinking) {
487+ const block: ContentBlock.ReasoningContentMember = {
488+ reasoningContent: {
489+ redactedContent: new Uint8Array(
490+ Buffer.from(message.redactedThinking),
491+ ),
492+ },
493+ };
494+ currentBlocks.push(block);
495+ } else {
496+ const block: ContentBlock.ReasoningContentMember = {
497+ reasoningContent: {
498+ reasoningText: {
499+ text: (message.content as string) || "",
500+ signature: message.signature,
501+ },
502+ },
503+ };
504+ currentBlocks.push(block);
505+ }
506+ }
443507 }
444508 }
445509
446- // Standard text message
447- if (typeof message.content === "string") {
510+ return converted;
511+ }
512+
513+ private _convertMessageContentToBlocks(
514+ content: MessageContent,
515+ addCaching: boolean,
516+ ): ContentBlock[] {
517+ const blocks: ContentBlock[] = [];
518+ if (typeof content === "string") {
519+ let contentText = content;
448520 if (addCaching) {
449- message.content += getSecureID();
521+ contentText += getSecureID();
450522 }
451- const content: any[] = [{ text: message.content }];
523+ blocks.push({ text: contentText });
452524 if (addCaching) {
453- content.push({ cachePoint: { type: "default" } });
525+ blocks.push({ cachePoint: { type: "default" } });
454526 }
455- return {
456- role: message.role,
457- content,
458- };
459- }
460-
461- // Improved multimodal content handling
462- if (Array.isArray(message.content)) {
463- const content: any[] = [];
464-
465- // Process all parts first
466- message.content.forEach((part) => {
527+ } else {
528+ for (const part of content) {
467529 if (part.type === "text") {
468530 if (addCaching) {
469531 part.text += getSecureID();
470532 }
471- content.push({ text: part.text });
533+ blocks.push({ text: part.text });
472534 } else if (part.type === "imageUrl" && part.imageUrl) {
473535 try {
474536 const [mimeType, base64Data] = part.imageUrl.url.split(",");
475537 const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
476- content.push({
477- image: {
478- format,
479- source: {
480- bytes: Buffer.from(base64Data, "base64"),
538+ if (
539+ format === ImageFormat.JPEG ||
540+ format === ImageFormat.PNG ||
541+ format === ImageFormat.WEBP ||
542+ format === ImageFormat.GIF
543+ ) {
544+ blocks.push({
545+ image: {
546+ format,
547+ source: {
548+ bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
549+ },
481550 },
482- },
483- });
551+ });
552+ } else {
553+ console.warn(
554+ `Bedrock: skipping unsupported image part format: ${format}`,
555+ part,
556+ );
557+ }
484558 } catch (error) {
485- console.warn(`Failed to process image: ${error}`);
559+ console.warn("Bedrock: failed to process image part", error, part);
486560 }
487561 }
488- });
489-
490- // Add cache point as a separate block at the end if needed
491- if (addCaching && content.length > 0) {
492- content.push({ cachePoint: { type: "default" } });
493562 }
494-
495- return {
496- role: message.role,
497- content,
498- } as Message;
499563 }
500- return null;
501- }
502-
503- private _convertMessages(messages: ChatMessage[]): any[] {
504- const filteredmessages = messages.filter(
505- (m) => m.role !== "system" && !!m.content,
506- );
507- const lastTwoUserMsgIndices = filteredmessages
508- .map((msg, index) => (msg.role === "user" ? index : -1))
509- .filter((index) => index !== -1)
510- .slice(-2);
511-
512- const converted = filteredmessages
513- .map((message, filteredMsgIdx) => {
514- // Add cache_control parameter to the last two user messages
515- // The second-to-last because it retrieves potentially already cached contents,
516- // The last one because we want it cached for later retrieval.
517- // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
518- const addCaching =
519- this.cacheBehavior?.cacheConversation &&
520- lastTwoUserMsgIndices.includes(filteredMsgIdx);
521-
522- try {
523- return this._convertMessage(message, addCaching);
524- } catch (error) {
525- console.error(`Failed to convert message: ${error}`);
526- return null;
527- }
528- })
529- .filter(Boolean);
530-
531- return converted;
564+ return blocks;
532565 }
533566
534567 private async _getCredentials() {