Skip to content

VishalYadavCF/ReAct-Agent-Practice

Repository files navigation

AI Agent Course - ReAct Pattern Implementation

This project demonstrates the implementation of AI agents using the ReAct (Reasoning and Acting) pattern with OpenAI's GPT models. The ReAct pattern enables AI agents to reason about problems and take actions to solve them iteratively.

🎯 Project Overview

The project showcases different approaches to building AI agents that can:

  • Reason through problems step-by-step
  • Take actions using available tools/functions
  • Process action results and provide final answers
  • Handle multi-turn conversations with memory

🏗️ Architecture

Core Components

  1. Main LLM Interface (main.py)

    • generate_text_basic(): Single-turn text generation
    • generate_text_memory(): Multi-turn conversation with memory
    • OpenAI API integration with environment variable support
  2. ReAct System Prompt (prompts.py)

    • Defines the Thought → Action → PAUSE → Action_Response loop
    • Provides clear instructions for JSON-structured function calls
    • Includes examples for weather-based decision making
  3. Tool System (sample_functions.py)

    • Mock weather API returning predefined weather conditions
    • Extensible tool registry for adding new functions
    • Currently supports: California, Paris, London, New York, Toronto
  4. JSON Processing (json_helpers.py)

    • Robust JSON extraction from LLM responses
    • Handles nested JSON structures and malformed responses
    • Pydantic model conversion utilities
  5. Agent Evolution (Multiple versions)

    • hc_agent.py: Hard-coded approach (basic implementation)
    • ra_v1.py: Initial ReAct pattern (commented out)
    • ra_v2_with_functions.py: Single-turn function calling
    • ra_final.py: Complete multi-turn ReAct agent

🚀 Getting Started

Prerequisites

  • Python 3.11+
  • OpenAI API key

Installation

  1. Clone the repository:
git clone <repository-url>
cd ai-agent-course-1
  1. Install dependencies:
pip install -r requirements.txt
  1. Set up environment variables: Create a .env file in the project root:
OPENAI_API_KEY=your_openai_api_key_here

Usage

Run the final ReAct agent:

python ra_final.py

The agent will:

  1. Ask whether to take an umbrella in Toronto
  2. Use the get_weather tool to check weather conditions
  3. Provide a reasoned recommendation based on the weather

🧠 ReAct Pattern Explained

The ReAct pattern follows this loop:

  1. Thought: Agent analyzes the question and plans next steps
  2. Action: Agent calls a specific function with structured JSON
  3. PAUSE: Agent waits for the action result
  4. Action_Response: System provides the function result
  5. Answer: Agent provides final response based on all information

Example Flow

Question: Should I take an umbrella today in Toronto?
Thought: I need to check the weather in Toronto first.
Action: {
  "function_name": "get_weather",
  "function_args": [{"arg_name": "city", "arg_value": "Toronto"}]
}
PAUSE
Action_Response: Weather in Toronto is rainy
Answer: Yes, you should take an umbrella today because it's rainy in Toronto.

📁 File Structure

ai-agent-course-1/
├── README.md                    # This file
├── requirements.txt             # Python dependencies
├── .env                        # Environment variables (create this)
├── main.py                     # OpenAI API interface
├── prompts.py                  # System prompts and instructions
├── sample_functions.py         # Available tools/functions
├── json_helpers.py             # JSON parsing utilities
├── ra_final.py                 # Complete ReAct agent (main implementation)
├── ra_v2_with_functions.py     # Single-turn function calling
├── ra_v1.py                    # Basic ReAct pattern
└── hc_agent.py                 # Hard-coded approach

🔧 Configuration

Supported Cities

The mock weather API currently supports:

  • California → sunny
  • Paris → rainy
  • London → cloudy
  • New York → sunny
  • Toronto → rainy

Model Configuration

  • Default model: gpt-4o
  • Alternative: gpt-3.5-turbo
  • Maximum turns: 5 (configurable in ra_final.py)

🎓 Learning Objectives

This project demonstrates:

  1. ReAct Pattern Implementation: How to structure AI agents for reasoning and acting
  2. Function Calling: Structured JSON-based tool integration
  3. Multi-turn Conversations: Memory management across interactions
  4. Error Handling: Robust JSON parsing and response validation
  5. Iterative Development: Evolution from simple to complex agent architectures

🔄 Agent Evolution

v1: Basic ReAct (hc_agent.py)

  • Hard-coded weather data
  • Single-turn interaction
  • No function calling

v2: Function Integration (ra_v2_with_functions.py)

  • Dynamic function calling
  • JSON response parsing
  • Single action execution

v3: Multi-turn ReAct (ra_final.py)

  • Complete ReAct loop implementation
  • Memory across turns
  • Iterative reasoning and acting
  • Configurable turn limits

🛠️ Extending the Agent

Adding New Tools

  1. Define the function in sample_functions.py:
def get_news(topic: str):
    # Your implementation
    return f"Latest news about {topic}"

tools = {
    "get_weather": get_weather,
    "get_news": get_news  # Add new tool
}
  1. Update the system prompt in prompts.py to include the new tool description.

Adding New Models

Update the model parameter in function calls:

response = generate_text_memory(messages, "gpt-3.5-turbo")

📚 Dependencies

  • openai==1.93.0: OpenAI API client
  • python-dotenv==1.1.1: Environment variable management
  • pydantic==2.11.7: Data validation and JSON handling

🤝 Contributing

This appears to be a learning project. To contribute:

  1. Fork the repository
  2. Create a feature branch
  3. Add new tools or improve existing functionality
  4. Test with different scenarios
  5. Submit a pull request

📝 License

This project is for educational purposes. Please check with the course provider for specific licensing terms.

🐛 Troubleshooting

Common Issues

  1. Missing OpenAI API Key: Ensure .env file contains valid OPENAI_API_KEY
  2. JSON Parsing Errors: Check LLM response format matches expected structure
  3. Max Turns Exceeded: Adjust max_turns in ra_final.py if needed
  4. City Not Found: Add new cities to sample_functions.py

Debug Mode

Uncomment print statements in ra_final.py to see intermediate results:

# print(f"{function_name=}")
# print(f"{function_args=}")

🎯 Next Steps

Potential enhancements:

  • Real weather API integration
  • More sophisticated tools (web search, calculations, etc.)
  • Error recovery and retry logic
  • Conversation state persistence
  • Web interface for agent interaction
  • Performance monitoring and logging

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages