44 lines
1.5 KiB
TypeScript
44 lines
1.5 KiB
TypeScript
import { ToolCallDelta, ToolCallState } from "core";
|
|
import { incrementalParseJson } from "core/util/incrementalParseJson";
|
|
|
|
// Merge streamed tool calls
|
|
// See example of data coming in here:
|
|
// https://platform.openai.com/docs/guides/function-calling?api-mode=chat#streaming
|
|
export function addToolCallDeltaToState(
|
|
toolCallDelta: ToolCallDelta,
|
|
currentState: ToolCallState | undefined,
|
|
): ToolCallState {
|
|
const currentCall = currentState?.toolCall;
|
|
|
|
// These will/should not be partially streamed
|
|
const callType = toolCallDelta.type ?? "function";
|
|
const callId = currentCall?.id || toolCallDelta.id || "";
|
|
|
|
// These may be streamed in chunks
|
|
const currentName = currentCall?.function.name ?? "";
|
|
const currentArgs = currentCall?.function.arguments ?? "";
|
|
|
|
const nameDelta = toolCallDelta.function?.name ?? "";
|
|
const argsDelta = toolCallDelta.function?.arguments ?? "";
|
|
|
|
// 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
|
|
const mergedName =
|
|
currentName === nameDelta ? currentName : currentName + nameDelta;
|
|
const mergedArgs = currentArgs + argsDelta;
|
|
|
|
const [_, parsedArgs] = incrementalParseJson(mergedArgs || "{}");
|
|
|
|
return {
|
|
status: "generating",
|
|
toolCall: {
|
|
id: callId,
|
|
type: callType,
|
|
function: {
|
|
name: mergedName,
|
|
arguments: mergedArgs,
|
|
},
|
|
},
|
|
toolCallId: callId,
|
|
parsedArgs,
|
|
};
|
|
}
|