Skip to content

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

  1. Entry: User message starts the loop
  2. Decision: Check for tool calls after each LLM response
  3. Action: Execute requested tools
  4. Feedback: Send results back to LLM
  5. 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 →

Learn AI Agent development through real source code