| 1 | import { ToolCallDelta, ToolCallState } from "core"; |
| 2 | import { 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 |
| 7 | export 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 | // Model streams in args in parts e.g. "{"file": "file1"" -> ", "line": 1}" |
| 48 | mergedArgs = currentArgs + argsDelta; |
| 49 | |
| 50 | // Note, removed case where model progresssively streams args but full args each time e.g. "{"file": "file1"}" -> "{"file": "file1", "line": 1}" |
| 51 | // Because no apis do this and difficult to detect reliably |
| 52 | } |
| 53 | |
| 54 | const [_, parsedArgs] = incrementalParseJson(mergedArgs || "{}"); |
| 55 | |
| 56 | return { |
| 57 | status: "generating", |
| 58 | toolCall: { |
| 59 | id: callId, |
| 60 | type: callType, |
| 61 | function: { |
| 62 | name: mergedName, |
| 63 | arguments: mergedArgs, |
| 64 | }, |
| 65 | }, |
| 66 | toolCallId: callId, |
| 67 | parsedArgs, |
| 68 | }; |
| 69 | } |