Lesson 2. The ReAct Cycle

ReAct (Reasoning + Acting) is the main operating mode of the agent: reasoning → action → observation → reasoning again. The entire history of steps – the trajectory – is added to the context, so the agent “remembers” what it has already done.

   ┌─────────────────────────┐
   │1. CONTEXT              │◀
   │system + entire history ││
   └────────────┬────────────┘│
                │             │
                ▼             │
   ┌─────────────────────────┐│
   │2. LLM decides            ││
   │thought or JSON call?    ││
   └─────┬──────────────┬────┘│
    call│              │ final text
         ▼              ▼     │
┌─────────────────┐┌─────────┐│
│ 3. TOOL           ││4. DONE││
│  (action)         ││ answer││
└────────┬────────┘└─────────┘│
         │ observation         │
         └────────────────────┐

What to read

  • [ReAct Cycle] – the “reasoning – action – observation” loop
  • [Agent Cycle in Code] – how the cycle looks in a program
  • [Tool Calls] – what happens during the “action” moment

In code

The skeleton of the cycle – everything that will be in our CLI agent:

python
messages = [system_prompt, user_task]
for step in range(MAX_STEPS):          # Harness fencing: step limit
    reply = chat(messages)             # 1. reasoning (or call)
    call = parse_tool(reply)           #    Did the LLM respond with a JSON call?
    if not call:
        print(reply)                   # 4. final answer – exit
        break
    obs = run_tool(call)               # 2. action
    messages += [                      # 3. observation – into the context
        {"role": "assistant", "content": reply},
        {"role": "user", "content": f"Observation: {obs}"},
    ]
js
for (let step = 0; step < MAX_STEPS; step++) {
  const reply = await chat(messages);       // 1. reasoning
  const call = parseTool(reply);            //    JSON call?
  if (!call) { console.log(reply); break; } // 4. final answer
  const obs = runTool(call);                // 2. action
  messages.push({ role: "assistant", content: reply },   // 3.
                { role: "user", content: "Observation: " + obs });
}

Key detail: the tool’s result is returned to the context as an “observation” – this is the agent’s eyes from lesson 1.

Practice

For your agent from lesson 1, write pseudocode for the cycle: what repeats, where the stop is, what goes into the trajectory. Mentally run through one task – what actions will it choose step by step.

Related: [Lesson 1. Agent Formula], [Lesson 3. Harness and Fencing]