Merge pull request #6333 from continuedev/dallin/agent-papercuts
Update Agent/Tool Message Construction and Handling
This commit is contained in:
commit
ad12f6fd87
30 changed files with 1708 additions and 736 deletions
|
|
@ -10,7 +10,7 @@ import {
|
|||
JSONModelDescription,
|
||||
PromptTemplate,
|
||||
} from "../";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { editConfigFile } from "../util/paths";
|
||||
|
||||
|
|
|
|||
|
|
@ -112,7 +112,7 @@ export async function* streamDiffLines({
|
|||
// If any rules are present this will result in using chat instead of legacy completion
|
||||
const systemMessage = rulesToInclude
|
||||
? getSystemMessageWithRules({
|
||||
rules: rulesToInclude,
|
||||
availableRules: rulesToInclude,
|
||||
userMessage:
|
||||
typeof prompt === "string"
|
||||
? ({
|
||||
|
|
@ -125,7 +125,7 @@ export async function* streamDiffLines({
|
|||
) as UserChatMessage | ToolResultChatMessage | undefined),
|
||||
baseSystemMessage: undefined,
|
||||
contextItems: [],
|
||||
})
|
||||
}).systemMessage
|
||||
: undefined;
|
||||
|
||||
if (systemMessage) {
|
||||
|
|
|
|||
|
|
@ -1,187 +0,0 @@
|
|||
import {
|
||||
ChatHistoryItem,
|
||||
ChatMessage,
|
||||
ContextItemWithId,
|
||||
RuleWithSource,
|
||||
TextMessagePart,
|
||||
ToolResultChatMessage,
|
||||
UserChatMessage,
|
||||
} from "../";
|
||||
import { findLast } from "../util/findLast";
|
||||
import { normalizeToMessageParts } from "../util/messageContent";
|
||||
import { isUserOrToolMsg } from "./messages";
|
||||
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
|
||||
import { RulePolicies } from "./rules/types";
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
|
||||
|
||||
export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
|
||||
|
||||
export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
|
||||
Always include the language and file name in the info string when you write code blocks.
|
||||
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
|
||||
`;
|
||||
|
||||
export const EDIT_CODE_INSTRUCTIONS = `\
|
||||
When addressing code modification requests, present a concise code snippet that
|
||||
emphasizes only the necessary changes and uses abbreviated placeholders for
|
||||
unmodified sections. For example:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... existing code ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... existing code ...
|
||||
|
||||
{{ another modification }}
|
||||
|
||||
// ... rest of code ...
|
||||
\`\`\`
|
||||
|
||||
In existing files, you should always restate the function or class that the snippet belongs to:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... existing code ...
|
||||
|
||||
function exampleFunction() {
|
||||
// ... existing code ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... rest of function ...
|
||||
}
|
||||
|
||||
// ... rest of code ...
|
||||
\`\`\`
|
||||
|
||||
Since users have access to their complete file, they prefer reading only the
|
||||
relevant modifications. It's perfectly acceptable to omit unmodified portions
|
||||
at the beginning, middle, or end of files using these "lazy" comments. Only
|
||||
provide the complete file when explicitly requested. Include a concise explanation
|
||||
of changes unless the user specifically asks for code only.
|
||||
`;
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
You are in chat mode.
|
||||
|
||||
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
|
||||
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
|
||||
|
||||
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
|
||||
${EDIT_CODE_INSTRUCTIONS}
|
||||
</important_rules>`;
|
||||
|
||||
export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
You are in agent mode.
|
||||
|
||||
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
|
||||
</important_rules>`;
|
||||
|
||||
/**
|
||||
* Helper function to get the context items for a user message
|
||||
*/
|
||||
function getUserContextItems(
|
||||
userMsg: UserChatMessage | ToolResultChatMessage | undefined,
|
||||
history: ChatHistoryItem[],
|
||||
): ContextItemWithId[] {
|
||||
if (!userMsg) return [];
|
||||
|
||||
// Find the history item that contains the userMsg
|
||||
const historyItem = history.find((item) => {
|
||||
// Check if the message ID matches
|
||||
if ("id" in userMsg && "id" in item.message) {
|
||||
return (item.message as any).id === (userMsg as any).id;
|
||||
}
|
||||
// Fallback to content comparison
|
||||
return (
|
||||
item.message.content === userMsg.content &&
|
||||
item.message.role === userMsg.role
|
||||
);
|
||||
});
|
||||
|
||||
return historyItem?.contextItems || [];
|
||||
}
|
||||
|
||||
export function constructMessages(
|
||||
messageMode: string,
|
||||
history: ChatHistoryItem[],
|
||||
baseChatOrAgentSystemMessage: string | undefined,
|
||||
rules: RuleWithSource[],
|
||||
rulePolicies?: RulePolicies,
|
||||
): ChatMessage[] {
|
||||
const filteredHistory = history.filter(
|
||||
(item) => item.message.role !== "system",
|
||||
);
|
||||
const msgs: ChatMessage[] = [];
|
||||
|
||||
for (let i = 0; i < filteredHistory.length; i++) {
|
||||
const historyItem = filteredHistory[i];
|
||||
|
||||
if (messageMode === "chat") {
|
||||
const toolMessage: ToolResultChatMessage =
|
||||
historyItem.message as ToolResultChatMessage;
|
||||
if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
|
||||
// remove all tool calls from the history
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (historyItem.message.role === "user") {
|
||||
// Gather context items for user messages
|
||||
let content = normalizeToMessageParts(historyItem.message);
|
||||
|
||||
const ctxItems = historyItem.contextItems
|
||||
.map((ctxItem) => {
|
||||
return {
|
||||
type: "text",
|
||||
text: `${ctxItem.content}\n`,
|
||||
} as TextMessagePart;
|
||||
})
|
||||
.filter((part) => !!part.text.trim());
|
||||
|
||||
content = [...ctxItems, ...content];
|
||||
msgs.push({
|
||||
...historyItem.message,
|
||||
content,
|
||||
});
|
||||
} else {
|
||||
msgs.push(historyItem.message);
|
||||
}
|
||||
}
|
||||
|
||||
const lastUserMsg = findLast(msgs, isUserOrToolMsg) as
|
||||
| UserChatMessage
|
||||
| ToolResultChatMessage
|
||||
| undefined;
|
||||
|
||||
// Get context items for the last user message
|
||||
const lastUserContextItems = getUserContextItems(
|
||||
lastUserMsg,
|
||||
filteredHistory,
|
||||
);
|
||||
const systemMessage = getSystemMessageWithRules({
|
||||
baseSystemMessage: baseChatOrAgentSystemMessage,
|
||||
rules,
|
||||
userMessage: lastUserMsg,
|
||||
contextItems: lastUserContextItems,
|
||||
rulePolicies,
|
||||
});
|
||||
|
||||
if (systemMessage.trim()) {
|
||||
msgs.unshift({
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
});
|
||||
}
|
||||
|
||||
// Remove the "id" from all of the messages
|
||||
return msgs.map((msg) => {
|
||||
const { id, ...rest } = msg as any;
|
||||
return rest;
|
||||
});
|
||||
}
|
||||
68
core/llm/defaultSystemMessages.ts
Normal file
68
core/llm/defaultSystemMessages.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
|
||||
|
||||
export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
|
||||
|
||||
export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
|
||||
Always include the language and file name in the info string when you write code blocks.
|
||||
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
|
||||
`;
|
||||
|
||||
export const EDIT_CODE_INSTRUCTIONS = `\
|
||||
When addressing code modification requests, present a concise code snippet that
|
||||
emphasizes only the necessary changes and uses abbreviated placeholders for
|
||||
unmodified sections. For example:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... existing code ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... existing code ...
|
||||
|
||||
{{ another modification }}
|
||||
|
||||
// ... rest of code ...
|
||||
\`\`\`
|
||||
|
||||
In existing files, you should always restate the function or class that the snippet belongs to:
|
||||
|
||||
\`\`\`language /path/to/file
|
||||
// ... existing code ...
|
||||
|
||||
function exampleFunction() {
|
||||
// ... existing code ...
|
||||
|
||||
{{ modified code here }}
|
||||
|
||||
// ... rest of function ...
|
||||
}
|
||||
|
||||
// ... rest of code ...
|
||||
\`\`\`
|
||||
|
||||
Since users have access to their complete file, they prefer reading only the
|
||||
relevant modifications. It's perfectly acceptable to omit unmodified portions
|
||||
at the beginning, middle, or end of files using these "lazy" comments. Only
|
||||
provide the complete file when explicitly requested. Include a concise explanation
|
||||
of changes unless the user specifically asks for code only.
|
||||
`;
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
You are in chat mode.
|
||||
|
||||
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
|
||||
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
|
||||
|
||||
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
|
||||
${EDIT_CODE_INSTRUCTIONS}
|
||||
</important_rules>`;
|
||||
|
||||
export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
You are in agent mode.
|
||||
|
||||
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
|
||||
</important_rules>`;
|
||||
|
|
@ -1,12 +1,10 @@
|
|||
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
import Bedrock from "./Bedrock.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
UserChatMessage,
|
||||
} from "../../index.js";
|
||||
import Bedrock from "./Bedrock.js";
|
||||
|
||||
// Mock AWS SDK
|
||||
jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
|
||||
|
|
@ -317,96 +315,266 @@ describe("Bedrock", () => {
|
|||
});
|
||||
});
|
||||
|
||||
it("should convert text messages correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "user",
|
||||
content: "Hello",
|
||||
} as UserChatMessage;
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "user",
|
||||
content: [{ text: "Hello" }],
|
||||
});
|
||||
it("should convert simple user and assistant messages correctly", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello" } as UserChatMessage,
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
];
|
||||
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{ role: "user", content: [{ text: "Hello" }] },
|
||||
{ role: "assistant", content: [{ text: "Hi there" }] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should convert tool responses correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "tool",
|
||||
content: "Tool result",
|
||||
toolCallId: "tool-1",
|
||||
};
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
toolResult: {
|
||||
toolUseId: "tool-1",
|
||||
content: [{ text: "Tool result" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("should convert tool calls correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-1",
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg":"value"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
toolUse: {
|
||||
toolUseId: "tool-1",
|
||||
name: "test_tool",
|
||||
input: { arg: "value" },
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle multimodal content correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "Look at this image:" },
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
|
||||
},
|
||||
},
|
||||
],
|
||||
} as UserChatMessage;
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "user",
|
||||
content: [
|
||||
{ text: "Look at this image:" },
|
||||
{
|
||||
image: {
|
||||
format: "jpeg",
|
||||
source: {
|
||||
bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"),
|
||||
it("should handle tool responses correctly", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Use a tool" } as UserChatMessage,
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg":"value"}',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "tool",
|
||||
content: "Tool result",
|
||||
toolCallId: "tool-1",
|
||||
},
|
||||
];
|
||||
|
||||
const availableTools = new Set(["test_tool"]);
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{ role: "user", content: [{ text: "Use a tool" }] },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
toolUse: {
|
||||
toolUseId: "tool-1",
|
||||
name: "test_tool",
|
||||
input: { arg: "value" },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
toolResult: {
|
||||
toolUseId: "tool-1",
|
||||
content: [{ text: "Tool result" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle tool calls with unavailable tools as text", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Use a tool" } as UserChatMessage,
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "unavailable_tool",
|
||||
arguments: '{"arg":"value"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// Empty set means no tools are available
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{ role: "user", content: [{ text: "Use a tool" }] },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
text: expect.stringContaining("Assistant tool call:"),
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle thinking messages correctly", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Think about this" } as UserChatMessage,
|
||||
{ role: "thinking", content: "I am thinking about the solution" },
|
||||
{ role: "assistant", content: "Here's my answer" },
|
||||
];
|
||||
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{ role: "user", content: [{ text: "Think about this" }] },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
reasoningContent: {
|
||||
reasoningText: {
|
||||
text: "I am thinking about the solution",
|
||||
signature: undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
{ text: "Here's my answer" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle redacted thinking messages", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Think about this" } as UserChatMessage,
|
||||
{
|
||||
role: "thinking",
|
||||
content: "",
|
||||
redactedThinking: "redacted-content-bytes",
|
||||
},
|
||||
{ role: "assistant", content: "Here's my answer" },
|
||||
];
|
||||
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{ role: "user", content: [{ text: "Think about this" }] },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
reasoningContent: {
|
||||
redactedContent: expect.any(Uint8Array),
|
||||
},
|
||||
},
|
||||
{ text: "Here's my answer" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
// Check that the Uint8Array contains the expected bytes
|
||||
const redactedContent =
|
||||
converted[1].content?.[0].reasoningContent?.redactedContent;
|
||||
expect(redactedContent).toBeInstanceOf(Uint8Array);
|
||||
expect(Buffer.from(redactedContent!).toString()).toBe(
|
||||
"redacted-content-bytes",
|
||||
);
|
||||
});
|
||||
|
||||
it("should convert multimodal content correctly", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "Look at this image:" },
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
|
||||
},
|
||||
},
|
||||
],
|
||||
} as UserChatMessage,
|
||||
];
|
||||
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrock["_convertMessages"](messages, availableTools);
|
||||
|
||||
expect(converted).toEqual([
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ text: "Look at this image:" },
|
||||
{
|
||||
image: {
|
||||
format: "jpeg",
|
||||
source: {
|
||||
bytes: expect.any(Uint8Array),
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
// Check that the image bytes were processed correctly
|
||||
const imageBytes = converted[0].content?.[1].image?.source?.bytes;
|
||||
expect(imageBytes).toBeInstanceOf(Uint8Array);
|
||||
expect(Buffer.from(imageBytes!).toString("base64")).toBe(
|
||||
"/9j/4AAQSkZJRg==",
|
||||
);
|
||||
});
|
||||
|
||||
it("should add cache points for prompt caching when needed", () => {
|
||||
// Create a test instance with caching behavior enabled
|
||||
const bedrockWithCaching = new TestBedrock({
|
||||
apiKey: "test-key",
|
||||
model: "anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
region: "us-east-1",
|
||||
});
|
||||
|
||||
// Set caching behavior
|
||||
bedrockWithCaching.cacheBehavior = {
|
||||
cacheConversation: true,
|
||||
cacheSystemMessage: true,
|
||||
};
|
||||
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "system", content: "You are a helpful assistant" },
|
||||
{ role: "user", content: "First message" } as UserChatMessage,
|
||||
{ role: "assistant", content: "First response" },
|
||||
{ role: "user", content: "Second message" } as UserChatMessage,
|
||||
];
|
||||
|
||||
const availableTools = new Set<string>();
|
||||
const converted = bedrockWithCaching["_convertMessages"](
|
||||
messages,
|
||||
availableTools,
|
||||
);
|
||||
|
||||
// The last two user messages should have cache points
|
||||
// But we're not testing the system message here since it's handled separately
|
||||
expect(converted.length).toBe(3);
|
||||
expect(converted[0].role).toBe("user");
|
||||
expect(converted[0].content?.some((block) => block.cachePoint)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(converted[1].role).toBe("assistant");
|
||||
expect(converted[2].role).toBe("user");
|
||||
expect(converted[2].content?.some((block) => block.cachePoint)).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
// Verify that text content includes a cache ID suffix
|
||||
const userMessageText = converted[0].content?.[0].text;
|
||||
expect(userMessageText).toMatch(/First message.+/);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import {
|
||||
BedrockRuntimeClient,
|
||||
ContentBlock,
|
||||
ConversationRole,
|
||||
ConverseStreamCommand,
|
||||
ConverseStreamCommandOutput,
|
||||
ImageFormat,
|
||||
InvokeModelCommand,
|
||||
Message,
|
||||
ToolConfiguration,
|
||||
|
|
@ -14,6 +16,7 @@ import {
|
|||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessageContent,
|
||||
} from "../../index.js";
|
||||
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
|
|
@ -289,8 +292,8 @@ class Bedrock extends BaseLLM {
|
|||
const systemMessage = stripImages(
|
||||
messages.find((m) => m.role === "system")?.content ?? "",
|
||||
);
|
||||
const convertedMessages = this._convertMessages(messages);
|
||||
|
||||
// Prompt and system message caching settings
|
||||
const shouldCacheSystemMessage =
|
||||
(!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
|
||||
this.completionOptions.promptCaching;
|
||||
|
|
@ -298,9 +301,7 @@ class Bedrock extends BaseLLM {
|
|||
shouldCacheSystemMessage ||
|
||||
this.cacheBehavior?.cacheConversation ||
|
||||
this.completionOptions.promptCaching;
|
||||
const shouldCacheToolsConfig = this.completionOptions.promptCaching;
|
||||
|
||||
// Add header for prompt caching
|
||||
if (enablePromptCaching) {
|
||||
this.requestOptions.headers = {
|
||||
...this.requestOptions.headers,
|
||||
|
|
@ -308,30 +309,37 @@ class Bedrock extends BaseLLM {
|
|||
};
|
||||
}
|
||||
|
||||
// First get tools
|
||||
const supportsTools =
|
||||
(this.capabilities?.tools ||
|
||||
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
|
||||
false;
|
||||
|
||||
let toolConfig =
|
||||
supportsTools && options.tools
|
||||
? ({
|
||||
tools: options.tools.map((tool) => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters,
|
||||
},
|
||||
},
|
||||
})),
|
||||
} as ToolConfiguration)
|
||||
: undefined;
|
||||
|
||||
if (toolConfig?.tools && shouldCacheToolsConfig) {
|
||||
toolConfig.tools.push({ cachePoint: { type: "default" } });
|
||||
let toolConfig: undefined | ToolConfiguration = undefined;
|
||||
const availableTools = new Set<string>();
|
||||
if (supportsTools && options.tools && options.tools.length > 0) {
|
||||
toolConfig = {
|
||||
tools: options.tools.map((tool) => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters,
|
||||
},
|
||||
},
|
||||
})),
|
||||
} as ToolConfiguration;
|
||||
const shouldCacheToolsConfig = this.completionOptions.promptCaching;
|
||||
if (shouldCacheToolsConfig) {
|
||||
toolConfig.tools!.push({ cachePoint: { type: "default" } });
|
||||
}
|
||||
options.tools.forEach((tool) => {
|
||||
availableTools.add(tool.function.name);
|
||||
});
|
||||
}
|
||||
|
||||
const convertedMessages = this._convertMessages(messages, availableTools);
|
||||
|
||||
return {
|
||||
modelId: options.model,
|
||||
system: systemMessage
|
||||
|
|
@ -368,167 +376,236 @@ class Bedrock extends BaseLLM {
|
|||
};
|
||||
}
|
||||
|
||||
private _convertMessage(
|
||||
message: ChatMessage,
|
||||
addCaching: boolean = false,
|
||||
): Message | null {
|
||||
// Handle system messages explicitly
|
||||
if (message.role === "system") {
|
||||
return null;
|
||||
}
|
||||
/*
|
||||
Converts the messages to the format expected by the Bedrock API.
|
||||
|
||||
*/
|
||||
private _convertMessages(
|
||||
messages: ChatMessage[],
|
||||
availableTools: Set<string>,
|
||||
): Message[] {
|
||||
let currentRole: "user" | "assistant" = "user";
|
||||
let currentBlocks: ContentBlock[] = [];
|
||||
|
||||
const cachePoint = addCaching
|
||||
? { cachePoint: { type: "default" } }
|
||||
: undefined;
|
||||
|
||||
// Tool response handling
|
||||
if (message.role === "tool") {
|
||||
return {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
toolResult: {
|
||||
toolUseId: message.toolCallId,
|
||||
content: [
|
||||
{
|
||||
text: message.content || "",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// Tool calls handling
|
||||
if (message.role === "assistant" && message.toolCalls) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: message.toolCalls.map((toolCall) => ({
|
||||
toolUse: {
|
||||
toolUseId: toolCall.id,
|
||||
name: toolCall.function?.name,
|
||||
input: safeParseToolCallArgs(toolCall),
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (message.role === "thinking") {
|
||||
if (message.redactedThinking) {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
redactedContent: new Uint8Array(
|
||||
Buffer.from(message.redactedThinking),
|
||||
),
|
||||
},
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content],
|
||||
};
|
||||
} else {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
reasoningText: {
|
||||
text: (message.content as string) || "",
|
||||
signature: message.signature,
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content],
|
||||
};
|
||||
const converted: Message[] = [];
|
||||
const pushCurrentMessage = () => {
|
||||
if (currentBlocks.length === 0 && converted.length > 1) {
|
||||
throw new Error(
|
||||
`Bedrock: no content in ${currentRole} message before conversational turn change`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Standard text message
|
||||
if (typeof message.content === "string") {
|
||||
if (addCaching) {
|
||||
message.content += getSecureID();
|
||||
if (currentBlocks.length > 0) {
|
||||
converted.push({
|
||||
role: currentRole,
|
||||
content: currentBlocks,
|
||||
});
|
||||
}
|
||||
const content: any[] = [{ text: message.content }];
|
||||
if (addCaching) {
|
||||
content.push({ cachePoint: { type: "default" } });
|
||||
}
|
||||
return {
|
||||
role: message.role,
|
||||
content,
|
||||
};
|
||||
}
|
||||
currentBlocks = [];
|
||||
};
|
||||
|
||||
// Improved multimodal content handling
|
||||
if (Array.isArray(message.content)) {
|
||||
const content: any[] = [];
|
||||
const nonSystemMessages = messages.filter((m) => m.role !== "system");
|
||||
const hasAddedToolCallIds = new Set<string>();
|
||||
|
||||
// Process all parts first
|
||||
message.content.forEach((part) => {
|
||||
if (part.type === "text") {
|
||||
if (addCaching) {
|
||||
part.text += getSecureID();
|
||||
for (let idx = 0; idx < nonSystemMessages.length; idx++) {
|
||||
const message = nonSystemMessages[idx];
|
||||
|
||||
if (message.role === "user" || message.role === "tool") {
|
||||
// Detect conversational turn change
|
||||
if (currentRole !== ConversationRole.USER) {
|
||||
pushCurrentMessage();
|
||||
currentRole = ConversationRole.USER;
|
||||
}
|
||||
|
||||
// USER messages:
|
||||
// Non-empty user message content is converted to "text" and "image" blocks
|
||||
// If ANY user message part is cached, we add a single cache point block when we push the message
|
||||
if (message.role === "user") {
|
||||
const trimmedContent =
|
||||
typeof message.content === "string"
|
||||
? message.content.trim()
|
||||
: message.content;
|
||||
if (trimmedContent) {
|
||||
currentBlocks.push(
|
||||
...this._convertMessageContentToBlocks(trimmedContent),
|
||||
);
|
||||
}
|
||||
content.push({ text: part.text });
|
||||
}
|
||||
// TOOL messages:
|
||||
// Tool messages are represented by "toolResult" blocks
|
||||
// toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig)
|
||||
// If it doesn't, we convert it to a text block
|
||||
else if (message.role === "tool") {
|
||||
const trimmedContent = message.content.trim() || "No tool output";
|
||||
if (hasAddedToolCallIds.has(message.toolCallId)) {
|
||||
currentBlocks.push({
|
||||
toolResult: {
|
||||
toolUseId: message.toolCallId,
|
||||
content: [
|
||||
{
|
||||
text: trimmedContent,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
} else {
|
||||
currentBlocks.push({
|
||||
text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (message.role === "assistant" || message.role === "thinking") {
|
||||
// Detect conversational turn change
|
||||
if (currentRole !== ConversationRole.ASSISTANT) {
|
||||
pushCurrentMessage();
|
||||
currentRole = ConversationRole.ASSISTANT;
|
||||
}
|
||||
|
||||
// ASSISTANT messages:
|
||||
// Non-empty assistant message content is converted to "text" and "image" blocks
|
||||
if (message.role === "assistant") {
|
||||
const trimmedContent =
|
||||
typeof message.content === "string"
|
||||
? message.content.trim()
|
||||
: message.content;
|
||||
if (trimmedContent) {
|
||||
currentBlocks.push(
|
||||
...this._convertMessageContentToBlocks(trimmedContent),
|
||||
);
|
||||
}
|
||||
// TOOL CALLS:
|
||||
// Tool calls are represented by "toolUse" blocks
|
||||
// Each tool call must have an id and a function name
|
||||
// The function name must match one of the available tools
|
||||
// Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools)
|
||||
if (message.toolCalls) {
|
||||
for (const toolCall of message.toolCalls) {
|
||||
if (toolCall.id && toolCall.function?.name) {
|
||||
if (availableTools.has(toolCall.function.name)) {
|
||||
currentBlocks.push({
|
||||
toolUse: {
|
||||
toolUseId: toolCall.id,
|
||||
name: toolCall.function.name,
|
||||
input: safeParseToolCallArgs(toolCall),
|
||||
},
|
||||
});
|
||||
hasAddedToolCallIds.add(toolCall.id);
|
||||
} else {
|
||||
const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`;
|
||||
currentBlocks.push({
|
||||
text: toolCallText,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.warn(
|
||||
`Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (message.role === "thinking") {
|
||||
// THINKING:
|
||||
// Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content
|
||||
if (message.redactedThinking) {
|
||||
const block: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
redactedContent: new Uint8Array(
|
||||
Buffer.from(message.redactedThinking),
|
||||
),
|
||||
},
|
||||
};
|
||||
currentBlocks.push(block);
|
||||
} else {
|
||||
const block: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
reasoningText: {
|
||||
text: (message.content as string) || "",
|
||||
signature: message.signature,
|
||||
},
|
||||
},
|
||||
};
|
||||
currentBlocks.push(block);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (currentBlocks.length > 0) {
|
||||
pushCurrentMessage();
|
||||
}
|
||||
|
||||
// If caching is enabled, we add cache_control parameter to the last two user messages
|
||||
// The second-to-last because it retrieves potentially already cached contents,
|
||||
// The last one because we want it cached for later retrieval.
|
||||
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
|
||||
if (this.cacheBehavior?.cacheConversation) {
|
||||
this._addCachingToLastTwoUserMessages(converted);
|
||||
}
|
||||
|
||||
return converted;
|
||||
}
|
||||
|
||||
private _addCachingToLastTwoUserMessages(converted: Message[]) {
|
||||
let numCached = 0;
|
||||
for (let i = converted.length - 1; i >= 0; i--) {
|
||||
const message = converted[i];
|
||||
if (message.role === "user") {
|
||||
message.content?.forEach((block) => {
|
||||
if (block.text) {
|
||||
block.text += getSecureID();
|
||||
}
|
||||
});
|
||||
message.content?.push({ cachePoint: { type: "default" } });
|
||||
numCached++;
|
||||
}
|
||||
if (numCached === 2) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Converts Continue message content (string/parts) to Bedrock ContentBlock format.
|
||||
// Unsupported/problematic image formats are skipped with a warning.
|
||||
private _convertMessageContentToBlocks(
|
||||
content: MessageContent,
|
||||
): ContentBlock[] {
|
||||
const blocks: ContentBlock[] = [];
|
||||
if (typeof content === "string") {
|
||||
blocks.push({ text: content });
|
||||
} else {
|
||||
for (const part of content) {
|
||||
if (part.type === "text") {
|
||||
blocks.push({ text: part.text });
|
||||
} else if (part.type === "imageUrl" && part.imageUrl) {
|
||||
try {
|
||||
const [mimeType, base64Data] = part.imageUrl.url.split(",");
|
||||
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
|
||||
content.push({
|
||||
image: {
|
||||
format,
|
||||
source: {
|
||||
bytes: Buffer.from(base64Data, "base64"),
|
||||
if (
|
||||
format === ImageFormat.JPEG ||
|
||||
format === ImageFormat.PNG ||
|
||||
format === ImageFormat.WEBP ||
|
||||
format === ImageFormat.GIF
|
||||
) {
|
||||
blocks.push({
|
||||
image: {
|
||||
format,
|
||||
source: {
|
||||
bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
} else {
|
||||
console.warn(
|
||||
`Bedrock: skipping unsupported image part format: ${format}`,
|
||||
part,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to process image: ${error}`);
|
||||
console.warn("Bedrock: failed to process image part", error, part);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Add cache point as a separate block at the end if needed
|
||||
if (addCaching && content.length > 0) {
|
||||
content.push({ cachePoint: { type: "default" } });
|
||||
}
|
||||
|
||||
return {
|
||||
role: message.role,
|
||||
content,
|
||||
} as Message;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private _convertMessages(messages: ChatMessage[]): any[] {
|
||||
const filteredmessages = messages.filter(
|
||||
(m) => m.role !== "system" && !!m.content,
|
||||
);
|
||||
const lastTwoUserMsgIndices = filteredmessages
|
||||
.map((msg, index) => (msg.role === "user" ? index : -1))
|
||||
.filter((index) => index !== -1)
|
||||
.slice(-2);
|
||||
|
||||
const converted = filteredmessages
|
||||
.map((message, filteredMsgIdx) => {
|
||||
// Add cache_control parameter to the last two user messages
|
||||
// The second-to-last because it retrieves potentially already cached contents,
|
||||
// The last one because we want it cached for later retrieval.
|
||||
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
|
||||
const addCaching =
|
||||
this.cacheBehavior?.cacheConversation &&
|
||||
lastTwoUserMsgIndices.includes(filteredMsgIdx);
|
||||
|
||||
try {
|
||||
return this._convertMessage(message, addCaching);
|
||||
} catch (error) {
|
||||
console.error(`Failed to convert message: ${error}`);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
return converted;
|
||||
return blocks;
|
||||
}
|
||||
|
||||
private async _getCredentials() {
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import {
|
|||
LLMOptions,
|
||||
} from "../..";
|
||||
import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages";
|
||||
import { BaseLLM } from "../index";
|
||||
import Anthropic from "./Anthropic";
|
||||
import Asksage from "./Asksage";
|
||||
|
|
|
|||
|
|
@ -327,27 +327,36 @@ export const getApplicableRules = (
|
|||
export const getSystemMessageWithRules = ({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules,
|
||||
availableRules,
|
||||
contextItems,
|
||||
rulePolicies = {},
|
||||
}: {
|
||||
baseSystemMessage?: string;
|
||||
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
|
||||
rules: RuleWithSource[];
|
||||
availableRules: RuleWithSource[];
|
||||
contextItems: ContextItemWithId[];
|
||||
rulePolicies?: RulePolicies;
|
||||
}) => {
|
||||
const applicableRules = getApplicableRules(
|
||||
}): {
|
||||
systemMessage: string;
|
||||
appliedRules: RuleWithSource[];
|
||||
} => {
|
||||
const appliedRules = getApplicableRules(
|
||||
userMessage,
|
||||
rules,
|
||||
availableRules,
|
||||
contextItems,
|
||||
rulePolicies,
|
||||
);
|
||||
let systemMessage = baseSystemMessage ?? "";
|
||||
|
||||
for (const rule of applicableRules) {
|
||||
systemMessage += `\n\n${rule.rule}`;
|
||||
for (const rule of appliedRules) {
|
||||
if (systemMessage) {
|
||||
systemMessage += "\n\n";
|
||||
}
|
||||
systemMessage += rule.rule;
|
||||
}
|
||||
|
||||
return systemMessage;
|
||||
return {
|
||||
systemMessage,
|
||||
appliedRules,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Tool } from "../..";
|
||||
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/constructMessages";
|
||||
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export interface EditToolArgs {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
export function findLastIndex(
|
||||
arr: any[],
|
||||
criterion: (item: any) => boolean,
|
||||
export function findLastIndex<T = any>(
|
||||
arr: T[],
|
||||
criterion: (item: T) => boolean,
|
||||
): number {
|
||||
let lastIndex = -1;
|
||||
|
||||
|
|
|
|||
6
extensions/vscode/package-lock.json
generated
6
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "1.1.52",
|
||||
"version": "1.1.54",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "1.1.52",
|
||||
"version": "1.1.54",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
@ -107,7 +107,7 @@
|
|||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.14",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "1.0.42",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
|
|||
|
|
@ -2,6 +2,9 @@ import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
|
|||
import { ApplyState } from "core";
|
||||
import { useContext } from "react";
|
||||
import { IdeMessengerContext } from "../context/IdeMessenger";
|
||||
import { useAppDispatch, useAppSelector } from "../redux/hooks";
|
||||
import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall";
|
||||
import { cancelToolCall } from "../redux/slices/sessionSlice";
|
||||
import { getMetaKeyLabel } from "../util";
|
||||
import { ToolTip } from "./gui/Tooltip";
|
||||
|
||||
|
|
@ -20,8 +23,21 @@ export default function AcceptRejectAllButtons({
|
|||
(state) => state.status === "done",
|
||||
);
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const currentToolCallApplyState = useAppSelector(
|
||||
selectCurrentToolCallApplyState,
|
||||
);
|
||||
const dispatch = useAppDispatch();
|
||||
async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
|
||||
if (
|
||||
status === "rejectDiff" &&
|
||||
currentToolCallApplyState?.status === "done"
|
||||
) {
|
||||
dispatch(
|
||||
cancelToolCall({
|
||||
toolCallId: currentToolCallApplyState.toolCallId!,
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const { filepath = "", streamId } of pendingApplyStates) {
|
||||
ideMessenger.post(status, {
|
||||
filepath,
|
||||
|
|
|
|||
|
|
@ -9,10 +9,6 @@ import { useContext, useRef } from "react";
|
|||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import { selectUseActiveFile } from "../../redux/selectors";
|
||||
import {
|
||||
selectCurrentToolCall,
|
||||
selectCurrentToolCallApplyState,
|
||||
} from "../../redux/selectors/selectCurrentToolCall";
|
||||
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
|
||||
import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice";
|
||||
import { exitEdit } from "../../redux/thunks/edit";
|
||||
|
|
@ -53,20 +49,12 @@ function InputToolbar(props: InputToolbarProps) {
|
|||
const useActiveFile = useAppSelector(selectUseActiveFile);
|
||||
const isInEdit = useAppSelector((store) => store.session.isInEdit);
|
||||
const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit);
|
||||
const toolCallState = useAppSelector(selectCurrentToolCall);
|
||||
const currentToolCallApplyState = useAppSelector(
|
||||
selectCurrentToolCallApplyState,
|
||||
);
|
||||
const hasReasoningEnabled = useAppSelector(
|
||||
(store) => store.session.hasReasoningEnabled,
|
||||
);
|
||||
|
||||
const isEnterDisabled =
|
||||
props.disabled ||
|
||||
(isInEdit && codeToEdit.length === 0) ||
|
||||
toolCallState?.status === "generated" ||
|
||||
(currentToolCallApplyState &&
|
||||
currentToolCallApplyState.status !== "closed");
|
||||
props.disabled || (isInEdit && codeToEdit.length === 0);
|
||||
|
||||
const toolsSupported = defaultModel && modelSupportsTools(defaultModel);
|
||||
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ import { useEffect } from "react";
|
|||
import { useSelector } from "react-redux";
|
||||
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
|
||||
import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall";
|
||||
import { cancelToolCall } from "../../../../redux/slices/sessionSlice";
|
||||
import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool";
|
||||
import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall";
|
||||
import { isJetBrains } from "../../../../util";
|
||||
import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
|
||||
import { EditOutcomeToolbar } from "./EditOutcomeToolbar";
|
||||
|
|
@ -50,7 +50,11 @@ export function LumpToolbar() {
|
|||
} else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void dispatch(cancelCurrentToolCall());
|
||||
void dispatch(
|
||||
cancelToolCall({
|
||||
toolCallId: toolCallState.toolCallId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import styled from "styled-components";
|
||||
import { useAppDispatch } from "../../../../redux/hooks";
|
||||
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
|
||||
import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall";
|
||||
import { cancelToolCall } from "../../../../redux/slices/sessionSlice";
|
||||
import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool";
|
||||
import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall";
|
||||
import {
|
||||
getAltKeyLabel,
|
||||
getFontSize,
|
||||
|
|
@ -27,6 +28,7 @@ const StopButton = styled.div`
|
|||
export function PendingToolCallToolbar() {
|
||||
const dispatch = useAppDispatch();
|
||||
const jetbrains = isJetBrains();
|
||||
const currentToolCall = useAppSelector(selectCurrentToolCall);
|
||||
|
||||
return (
|
||||
<Container>
|
||||
|
|
@ -37,7 +39,17 @@ export function PendingToolCallToolbar() {
|
|||
<div className="flex gap-2 pb-0.5">
|
||||
<StopButton
|
||||
className="text-description"
|
||||
onClick={() => dispatch(cancelCurrentToolCall())}
|
||||
onClick={
|
||||
currentToolCall
|
||||
? () => {
|
||||
dispatch(
|
||||
cancelToolCall({
|
||||
toolCallId: currentToolCall.toolCallId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
data-testid="reject-tool-call-button"
|
||||
>
|
||||
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import {
|
|||
DEFAULT_AGENT_SYSTEM_MESSAGE_URL,
|
||||
DEFAULT_CHAT_SYSTEM_MESSAGE,
|
||||
DEFAULT_CHAT_SYSTEM_MESSAGE_URL,
|
||||
} from "core/llm/constructMessages";
|
||||
} from "core/llm/defaultSystemMessages";
|
||||
import { useContext, useMemo } from "react";
|
||||
import { useAuth } from "../../../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
|
||||
|
|
|
|||
|
|
@ -123,40 +123,35 @@ export function ContextItemsPeekItem({
|
|||
return (
|
||||
<div
|
||||
onClick={() => openContextItem(contextItem, ideMessenger)}
|
||||
className="group mr-2 flex cursor-pointer items-center overflow-hidden text-ellipsis whitespace-nowrap rounded px-1.5 py-1 text-xs hover:bg-white/10"
|
||||
className="mr-2 flex cursor-pointer flex-row items-center gap-1.5 whitespace-nowrap rounded px-1.5 py-1 text-xs hover:bg-white/10"
|
||||
data-testid="context-items-peek-item"
|
||||
>
|
||||
<div className="flex w-full items-center">
|
||||
{getContextItemIcon()}
|
||||
<div className="flex min-w-0 flex-1 gap-2 text-xs">
|
||||
<div
|
||||
className={`max-w-[50%] flex-shrink-0 truncate ${isUrl ? "hover:underline" : ""}`}
|
||||
>
|
||||
{contextItem.name}
|
||||
</div>
|
||||
<div
|
||||
className={`min-w-0 flex-1 overflow-hidden truncate whitespace-nowrap text-xs text-gray-400 ${isUrl ? "hover:underline" : ""}`}
|
||||
onClick={
|
||||
isUrl
|
||||
? (e) => {
|
||||
if (contextItem.uri?.value) {
|
||||
e.stopPropagation();
|
||||
ideMessenger.post("openUrl", contextItem.uri.value);
|
||||
} else {
|
||||
console.error("Couldn't open url", contextItem.uri);
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{contextItem.uri?.type === "file"
|
||||
? getUriPathBasename(contextItem.description)
|
||||
: contextItem.description}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{getContextItemIcon()}
|
||||
<span className={`line-clamp-1 max-w-[130px] flex-shrink-0`}>
|
||||
{contextItem.name}
|
||||
</span>
|
||||
<div
|
||||
className={`group flex flex-row items-center gap-1.5 pr-1.5 text-xs text-gray-400 ${isUrl ? "hover:underline" : ""}`}
|
||||
onClick={
|
||||
isUrl
|
||||
? (e) => {
|
||||
if (contextItem.uri?.value) {
|
||||
e.stopPropagation();
|
||||
ideMessenger.post("openUrl", contextItem.uri.value);
|
||||
} else {
|
||||
console.error("Couldn't open url", contextItem.uri);
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<span className={`line-clamp-1 flex-1 break-all`}>
|
||||
{contextItem.uri?.type === "file"
|
||||
? getUriPathBasename(contextItem.description)
|
||||
: contextItem.description}
|
||||
</span>
|
||||
{isUrl && (
|
||||
<ArrowTopRightOnSquareIcon className="mx-2 h-4 w-4 flex-shrink-0 text-gray-400 opacity-0 group-hover:opacity-100" />
|
||||
<ArrowTopRightOnSquareIcon className="h-3 w-3 flex-shrink-0 text-gray-400 opacity-80 group-hover:opacity-100" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -268,7 +268,6 @@ function ParallelListeners() {
|
|||
currentToolCallApplyState.streamId === state.streamId
|
||||
) {
|
||||
if (state.status === "done" && autoAcceptEditToolDiffs) {
|
||||
console.log("AUTO ACCEPTED");
|
||||
ideMessenger.post("acceptDiff", {
|
||||
streamId: state.streamId,
|
||||
filepath: state.filepath,
|
||||
|
|
@ -281,6 +280,11 @@ function ParallelListeners() {
|
|||
toolCallId: currentToolCallApplyState.toolCallId!,
|
||||
}),
|
||||
);
|
||||
void dispatch(
|
||||
streamResponseAfterToolCall({
|
||||
toolCallId: currentToolCallApplyState.toolCallId!,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// const output: ContextItem = {
|
||||
// name: "Edit tool output",
|
||||
|
|
@ -288,11 +292,6 @@ function ParallelListeners() {
|
|||
// description: "",
|
||||
// };
|
||||
// dispatch(setToolCallOutput([]));
|
||||
void dispatch(
|
||||
streamResponseAfterToolCall({
|
||||
toolCallId: currentToolCallApplyState.toolCallId!,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
27
gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts
Normal file
27
gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { ContextItem, ContextItemWithId, ToolCallState } from "core";
|
||||
|
||||
export function toolCallStateToContextItems(
|
||||
toolCallState: ToolCallState | undefined,
|
||||
): ContextItemWithId[] {
|
||||
if (!toolCallState) {
|
||||
return [];
|
||||
}
|
||||
return (
|
||||
toolCallState.output?.map((ctxItem) =>
|
||||
toolCallCtxItemToCtxItemWithId(ctxItem, toolCallState.toolCallId),
|
||||
) ?? []
|
||||
);
|
||||
}
|
||||
|
||||
export function toolCallCtxItemToCtxItemWithId(
|
||||
ctxItem: ContextItem,
|
||||
toolCallId: string,
|
||||
): ContextItemWithId {
|
||||
return {
|
||||
...ctxItem,
|
||||
id: {
|
||||
providerTitle: "toolCall",
|
||||
itemId: toolCallId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -20,13 +20,18 @@ import {
|
|||
SessionMetadata,
|
||||
} from "core";
|
||||
import { NEW_SESSION_TITLE } from "core/util/constants";
|
||||
import { renderChatMessage } from "core/util/messageContent";
|
||||
import {
|
||||
renderChatMessage,
|
||||
renderContextItems,
|
||||
} from "core/util/messageContent";
|
||||
import { findUriInDirs, getUriPathBasename } from "core/util/uri";
|
||||
import { findLastIndex } from "lodash";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem";
|
||||
import { addToolCallDeltaToState } from "../../util/toolCallState";
|
||||
import { RootState } from "../store";
|
||||
import { streamResponseThunk } from "../thunks/streamResponse";
|
||||
import { findCurrentToolCall, findToolCall } from "../util";
|
||||
import { findCurrentToolCall, findToolCall, findToolOutput } from "../util";
|
||||
|
||||
const getIdeMessenger = () => (window as any).ideMessenger;
|
||||
|
||||
|
|
@ -107,19 +112,39 @@ export const sessionSlice = createSlice({
|
|||
curMessage.isGatheringContext = payload;
|
||||
}
|
||||
},
|
||||
clearLastEmptyResponse: (state) => {
|
||||
clearDanglingMessages: (state) => {
|
||||
// This is used during cancellation
|
||||
// After the last user or tool message, we can have thinking and or valid assitant message (content or generated tool calls) OR nothing.
|
||||
// The only thing allowed after the last assistant message that has either content or generated tool calls
|
||||
// is a user or tool message
|
||||
if (state.history.length < 2) {
|
||||
return;
|
||||
}
|
||||
const lastMessage = state.history[state.history.length - 1];
|
||||
const lastUserOrToolIdx = findLastIndex(
|
||||
state.history,
|
||||
(item) => item.message.role === "tool" || item.message.role === "user",
|
||||
);
|
||||
|
||||
// Only clear in the case of an empty message
|
||||
if (!lastMessage.message.content.length) {
|
||||
state.mainEditorContentTrigger =
|
||||
state.history[state.history.length - 2].editorState;
|
||||
state.history = state.history.slice(0, -2);
|
||||
// TODO is this logic correct for tool use conversations?
|
||||
// Maybe slice at last index of "user" role message?
|
||||
let validAssistantMessageIdx = -1;
|
||||
for (let i = state.history.length - 1; i > lastUserOrToolIdx; i--) {
|
||||
const message = state.history[i];
|
||||
if (
|
||||
message.message.content ||
|
||||
message.toolCallState?.status !== "generating"
|
||||
) {
|
||||
validAssistantMessageIdx = i;
|
||||
// Cancel any tool calls that are dangling and generated
|
||||
if (message.toolCallState?.status === "generated") {
|
||||
message.toolCallState.status = "canceled";
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (validAssistantMessageIdx === -1) {
|
||||
state.history = state.history.slice(0, lastUserOrToolIdx + 1);
|
||||
} else {
|
||||
state.history = state.history.slice(0, validAssistantMessageIdx + 1);
|
||||
}
|
||||
},
|
||||
// Trigger value picked up by editor with isMainInput to set its content
|
||||
|
|
@ -527,6 +552,7 @@ export const sessionSlice = createSlice({
|
|||
contextItems: ContextItem[];
|
||||
}>,
|
||||
) => {
|
||||
// Update tool call state and corresponding tool output message
|
||||
const toolCallState = findToolCall(
|
||||
state.history,
|
||||
action.payload.toolCallId,
|
||||
|
|
@ -534,6 +560,15 @@ export const sessionSlice = createSlice({
|
|||
if (toolCallState) {
|
||||
toolCallState.output = action.payload.contextItems;
|
||||
}
|
||||
const toolItem = findToolOutput(state.history, action.payload.toolCallId);
|
||||
if (toolItem) {
|
||||
toolItem.message.content = renderContextItems(
|
||||
action.payload.contextItems,
|
||||
);
|
||||
toolItem.contextItems = action.payload.contextItems.map((item) =>
|
||||
toolCallCtxItemToCtxItemWithId(item, action.payload.toolCallId),
|
||||
);
|
||||
}
|
||||
},
|
||||
cancelToolCall: (
|
||||
state,
|
||||
|
|
@ -679,7 +714,7 @@ export const {
|
|||
setActive,
|
||||
submitEditorAndInitAtIndex,
|
||||
updateHistoryItemAtIndex,
|
||||
clearLastEmptyResponse,
|
||||
clearDanglingMessages,
|
||||
setMainEditorContentTrigger,
|
||||
deleteMessage,
|
||||
setIsGatheringContext,
|
||||
|
|
|
|||
|
|
@ -1,50 +0,0 @@
|
|||
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
|
||||
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
|
||||
import { cancelToolCall, updateToolCallOutput } from "../slices/sessionSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
|
||||
|
||||
export const cancelCurrentToolCall = createAsyncThunk<
|
||||
void,
|
||||
undefined,
|
||||
ThunkApiType
|
||||
>("chat/cancelTool", async (_, { dispatch, extra, getState }) => {
|
||||
const state = getState();
|
||||
const toolCallState = selectCurrentToolCall(state);
|
||||
|
||||
if (!toolCallState) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (toolCallState.status !== "generated") {
|
||||
return;
|
||||
}
|
||||
|
||||
const { toolCallId } = toolCallState;
|
||||
dispatch(
|
||||
cancelToolCall({
|
||||
toolCallId,
|
||||
}),
|
||||
);
|
||||
|
||||
dispatch(
|
||||
updateToolCallOutput({
|
||||
toolCallId,
|
||||
contextItems: [
|
||||
{
|
||||
name: "Tool Cancelled",
|
||||
description: "Tool Cancelled",
|
||||
content:
|
||||
"The tool call was cancelled by the user. Please try something else or request further instructions.",
|
||||
hidden: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const output = await dispatch(
|
||||
streamResponseAfterToolCall({
|
||||
toolCallId,
|
||||
}),
|
||||
);
|
||||
unwrapResult(output);
|
||||
});
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import {
|
||||
abortStream,
|
||||
clearLastEmptyResponse,
|
||||
clearDanglingMessages,
|
||||
setInactive,
|
||||
} from "../slices/sessionSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
|
|
@ -12,9 +12,7 @@ export const cancelStream = createAsyncThunk<void, undefined, ThunkApiType>(
|
|||
dispatch(setInactive());
|
||||
dispatch(abortStream());
|
||||
|
||||
// In the case tool calls were being generated,
|
||||
// Replace them with
|
||||
// If the assistant message is empty, then remove it and the user message, placing the user input in the main text box
|
||||
dispatch(clearLastEmptyResponse());
|
||||
// Clear any dangling incomplete tool calls, thinking messages, etc.
|
||||
dispatch(clearDanglingMessages());
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
|
||||
import { ChatMessage, LLMFullCompletionOptions } from "core";
|
||||
import { LLMFullCompletionOptions } from "core";
|
||||
import { modelSupportsTools } from "core/llm/autodetect";
|
||||
import { ToCoreProtocol } from "core/protocol";
|
||||
import { selectActiveTools } from "../selectors/selectActiveTools";
|
||||
|
|
@ -9,38 +9,40 @@ import {
|
|||
abortStream,
|
||||
addPromptCompletionPair,
|
||||
setActive,
|
||||
setAppliedRulesAtIndex,
|
||||
setInactive,
|
||||
setToolGenerated,
|
||||
streamUpdate,
|
||||
} from "../slices/sessionSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
import {
|
||||
constructMessages,
|
||||
getBaseSystemMessage,
|
||||
} from "../util/constructMessages";
|
||||
import { callCurrentTool } from "./callCurrentTool";
|
||||
|
||||
export const streamNormalInput = createAsyncThunk<
|
||||
void,
|
||||
{
|
||||
messages: ChatMessage[];
|
||||
legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"];
|
||||
},
|
||||
ThunkApiType
|
||||
>(
|
||||
"chat/streamNormalInput",
|
||||
async (
|
||||
{ messages, legacySlashCommandData },
|
||||
{ dispatch, extra, getState },
|
||||
) => {
|
||||
// Gather state
|
||||
async ({ legacySlashCommandData }, { dispatch, extra, getState }) => {
|
||||
const state = getState();
|
||||
const selectedChatModel = selectSelectedChatModel(state);
|
||||
|
||||
const streamAborter = state.session.streamAborter;
|
||||
if (!selectedChatModel) {
|
||||
throw new Error("Default model not defined");
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
let completionOptions: LLMFullCompletionOptions = {};
|
||||
// Get tools
|
||||
const activeTools = selectActiveTools(state);
|
||||
const toolsSupported = modelSupportsTools(selectedChatModel);
|
||||
|
||||
// Construct completion options
|
||||
let completionOptions: LLMFullCompletionOptions = {};
|
||||
if (toolsSupported && activeTools.length > 0) {
|
||||
completionOptions = {
|
||||
tools: activeTools,
|
||||
|
|
@ -55,20 +57,46 @@ export const streamNormalInput = createAsyncThunk<
|
|||
};
|
||||
}
|
||||
|
||||
// Construct messages (excluding system message)
|
||||
const baseSystemMessage = getBaseSystemMessage(
|
||||
state.session.mode,
|
||||
selectedChatModel,
|
||||
);
|
||||
|
||||
const withoutMessageIds = state.session.history.map((item) => {
|
||||
const { id, ...messageWithoutId } = item.message;
|
||||
return { ...item, message: messageWithoutId };
|
||||
});
|
||||
const { messages, appliedRules, appliedRuleIndex } = constructMessages(
|
||||
withoutMessageIds,
|
||||
baseSystemMessage,
|
||||
state.config.config.rules,
|
||||
state.ui.ruleSettings,
|
||||
);
|
||||
|
||||
// TODO parallel tool calls will cause issues with this
|
||||
// because there will be multiple tool messages, so which one should have applied rules?
|
||||
dispatch(
|
||||
setAppliedRulesAtIndex({
|
||||
index: appliedRuleIndex,
|
||||
appliedRules: appliedRules,
|
||||
}),
|
||||
);
|
||||
|
||||
dispatch(setActive());
|
||||
|
||||
// Send request
|
||||
// Send request and stream response
|
||||
const streamAborter = state.session.streamAborter;
|
||||
const gen = extra.ideMessenger.llmStreamChat(
|
||||
{
|
||||
completionOptions,
|
||||
title: selectedChatModel.title,
|
||||
messages,
|
||||
messages: messages,
|
||||
legacySlashCommandData,
|
||||
},
|
||||
streamAborter.signal,
|
||||
);
|
||||
|
||||
// Stream response
|
||||
let next = await gen.next();
|
||||
while (!next.done) {
|
||||
if (!getState().session.isStreaming) {
|
||||
|
|
|
|||
|
|
@ -1,15 +1,11 @@
|
|||
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
|
||||
import { JSONContent } from "@tiptap/core";
|
||||
import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core";
|
||||
import { constructMessages } from "core/llm/constructMessages";
|
||||
import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules";
|
||||
import { InputModifiers } from "core";
|
||||
import posthog from "posthog-js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
|
||||
import { getBaseSystemMessage } from "../../util";
|
||||
import { selectSelectedChatModel } from "../slices/configSlice";
|
||||
import {
|
||||
setAppliedRulesAtIndex,
|
||||
submitEditorAndInitAtIndex,
|
||||
updateHistoryItemAtIndex,
|
||||
} from "../slices/sessionSlice";
|
||||
|
|
@ -77,7 +73,7 @@ export const streamResponseThunk = createAsyncThunk<
|
|||
.map((item) => item.uri!.value),
|
||||
...selectedCode.map((rif) => rif.filepath),
|
||||
];
|
||||
dispatch(updateFileSymbolsFromFiles(filesForSymbols));
|
||||
void dispatch(updateFileSymbolsFromFiles(filesForSymbols));
|
||||
|
||||
dispatch(
|
||||
updateHistoryItemAtIndex({
|
||||
|
|
@ -93,47 +89,6 @@ export const streamResponseThunk = createAsyncThunk<
|
|||
}),
|
||||
);
|
||||
|
||||
// Get updated history after the update
|
||||
const updatedHistory = getState().session.history;
|
||||
|
||||
// Determine which rules apply to this message
|
||||
const userMsg = updatedHistory[inputIndex].message;
|
||||
const rules = getState().config.config.rules;
|
||||
const rulePolicies = getState().ui.ruleSettings;
|
||||
|
||||
// Calculate applicable rules once
|
||||
// We need to check the message type to match what getApplicableRules expects
|
||||
const applicableRules = getApplicableRules(
|
||||
userMsg.role === "user" || userMsg.role === "tool"
|
||||
? (userMsg as UserChatMessage | ToolResultChatMessage)
|
||||
: undefined,
|
||||
rules,
|
||||
selectedContextItems,
|
||||
rulePolicies,
|
||||
);
|
||||
|
||||
// Store in history for UI display
|
||||
dispatch(
|
||||
setAppliedRulesAtIndex({
|
||||
index: inputIndex,
|
||||
appliedRules: applicableRules,
|
||||
}),
|
||||
);
|
||||
|
||||
const messageMode = getState().session.mode;
|
||||
const baseChatOrAgentSystemMessage = getBaseSystemMessage(
|
||||
selectedChatModel,
|
||||
messageMode,
|
||||
);
|
||||
|
||||
const messages = constructMessages(
|
||||
messageMode,
|
||||
[...updatedHistory],
|
||||
baseChatOrAgentSystemMessage,
|
||||
applicableRules,
|
||||
rulePolicies,
|
||||
);
|
||||
|
||||
posthog.capture("step run", {
|
||||
step_name: "User Input",
|
||||
params: {},
|
||||
|
|
@ -150,7 +105,6 @@ export const streamResponseThunk = createAsyncThunk<
|
|||
unwrapResult(
|
||||
await dispatch(
|
||||
streamNormalInput({
|
||||
messages,
|
||||
legacySlashCommandData: legacyCommandWithInput
|
||||
? {
|
||||
command: legacyCommandWithInput.command,
|
||||
|
|
|
|||
|
|
@ -1,10 +1,7 @@
|
|||
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
|
||||
import { ChatMessage } from "core";
|
||||
import { constructMessages } from "core/llm/constructMessages";
|
||||
import { renderContextItems } from "core/util/messageContent";
|
||||
import { getBaseSystemMessage } from "../../util";
|
||||
import { selectSelectedChatModel } from "../slices/configSlice";
|
||||
import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice";
|
||||
import { streamUpdate } from "../slices/sessionSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
import { findToolCall } from "../util";
|
||||
import { resetStateForNewMessage } from "./resetStateForNewMessage";
|
||||
|
|
@ -21,15 +18,8 @@ export const streamResponseAfterToolCall = createAsyncThunk<
|
|||
await dispatch(
|
||||
streamThunkWrapper(async () => {
|
||||
const state = getState();
|
||||
const initialHistory = state.session.history;
|
||||
const selectedChatModel = selectSelectedChatModel(state);
|
||||
|
||||
if (!selectedChatModel) {
|
||||
throw new Error("No model selected");
|
||||
}
|
||||
|
||||
const toolCallState = findToolCall(state.session.history, toolCallId);
|
||||
|
||||
if (!toolCallState) {
|
||||
return; // in cases where edit tool is cancelled mid apply, this will be triggered
|
||||
}
|
||||
|
|
@ -40,41 +30,15 @@ export const streamResponseAfterToolCall = createAsyncThunk<
|
|||
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
// TODO parallel tool calls - dispatch one tool message per tool call
|
||||
const newMessage: ChatMessage = {
|
||||
role: "tool",
|
||||
content: renderContextItems(toolOutput),
|
||||
toolCallId,
|
||||
};
|
||||
dispatch(streamUpdate([newMessage]));
|
||||
dispatch(
|
||||
addContextItemsAtIndex({
|
||||
index: initialHistory.length,
|
||||
contextItems: toolOutput.map((contextItem) => ({
|
||||
...contextItem,
|
||||
id: {
|
||||
providerTitle: "toolCall",
|
||||
itemId: toolCallId,
|
||||
},
|
||||
})),
|
||||
}),
|
||||
);
|
||||
|
||||
const updatedHistory = getState().session.history;
|
||||
const messageMode = getState().session.mode;
|
||||
|
||||
const baseChatOrAgentSystemMessage = getBaseSystemMessage(
|
||||
selectedChatModel,
|
||||
messageMode,
|
||||
);
|
||||
|
||||
const messages = constructMessages(
|
||||
messageMode,
|
||||
[...updatedHistory],
|
||||
baseChatOrAgentSystemMessage,
|
||||
state.config.config.rules,
|
||||
);
|
||||
|
||||
unwrapResult(await dispatch(streamNormalInput({ messages })));
|
||||
unwrapResult(await dispatch(streamNormalInput({})));
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ export const streamThunkWrapper = createAsyncThunk<
|
|||
);
|
||||
}
|
||||
} catch (e) {
|
||||
dispatch(cancelStream());
|
||||
await dispatch(cancelStream());
|
||||
dispatch(setDialogMessage(<StreamErrorDialog error={e} />));
|
||||
dispatch(setShowDialog(true));
|
||||
}
|
||||
|
|
|
|||
734
gui/src/redux/util/constructMessages.test.ts
Normal file
734
gui/src/redux/util/constructMessages.test.ts
Normal file
|
|
@ -0,0 +1,734 @@
|
|||
import {
|
||||
AssistantChatMessage,
|
||||
ChatHistoryItem,
|
||||
ChatMessage,
|
||||
ContextItemWithId,
|
||||
ModelDescription,
|
||||
RuleWithSource,
|
||||
ThinkingChatMessage,
|
||||
ToolResultChatMessage,
|
||||
UserChatMessage,
|
||||
} from "core";
|
||||
import {
|
||||
DEFAULT_AGENT_SYSTEM_MESSAGE,
|
||||
DEFAULT_CHAT_SYSTEM_MESSAGE,
|
||||
} from "core/llm/defaultSystemMessages";
|
||||
import { renderChatMessage } from "core/util/messageContent";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import {
|
||||
CANCELLED_TOOL_CALL_MESSAGE,
|
||||
constructMessages,
|
||||
getBaseSystemMessage,
|
||||
NO_TOOL_CALL_OUTPUT_MESSAGE,
|
||||
} from "./constructMessages";
|
||||
|
||||
// For these tests we will mock the rules to simulate different scenarios
|
||||
const CONTEXT_RULE: RuleWithSource = {
|
||||
source: "rules-block",
|
||||
rule: "CONTEXT_RULE",
|
||||
description: "CONTEXT_TRIGGER",
|
||||
};
|
||||
const LAST_MESSAGE_RULE: RuleWithSource = {
|
||||
source: "rules-block",
|
||||
rule: "LAST_MESSAGE_RULE",
|
||||
description: "LAST_MESSAGE_TRIGGER",
|
||||
};
|
||||
const NORMAL_RULE: RuleWithSource = {
|
||||
source: "rules-block",
|
||||
rule: "Always apply rule",
|
||||
};
|
||||
|
||||
vi.mock("core/llm/rules/getSystemMessageWithRules", async (importOriginal) => {
|
||||
const original = (await importOriginal()) as any;
|
||||
return {
|
||||
...original,
|
||||
getSystemMessageWithRules: ({
|
||||
baseSystemMessage,
|
||||
availableRules,
|
||||
userMessage,
|
||||
contextItems,
|
||||
rulePolicies,
|
||||
}: {
|
||||
baseSystemMessage: string;
|
||||
availableRules: RuleWithSource[];
|
||||
userMessage?: UserChatMessage | ToolResultChatMessage;
|
||||
contextItems: ContextItemWithId[];
|
||||
rulePolicies?: Record<string, any>;
|
||||
}) => {
|
||||
// Filter rules based on our mock logic
|
||||
const appliedRules = availableRules.filter((rule) => {
|
||||
if (rule.rule === LAST_MESSAGE_RULE.rule) {
|
||||
if (userMessage) {
|
||||
return renderChatMessage(userMessage).includes(
|
||||
LAST_MESSAGE_RULE.description!,
|
||||
);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (rule.rule === CONTEXT_RULE.rule) {
|
||||
return contextItems.some((item) =>
|
||||
item.content.includes(CONTEXT_RULE.description!),
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
// Build the system message with applied rules
|
||||
let systemMessage = baseSystemMessage || "";
|
||||
if (appliedRules.length > 0) {
|
||||
systemMessage += "\n\nRules to follow:\n";
|
||||
for (const rule of appliedRules) {
|
||||
systemMessage += `- ${rule.rule}\n`;
|
||||
}
|
||||
}
|
||||
|
||||
return { systemMessage, appliedRules };
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
test("getBaseSystemMessage should return the correct system message based on mode", () => {
|
||||
const mockModel = {
|
||||
baseAgentSystemMessage: "Custom Agent System Message",
|
||||
baseChatSystemMessage: "Custom Chat System Message",
|
||||
} as ModelDescription;
|
||||
|
||||
// Test agent mode with custom message
|
||||
expect(getBaseSystemMessage("agent", mockModel)).toBe(
|
||||
"Custom Agent System Message",
|
||||
);
|
||||
|
||||
// Test chat mode with custom message
|
||||
expect(getBaseSystemMessage("chat", mockModel)).toBe(
|
||||
"Custom Chat System Message",
|
||||
);
|
||||
|
||||
// Test agent mode with default message
|
||||
expect(getBaseSystemMessage("agent", {} as ModelDescription)).toBe(
|
||||
DEFAULT_AGENT_SYSTEM_MESSAGE,
|
||||
);
|
||||
|
||||
// Test chat mode with default message
|
||||
expect(getBaseSystemMessage("chat", {} as ModelDescription)).toBe(
|
||||
DEFAULT_CHAT_SYSTEM_MESSAGE,
|
||||
);
|
||||
});
|
||||
|
||||
describe("constructMessages", () => {
|
||||
// Setup mock data
|
||||
let mockHistory: ChatHistoryItem[];
|
||||
const mockRules: RuleWithSource[] = [
|
||||
CONTEXT_RULE,
|
||||
LAST_MESSAGE_RULE,
|
||||
NORMAL_RULE,
|
||||
];
|
||||
|
||||
const createContextItem = (
|
||||
id: string,
|
||||
content: string,
|
||||
): ContextItemWithId => ({
|
||||
id: {
|
||||
providerTitle: "test-provider",
|
||||
itemId: id,
|
||||
},
|
||||
content,
|
||||
name: `Context Item ${id}`,
|
||||
description: `Description for ${id}`,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset mock history before each test
|
||||
mockHistory = [];
|
||||
});
|
||||
|
||||
test("should ignore empty, tool, and system messages that go in", () => {
|
||||
// Setup history with various message types including ones to be ignored
|
||||
mockHistory = [
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "I should be ignored",
|
||||
} as ChatMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
{
|
||||
message: {
|
||||
role: "tool",
|
||||
content: "I should be ignored",
|
||||
toolCallId: "123",
|
||||
} as ToolResultChatMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
{
|
||||
message: { role: "user", content: "" } as ChatMessage, // Empty message
|
||||
contextItems: [],
|
||||
},
|
||||
{
|
||||
message: { role: "user", content: "Valid user message" } as ChatMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
];
|
||||
|
||||
const { messages } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// Should only contain a system message (added by the function) and the valid user message
|
||||
expect(messages.length).toBe(2);
|
||||
expect(messages[0].role).toBe("system");
|
||||
expect(messages[1].role).toBe("user");
|
||||
expect(messages[1].content).toEqual([
|
||||
{ type: "text", text: "Valid user message" },
|
||||
]);
|
||||
expect(messages.some((msg) => msg.content === "I should be ignored")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("should convert user messages to message parts arrays with context items", () => {
|
||||
const contextItems = [
|
||||
createContextItem("1", "Context content 1"),
|
||||
createContextItem("2", "Context content 2"),
|
||||
];
|
||||
|
||||
mockHistory = [
|
||||
{
|
||||
message: {
|
||||
role: "user",
|
||||
content: "User message with context",
|
||||
} as ChatMessage,
|
||||
contextItems,
|
||||
},
|
||||
];
|
||||
|
||||
const { messages } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// Check that user message was converted to parts array with context items first
|
||||
expect(messages.length).toBe(2); // System message + user message
|
||||
expect(messages[1].role).toBe("user");
|
||||
|
||||
// Check content structure
|
||||
const content = messages[1].content as any[];
|
||||
expect(content.length).toBe(3); // 2 context items + original message
|
||||
expect(content[0].text).toContain("Context content 1");
|
||||
expect(content[1].text).toContain("Context content 2");
|
||||
expect(content[2].text).toBe("User message with context");
|
||||
});
|
||||
|
||||
test("should inject thinking messages with no changes", () => {
|
||||
const thinkingMessage: ThinkingChatMessage = {
|
||||
role: "thinking",
|
||||
content: "Thinking process...",
|
||||
};
|
||||
|
||||
mockHistory = [
|
||||
{
|
||||
message: thinkingMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
];
|
||||
|
||||
const { messages } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// Should have system message + thinking message
|
||||
expect(messages.length).toBe(2);
|
||||
expect(messages[1].role).toBe("thinking");
|
||||
expect(messages[1].content).toBe("Thinking process...");
|
||||
});
|
||||
|
||||
test("should inject assistant messages with no changes", () => {
|
||||
const assistantMessage: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: "Assistant response",
|
||||
};
|
||||
|
||||
mockHistory = [
|
||||
{
|
||||
message: assistantMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
];
|
||||
|
||||
const { messages } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// Should have system message + assistant message
|
||||
expect(messages.length).toBe(2);
|
||||
expect(messages[1].role).toBe("assistant");
|
||||
expect(messages[1].content).toBe("Assistant response");
|
||||
});
|
||||
|
||||
test("should follow assistant messages with tool calls by tool messages containing the tool output", () => {
|
||||
const assistantWithToolCall: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: "I will search for that",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-call-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
arguments: '{"query": "test"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// With tool output
|
||||
mockHistory = [
|
||||
{
|
||||
message: {
|
||||
role: "user",
|
||||
content: "Can you search for something?",
|
||||
} as UserChatMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
{
|
||||
message: assistantWithToolCall,
|
||||
contextItems: [],
|
||||
toolCallState: {
|
||||
toolCallId: "tool-call-1",
|
||||
toolCall: {
|
||||
id: "tool-call-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
arguments: '{"query": "test"}',
|
||||
},
|
||||
},
|
||||
status: "done",
|
||||
parsedArgs: { query: "test" },
|
||||
output: [createContextItem("search-result", "Search result content")],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const { messages } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// Should have: system + user + assistant + tool messages
|
||||
expect(messages.length).toBe(4);
|
||||
expect(messages[2].role).toBe("assistant");
|
||||
expect(messages[3].role).toBe("tool");
|
||||
const toolMessage = messages[3] as ToolResultChatMessage;
|
||||
expect(toolMessage.toolCallId).toBe("tool-call-1");
|
||||
expect(toolMessage.content).toContain("Search result content");
|
||||
});
|
||||
|
||||
test("should show cancelled message for cancelled tool calls", () => {
|
||||
const assistantWithToolCall: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: "I will search for that",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-call-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
arguments: '{"query": "test"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// With cancelled tool call
|
||||
mockHistory = [
|
||||
{
|
||||
message: assistantWithToolCall,
|
||||
contextItems: [],
|
||||
toolCallState: {
|
||||
toolCallId: "tool-call-1",
|
||||
toolCall: {
|
||||
id: "tool-call-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
arguments: '{"query": "test"}',
|
||||
},
|
||||
},
|
||||
status: "canceled",
|
||||
parsedArgs: { query: "test" },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const { messages } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// Should have system + assistant + tool message with cancelled message
|
||||
expect(messages.length).toBe(3);
|
||||
expect(messages[2].role).toBe("tool");
|
||||
const toolMessage = messages[2] as ToolResultChatMessage;
|
||||
expect(toolMessage.toolCallId).toBe("tool-call-1");
|
||||
expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE);
|
||||
});
|
||||
|
||||
test('should show "No tool output" for tool calls without output', () => {
|
||||
const assistantWithToolCall: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: "I will search for that",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-call-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
arguments: '{"query": "test"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// With tool call but no output
|
||||
mockHistory = [
|
||||
{
|
||||
message: assistantWithToolCall,
|
||||
contextItems: [],
|
||||
toolCallState: {
|
||||
toolCallId: "tool-call-1",
|
||||
toolCall: {
|
||||
id: "tool-call-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
arguments: '{"query": "test"}',
|
||||
},
|
||||
},
|
||||
status: "generating", // Not done yet
|
||||
parsedArgs: { query: "test" },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const { messages } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// Should have system + assistant + tool message with "No tool output"
|
||||
expect(messages.length).toBe(3);
|
||||
expect(messages[2].role).toBe("tool");
|
||||
expect(messages[2].content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
|
||||
});
|
||||
|
||||
test("should start with system message using base message if provided", () => {
|
||||
mockHistory = [
|
||||
{
|
||||
message: { role: "user", content: "Hello" } as UserChatMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
];
|
||||
|
||||
const { messages } = constructMessages(
|
||||
mockHistory,
|
||||
"Custom Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
expect(messages[0].role).toBe("system");
|
||||
expect(messages[0].content).toContain("Custom Base System Message");
|
||||
});
|
||||
|
||||
test("should handle multiple tool calls in a single assistant message", () => {
|
||||
const assistantWithMultipleToolCalls: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: "I will search and check the weather",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-call-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
arguments: '{"query": "test"}',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "tool-call-2",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "weather",
|
||||
arguments: '{"location": "New York"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// Only the first tool call has output
|
||||
mockHistory = [
|
||||
{
|
||||
message: assistantWithMultipleToolCalls,
|
||||
contextItems: [],
|
||||
toolCallState: {
|
||||
toolCallId: "tool-call-1",
|
||||
toolCall: {
|
||||
id: "tool-call-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
arguments: '{"query": "test"}',
|
||||
},
|
||||
},
|
||||
status: "done",
|
||||
parsedArgs: { query: "test" },
|
||||
output: [createContextItem("search-result", "Search result content")],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const { messages } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// Should have: system + assistant + 2 tool messages
|
||||
expect(messages.length).toBe(4);
|
||||
expect(messages[1].role).toBe("assistant");
|
||||
|
||||
// First tool message should have output
|
||||
expect(messages[2].role).toBe("tool");
|
||||
expect(messages[3].role).toBe("tool");
|
||||
|
||||
const toolMessage1 = messages[2] as ToolResultChatMessage;
|
||||
const toolMessage2 = messages[3] as ToolResultChatMessage;
|
||||
expect(toolMessage1.toolCallId).toBe("tool-call-1");
|
||||
expect(toolMessage1.content).toContain("Search result content");
|
||||
|
||||
// Second tool message should have "No tool output"
|
||||
expect(toolMessage2.toolCallId).toBe("tool-call-2");
|
||||
expect(toolMessage2.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
|
||||
});
|
||||
|
||||
test("should handle messages with array content", () => {
|
||||
// User message with array content (including an image)
|
||||
const userMessageWithArray: UserChatMessage = {
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "Here is some text" },
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: "https://example.com/image.jpg" },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
mockHistory = [
|
||||
{
|
||||
message: userMessageWithArray,
|
||||
contextItems: [createContextItem("ctx", "Context text")],
|
||||
},
|
||||
];
|
||||
|
||||
const { messages, appliedRules } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// Check the user message content structure
|
||||
expect(messages.length).toBe(2);
|
||||
expect(messages[1].role).toBe("user");
|
||||
|
||||
const content = messages[1].content as any[];
|
||||
// Should have context item + original 2 parts
|
||||
expect(content.length).toBe(3);
|
||||
expect(content[0].type).toBe("text");
|
||||
expect(content[0].text).toContain("Context text");
|
||||
expect(content[1].type).toBe("text");
|
||||
expect(content[1].text).toBe("Here is some text");
|
||||
expect(content[2].type).toBe("imageUrl");
|
||||
expect(content[2].imageUrl.url).toBe("https://example.com/image.jpg");
|
||||
|
||||
// This also verifies that rules are NOT applied if the triggers are not present
|
||||
expect(appliedRules).toHaveLength(1);
|
||||
expect(appliedRules).toContainEqual(NORMAL_RULE);
|
||||
});
|
||||
|
||||
test("system message should include rules triggered by context items from the last user message forward", () => {
|
||||
// Create context item that should trigger the CONTEXT_RULE
|
||||
const triggeringContextItem = createContextItem(
|
||||
"trigger",
|
||||
`Some content with ${CONTEXT_RULE.description} in it`,
|
||||
);
|
||||
|
||||
mockHistory = [
|
||||
// First user message with non-triggering context
|
||||
{
|
||||
message: { role: "user", content: "First message" } as UserChatMessage,
|
||||
contextItems: [createContextItem("normal", "Normal context")],
|
||||
},
|
||||
// Assistant response
|
||||
{
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "Assistant response",
|
||||
} as AssistantChatMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
// Last user message with triggering context
|
||||
{
|
||||
message: { role: "user", content: "Last message" } as UserChatMessage,
|
||||
contextItems: [triggeringContextItem],
|
||||
},
|
||||
];
|
||||
|
||||
const { messages, appliedRules } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// Verify context rule was applied in the system message
|
||||
expect(appliedRules).toHaveLength(2);
|
||||
expect(appliedRules).toContainEqual(NORMAL_RULE);
|
||||
expect(appliedRules).toContainEqual(CONTEXT_RULE);
|
||||
expect(messages[0].role).toBe("system");
|
||||
expect(messages[0].content).toContain("Base System Message");
|
||||
expect(messages[0].content).toContain(CONTEXT_RULE.rule);
|
||||
});
|
||||
|
||||
test("system message should include rules triggered by tool output after the last user message", () => {
|
||||
// Create a history with a user message, assistant with tool call, and tool output containing triggering content
|
||||
const assistantWithToolCall: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: "I will search for that",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-call-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
arguments: '{"query": "test"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// Tool output containing the trigger for CONTEXT_RULE
|
||||
const triggeringToolOutput = createContextItem(
|
||||
"search-result",
|
||||
`Search result with ${CONTEXT_RULE.description} trigger`,
|
||||
);
|
||||
|
||||
mockHistory = [
|
||||
{
|
||||
message: {
|
||||
role: "user",
|
||||
content: "Can you search for something?",
|
||||
} as UserChatMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
{
|
||||
message: assistantWithToolCall,
|
||||
contextItems: [],
|
||||
toolCallState: {
|
||||
toolCallId: "tool-call-1",
|
||||
toolCall: {
|
||||
id: "tool-call-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
arguments: '{"query": "test"}',
|
||||
},
|
||||
},
|
||||
status: "done",
|
||||
parsedArgs: { query: "test" },
|
||||
output: [triggeringToolOutput],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const { messages, appliedRules } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// Verify context rule was applied in the system message due to the tool output
|
||||
expect(appliedRules).toHaveLength(2);
|
||||
expect(appliedRules).toContainEqual(NORMAL_RULE);
|
||||
expect(appliedRules).toContainEqual(CONTEXT_RULE);
|
||||
expect(messages[0].role).toBe("system");
|
||||
expect(messages[0].content).toContain("Base System Message");
|
||||
expect(messages[0].content).toContain(CONTEXT_RULE.rule);
|
||||
});
|
||||
|
||||
test("system message should only apply rules triggered by the last user message", () => {
|
||||
// First user message with trigger for LAST_MESSAGE_RULE
|
||||
const firstUserMessage = {
|
||||
role: "user",
|
||||
content: `This contains ${LAST_MESSAGE_RULE.description}`,
|
||||
} as UserChatMessage;
|
||||
|
||||
// Last user message without any triggers
|
||||
const lastUserMessage = {
|
||||
role: "user",
|
||||
content: "This is a normal message",
|
||||
} as UserChatMessage;
|
||||
|
||||
mockHistory = [
|
||||
{
|
||||
message: firstUserMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
{
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "First response",
|
||||
} as AssistantChatMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
{
|
||||
message: lastUserMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
];
|
||||
|
||||
const { messages, appliedRules } = constructMessages(
|
||||
mockHistory,
|
||||
"Base System Message",
|
||||
mockRules,
|
||||
{},
|
||||
);
|
||||
|
||||
// LAST_MESSAGE_RULE should not be applied since the trigger is not in the last message
|
||||
expect(appliedRules).toHaveLength(1);
|
||||
expect(appliedRules).toContainEqual(NORMAL_RULE); // Normal rule should always apply
|
||||
expect(messages[0].role).toBe("system");
|
||||
expect(messages[0].content).toContain("Base System Message");
|
||||
expect(messages[0].content).not.toContain(LAST_MESSAGE_RULE.rule);
|
||||
});
|
||||
});
|
||||
173
gui/src/redux/util/constructMessages.ts
Normal file
173
gui/src/redux/util/constructMessages.ts
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
import {
|
||||
ChatHistoryItem,
|
||||
ChatMessage,
|
||||
ContextItemWithId,
|
||||
ModelDescription,
|
||||
RuleWithSource,
|
||||
TextMessagePart,
|
||||
ToolResultChatMessage,
|
||||
UserChatMessage,
|
||||
} from "core";
|
||||
import {
|
||||
DEFAULT_AGENT_SYSTEM_MESSAGE,
|
||||
DEFAULT_CHAT_SYSTEM_MESSAGE,
|
||||
} from "core/llm/defaultSystemMessages";
|
||||
import { chatMessageIsEmpty } from "core/llm/messages";
|
||||
import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules";
|
||||
import { RulePolicies } from "core/llm/rules/types";
|
||||
import { findLast, findLastIndex } from "core/util/findLast";
|
||||
import {
|
||||
normalizeToMessageParts,
|
||||
renderContextItems,
|
||||
} from "core/util/messageContent";
|
||||
import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem";
|
||||
|
||||
export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output";
|
||||
export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call.";
|
||||
|
||||
interface MessageWithContextItems {
|
||||
ctxItems: ContextItemWithId[];
|
||||
message: ChatMessage;
|
||||
}
|
||||
export function constructMessages(
|
||||
history: ChatHistoryItem[],
|
||||
baseSystemMessage: string | undefined,
|
||||
availableRules: RuleWithSource[],
|
||||
rulePolicies: RulePolicies,
|
||||
): {
|
||||
messages: ChatMessage[];
|
||||
appliedRules: RuleWithSource[];
|
||||
appliedRuleIndex: number;
|
||||
} {
|
||||
const historyCopy = [...history];
|
||||
|
||||
const msgs: MessageWithContextItems[] = [];
|
||||
let appliedRuleIndex = -1;
|
||||
let index = -1;
|
||||
for (const item of historyCopy) {
|
||||
index++;
|
||||
if (
|
||||
item.message.role === "system" ||
|
||||
item.message.role === "tool" ||
|
||||
chatMessageIsEmpty(item.message)
|
||||
) {
|
||||
// Tool messages will be re-inserted
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item.message.role === "user") {
|
||||
appliedRuleIndex = index;
|
||||
// Gather context items for user messages
|
||||
let content = normalizeToMessageParts(item.message);
|
||||
|
||||
const ctxItemParts = item.contextItems
|
||||
.map((ctxItem) => {
|
||||
return {
|
||||
type: "text",
|
||||
text: `${ctxItem.content}\n`,
|
||||
} as TextMessagePart;
|
||||
})
|
||||
.filter((part) => !!part.text.trim());
|
||||
|
||||
content = [...ctxItemParts, ...content];
|
||||
msgs.push({
|
||||
ctxItems: item.contextItems,
|
||||
message: {
|
||||
...item.message,
|
||||
content,
|
||||
},
|
||||
});
|
||||
} else if (item.message.role === "thinking") {
|
||||
msgs.push({
|
||||
ctxItems: item.contextItems,
|
||||
message: item.message,
|
||||
});
|
||||
} else if (item.message.role === "assistant") {
|
||||
msgs.push({
|
||||
ctxItems: item.contextItems,
|
||||
message: item.message,
|
||||
});
|
||||
|
||||
// Add a tool message for each tool call
|
||||
if (item.message.toolCalls?.length) {
|
||||
// If the assistant message has tool calls, we need to insert tool messages
|
||||
for (const toolCall of item.message.toolCalls) {
|
||||
let content: string = NO_TOOL_CALL_OUTPUT_MESSAGE;
|
||||
// TODO parallel tool calls: toolCallState only supports one tool call per message for now
|
||||
if (item.toolCallState?.status === "canceled") {
|
||||
content = CANCELLED_TOOL_CALL_MESSAGE;
|
||||
} else if (
|
||||
item.toolCallState?.toolCallId === toolCall.id &&
|
||||
item.toolCallState?.output
|
||||
) {
|
||||
content = renderContextItems(item.toolCallState.output);
|
||||
}
|
||||
msgs.push({
|
||||
ctxItems: toolCallStateToContextItems(item.toolCallState),
|
||||
message: {
|
||||
role: "tool",
|
||||
content,
|
||||
toolCallId: toolCall.id!,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Some rules only apply to the last user or tool message
|
||||
const lastUserOrToolMsg = findLast(
|
||||
msgs,
|
||||
(item) => item.message.role === "user" || item.message.role === "tool",
|
||||
)?.message as UserChatMessage | ToolResultChatMessage;
|
||||
|
||||
// Some rules apply to all context items since the last user message, inclusiv
|
||||
const lastUserMsgIndex = findLastIndex(
|
||||
msgs,
|
||||
(item) => item.message.role === "user",
|
||||
);
|
||||
const itemsBackToLastUserMessage = msgs
|
||||
.slice(lastUserMsgIndex, msgs.length)
|
||||
.filter(
|
||||
(item) => item.message.role === "tool" || item.message.role === "user",
|
||||
);
|
||||
const rulesContextItems = itemsBackToLastUserMessage
|
||||
.map((item) => item.ctxItems)
|
||||
.flat();
|
||||
|
||||
const { systemMessage, appliedRules } = getSystemMessageWithRules({
|
||||
baseSystemMessage,
|
||||
availableRules,
|
||||
userMessage: lastUserOrToolMsg,
|
||||
contextItems: rulesContextItems,
|
||||
rulePolicies,
|
||||
});
|
||||
|
||||
if (systemMessage.trim()) {
|
||||
msgs.unshift({
|
||||
ctxItems: [],
|
||||
message: {
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const messages = msgs.map((m) => m.message);
|
||||
return {
|
||||
messages,
|
||||
appliedRules,
|
||||
appliedRuleIndex,
|
||||
};
|
||||
}
|
||||
|
||||
export function getBaseSystemMessage(
|
||||
messageMode: string,
|
||||
model: ModelDescription,
|
||||
): string {
|
||||
if (messageMode === "agent") {
|
||||
return model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE;
|
||||
} else {
|
||||
return model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { ContextItem, ToolCallState } from "core";
|
||||
import { safeParseToolCallArgs } from "core/tools/parseArgs";
|
||||
import { IIdeMessenger } from "../../context/IdeMessenger";
|
||||
import { ChatHistoryItemWithMessageId } from "../slices/sessionSlice";
|
||||
import { RootState } from "../store";
|
||||
|
||||
export function findCurrentToolCall(
|
||||
|
|
@ -9,6 +10,7 @@ export function findCurrentToolCall(
|
|||
return chatHistory[chatHistory.length - 1]?.toolCallState;
|
||||
}
|
||||
|
||||
// TODO parallel tool calls - find tool call must search within arrays
|
||||
export function findToolCall(
|
||||
chatHistory: RootState["session"]["history"],
|
||||
toolCallId: string,
|
||||
|
|
@ -18,6 +20,16 @@ export function findToolCall(
|
|||
)?.toolCallState;
|
||||
}
|
||||
|
||||
export function findToolOutput(
|
||||
chatHistory: RootState["session"]["history"],
|
||||
toolCallId: string,
|
||||
): ChatHistoryItemWithMessageId | undefined {
|
||||
return chatHistory.find(
|
||||
(item) =>
|
||||
item.message.role === "tool" && item.message.toolCallId === toolCallId,
|
||||
);
|
||||
}
|
||||
|
||||
export function logToolUsage(
|
||||
toolCallState: ToolCallState,
|
||||
success: boolean,
|
||||
|
|
|
|||
|
|
@ -1,10 +1,4 @@
|
|||
import { MessageModes, ModelDescription } from "core";
|
||||
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
|
||||
import {
|
||||
DEFAULT_AGENT_SYSTEM_MESSAGE,
|
||||
DEFAULT_CHAT_SYSTEM_MESSAGE,
|
||||
} from "core/llm/constructMessages";
|
||||
import _ from "lodash";
|
||||
import { KeyboardEvent as ReactKeyboardEvent } from "react";
|
||||
import { getLocalStorage } from "./localStorage";
|
||||
|
||||
|
|
@ -88,52 +82,6 @@ export function isPrerelease() {
|
|||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the values of an object's properties based on the specified paths.
|
||||
*
|
||||
* This function creates a deep clone of the provided object and updates its properties
|
||||
* based on the given path-to-value mappings. If a value in the mapping is a function,
|
||||
* it will be used to determine the new value for the property. Otherwise, the value itself
|
||||
* will be set for the property.
|
||||
*
|
||||
* @param {Object} old - The original object to be cloned and updated.
|
||||
* @param {Object} pathToValue - An object where the keys represent the paths to the properties
|
||||
* to be updated and the values represent the new values or functions
|
||||
* to determine the new values.
|
||||
* @returns {Object} A new object with the updated values.
|
||||
*/
|
||||
export function updatedObj(old: any, pathToValue: { [key: string]: any }) {
|
||||
const newObject = _.cloneDeep(old);
|
||||
|
||||
for (const key in pathToValue) {
|
||||
if (typeof pathToValue[key] === "function") {
|
||||
_.updateWith(newObject, key, pathToValue[key]);
|
||||
} else {
|
||||
_.updateWith(newObject, key, (__) => pathToValue[key]);
|
||||
}
|
||||
}
|
||||
|
||||
return newObject;
|
||||
}
|
||||
|
||||
export function isLocalProfile(profile: ProfileDescription): boolean {
|
||||
return profile.profileType === "local";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the base system message for the agent or chat mode from the model description.
|
||||
*/
|
||||
export function getBaseSystemMessage(
|
||||
modelDetails: ModelDescription | null,
|
||||
mode: MessageModes,
|
||||
) {
|
||||
let baseChatOrAgentSystemMessage: string | undefined;
|
||||
if (mode === "agent") {
|
||||
baseChatOrAgentSystemMessage =
|
||||
modelDetails?.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE;
|
||||
} else {
|
||||
baseChatOrAgentSystemMessage =
|
||||
modelDetails?.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE;
|
||||
}
|
||||
return baseChatOrAgentSystemMessage;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue