Implementation:Run llama Llama index ReActAgent From Defaults
Overview
ReActAgent is the LlamaIndex implementation of the ReAct (Reasoning + Acting) agent paradigm. It extends BaseWorkflowAgent, which itself combines Pydantic's BaseModel for configuration with LlamaIndex's Workflow for execution orchestration. The agent is instantiated directly through its constructor (there is no separate from_defaults classmethod -- the constructor itself handles all defaults).
Principle:Run_llama_Llama_index_Agent_Configuration
Source File
llama-index-core/llama_index/core/agent/workflow/react_agent.py, Lines 37-326
Class Hierarchy
class ReActAgent(BaseWorkflowAgent):
"""React agent implementation."""
Where BaseWorkflowAgent is defined in llama-index-core/llama_index/core/agent/workflow/base_agent.py as:
class BaseWorkflowAgent(Workflow, BaseModel, PromptMixin, metaclass=BaseWorkflowAgentMeta):
"""Base class for all agents, combining config and logic."""
Constructor Parameters (from BaseWorkflowAgent)
| Parameter | Type | Default | Description |
|---|---|---|---|
| name | str |
"Agent" |
The name of the agent, used for identification in multi-agent workflows. |
| description | str |
"An agent that can perform a task" |
Description of the agent's purpose and responsibilities. |
| system_prompt | Optional[str] |
None |
System prompt prepended to the ReAct prompt template. Guides the agent's behavior and persona. |
| tools | Optional[List[Union[BaseTool, Callable]]] |
None |
Tools available to the agent. Plain callables are auto-wrapped as FunctionTool via a field validator.
|
| tool_retriever | Optional[ObjectRetriever] |
None |
Dynamic tool retriever. Can be provided instead of a static tool list. |
| can_handoff_to | Optional[List[str]] |
None |
Names of agents this agent can hand off to in multi-agent systems. |
| llm | Optional[LLM] |
Settings.llm |
The language model for reasoning and generation. Falls back to the global Settings.llm.
|
| initial_state | Optional[Dict[str, Any]] |
{} |
Initial state dictionary, accessible via await ctx.store.get('state').
|
| state_prompt | Optional[Union[str, BasePromptTemplate]] |
DEFAULT_STATE_PROMPT |
Prompt template used to inject state into the conversation. |
| output_cls | Optional[Type[BaseModel]] |
None |
Pydantic model for structured output generation after the agent completes. If set, structured_output_fn is ignored.
|
| structured_output_fn | Optional[Callable[[List[ChatMessage]], Dict]] |
None |
Custom function for structured output from chat history. Ignored if output_cls is set.
|
| streaming | bool |
True |
Whether to stream LLM output token-by-token to the event stream. |
| early_stopping_method | Literal["force", "generate"] |
"force" |
Behavior when max iterations is reached. "force" raises an error; "generate" makes a final LLM call.
|
| timeout | Optional[float] |
None |
Maximum execution time in seconds for the entire workflow. |
| verbose | bool |
False |
Whether to enable verbose logging output. |
ReAct-Specific Fields
In addition to the BaseWorkflowAgent parameters, ReActAgent adds three fields:
| Field | Type | Default | Description |
|---|---|---|---|
| reasoning_key | str |
"current_reasoning" |
Key for storing the reasoning step chain in the workflow context store. |
| output_parser | ReActOutputParser |
ReActOutputParser() |
Parser that extracts structured reasoning steps (Thought, Action, Answer) from the LLM's text output. |
| formatter | ReActChatFormatter |
default_formatter() |
Formats tool descriptions, chat history, and reasoning steps into the LLM prompt. Auto-merges with system_prompt.
|
Tool Validation
The tools field includes a Pydantic field validator that automatically converts plain callables to FunctionTool instances:
@field_validator("tools", mode="before")
def validate_tools(cls, v):
validated_tools = []
for tool in v:
if not isinstance(tool, BaseTool):
validated_tools.append(FunctionTool.from_defaults(tool))
else:
validated_tools.append(tool)
# Validates that no tool is named "handoff" (reserved name)
return validated_tools
This means you can pass plain Python functions directly to the tools parameter:
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
# The function is auto-wrapped as a FunctionTool
agent = ReActAgent(tools=[add], llm=llm)
Formatter Validation
A model validator ensures the system_prompt is properly merged with the ReAct formatter's context:
@model_validator(mode="after")
def validate_formatter(self) -> "ReActAgent":
if self.formatter.context and self.system_prompt and self.system_prompt not in self.formatter.context:
self.formatter.context = self.system_prompt + "\n\n" + self.formatter.context.strip()
elif not self.formatter.context and self.system_prompt:
self.formatter.context = self.system_prompt
return self
Usage Example
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.tools import FunctionTool, QueryEngineTool
from llama_index.core.llms import OpenAI
# Define tools
def multiply(a: int, b: int) -> int:
"""Multiply two numbers together."""
return a * b
multiply_tool = FunctionTool.from_defaults(fn=multiply)
query_tool = QueryEngineTool.from_defaults(
query_engine=index.as_query_engine(),
name="knowledge_base",
description="Search the company knowledge base for information.",
)
# Create the ReAct agent
agent = ReActAgent(
name="research_assistant",
description="An assistant that can search documents and perform calculations.",
system_prompt="You are a helpful research assistant. Always cite your sources.",
tools=[multiply_tool, query_tool],
llm=OpenAI(model="gpt-4"),
streaming=True,
early_stopping_method="generate",
timeout=120.0,
verbose=True,
)
Import Statement
from llama_index.core.agent.workflow import ReActAgent