Agentic AIPHPverifiedVerified

ReAct Agent Pattern in PHP

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 PHP

1Step 1: Define the Tool interface and AgentStep value object

interface Tool
{
    public function getName(): string;
    public function getDescription(): string;
    public function execute(string $input): string;
}

class AgentStep
{
    public function __construct(
        public readonly string $thought,
        public readonly string $action,
        public readonly string $actionInput,
        public readonly string $observation,
    ) {}
}

2Step 2: Implement the ReAct reasoning loop

const MAX_STEPS = 10;

function reactLoop(string $query, array $tools, callable $llm): string
{
    /** @var AgentStep[] $steps */
    $steps = [];

    for ($i = 0; $i < MAX_STEPS; $i++) {
        // Reason about what to do next
        $prompt = buildPrompt($query, $tools, $steps);
        $response = $llm($prompt);

        // Parse thought and action from response
        $parsed = parseResponse($response);

        if ($parsed['isFinal']) {
            return $parsed['finalAnswer'];
        }

        // Execute the chosen tool
        $tool = findTool($tools, $parsed['action']);
        if ($tool === null) {
            throw new \RuntimeException("Unknown tool: {$parsed['action']}");
        }

        $observation = $tool->execute($parsed['actionInput']);

        $steps[] = new AgentStep(
            thought: $parsed['thought'],
            action: $parsed['action'],
            actionInput: $parsed['actionInput'],
            observation: $observation,
        );
    }

    return 'Max steps reached without final answer.';
}

3Step 3: Build the prompt and parse LLM responses

function buildPrompt(string $query, array $tools, array $steps): string
{
    $toolNames = array_map(fn(Tool $t) => $t->getName(), $tools);
    return "Query: {$query}\nTools: " . implode(', ', $toolNames);
}

function parseResponse(string $response): array
{
    return [
        'thought' => '', 'action' => '', 'actionInput' => '',
        'isFinal' => false, 'finalAnswer' => '',
    ];
}

function findTool(array $tools, string $name): ?Tool
{
    foreach ($tools as $tool) {
        if ($tool->getName() === $name) return $tool;
    }
    return null;
}

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.