(userText)
| 624 | } |
| 625 | |
| 626 | async function runAgentTurn(userText) { |
| 627 | const apiKey = apiKeyEl.value.trim(); |
| 628 | if (!apiKey) throw new Error("Missing API key"); |
| 629 | |
| 630 | const provider = PROVIDERS[getProviderValue()]; |
| 631 | const { chat } = provider.api; |
| 632 | const baseURL = provider.baseUrlDefault ? baseUrlEl.value.trim() : undefined; |
| 633 | let firstIterationMinuteBucket = null; |
| 634 | |
| 635 | messages.push({ role: "user", content: userText }); |
| 636 | |
| 637 | for (let i = 0; i < 64; i++) { |
| 638 | const compactedMinuteBucket = await compactHistoryWithLLM(chat, apiKey, baseURL, modelEl.value); |
| 639 | if (firstIterationMinuteBucket === null && compactedMinuteBucket !== null) { |
| 640 | firstIterationMinuteBucket = compactedMinuteBucket; |
| 641 | } |
| 642 | if (messages.length > MAX_HISTORY_MESSAGES * 2) trimHistory(); |
| 643 | |
| 644 | const messages_with_system = [{ role: "system", content: SYSTEM_INSTRUCTIONS }, ...messages]; |
| 645 | const { minuteBucket, response } = await chatWithMinuteDelay({ |
| 646 | chat, |
| 647 | apiKey, |
| 648 | baseURL, |
| 649 | model: modelEl.value, |
| 650 | messages: messages_with_system, |
| 651 | tools, |
| 652 | }); |
| 653 | if (firstIterationMinuteBucket === null) { |
| 654 | firstIterationMinuteBucket = minuteBucket; |
| 655 | } |
| 656 | |
| 657 | const message = response.choices?.[0]?.message; |
| 658 | if (!message) throw new Error("No message in response"); |
| 659 | |
| 660 | messages.push(message); |
| 661 | |
| 662 | if (message.content) addMessage("assistant", message.content); |
| 663 | |
| 664 | const calls = message.tool_calls ?? []; |
| 665 | if (calls.length === 0) { |
| 666 | console.log("Estimated token usage by minute", getEstimatedTokenMinuteLog(firstIterationMinuteBucket)); |
| 667 | return; |
| 668 | } |
| 669 | |
| 670 | for (const call of calls) { |
| 671 | let args = {}; |
| 672 | try { args = call.function.arguments ? JSON.parse(call.function.arguments) : {}; } |
| 673 | catch { args = {}; } |
| 674 | |
| 675 | addMessage("tool", `→ ${call.function.name}(${JSON.stringify(args)})`); |
| 676 | |
| 677 | const toolRes = await callWorker("toolCall", { name: call.function.name, args }); |
| 678 | |
| 679 | const fullResult = JSON.stringify(toolRes.result); |
| 680 | |
| 681 | messages.push({ |
| 682 | role: "tool", |
| 683 | tool_call_id: call.id, |
no test coverage detected