Elffuss BraidHub

kikocis/continue public

99fe51849b68 · 2.3 KiBRawPermalink
1import { ToolCallDelta, ToolCallState } from "core";
2import { incrementalParseJson } from "core/util/incrementalParseJson";
3
4// Merge streamed tool calls
5// See example of data coming in here:
6// https://platform.openai.com/docs/guides/function-calling?api-mode=chat#streaming
7export function addToolCallDeltaToState(
8 toolCallDelta: ToolCallDelta,
9 currentState: ToolCallState | undefined,
10): ToolCallState {
11 const currentCall = currentState?.toolCall;
12
13 // If we have a current state and the delta has a different ID, ignore the delta
14 if (
15 currentState &&
16 toolCallDelta.id &&
17 currentCall?.id !== toolCallDelta.id
18 ) {
19 return currentState;
20 }
21
22 // These will/should not be partially streamed
23 const callType = toolCallDelta.type ?? "function";
24 const callId = currentCall?.id || toolCallDelta.id || "";
25
26 // These may be streamed in chunks
27 const currentName = currentCall?.function.name ?? "";
28 const currentArgs = currentCall?.function.arguments ?? "";
29
30 const nameDelta = toolCallDelta.function?.name ?? "";
31 const argsDelta = toolCallDelta.function?.arguments ?? "";
32
33 let mergedName = currentName;
34 if (nameDelta.startsWith(currentName)) {
35 // Case where model progresssively streams name but full name each time e.g. "readFi" -> "readFil" -> "readFile"
36 mergedName = nameDelta;
37 } else if (!currentName.startsWith(nameDelta)) {
38 mergedName = currentName + nameDelta;
39 }
40
41 // Similar logic for args, with an extra JSON check
42 let mergedArgs = currentArgs;
43 try {
44 // If args is JSON parseable, it is complete, don't add to it
45 JSON.parse(currentArgs);
46 } catch (e) {
47 if (argsDelta.startsWith(currentArgs)) {
48 // Case where model progresssively streams args but full args each time e.g. "{"file": "file1"}" -> "{"file": "file1", "line": 1}"
49 mergedArgs = argsDelta;
50 } else if (!currentArgs.startsWith(argsDelta)) {
51 // Case where model streams in args in parts e.g. "{"file": "file1"" -> ", "line": 1}"
52 mergedArgs = currentArgs + argsDelta;
53 }
54 }
55
56 const [_, parsedArgs] = incrementalParseJson(mergedArgs || "{}");
57
58 return {
59 status: "generating",
60 toolCall: {
61 id: callId,
62 type: callType,
63 function: {
64 name: mergedName,
65 arguments: mergedArgs,
66 },
67 },
68 toolCallId: callId,
69 parsedArgs,
70 };
71}