Elffuss BraidHub

kikocis/continue public

fix bedrock caching, add comments to message conversions
Changeseta968bb06ae87621e2086574ff86436ab5c9eb7f9daabcaf24fe2867d2c5c2940
AuthorDallin Romney <dallinromney@gmail.com> · 2025-07-01 20:14 -07:00
CommitterDallin Romney <dallinromney@gmail.com> · 2025-07-01 20:14 -07:00
Parents5d2495085c35

Browse the files at this changeset

1 file changed

modified core/llm/llms/Bedrock.ts +60 −49
@@ -376,26 +376,16 @@
376376 };
377377 }
378378
379+ /*
380+ Converts the messages to the format expected by the Bedrock API.
381+
382+ */
379383 private _convertMessages(
380384 messages: ChatMessage[],
381385 availableTools: Set<string>,
382386 ): 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- }
393- }
394-
395- const hasAddedToolCallIds = new Set<string>();
396387 let currentRole: "user" | "assistant" = "user";
397388 let currentBlocks: ContentBlock[] = [];
398- let addCachePoint = false;
399389
400390 const converted: Message[] = [];
401391 const pushCurrentMessage = () => {
@@ -405,53 +395,46 @@
405395 );
406396 }
407397 if (currentBlocks.length > 0) {
408- if (addCachePoint) {
409- currentBlocks.push({ cachePoint: { type: "default" } });
410- }
411398 converted.push({
412399 role: currentRole,
413400 content: currentBlocks,
414401 });
415402 }
416- // Change roles and reset
417403 currentBlocks = [];
418- addCachePoint = false;
419404 };
420405
406+ const nonSystemMessages = messages.filter((m) => m.role !== "system");
407+ const hasAddedToolCallIds = new Set<string>();
408+
421409 for (let idx = 0; idx < nonSystemMessages.length; idx++) {
422410 const message = nonSystemMessages[idx];
423411
424412 if (message.role === "user" || message.role === "tool") {
413+ // Detect conversational turn change
425414 if (currentRole !== ConversationRole.USER) {
426415 pushCurrentMessage();
427416 currentRole = ConversationRole.USER;
428417 }
429418
419+ // USER messages:
420+ // Non-empty user message content is converted to "text" and "image" blocks
421+ // If ANY user message part is cached, we add a single cache point block when we push the message
430422 if (message.role === "user") {
431423 const trimmedContent =
432424 typeof message.content === "string"
433425 ? message.content.trim()
434426 : message.content;
435427 if (trimmedContent) {
436- // Add cache_control parameter to the last two user messages
437- // The second-to-last because it retrieves potentially already cached contents,
438- // The last one because we want it cached for later retrieval.
439- // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
440- const messageIsCached = !!(
441- this.cacheBehavior?.cacheConversation &&
442- lastTwoUserMsgIndices.includes(idx)
443- );
444- if (messageIsCached) {
445- addCachePoint = true;
446- }
447428 currentBlocks.push(
448- ...this._convertMessageContentToBlocks(
449- trimmedContent,
450- messageIsCached,
451- ),
429+ ...this._convertMessageContentToBlocks(trimmedContent),
452430 );
453431 }
454- } else if (message.role === "tool") {
432+ }
433+ // TOOL messages:
434+ // Tool messages are represented by "toolResult" blocks
435+ // toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig)
436+ // If it doesn't, we convert it to a text block
437+ else if (message.role === "tool") {
455438 const trimmedContent = message.content.trim() || "No tool output";
456439 if (hasAddedToolCallIds.has(message.toolCallId)) {
457440 currentBlocks.push({
@@ -471,11 +454,14 @@
471454 }
472455 }
473456 } else if (message.role === "assistant" || message.role === "thinking") {
457+ // Detect conversational turn change
474458 if (currentRole !== ConversationRole.ASSISTANT) {
475459 pushCurrentMessage();
476460 currentRole = ConversationRole.ASSISTANT;
477461 }
478462
463+ // ASSISTANT messages:
464+ // Non-empty assistant message content is converted to "text" and "image" blocks
479465 if (message.role === "assistant") {
480466 const trimmedContent =
481467 typeof message.content === "string"
@@ -483,14 +469,18 @@
483469 : message.content;
484470 if (trimmedContent) {
485471 currentBlocks.push(
486- ...this._convertMessageContentToBlocks(trimmedContent, false),
472+ ...this._convertMessageContentToBlocks(trimmedContent),
487473 );
488474 }
475+ // TOOL CALLS:
476+ // Tool calls are represented by "toolUse" blocks
477+ // Each tool call must have an id and a function name
478+ // The function name must match one of the available tools
479+ // Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools)
489480 if (message.toolCalls) {
490481 for (const toolCall of message.toolCalls) {
491482 if (toolCall.id && toolCall.function?.name) {
492483 if (availableTools.has(toolCall.function.name)) {
493- hasAddedToolCallIds.add(toolCall.id);
494484 currentBlocks.push({
495485 toolUse: {
496486 toolUseId: toolCall.id,
@@ -498,6 +488,7 @@
498488 input: safeParseToolCallArgs(toolCall),
499489 },
500490 });
491+ hasAddedToolCallIds.add(toolCall.id);
501492 } else {
502493 const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`;
503494 currentBlocks.push({
@@ -513,6 +504,8 @@
513504 }
514505 }
515506 } else if (message.role === "thinking") {
507+ // THINKING:
508+ // Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content
516509 if (message.redactedThinking) {
517510 const block: ContentBlock.ReasoningContentMember = {
518511 reasoningContent: {
@@ -540,29 +533,47 @@
540533 pushCurrentMessage();
541534 }
542535
536+ // If caching is enabled, we add cache_control parameter to the last two user messages
537+ // The second-to-last because it retrieves potentially already cached contents,
538+ // The last one because we want it cached for later retrieval.
539+ // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
540+ if (this.cacheBehavior?.cacheConversation) {
541+ this._addCachingToLastTwoUserMessages(converted);
542+ }
543+
543544 return converted;
544545 }
545546
547+ private _addCachingToLastTwoUserMessages(converted: Message[]) {
548+ let numCached = 0;
549+ for (let i = converted.length - 1; i >= 0; i--) {
550+ const message = converted[i];
551+ if (message.role === "user") {
552+ message.content?.forEach((block) => {
553+ if (block.text) {
554+ block.text += getSecureID();
555+ }
556+ });
557+ message.content?.push({ cachePoint: { type: "default" } });
558+ numCached++;
559+ }
560+ if (numCached === 2) {
561+ break;
562+ }
563+ }
564+ }
565+
566+ // Converts Continue message content (string/parts) to Bedrock ContentBlock format.
567+ // Unsupported/problematic image formats are skipped with a warning.
546568 private _convertMessageContentToBlocks(
547569 content: MessageContent,
548- addCaching: boolean,
549570 ): ContentBlock[] {
550571 const blocks: ContentBlock[] = [];
551572 if (typeof content === "string") {
552- let contentText = content;
553- if (addCaching) {
554- contentText += getSecureID();
555- }
556- blocks.push({ text: contentText });
557- if (addCaching) {
558- blocks.push({ cachePoint: { type: "default" } });
559- }
573+ blocks.push({ text: content });
560574 } else {
561575 for (const part of content) {
562576 if (part.type === "text") {
563- if (addCaching) {
564- part.text += getSecureID();
565- }
566577 blocks.push({ text: part.text });
567578 } else if (part.type === "imageUrl" && part.imageUrl) {
568579 try {