| 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 | // These will/should not be partially streamed |
| 14 | const callType = toolCallDelta.type ?? "function"; |
| 15 | const callId = currentCall?.id || toolCallDelta.id || ""; |
| 16 | |
| 17 | // These may be streamed in chunks |
| 18 | const currentName = currentCall?.function.name ?? ""; |
| 19 | const currentArgs = currentCall?.function.arguments ?? ""; |
| 20 | |
| 21 | const nameDelta = toolCallDelta.function?.name ?? ""; |
| 22 | const argsDelta = toolCallDelta.function?.arguments ?? ""; |
| 23 | |
| 24 | const mergedName = |
| 25 | currentName === nameDelta ? currentName : currentName + nameDelta; // Some models may include the name repeatedly. This doesn't account for an edge case where the name is like "dothisdothis" and it happens to stream name in chunks "dothis" and "dothis" but that's a super edge case |
| 26 | const mergedArgs = currentArgs + argsDelta; |
| 27 | |
| 28 | const [_, parsedArgs] = incrementalParseJson(mergedArgs || "{}"); |
| 29 | |
| 30 | return { |
| 31 | status: "generating", |
| 32 | toolCall: { |
| 33 | id: callId, |
| 34 | type: callType, |
| 35 | function: { |
| 36 | name: mergedName, |
| 37 | arguments: mergedArgs, |
| 38 | }, |
| 39 | }, |
| 40 | toolCallId: callId, |
| 41 | parsedArgs, |
| 42 | }; |
| 43 | } |