The ReAct (Reasoning + Acting) Loop is a pattern that interleaves thinking and tool use in a cycle. The agent produces a Thought explaining its reasoning, takes an Action by calling a tool, receives an Observation with the result, and repeats until it has enough information to answer.
At a Glance
- Problem: Reasoning alone cannot answer questions that depend on external or current information, while acting without reasoning flails, repeating searches and failing to connect results the agent has already received.
- Forces: Adaptivity to each new observation versus predictable latency and cost; an interpretable reasoning trace versus the tokens it spends; enough iterations to finish hard tasks versus a cap that also cuts off a run making real progress.
- Solution: Run a loop in which the agent writes a Thought about what it knows and still needs, takes an Action through a tool call, reads the Observation, and repeats until its reasoning decides it can answer.
- Consequences: Gains: handles tasks whose path is unknown in advance and leaves a traceable chain of reasoning for debugging. Costs: variable iteration counts make latency and spend hard to plan, and agents can loop or wander without repetition detection.
What problem does the ReAct Loop solve?
A language model that only reasons about a problem is limited to what it already knows. It can think through a question step by step, but if the answer depends on external information, current data, or the result of some computation, thinking harder will not help. The model needs to go out and get that information.
A model that acts without reasoning tends to flail. It can call tools in an arbitrary order, repeat the same search with different phrasing, or fail to connect results it has already received. Without reasoning to steer them, the actions produce noise.
The model has to do both: reason about what it knows and what it still needs, take a targeted action, reason about what it learned, and take the next action. Either half on its own falls short, and the pattern works because it alternates them.
How does the ReAct Loop work?
The ReAct pattern turns this interleaving into a loop with three parts. The agent produces a Thought explaining what it knows so far and what it needs to do next. It then takes an Action, typically a tool call like a web search, database query, or API request. It receives an Observation, which is the result of that action. Then it loops back to produce another Thought incorporating the new information.
This cycle repeats until the agent decides it has enough information to produce a final answer. The decision to stop is itself a reasoning step. The agent's Thought might say something like "I now have the revenue figures for all three companies and can compare them."
Each action follows from explicit reasoning. Before the agent calls a tool, it states why it needs that piece of information, which leaves a chain of logic you can inspect when things go wrong.
In a typical ReAct trace, the user asks a question and the agent works out what information it needs. It searches, reads the result, and realizes it needs one more data point, so it searches again. Then it combines both results into an answer. Each step builds on the one before it.
The same loop handles question answering over documents, API calls, website browsing, data analysis, and many other tasks where the agent needs external information. That range is probably why it has become the most widely adopted agentic pattern in practice.
When should you use the ReAct Loop?
ReAct is a good default choice for any task that requires the model to gather information or interact with external systems before producing an answer.
Use it when:
- The answer depends on information the model does not have in its training data
- The task requires combining information from multiple sources
- You need an audit trail of the agent's reasoning and actions
- The number of steps needed is not predictable in advance
- The task is interactive, where the result of one action determines the next
Skip it when:
- The task can be answered purely from the model's existing knowledge
- The workflow is completely deterministic and can be hard-coded as a pipeline
- You need guaranteed completion within a fixed number of steps (the length of a ReAct loop varies from run to run)
- The task decomposes cleanly into a plan that should be created upfront
When not to use it: if the request needs exactly one tool call, use Tool Calling directly and skip the Thought-Action-Observation wrapper. If you cannot afford to pay for failed reasoning detours, for example when you pay per call on a metered tool API, a fixed Prompt Chaining flow caps the spend.
Implementation
# Using OpenAI SDK for illustration — swap client for any provider
import json
from openai import OpenAI
client = OpenAI()
tools = [{
"type": "function",
"function": {
"name": "search",
"description": "Search for information on a topic",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string", "description": "Search query"}},
"required": ["query"],
},
},
}]
def search(query: str) -> str:
"""Stub — replace with real search API."""
return f"Results for '{query}': The population of France is approximately 68 million."
TOOL_MAP = {"search": search}
def react_loop(question: str, max_iterations: int = 5) -> str:
"""ReAct loop: reason, act, observe, repeat."""
messages = [
{"role": "system", "content": "You are a helpful assistant. Think step by step. Use tools when you need external information."},
{"role": "user", "content": question},
]
for i in range(max_iterations):
response = client.chat.completions.create(
model="gpt-4o", messages=messages, tools=tools,
)
msg = response.choices[0].message
# No tool calls — agent is done reasoning
if not msg.tool_calls:
return msg.content
# Execute each tool call (Action) and collect results (Observation)
messages.append(msg)
for tc in msg.tool_calls:
fn = TOOL_MAP.get(tc.function.name)
result = fn(**json.loads(tc.function.arguments)) if fn else "Unknown tool"
messages.append({"role": "tool", "tool_call_id": tc.id, "content": result})
return "Reached max iterations without a final answer."
# Usage
print(react_loop("What is the population of France?"))
Worked Example: Cost and Latency
A research assistant answers 2,000 multi-source questions a day on the large model.
| Setup | Calls per request | Tokens per request (in / out) | Cost per 1,000 requests | Latency per request |
|---|---|---|---|---|
| Direct tool call, no reasoning loop | 2 | 2,850 / 350 | $13.80 | 6.8 s |
| ReAct, typical run of 4 iterations | 5 | 14,500 / 900 | $57.00 | 17.5 s |
| ReAct, run that hits a 10-iteration cap | 11 | 63,250 / 1,800 | $216.75 | 35.5 s |
Assumptions: a 1,000-token system prompt and question, 150 output tokens per Thought and Action, 800 tokens per Observation, and a 300-token final answer. Every call re-sends the whole transcript, so each iteration adds 950 tokens to the next call's input. The direct call skips the Thought and writes a 50-token tool call; tool execution time is excluded.
For the typical run, the five calls read 1,000 + 1,950 + 2,900 + 3,850 + 4,800 = 14,500 tokens, or $0.0435, and write 4 × 150 + 300 = 900 tokens, or $0.0135, so $57.00 per 1,000 requests. Latency is 4 × (0.5 + 150 / 60) + (0.5 + 300 / 60) = 17.5 s. The capped run reads 4.4 times as many input tokens as the typical one, for 2.5 times as many iterations.
Use the loop when questions really need several lookups; for single-lookup questions the direct call is 4 times cheaper and 2.6 times faster, and the cap should be set from what a 10-iteration run costs, not from how many steps feel safe.
What are the common pitfalls?
Loops that never terminate. The agent keeps searching, finding somewhat relevant information, deciding it is not quite enough, and searching again. A maximum iteration cap is the standard backstop and you should have one, typically somewhere between 5 and 15 cycles. The cap is blunt, though. It fires the same way whether the agent was making steady progress or calling the same tool with the same arguments for the fifth time, and it truncates the run rather than correcting it.
A better approach is to detect repetition and nudge the agent. Count consecutive calls to the same tool with identical arguments, and at escalating run lengths inject an advisory message telling the agent to re-read the last result and either change approach or conclude. Because it never blocks the call, a legitimately repeated retry is unaffected and the model keeps the final decision. DeepSeek's harness ships this as a plugin with reminders at 3, 5, and 8 consecutive repeats: a short generic nudge at the first threshold, then a detailed one naming the tool, the run length, and the arguments.
Getting the detection right matters more than the exact thresholds. Canonicalize arguments before comparing them, with a deep key sort and then serialization, so calls differing only in property order still count as identical. Let bookkeeping calls pass through the chain without resetting it, because if a scratchpad or todo update between two identical searches resets the counter, any small interleaved call launders the loop. Count denied calls too, since an agent hammering a call that keeps getting rejected is the most common loop there is. And key the counter per agent, so a subagent stuck in a loop does not trip a reminder for its parent.
Reasoning that ignores observations. Sometimes the agent's Thought ignores what the previous Observation returned. The agent goes through the motions of the loop without reasoning about what it learned, which usually shows up as repeated similar searches or relevant data left unused. A system prompt that tells the agent to reference previous observations can help.
Action selection that is too narrow. The agent gets fixated on a single tool or approach. It keeps searching the web with slightly different queries when the answer might be in a database it also has access to. Tool descriptions that say when to use each tool help the agent choose better.
Observation overload. A tool call might return a large amount of data, filling up the context window and pushing earlier reasoning out. The agent loses track of what it was doing and starts reasoning in circles. Truncating or summarizing long tool outputs before feeding them back to the agent keeps the context manageable.
Reasoning overhead on simple tasks. For straightforward questions that need a single tool call, the full Thought-Action-Observation cycle adds unnecessary latency and cost. If you know a task is simple, consider a direct tool call without the reasoning wrapper.
What are the trade-offs?
You gain the ability to handle tasks where the path to a solution is not known in advance, and a reasoning trace you can read. That trace helps with debugging and with building user trust.
You pay with unpredictable latency and cost. Because the number of iterations varies per query, you cannot easily predict how long a request will take or how much it will cost. This makes capacity planning harder than with fixed pipelines.
Token efficiency is moderate. The reasoning text consumes tokens that do not directly contribute to the final answer. Each Thought is the agent talking to itself, and those tokens are what you pay for interpretability. You can reduce this cost by using shorter reasoning prompts, but that risks reducing the quality of the agent's decisions.
The pattern scales linearly with task complexity. Harder tasks need more iterations, which means more time and money. This is usually the right behavior, but it means a poorly scoped question can trigger an expensive chain of actions. Input validation and query refinement before entering the loop help control this.
Compared to Plan and Execute, ReAct is more adaptive but less efficient. It handles surprises well because it reasons about each new observation in context. But it can wander when a more structured approach would reach the answer faster. For tasks with clear structure, check whether Plan and Execute fits better.
Goes Well With
Tool Calling is the mechanism that makes the Action step possible. Each action in a ReAct loop is typically a tool call. The better your tool definitions (clear names, good descriptions, well-typed parameters), the better the agent will select and use them during the loop.
Chain of Thought strengthens the Thought step. ReAct already includes reasoning, but asking for chain-of-thought style step-by-step thinking inside each Thought makes that reasoning more thorough. It helps most on complex tasks where the agent has to synthesize information from multiple observations.
Plan and Execute offers a complementary approach for tasks with clear structure. You can even combine them, using Plan and Execute at the top level and ReAct loops within each execution step. The plan sets the overall direction, and a ReAct loop works out the details of each step.
References
- Yao, S., et al. (2023). ReAct: Synergizing Reasoning and Acting in Language Models. ICLR 2023. arXiv
Further Reading
- DeepSeek Harness,
repeat-tool-reminder. A production implementation of the advisory loop-breaker described above. It counts runs of identical tool calls and injects escalating reminders without ever vetoing a call. GitHub - Yao et al., "ReAct: Synergizing Reasoning and Acting in Language Models" (2022). The paper that formalized the interleaving of reasoning traces and tool-use actions, showing that combining both outperforms either reasoning-only or acting-only approaches. arXiv:2210.03629