How to Intermediate · 3 min read

How to use ReActAgent in LlamaIndex

Quick answer
Use ReActAgent in LlamaIndex by importing it from llama_index.agents.react and initializing it with a language model and a LLMRetriever. This agent combines reasoning and acting capabilities, allowing you to query your indexed documents interactively with reasoning steps.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install llama-index openai>=1.0

Setup

Install the required packages and set your OpenAI API key as an environment variable.

bash
pip install llama-index openai>=1.0

Step by step

This example shows how to create a simple ReActAgent with LlamaIndex using the OpenAI gpt-4o model and a retriever from an index.

python
import os
from llama_index import GPTVectorStoreIndex, SimpleDirectoryReader, LLMRetriever
from llama_index.agents.react import ReActAgent
from openai import OpenAI

# Set up OpenAI client
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

# Load documents from a directory
documents = SimpleDirectoryReader("./data").load_data()

# Create a vector store index
index = GPTVectorStoreIndex.from_documents(documents, client=client, model="gpt-4o")

# Create a retriever from the index
retriever = LLMRetriever(index=index, client=client, model="gpt-4o")

# Initialize the ReActAgent with the retriever and language model
agent = ReActAgent(
    retriever=retriever,
    llm=client,
    model="gpt-4o"
)

# Run a query with reasoning and actions
query = "Explain the main topics covered in the documents and provide references."
response = agent.query(query)
print(response)
output
Explain the main topics covered in the documents and provide references.

[Agent's detailed reasoning and references based on indexed documents]

Common variations

  • Use gpt-4o-mini or other OpenAI models for faster or cheaper responses.
  • Use async calls if integrating into async frameworks.
  • Customize the ReActAgent with different prompt templates or memory modules.
python
import asyncio

async def async_query():
    response = await agent.aquery("Summarize the documents asynchronously.")
    print(response)

asyncio.run(async_query())
output
[Agent's asynchronous response summarizing documents]

Troubleshooting

  • If you get authentication errors, verify your OPENAI_API_KEY environment variable is set correctly.
  • If the agent returns irrelevant answers, ensure your documents are properly loaded and indexed.
  • Check your model name matches current supported models like gpt-4o.

Key Takeaways

  • Use ReActAgent with a retriever and OpenAI client for reasoning over indexed documents.
  • Initialize ReActAgent with current models like gpt-4o for best results.
  • Customize the agent with async calls or different prompt templates for flexibility.
Verified 2026-04 · gpt-4o
Verify ↗