Elffuss BraidHub

kikocis/continue public

2ad2cb09cca6 · 1.9 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 // This prevents multiple tool calls for now, by ignoring new tool call ids
12 if (
13 toolCallDelta.id &&
14 currentState?.toolCallId &&
15 toolCallDelta.id !== currentState?.toolCallId
16 ) {
17 return currentState;
18 }
19
20 const currentCall = currentState?.toolCall;
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 // Case where model streams in full name each time e.g. readFile -> readFile -> readFile
39 // do nothing
40 } else {
41 // Case where model streams in name in parts e.g. "read" -> "File"
42 mergedName = currentName + nameDelta;
43 }
44
45 const mergedArgs = currentArgs + argsDelta;
46
47 const [_, parsedArgs] = incrementalParseJson(mergedArgs || "{}");
48
49 return {
50 status: "generating",
51 toolCall: {
52 id: callId,
53 type: callType,
54 function: {
55 name: mergedName,
56 arguments: mergedArgs,
57 },
58 },
59 toolCallId: callId,
60 parsedArgs,
61 };
62}