continue-custom/core/llm/constructMessages.ts
2025-06-27 21:34:21 -07:00

232 lines
6.8 KiB
TypeScript

import {
ChatHistoryItem,
ChatMessage,
ContextItemWithId,
RuleWithSource,
TextMessagePart,
Tool,
ToolResultChatMessage,
UserChatMessage,
} from "../";
import { findLast } from "../util/findLast";
import {
normalizeToMessageParts,
renderContextItems,
} 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";
const EDIT_MESSAGE = `\
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'
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.
${EDIT_MESSAGE}
</important_rules>`;
export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
<important_rules>
You are in agent mode.
${EDIT_MESSAGE}
</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[],
tools: Tool[],
rulePolicies?: RulePolicies,
): ChatMessage[] {
const validTools = new Set(tools.map((tool) => tool.function.name));
const filteredHistory = history.filter(
(item) => item.message.role !== "system",
);
const msgs: ChatMessage[] = [];
for (const item of filteredHistory) {
if (item.message.role === "tool") {
continue; // Tool messages will be re-inserted
}
// This was implemented for APIs that require all tool calls to have
// A corresponsing tool sent, which means if a user excluded a tool
// Then sessions with that tool call in the history would fail
// 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 (item.message.role === "user") {
// Gather context items for user messages
let content = normalizeToMessageParts(item.message);
const ctxItems = item.contextItems
.map((ctxItem) => {
return {
type: "text",
text: `${ctxItem.content}\n`,
} as TextMessagePart;
})
.filter((part) => !!part.text.trim());
content = [...ctxItems, ...content];
msgs.push({
...item.message,
content,
});
} else {
msgs.push(item.message);
}
if (item.message.role === "assistant") {
// First, push a version of the message with any valid tools calls
const validToolCalls = item.message.toolCalls?.filter(
(toolCall) =>
toolCall.function?.name &&
toolCall.id &&
validTools.has(toolCall.function.name),
);
// Case where no valid tool calls or content are present
msgs.push({
...item.message,
toolCalls: validToolCalls,
});
// Then push a tool message for each valid tool call
if (validToolCalls?.length) {
// If the assistant message has tool calls, we need to insert tool messages
for (const toolCall of validToolCalls) {
let content: string = "No tool output";
// TODO toolCallState only supports one tool call per message for now
if (
item.toolCallState?.toolCallId === toolCall.id &&
item.toolCallState?.output
) {
content = renderContextItems(item.toolCallState.output);
}
msgs.push({
role: "tool",
content,
toolCallId: toolCall.id!,
});
}
}
}
}
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;
});
}