ReAct Agent
Interleaves chain-of-thought Reasoning with Action execution, enabling LLMs to dynamically plan, act, and observe in a loop.
errorThe Challenge
Standard LLM prompting produces static responses without the ability to gather new information or take actions mid-generation. The model cannot verify its own claims, access external data, or adapt its approach based on intermediate results.
check_circleThe Solution
Structure the agent into a Thought → Action → Observation loop. The LLM first reasons about what to do (Thought), then executes a tool or API call (Action), observes the result (Observation), and uses that to inform its next reasoning step. This continues until the task is complete.
Architecture Overview
Rendering diagram...
Implementation
interface Tool {
name: string;
description: string;
execute(input: string): Promise<string>;
}
interface AgentStep {
thought: string;
action: string;
actionInput: string;
observation: string;
}
const MAX_STEPS = 10;
async function reactLoop(
query: string,
tools: Tool[],
llm: (prompt: string) => Promise<string>
): Promise<string> {
const steps: AgentStep[] = [];
for (let i = 0; i < MAX_STEPS; i++) {
// Reason about what to do next
const prompt = buildPrompt(query, tools, steps);
const response = await llm(prompt);
// Parse thought and action from response
const { thought, action, actionInput, isFinal, finalAnswer } =
parseResponse(response);
if (isFinal) return finalAnswer;
// Execute the chosen tool
const tool = tools.find((t) => t.name === action);
if (!tool) throw new Error(`Unknown tool: ${action}`);
const observation = await tool.execute(actionInput);
steps.push({ thought, action, actionInput, observation });
}
return "Max steps reached without final answer.";
}
function buildPrompt(
query: string,
tools: Tool[],
steps: AgentStep[]
): string {
// Build prompt with tools, history, and instructions
return `Query: ${query}\nTools: ${tools.map(t => t.name).join(", ")}`;
}
function parseResponse(response: string) {
// Parse LLM output into structured action
return {
thought: "",
action: "",
actionInput: "",
isFinal: false,
finalAnswer: "",
};
}Real-World Analogy
“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.”