Elffuss BraidHub

kikocis/continue public

80d4c66b3ffb · 2.6 KiBRawPermalink
1import {
2 AssistantChatMessage,
3 MessagePart,
4 ToolCallState,
5 UserChatMessage,
6} from "../..";
7import {
8 normalizeToMessageParts,
9 renderContextItems,
10} from "../../util/messageContent";
11import {
12 CANCELLED_TOOL_CALL_MESSAGE,
13 NO_TOOL_CALL_OUTPUT_MESSAGE,
14} from "../constants";
15function toolCallStateToSystemToolCall(state: ToolCallState): string {
16 let parts = ["```tool"];
17 parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
18 try {
19 for (const arg in state.parsedArgs) {
20 parts.push(`BEGIN_ARG: ${arg}`);
21 parts.push(JSON.stringify(state.parsedArgs[arg]));
22 parts.push(`END_ARG`);
23 }
24 } catch (e) {
25 console.log("Failed to stringify json args", state.parsedArgs);
26 }
27 // TODO - include tool call id for parallel. Confuses dumb models
28 parts.push("```");
29 return parts.join("\n");
30}
31
32function toolCallStateToSystemToolOutput(state: ToolCallState): string {
33 let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`;
34 // TODO - include tool call id for parallel. Confuses dumb models
35 // let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`;
36 if (state.status === "canceled") {
37 output += CANCELLED_TOOL_CALL_MESSAGE;
38 } else if (state.output?.length) {
39 output += renderContextItems(state.output);
40 } else {
41 output += NO_TOOL_CALL_OUTPUT_MESSAGE;
42 }
43 return output;
44}
45
46export function convertToolCallStatesToSystemCallsAndOutput(
47 originalAssistantMessage: AssistantChatMessage,
48 toolCallStates: ToolCallState[],
49): {
50 assistantMessage: AssistantChatMessage;
51 userMessage: UserChatMessage;
52} {
53 const parts = normalizeToMessageParts(originalAssistantMessage);
54 if (originalAssistantMessage.toolCalls) {
55 parts.push(
56 ...toolCallStates.map((state) => ({
57 type: "text" as const,
58 text: toolCallStateToSystemToolCall(state),
59 })),
60 );
61 }
62
63 // new message with tool calls moved to content
64 const assistantMessage: AssistantChatMessage = {
65 ...originalAssistantMessage,
66 content: parts,
67 toolCalls: undefined, // remove tool calls from the assistant message
68 };
69
70 const userParts: MessagePart[] = [];
71 if (toolCallStates) {
72 for (const state of toolCallStates) {
73 userParts.push({
74 type: "text",
75 text: toolCallStateToSystemToolOutput(state),
76 });
77 }
78 }
79 if (userParts.length === 0) {
80 userParts.push({
81 type: "text",
82 text: "Error: no tool output for tool calls",
83 });
84 }
85
86 const userMessage: UserChatMessage = {
87 role: "user",
88 content: userParts,
89 };
90
91 return {
92 assistantMessage,
93 userMessage,
94 };
95}