This project implements the ReAct (Reasoning and Acting) framework for Large Language Models (LLMs), based on the research paper "ReAct: Synergizing Reasoning and Acting in Language Models" by Shunyu Yao et al.
ReAct is a novel paradigm that synergizes reasoning and acting in language models. The framework combines:
- Reasoning: The model's ability to generate thoughts and explanations
- Acting: The model's capability to take actions based on those thoughts
The process follows this pattern:
- Thought: The model reasons about the current situation
- Action: The model decides on an action to take
- Observation: The model observes the result of the action
- Thought: The model reasons about the observation and decides next steps
This creates a powerful loop of reasoning and action that leads to more reliable and explainable outcomes.
This implementation uses LangChain to create a ReAct agent with the following components:
The agent has access to the following custom tools:
get_text_length: A tool that returns the length of a text string in characters (strips whitespace and quotes)
-
Agent Setup:
- Uses ChatOpenAI (gpt-4o-mini) as the base LLM
- Implements zero-temperature setting for deterministic outputs
- Uses custom callback handler (
AgentCallbackHandler) for monitoring agent's progress - Implements tool finding functionality with
find_tool_by_name
-
Prompt Template:
- Implements a chain-of-thought prompt template
- Uses LangChain's built-in tool description rendering
- Configures appropriate stop sequences for tool execution
- Includes format guidance for:
- Question
- Thought
- Action
- Action Input
- Observation
- Final Answer
-
Agent Execution Flow:
- Implements an iterative execution loop until reaching
AgentFinish - Uses
ReActSingleInputOutputParserfor structured output parsing - Maintains intermediate steps for tracking agent's reasoning process
- Properly handles tool execution and observation recording
- Implements an iterative execution loop until reaching
- Python 3.x
- LangChain
- OpenAI API key (set via environment variables)
- Python-dotenv for environment management
-
Set up your environment variables:
OPENAI_API_KEY=your_api_key_here
-
Run the main script:
python main.py
The current implementation demonstrates the agent determining the length of the word 'DOG' in characters. The agent:
- Receives the question
- Thinks about how to solve it
- Uses the
get_text_lengthtool - Processes the observation
- Provides the final answer
main.py: Core implementation of the ReAct agent with tool definitions and execution loopcallbacks.py: Custom callback handler for agent monitoring.env: Environment variables configuration (not tracked in git)
- Add more custom tools to expand agent capabilities
- Implement more complex reasoning chains
- Add error handling and retry mechanisms
- Expand the example use cases
Feel free to submit issues and enhancement requests!