| 304 | } | 306 | } |
| 305 | if (typeof parsed?.content_block === 'object') { | 307 | if (typeof parsed?.content_block === 'object') { |
| 306 | const choiceIndex = 0; | 308 | const choiceIndex = 0; |
| | 309 | const toolCallIndex = parsed?.index ?? 0; |
| 307 | | 310 | |
| 308 | if (parsed?.content_block?.type === 'tool_use') { | 311 | if (parsed?.content_block?.type === 'tool_use') { |
| 309 | if (!Array.isArray(toolCalls[choiceIndex])) { | 312 | if (!Array.isArray(toolCalls[choiceIndex])) { |
| 310 | toolCalls[choiceIndex] = []; | 313 | toolCalls[choiceIndex] = []; |
| 311 | } | 314 | } |
| 312 | | | |
| 313 | const toolCallIndex = toolCalls[choiceIndex].length; | | |
| 314 | | | |
| 315 | if (toolCalls[choiceIndex][toolCallIndex] === undefined) { | 315 | if (toolCalls[choiceIndex][toolCallIndex] === undefined) { |
| 316 | toolCalls[choiceIndex][toolCallIndex] = {}; | 316 | toolCalls[choiceIndex][toolCallIndex] = {}; |
| 317 | } | 317 | } |
| 318 | | | |
| 319 | const targetToolCall = toolCalls[choiceIndex][toolCallIndex]; | 318 | const targetToolCall = toolCalls[choiceIndex][toolCallIndex]; |
| 320 | Object.assign(targetToolCall, parsed.content_block); | 319 | ToolManager.#applyToolCallDelta(targetToolCall, parsed.content_block); |
| | 320 | } |
| | 321 | } |
| | 322 | if (typeof parsed?.delta === 'object') { |
| | 323 | const choiceIndex = 0; |
| | 324 | const toolCallIndex = parsed?.index ?? 0; |
| | 325 | const targetToolCall = toolCalls[choiceIndex]?.[toolCallIndex]; |
| | 326 | if (targetToolCall){ |
| | 327 | if (parsed?.delta?.type === 'input_json_delta') { |
| | 328 | const jsonDelta = parsed?.delta?.partial_json; |
| | 329 | if (!targetToolCall[this.#INPUT_DELTA_KEY]) { |
| | 330 | targetToolCall[this.#INPUT_DELTA_KEY] = ''; |
| | 331 | } |
| | 332 | targetToolCall[this.#INPUT_DELTA_KEY] += jsonDelta; |
| | 333 | } |
| | 334 | } |
| | 335 | } |
| | 336 | if (parsed?.type === 'content_block_stop') { |
| | 337 | const choiceIndex = 0; |
| | 338 | const toolCallIndex = parsed?.index ?? 0; |
| | 339 | const targetToolCall = toolCalls[choiceIndex]?.[toolCallIndex]; |
| | 340 | if (targetToolCall) { |
| | 341 | const jsonDeltaString = targetToolCall[this.#INPUT_DELTA_KEY]; |
| | 342 | if (jsonDeltaString) { |
| | 343 | try { |
| | 344 | const jsonDelta = { input: JSON.parse(jsonDeltaString) }; |
| | 345 | delete targetToolCall[this.#INPUT_DELTA_KEY]; |
| | 346 | ToolManager.#applyToolCallDelta(targetToolCall, jsonDelta); |
| | 347 | } catch (error) { |
| | 348 | console.warn('Failed to apply input JSON delta:', error); |
| | 349 | } |
| | 350 | } |
| 321 | } | 351 | } |
| 322 | } | 352 | } |
| 323 | } | 353 | } |