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.
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
-
Main LLM Interface (
main.py
)generate_text_basic()
: Single-turn text generationgenerate_text_memory()
: Multi-turn conversation with memory- OpenAI API integration with environment variable support
-
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
-
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
-
JSON Processing (
json_helpers.py
)- Robust JSON extraction from LLM responses
- Handles nested JSON structures and malformed responses
- Pydantic model conversion utilities
-
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 callingra_final.py
: Complete multi-turn ReAct agent
- Python 3.11+
- OpenAI API key
- Clone the repository:
git clone <repository-url>
cd ai-agent-course-1
- Install dependencies:
pip install -r requirements.txt
- Set up environment variables:
Create a
.env
file in the project root:
OPENAI_API_KEY=your_openai_api_key_here
Run the final ReAct agent:
python ra_final.py
The agent will:
- Ask whether to take an umbrella in Toronto
- Use the
get_weather
tool to check weather conditions - Provide a reasoned recommendation based on the weather
The ReAct pattern follows this loop:
- Thought: Agent analyzes the question and plans next steps
- Action: Agent calls a specific function with structured JSON
- PAUSE: Agent waits for the action result
- Action_Response: System provides the function result
- Answer: Agent provides final response based on all information
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.
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
The mock weather API currently supports:
- California → sunny
- Paris → rainy
- London → cloudy
- New York → sunny
- Toronto → rainy
- Default model:
gpt-4o
- Alternative:
gpt-3.5-turbo
- Maximum turns: 5 (configurable in
ra_final.py
)
This project demonstrates:
- ReAct Pattern Implementation: How to structure AI agents for reasoning and acting
- Function Calling: Structured JSON-based tool integration
- Multi-turn Conversations: Memory management across interactions
- Error Handling: Robust JSON parsing and response validation
- Iterative Development: Evolution from simple to complex agent architectures
- Hard-coded weather data
- Single-turn interaction
- No function calling
- Dynamic function calling
- JSON response parsing
- Single action execution
- Complete ReAct loop implementation
- Memory across turns
- Iterative reasoning and acting
- Configurable turn limits
- 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
}
- Update the system prompt in
prompts.py
to include the new tool description.
Update the model parameter in function calls:
response = generate_text_memory(messages, "gpt-3.5-turbo")
openai==1.93.0
: OpenAI API clientpython-dotenv==1.1.1
: Environment variable managementpydantic==2.11.7
: Data validation and JSON handling
This appears to be a learning project. To contribute:
- Fork the repository
- Create a feature branch
- Add new tools or improve existing functionality
- Test with different scenarios
- Submit a pull request
This project is for educational purposes. Please check with the course provider for specific licensing terms.
- Missing OpenAI API Key: Ensure
.env
file contains validOPENAI_API_KEY
- JSON Parsing Errors: Check LLM response format matches expected structure
- Max Turns Exceeded: Adjust
max_turns
inra_final.py
if needed - City Not Found: Add new cities to
sample_functions.py
Uncomment print statements in ra_final.py
to see intermediate results:
# print(f"{function_name=}")
# print(f"{function_args=}")
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