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