Loop Structure
Translation in Progress
This page is being translated. Content below is a placeholder.
Core Logic
The Agent loop is the heart of any Agent:
typescript
async function agentLoop(userMessage: string): Promise<string> {
const chat = model.startChat()
let response = await chat.sendMessage(userMessage)
while (true) {
const functionCalls = response.response.functionCalls()
// No tool calls = task complete
if (!functionCalls?.length) {
return response.response.text()
}
// Execute tools
const results = []
for (const call of functionCalls) {
const result = await executeTool(call)
results.push({
functionResponse: { name: call.name, response: result }
})
}
// Continue conversation with results
response = await chat.sendMessage(results)
}
}Flowchart
Key Points
- Entry: User message starts the loop
- Decision: Check for tool calls after each LLM response
- Action: Execute requested tools
- Feedback: Send results back to LLM
- Exit: No tool calls means task complete
Summary
- Agent loop = send message → check tools → execute → repeat
- Loop exits when LLM has no more tool calls
- Keep track of turn count to prevent infinite loops
Next
Learn about state management: State & Context →