agent loop

The core execution cycle of an AI agent: observe → think → act → observe. Repeats until the agent decides the task is complete or a stop condition is met.

Syntax

ai-agents
while not done:
  observation -> LLM -> action -> execute -> new observation

Example

ai-agents
// ReAct agent loop:
async function agentLoop(task, tools, maxSteps = 10) {
  let messages = [{ role: "user", content: task }];
  
  for (let step = 0; step < maxSteps; step++) {
    const response = await llm.invoke(messages);
    
    if (response.tool_calls?.length) {
      const result = await executeTool(response.tool_calls[0]);
      messages.push({ role: "tool", content: result });
    } else {
      return response.content; // Final answer
    }
  }
}