Elffuss BraidHub

kikocis/continue public

b0e1430b706d · 10.4 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 const lastAssistantIndex = historyItems.findLastIndex(
226 (item) => item.message.role === "assistant",
227 );
228
229 if (lastAssistantIndex < 0) return;
230 if (!historyItems[lastAssistantIndex].toolCallStates) return;
231
232 const toolState = historyItems[lastAssistantIndex].toolCallStates?.find(
233 (ts: ToolCallState) => ts.toolCallId === unifiedMessage.toolCallId,
234 );
235
236 if (toolState) {
237 toolState.output = [
238 {
239 content: unifiedMessage.content as string,
240 name: `Tool Result: ${toolCall.function.name}`,
241 description: "Tool execution result",
242 },
243 ];
244 }
245}
246
247/**
248 * Convert array of ChatCompletionMessageParam to ChatHistoryItem array
249 */
250export function convertToUnifiedHistory(
251 messages: ChatCompletionMessageParam[],
252): ChatHistoryItem[] {
253 const historyItems: ChatHistoryItem[] = [];
254 const pendingToolCalls: Map<string, ToolCall> = new Map();
255
256 for (const message of messages) {
257 const unifiedMessage = convertToUnifiedMessage(message);
258
259 if (unifiedMessage.role === "assistant" && unifiedMessage.toolCalls) {
260 // Store tool calls for matching with results
261 const toolCallStates: ToolCallState[] = unifiedMessage.toolCalls.map(
262 (tc: any) => {
263 const toolCall: ToolCall = {
264 id: tc.id || "",
265 type: "function",
266 function: {
267 name: tc.function?.name || "",
268 arguments: tc.function?.arguments || "",
269 },
270 };
271 pendingToolCalls.set(toolCall.id, toolCall);
272
273 return {
274 toolCallId: toolCall.id,
275 toolCall,
276 status: "done" as ToolStatus, // Historical calls are complete
277 parsedArgs: tryParseJson(toolCall.function.arguments),
278 };
279 },
280 );
281
282 historyItems.push(createHistoryItem(unifiedMessage, [], toolCallStates));
283 } else if (unifiedMessage.role === "tool") {
284 // Tool result - handle separately to reduce nesting
285 handleToolResult(unifiedMessage, pendingToolCalls, historyItems);
286 // Don't add tool messages as separate history items
287 } else {
288 historyItems.push(createHistoryItem(unifiedMessage));
289 }
290 }
291
292 return historyItems;
293}
294
295/**
296 * Convert ChatHistoryItem array to ChatCompletionMessageParam array
297 */
298export function convertFromUnifiedHistory(
299 historyItems: ChatHistoryItem[],
300): ChatCompletionMessageParam[] {
301 const messages: ChatCompletionMessageParam[] = [];
302
303 for (const item of historyItems) {
304 const baseMessage = convertFromUnifiedMessage(item.message);
305
306 // If this is a user message with context items, expand the content
307 if (
308 item.message.role === "user" &&
309 item.contextItems &&
310 item.contextItems.length > 0
311 ) {
312 const contextContent = item.contextItems
313 .map(
314 (contextItem: ContextItemWithId) =>
315 `<context name="${contextItem.name}">\n${contextItem.content}\n</context>\n\n`,
316 )
317 .join("");
318
319 baseMessage.content =
320 typeof baseMessage.content === "string"
321 ? contextContent + baseMessage.content
322 : baseMessage.content; // Keep array format if it's already an array
323 }
324
325 messages.push(baseMessage);
326
327 // Add tool result messages if there are completed tool calls
328 if (item.toolCallStates) {
329 for (const toolState of item.toolCallStates) {
330 if (toolState.output && toolState.output.length > 0) {
331 messages.push({
332 role: "tool",
333 content: toolState.output.map((o: any) => o.content).join("\n"),
334 tool_call_id: toolState.toolCallId,
335 });
336 }
337 }
338 }
339 }
340
341 return messages;
342}
343
344/**
345 * Convert ChatHistoryItem array to ChatCompletionMessageParam array with injected system message
346 * @param historyItems - The chat history items
347 * @param systemMessage - The system message to inject at the beginning
348 */
349export function convertFromUnifiedHistoryWithSystemMessage(
350 historyItems: ChatHistoryItem[],
351 systemMessage: string,
352): ChatCompletionMessageParam[] {
353 const messages: ChatCompletionMessageParam[] = [];
354
355 // Inject system message at the beginning
356 messages.push({
357 role: "system",
358 content: systemMessage,
359 });
360
361 // Convert the rest of the history
362 const convertedMessages = convertFromUnifiedHistory(historyItems);
363 messages.push(...convertedMessages);
364
365 return messages;
366}
367
368/**
369 * Extract tool call information from a ChatHistoryItem
370 */
371export function extractToolCallInfo(historyItem: ChatHistoryItem): {
372 hasToolCalls: boolean;
373 toolCalls?: ToolCall[];
374 toolStates?: ToolCallState[];
375} {
376 const hasToolCalls = !!(
377 historyItem.toolCallStates && historyItem.toolCallStates.length > 0
378 );
379
380 return {
381 hasToolCalls,
382 toolCalls: historyItem.toolCallStates?.map((ts: any) => ts.toolCall),
383 toolStates: historyItem.toolCallStates,
384 };
385}
386
387/**
388 * Helper to safely parse JSON
389 */
390function tryParseJson(str: string): any {
391 try {
392 return JSON.parse(str);
393 } catch {
394 return str;
395 }
396}