How the agent loop works

Think, Act, Observe, Answer

Every AI agent runs a simple loop called ReAct (Reason + Act): it reads your prompt, decides whether it needs a tool, runs that tool, observes the returned value, and either loops again or writes the final answer.

Understanding this loop makes every other PraisonAI feature click — guardrails check the answer, hooks watch each step, and ExecutionConfig(max_steps=…) caps how many turns the loop may take.

Example

from praisonai import Agent, tool

@tool
def stock_count(item: str) -> int:
    """Return remaining warehouse units for an item."""
    return {'keyboard': 14, 'mouse': 3}.get(item.lower(), 0)

agent = Agent(
    instructions='Always check stock_count before answering inventory questions.',
    tools=[stock_count],
)
print(agent.start('How many mice are left in stock?'))

Try it Yourself

Example explained

  • @tool — Exposes stock_count so the model can choose it during the Act step.
  • agent.start(…) — Runs the Think -> Act (stock_count) -> Observe (3) -> Final Answer loop automatically.

Why bounding the loop matters in production

Every iteration of Think -> Act -> Observe consumes tokens and wall-clock time. Once you understand the loop, always pair tool-using agents with ExecutionConfig(max_iter=…, max_budget=…) so a flaky tool cannot spin forever.

Common pitfall: omitting clear docstrings on tools forces the loop to guess argument formats and burn extra retry iterations.

Reference: documentation