Agentic AIPythonverifiedVerified

ReAct Agent Pattern in Python

Interleaves chain-of-thought Reasoning with Action execution, enabling LLMs to dynamically plan, act, and observe in a loop.

How to Implement the ReAct Agent Pattern in Python

1Step 1: Define the Tool and AgentStep data structures

from dataclasses import dataclass, field
from typing import Callable, Awaitable


@dataclass
class Tool:
    name: str
    description: str
    execute: Callable[[str], Awaitable[str]]


@dataclass
class AgentStep:
    thought: str
    action: str
    action_input: str
    observation: str

2Step 2: Implement the ReAct reasoning loop

MAX_STEPS = 10


async def react_loop(
    query: str,
    tools: list[Tool],
    llm: Callable[[str], Awaitable[str]],
) -> str:
    steps: list[AgentStep] = []

    for _ in range(MAX_STEPS):
        prompt = build_prompt(query, tools, steps)
        response = await llm(prompt)

        thought, action, action_input, is_final, final_answer = parse_response(response)

        if is_final:
            return final_answer

        tool = next((t for t in tools if t.name == action), None)
        if tool is None:
            raise ValueError(f"Unknown tool: {action}")

        observation = await tool.execute(action_input)
        steps.append(AgentStep(thought, action, action_input, observation))

    return "Max steps reached without final answer."

3Step 3: Build the prompt and parse LLM responses

def build_prompt(query: str, tools: list[Tool], steps: list[AgentStep]) -> str:
    tool_names = ", ".join(t.name for t in tools)
    return f"Query: {query}\nTools: {tool_names}"


def parse_response(response: str) -> tuple[str, str, str, bool, str]:
    return ("", "", "", False, "")

ReAct Agent Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

ReAct Agent Pattern in the Real World

Like a detective investigating a case: they form a hypothesis (Thought), gather evidence by interviewing witnesses or examining clues (Action), analyze what they found (Observation), and then refine their theory. They keep investigating until they solve the case.