| 727 | 727 | |
| 728 | 728 | if (toolCalling && Array.isArray(chatPrompt.invocations)) { |
| 729 | 729 | /** @type {import('./tool-calling.js').ToolInvocation[]} */ |
| 730 | 730 | const invocations = chatPrompt.invocations.slice().reverse(); |
| 731 | 731 | const toolCallMessage = new Message('assistant', undefined, 'toolCall-' + chatMessage.identifier); |
| 732 | 732 | toolCallMessage.setToolCalls(invocations); |
| 733 | 733 | if (chatCompletion.canAfford(toolCallMessage)) { |
| 734 | | - for (const invocation of invocations) { |
| 734 | + chatCompletion.reserveBudget(toolCallMessage); |
| 735 | + for (const invocation of invocations.slice().reverse()) { |
| 735 | 736 | const toolResultMessage = new Message('tool', invocation.result, invocation.id); |
| 736 | 737 | const canAfford = chatCompletion.canAfford(toolResultMessage) && chatCompletion.canAfford(toolCallMessage); |
| 737 | 738 | if (!canAfford) { |
| 738 | 739 | break; |
| 739 | 740 | } |
| 740 | 741 | chatCompletion.insertAtStart(toolResultMessage, 'chatHistory'); |
| 741 | 742 | } |
| 743 | + chatCompletion.freeBudget(toolCallMessage); |
| 742 | 744 | chatCompletion.insertAtStart(toolCallMessage, 'chatHistory'); |
| 743 | 745 | } |
| 744 | 746 | } |