Elffuss BraidHub

kikocis/continue public

3a1e5cc69df2 · 10.5 KiBRawPermalink
1/**
2 * Message conversion utilities for transitioning to unified ChatHistoryItem type.
3 *
4 * This module provides conversion functions between the OpenAI ChatCompletionMessageParam
5 * format and the unified ChatHistoryItem format from the core package.
6 */
7
8import type { ChatCompletionMessageParam } from "openai/resources.mjs";
9import type {
10 AssistantChatMessage,
11 ChatHistoryItem,
12 ChatMessage,
13 ContextItemWithId,
14 MessageContent,
15 ToolCall,
16 ToolCallState,
17 ToolStatus,
18} from "../index.js";
19
20/**
21 * Convert ChatCompletionMessageParam to ChatMessage
22 */
23export function convertToUnifiedMessage(
24 message: ChatCompletionMessageParam,
25): ChatMessage {
26 switch (message.role) {
27 case "system":
28 return {
29 role: "system",
30 content: typeof message.content === "string" ? message.content : "",
31 };
32
33 case "user":
34 return {
35 role: "user",
36 content: convertMessageContent(message.content),
37 };
38
39 case "assistant": {
40 const assistantMessage: AssistantChatMessage = {
41 role: "assistant",
42 content: convertMessageContent(message.content || ""),
43 };
44
45 // Convert tool calls if present
46 if ("tool_calls" in message && message.tool_calls) {
47 assistantMessage.toolCalls = message.tool_calls.map((tc: any) => ({
48 id: tc.id,
49 type: "function" as const,
50 function: {
51 name: tc.function?.name || "",
52 arguments: tc.function?.arguments || "",
53 },
54 }));
55 }
56
57 return assistantMessage;
58 }
59
60 case "tool":
61 return {
62 role: "tool",
63 content: typeof message.content === "string" ? message.content : "",
64 toolCallId: message.tool_call_id,
65 };
66
67 default:
68 throw new Error(`Unsupported message role: ${(message as any).role}`);
69 }
70}
71
72/**
73 * Convert ChatMessage to ChatCompletionMessageParam
74 */
75export function convertFromUnifiedMessage(
76 message: ChatMessage,
77): ChatCompletionMessageParam {
78 switch (message.role) {
79 case "system":
80 return {
81 role: "system",
82 content: message.content,
83 };
84
85 case "user":
86 return {
87 role: "user",
88 content: convertFromMessageContent(message.content),
89 };
90
91 case "assistant": {
92 const assistantMessage: ChatCompletionMessageParam = {
93 role: "assistant",
94 content: convertFromMessageContent(message.content),
95 };
96
97 // Convert tool calls if present
98 if (message.toolCalls && message.toolCalls.length > 0) {
99 (assistantMessage as any).tool_calls = message.toolCalls.map(
100 (tc: any) => ({
101 id: tc.id,
102 type: "function",
103 function: {
104 name: tc.function?.name || "",
105 arguments: tc.function?.arguments || "",
106 },
107 }),
108 );
109 }
110
111 return assistantMessage;
112 }
113
114 case "tool":
115 return {
116 role: "tool",
117 content: message.content,
118 tool_call_id: message.toolCallId,
119 };
120
121 case "thinking":
122 // Thinking messages don't have a direct equivalent in OpenAI format
123 // Convert to assistant message with content
124 return {
125 role: "assistant",
126 content: convertFromMessageContent(message.content),
127 };
128
129 default:
130 throw new Error(`Unsupported message role: ${(message as any).role}`);
131 }
132}
133
134/**
135 * Convert OpenAI message content to unified MessageContent format
136 */
137function convertMessageContent(
138 content: string | null | Array<any>,
139): MessageContent {
140 if (content === null) {
141 return "";
142 }
143
144 if (typeof content === "string") {
145 return content;
146 }
147
148 if (Array.isArray(content)) {
149 return content.map((part: any) => {
150 if (part.type === "text") {
151 return {
152 type: "text" as const,
153 text: part.text,
154 };
155 } else if (part.type === "image_url") {
156 return {
157 type: "imageUrl" as const,
158 imageUrl: { url: part.image_url.url },
159 };
160 }
161 throw new Error(`Unsupported content part type: ${part.type}`);
162 });
163 }
164
165 throw new Error(`Unsupported content type: ${typeof content}`);
166}
167
168/**
169 * Convert unified MessageContent to OpenAI format
170 */
171function convertFromMessageContent(
172 content: MessageContent,
173): string | Array<any> {
174 if (typeof content === "string") {
175 return content;
176 }
177
178 if (Array.isArray(content)) {
179 return content.map((part: any) => {
180 if (part.type === "text") {
181 return {
182 type: "text",
183 text: part.text,
184 };
185 } else if (part.type === "imageUrl") {
186 return {
187 type: "image_url",
188 image_url: { url: part.imageUrl.url },
189 };
190 }
191 throw new Error(`Unsupported content part type: ${part.type}`);
192 });
193 }
194
195 throw new Error(`Unsupported content type: ${typeof content}`);
196}
197
198/**
199 * Create a ChatHistoryItem from a ChatMessage
200 */
201export function createHistoryItem(
202 message: ChatMessage,
203 contextItems: ContextItemWithId[] = [],
204 toolCallStates?: ToolCallState[],
205): ChatHistoryItem {
206 return {
207 message,
208 contextItems,
209 ...(toolCallStates && { toolCallStates }),
210 };
211}
212
213/**
214 * Handle tool result message by updating the corresponding tool call state
215 */
216function handleToolResult(
217 unifiedMessage: ChatMessage & { role: "tool" },
218 pendingToolCalls: Map<string, ToolCall>,
219 historyItems: ChatHistoryItem[],
220): void {
221 const toolCall = pendingToolCalls.get(unifiedMessage.toolCallId);
222 if (!toolCall) return;
223
224 // Add tool result as context to the previous assistant message
225 let lastAssistantIndex = -1;
226 for (let i = historyItems.length - 1; i >= 0; i--) {
227 if (historyItems[i].message.role === "assistant") {
228 lastAssistantIndex = i;
229 break;
230 }
231 }
232 if (lastAssistantIndex < 0) return;
233 if (!historyItems[lastAssistantIndex].toolCallStates) return;
234
235 const toolState = historyItems[lastAssistantIndex].toolCallStates?.find(
236 (ts: ToolCallState) => ts.toolCallId === unifiedMessage.toolCallId,
237 );
238
239 if (toolState) {
240 toolState.output = [
241 {
242 content: unifiedMessage.content as string,
243 name: `Tool Result: ${toolCall.function.name}`,
244 description: "Tool execution result",
245 },
246 ];
247 }
248}
249
250/**
251 * Convert array of ChatCompletionMessageParam to ChatHistoryItem array
252 */
253export function convertToUnifiedHistory(
254 messages: ChatCompletionMessageParam[],
255): ChatHistoryItem[] {
256 const historyItems: ChatHistoryItem[] = [];
257 const pendingToolCalls: Map<string, ToolCall> = new Map();
258
259 for (const message of messages) {
260 const unifiedMessage = convertToUnifiedMessage(message);
261
262 if (unifiedMessage.role === "assistant" && unifiedMessage.toolCalls) {
263 // Store tool calls for matching with results
264 const toolCallStates: ToolCallState[] = unifiedMessage.toolCalls.map(
265 (tc: any) => {
266 const toolCall: ToolCall = {
267 id: tc.id || "",
268 type: "function",
269 function: {
270 name: tc.function?.name || "",
271 arguments: tc.function?.arguments || "",
272 },
273 };
274 pendingToolCalls.set(toolCall.id, toolCall);
275
276 return {
277 toolCallId: toolCall.id,
278 toolCall,
279 status: "done" as ToolStatus, // Historical calls are complete
280 parsedArgs: tryParseJson(toolCall.function.arguments),
281 };
282 },
283 );
284
285 historyItems.push(createHistoryItem(unifiedMessage, [], toolCallStates));
286 } else if (unifiedMessage.role === "tool") {
287 // Tool result - handle separately to reduce nesting
288 handleToolResult(unifiedMessage, pendingToolCalls, historyItems);
289 // Don't add tool messages as separate history items
290 } else {
291 historyItems.push(createHistoryItem(unifiedMessage));
292 }
293 }
294
295 return historyItems;
296}
297
298/**
299 * Convert ChatHistoryItem array to ChatCompletionMessageParam array
300 */
301export function convertFromUnifiedHistory(
302 historyItems: ChatHistoryItem[],
303): ChatCompletionMessageParam[] {
304 const messages: ChatCompletionMessageParam[] = [];
305
306 for (const item of historyItems) {
307 const baseMessage = convertFromUnifiedMessage(item.message);
308
309 // If this is a user message with context items, expand the content
310 if (
311 item.message.role === "user" &&
312 item.contextItems &&
313 item.contextItems.length > 0
314 ) {
315 const contextContent = item.contextItems
316 .map(
317 (contextItem: ContextItemWithId) =>
318 `<context name="${contextItem.name}">\n${contextItem.content}\n</context>\n\n`,
319 )
320 .join("");
321
322 baseMessage.content =
323 typeof baseMessage.content === "string"
324 ? contextContent + baseMessage.content
325 : baseMessage.content; // Keep array format if it's already an array
326 }
327
328 messages.push(baseMessage);
329
330 // Add tool result messages if there are completed tool calls
331 if (item.toolCallStates) {
332 for (const toolState of item.toolCallStates) {
333 if (toolState.output && toolState.output.length > 0) {
334 messages.push({
335 role: "tool",
336 content: toolState.output.map((o: any) => o.content).join("\n"),
337 tool_call_id: toolState.toolCallId,
338 });
339 }
340 }
341 }
342 }
343
344 return messages;
345}
346
347/**
348 * Convert ChatHistoryItem array to ChatCompletionMessageParam array with injected system message
349 * @param historyItems - The chat history items
350 * @param systemMessage - The system message to inject at the beginning
351 */
352export function convertFromUnifiedHistoryWithSystemMessage(
353 historyItems: ChatHistoryItem[],
354 systemMessage: string,
355): ChatCompletionMessageParam[] {
356 const messages: ChatCompletionMessageParam[] = [];
357
358 // Inject system message at the beginning
359 messages.push({
360 role: "system",
361 content: systemMessage,
362 });
363
364 // Convert the rest of the history
365 const convertedMessages = convertFromUnifiedHistory(historyItems);
366 messages.push(...convertedMessages);
367
368 return messages;
369}
370
371/**
372 * Extract tool call information from a ChatHistoryItem
373 */
374export function extractToolCallInfo(historyItem: ChatHistoryItem): {
375 hasToolCalls: boolean;
376 toolCalls?: ToolCall[];
377 toolStates?: ToolCallState[];
378} {
379 const hasToolCalls = !!(
380 historyItem.toolCallStates && historyItem.toolCallStates.length > 0
381 );
382
383 return {
384 hasToolCalls,
385 toolCalls: historyItem.toolCallStates?.map((ts: any) => ts.toolCall),
386 toolStates: historyItem.toolCallStates,
387 };
388}
389
390/**
391 * Helper to safely parse JSON
392 */
393function tryParseJson(str: string): any {
394 try {
395 return JSON.parse(str);
396 } catch {
397 return str;
398 }
399}