Building autonomous agents with the ReAct reasoning loop
How the ReAct pattern combines reasoning, tool execution, finish conditions, and self-correction in a bounded multi-turn agent loop.
Single-turn function calling lets a host run one predetermined tool step, but real backend tasks rarely finish in one call. This post explains how the ReAct (Reasoning + Acting) pattern turns an LLM into a bounded, self-correcting agent loop, along with a Kotlin runner and the production bottlenecks I watch for.
Single-turn tool calling vs. a ReAct loop
The structural difference between single-turn function calling and a multi-turn agent comes down to who decides the next step.
1
2
3
4
5
6
7
[Single-turn Function Calling]
User prompt -> 1 tool call -> Tool output -> Final answer
(Fixed flow; can't inspect intermediate data and branch to a new tool)
[Agentic ReAct Loop]
User prompt -> [Thought -> Action -> Observation] x N -> Finish condition -> Final answer
(The model inspects each Observation and dynamically chooses the next Action)
Consider a request like: "Find VIP customers showing churn signals last month, check our payment logs for their recent failures, and alert their account manager on Slack."
No single API handles that end to end:
- Query the CRM API for VIP customers.
- Filter the returned records for churn signals.
- Extract those customer IDs and query the payment log service.
- Draft a summary from the logs and post it to the Slack webhook API.
Each step’s output becomes the next step’s input. If a query returns empty results or throws a 400, the workflow has to adapt instead of crashing. Proposed by Yao et al. (2022), the ReAct pattern interleaves internal reasoning with external actions so the model can steer through these branches on its own.
Inside the Thought, Action, and Observation cycle
ReAct works best when you think of it as a state machine rather than a prompt trick.
flowchart TD
START["User goal input"] --> THOUGHT["1. Thought\nAssess state and plan next step"]
THOUGHT --> DECISION{"Goal met?"}
DECISION -->|"More work needed"| ACTION["2. Action\nSelect tool and arguments"]
ACTION --> OBSERVE["3. Observation\nCapture host tool output"]
OBSERVE --> THOUGHT
DECISION -->|"Done"| FINISH["Final Answer"]
FINISH --> DONE["Return result and exit loop"]
Each phase serves a distinct role:
- Thought (internal reasoning): Before invoking anything, the model summarizes what it knows so far and states what it needs next. Writing out the rationale acts as a brake against premature or irrelevant tool calls and reduces hallucination.
- Action (tool invocation): Based on the thought, the model picks a concrete tool and generates structured arguments—for example,
lookup_user_logs(userId="VIP-8901", days=30). - Observation (environment feedback): The host runs the tool and feeds the raw output—or error message—back into the context window. That observation becomes ground truth for the next
Thought.
Implementing a bounded ReAct runner in Kotlin
Never let an agent loop run unbounded. I wrap the ReAct cycle in a runner that enforces a hard maxIterations ceiling and catches tool exceptions so the model can inspect failures rather than crashing the request thread.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// src/main/kotlin/com/example/ai/agent/ReActAgentRunner.kt
package com.example.ai.agent
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
data class AgentExecutionResult(
val finalAnswer: String,
val totalIterations: Int,
val history: List<AgentStep>
)
data class AgentStep(
val iteration: Int,
val thought: String?,
val actionName: String?,
val actionArguments: String?,
val observation: String?
)
@Component
class ReActAgentRunner(
private val llmClient: AgentLlmClient,
private val toolDispatcher: AgentToolDispatcher
) {
private val log = LoggerFactory.getLogger(javaClass)
private val maxIterations = 8
fun run(userGoal: String): AgentExecutionResult {
val history = mutableListOf<AgentStep>()
var currentContext = "User Goal: $userGoal\n"
for (iteration in 1..maxIterations) {
log.info("Starting ReAct step {}/{}", iteration, maxIterations)
// 1. Ask the LLM for the next Thought and Action
val stepDecision = llmClient.decideNextStep(currentContext)
// 2. Check finish condition (Finish action or Final Answer)
if (stepDecision.isFinished) {
log.info("Finish condition met at step {}", iteration)
history.add(AgentStep(iteration, stepDecision.thought, null, null, null))
return AgentExecutionResult(
finalAnswer = stepDecision.finalAnswer ?: "Request completed.",
totalIterations = iteration,
history = history
)
}
// 3. Execute the Action and capture the Observation
val toolName = stepDecision.toolName ?: throw IllegalStateException("Missing tool name")
val arguments = stepDecision.arguments ?: "{}"
val observation = try {
toolDispatcher.execute(toolName, arguments)
} catch (ex: Exception) {
log.warn("Tool execution failed: tool={}, error={}", toolName, ex.message)
"Error: Tool execution failed with message: ${ex.message}"
}
// 4. Record the step and append it to the running context
val stepRecord = AgentStep(
iteration = iteration,
thought = stepDecision.thought,
actionName = toolName,
actionArguments = arguments,
observation = observation
)
history.add(stepRecord)
currentContext += """
Thought: ${stepDecision.thought}
Action: $toolName($arguments)
Observation: $observation
""".trimIndent() + "\n"
}
// Safe fallback when the iteration budget is exhausted
log.error("Force-stopping ReAct loop after reaching maxIterations ({})", maxIterations)
return AgentExecutionResult(
finalAnswer = "Could not complete the task within the iteration limit. Returning partial findings.",
totalIterations = maxIterations,
history = history
)
}
}
Controlling finish conditions and preventing runaway loops
Deciding when to stop is just as important as deciding which tool to call. Most production runners rely on one of two exit mechanisms:
- Dedicated finish tool: Register a virtual tool such as
finish(final_response="...")alongside your real tools. Once the model has enough evidence, it callsfinishand the runner exits cleanly. - Prefix or no-tool-call detection: With native function calling APIs, the runner exits when
finish_reasonis"stop"(notool_callsemitted). With text-based ReAct prompts, the parser watches for aFinal Answer:prefix.
Models occasionally get stuck calling the same tool with identical arguments when a downstream service keeps returning empty results. Always pair
maxIterationswith cycle detection in your runner: if the model repeats the exact(toolName, arguments)pair twice in a row, inject a warning observation or abort the loop.
Self-correction when tool calls fail
The biggest advantage of ReAct over hardcoded orchestration scripts is recovery from predictable tool errors. In a static batch job, a 404 Not Found or 400 Bad Request kills the pipeline. In a ReAct loop, the error message becomes the Observation, giving the model a chance to fix its own input on the next turn.
flowchart TD
subgraph Attempt1 ["Iteration 1 (Failed)"]
T1["Thought: Fetch recent invoices for user 1024"]
A1["Action: fetch_billings(userId='1024')"]
O1["Observation: Error 404 (Prefix 'USR-' required)"]
T1 --> A1 --> O1
end
subgraph Attempt2 ["Iteration 2 (Self-corrected)"]
T2["Thought: Missing 'USR-' prefix.\nRetry with 'USR-1024'."]
A2["Action: fetch_billings(userId='USR-1024')"]
O2["Observation: 200 OK (Invoice list returned)"]
T2 --> A2 --> O2
end
O1 -->|"Feed error back"| T2
O2 --> FIN["Final Answer: Summarize billing history"]
Here’s what a real self-correction trace looks like when a contact search returns nothing and the agent switches tools:
1
2
3
4
5
6
7
8
9
10
11
12
13
[Step 1]
Thought: Look up customer 'Alex Park' in the address book to get a phone number.
Action: search_contacts(name="Alex Park")
Observation: [] (0 results found)
[Step 2]
Thought: The external contact directory returned nothing. Alex Park might be an internal employee—try search_employee instead.
Action: search_employee(query="Alex Park")
Observation: [{"empId": "EMP-9921", "dept": "Platform Engineering", "phone": "555-014-5678"}]
[Step 3]
Thought: Found EMP-9921 in Platform Engineering. I have everything needed to answer.
Final Answer: Alex Park (Platform Engineering) can be reached at 555-014-5678.
Don’t swallow exception details into generic "Operation failed" strings. Returning specific, actionable error messages (like missing ID prefixes or valid enum values) dramatically improves self-correction rates.
Production bottlenecks, trade-offs, and checklist
Before putting a ReAct loop in front of real users, you have to account for two scaling costs—and know when a simpler design is better.
Context bloat and cumulative latency
- Context bloat: Every iteration appends another
Thought,Action, andObservationto the prompt. If a single database tool dumps a 40 KB JSON array, input tokens explode by step 4. Apply field projection in the host dispatcher so only relevant fields enter the context, and summarize older observations when loops exceed 4–5 steps. - Cumulative latency: Each step adds a full LLM round-trip plus tool execution time, easily pushing total wall-clock time past 10–20 seconds. Combine independent lookups with parallel tool calling and stream intermediate
Thought/Actionstatus events to the UI over SSE so users know the request isn’t hung.
When not to use a ReAct loop
| Workflow shape | Better choice | Reason |
|---|---|---|
| Fixed 3-step ETL or approval pipeline | Standard code / workflow engine | Deterministic steps don’t benefit from probabilistic routing |
| Single lookup with clear intent | Single-turn function calling | Lower latency, lower token cost, simpler debugging |
| High-stakes state mutation (refunds, deletes) | ReAct + Human-in-the-Loop approval | Autonomous loops shouldn’t execute destructive writes unchecked |
| Open-ended diagnostics across multiple APIs | Bounded ReAct loop | Excels when the next query depends on what the last one returned |
Production checklist
- Set both
maxIterations(usually 5–10) and a wall-clock timeout per run. - Add duplicate
(toolName, arguments)cycle detection in the host runner. - Return descriptive validation errors in
Observationso the model can self-correct without guessing. - Filter and truncate large tool responses before appending them to conversation history.
- Log every
AgentStepwith token counts and latency so you can debug looping or expensive prompts after deployment.