Add Claude streamed tool parser

0cab91e0f8c0074d4bfdf33c3971b3dde1029412

Cohee <18619528+Cohee1207@users.noreply.github.com>

1 files changed, +39 -22Ignore whitespace
public/scripts/tool-calling.js+39 -22
@@ -256,41 +256,58 @@ export class ToolManager {
256256 * @returns {void}
257257 */
258258 static parseToolCalls(toolCalls, parsed) {
259259 if (!Array.isArray(parsed?.choices)) {
260- return;
260+ for (const choice of parsed.choices) {
261- }
261+ const choiceIndex = (typeof choice.index === 'number') ? choice.index : null;
262- for (const choice of parsed.choices) {
262+ const choiceDelta = choice.delta;
263- const choiceIndex = (typeof choice.index === 'number') ? choice.index : null;
264- const choiceDelta = choice.delta;
265263
266264 if (choiceIndex === null || !choiceDelta) {
267265 continue;
268266 }
269267
270268 const toolCallDeltas = choiceDelta?.tool_calls;
271269
272270 if (!Array.isArray(toolCallDeltas)) {
273271 continue;
274272 }
275273
276274 if (!Array.isArray(toolCalls[choiceIndex])) {
277275 toolCalls[choiceIndex] = [];
278276 }
279277
280278 for (const toolCallDelta of toolCallDeltas) {
281279 const toolCallIndex = (typeof toolCallDelta?.index === 'number') ? toolCallDelta.index : toolCallDeltas.indexOf(toolCallDelta);
282280
283281 if (isNaN(toolCallIndex) || toolCallIndex < 0) {
284282 continue;
283+ }
284+
285+ if (toolCalls[choiceIndex][toolCallIndex] === undefined) {
286+ toolCalls[choiceIndex][toolCallIndex] = {};
287+ }
288+
289+ const targetToolCall = toolCalls[choiceIndex][toolCallIndex];
290+
291+ ToolManager.#applyToolCallDelta(targetToolCall, toolCallDelta);
292+ }
293+ }
294+ }
295+ if (typeof parsed?.content_block === 'object') {
296+ const choiceIndex = 0;
297+
298+ if (parsed?.content_block?.type === 'tool_use') {
299+ if (!Array.isArray(toolCalls[choiceIndex])) {
300+ toolCalls[choiceIndex] = [];
285301 }
286302
303+ const toolCallIndex = toolCalls[choiceIndex].length;
304+
287305 if (toolCalls[choiceIndex][toolCallIndex] === undefined) {
288306 toolCalls[choiceIndex][toolCallIndex] = {};
289307 }
290308
291309 const targetToolCall = toolCalls[choiceIndex][toolCallIndex];
292-
310+ Object.assign(targetToolCall, parsed.content_block);
293- ToolManager.#applyToolCallDelta(targetToolCall, toolCallDelta);
294311 }
295312 }
296313 }