Complete educational code examples and production-ready patterns for building AI agents with the OpenAI Agents SDK
New to AI agents? This repository is your complete learning journey! Whether you're a complete beginner or an experienced developer, you'll master building AI agents step-by-step.
- Complete Beginners - Never built an AI agent before? Start here!
- Python Developers - Ready to add AI capabilities to your apps
- AI Enthusiasts - Want to understand how modern AI agents work
- Production Teams - Need battle-tested patterns for real applications
Think of an AI agent as a smart assistant that can:
- Understand natural language requests
- Think through problems step-by-step
- Use tools like searching the web, reading files, or calling APIs
- Remember previous conversations
- Work with other agents to solve complex tasks
Real Examples: Customer support bots, research assistants, code helpers, data analysts
This repository contains all the working code examples, projects, and implementations from "The Complete OpenAI Agents SDK Blueprint" by James Karanja Maina. Each chapter builds progressively from basic concepts to advanced production-ready multi-agent systems.
β±οΈ Get your first AI agent running in under 5 minutes!
- Python 3.8+ (Check:
python --version
) - OpenAI API key (Get one here - $5 credit gets you started)
- Basic Python knowledge (if/else, functions, imports)
Don't worry about "async programming" - we'll teach you!
Step 1: Download the Code
# Clone the repository
git clone <repository-url>
cd openai-agents-blueprint
Step 2: Create Your Python Environment
# Create a clean environment (recommended!)
python -m venv .venv
# Activate it
source .venv/bin/activate # On Linux/Mac
# .venv\Scripts\activate # On Windows
Why? This keeps your project dependencies separate from other Python projects.
Step 3: Install Required Packages
# Install everything you need
pip install -r requirements.txt
This installs the OpenAI Agents SDK and other helpful tools.
Step 4: Add Your API Key
# Copy the example environment file
cp .env.example .env
# Edit with your favorite text editor
nano .env # or code .env, or notepad .env
In the .env file, add your OpenAI API key:
OPENAI_API_KEY=sk-your-actual-api-key-here
DEFAULT_MODEL=gpt-4o-mini
python test_setup.py
You should see:
β
Environment setup verified
β
API key loaded: sk-proj-ab...
β
Agent created successfully
β
Agent execution successful: Hello from the OpenAI Agents SDK!
π Success! Your first AI agent just worked! It connected to OpenAI and generated a response.
# Run the classic "Hello World" agent
python chapter1/01_hello_world.py
What just happened? You created an AI agent that wrote a haiku about programming recursion! The agent:
- Received your request
- Thought about it using GPT-4
- Generated a creative response
- Returned it to your program
This is the foundation of all AI agents! π
Can you really build and deploy production-ready AI agents in under 2 hours?
Absolutely! Here's your timed roadmap:
Time | Milestone | What You'll Build |
---|---|---|
0-10 min | β Setup Complete | Working development environment |
10-25 min | β First Agent | AI agent that uses tools and functions |
25-45 min | β Production Framework | Customer service agent with testing |
45-70 min | β Multi-Agent System | Team of specialized agents working together |
70-90 min | β Containerized | Docker container with health checks |
90-120 min | β Production Deployed | Kubernetes deployment with auto-scaling |
By hour 2, you'll have:
- β Working AI agents that can use tools and APIs
- β Production framework with testing and monitoring
- β Multi-agent orchestration with specialized roles
- β Docker deployment ready for any cloud platform
- β Kubernetes configuration for enterprise scaling
- β Safety guardrails and content moderation
- β Performance monitoring and error handling
π° Real Value: Skip 2-3 months of research and setup - get straight to production!
- 100+ hands-on examples - Every concept has working code
- Step-by-step progression - From "Hello World" to production systems
- Copy-paste ready - All examples run immediately
- Real-world focused - Patterns you'll actually use at work
π‘ Example: Chapter 1 starts with a 10-line "Hello World" agent, Chapter 8 ends with a full monitoring system!
- Complete starter project - Skip months of setup
- Best practices built-in - Error handling, testing, deployment
- Docker & Kubernetes - Deploy anywhere from day one
- Monitoring included - See how your agents perform
π‘ Example: The Chapter 3 framework includes everything you need to deploy a customer service agent to production.
- Content filtering - Prevent harmful outputs automatically
- Input validation - Protect against malicious requests
- Rate limiting - Control costs and abuse
- Security patterns - API key management, authentication
π‘ Example: Chapter 4 shows how to build agents that automatically reject inappropriate requests.
- Real-time monitoring - Watch your agents work
- Performance tracking - Optimize response times and costs
- Error debugging - Fix problems quickly
- Usage analytics - Understand user patterns
π‘ Example: Chapter 8 shows dashboards tracking token usage, response times, and error rates.
- Agent teamwork - Multiple specialists working together
- Smart routing - Send requests to the right agent
- Shared memory - Agents that remember context
- Parallel processing - Handle multiple requests simultaneously
π‘ Example: Chapter 5 builds a research team where agents specialize in web search, academic papers, and industry reports.
Don't worry - you don't need to understand all of these! We'll explain them as we go.
openai-agents==0.1.0 # The main SDK - your AI agent toolkit
openai==1.93.0 # Connects to OpenAI's GPT models
pydantic==2.11.7 # Makes sure your data is correct
python-dotenv==1.1.1 # Keeps your API keys safe
rich==14.0.0 # Makes terminal output beautiful
What these do:
- openai-agents - The magic! Turns Python code into AI agents
- openai - Talks to ChatGPT/GPT-4 for you
- pydantic - Prevents bugs by checking data types
- python-dotenv - Loads your API key securely
- rich - Makes output colorful and pretty
pytest==<latest> # Runs automated tests
pytest-asyncio # Tests async code (we'll explain this!)
uvicorn==0.34.3 # Web server for your agent
starlette==0.47.1 # Web framework (like Flask but faster)
docker # Packages your app for deployment
kubernetes # Runs your app at scale
terraform # Creates cloud infrastructure
When do you need these?
- Learning: Just the core dependencies
- Building apps: Add the testing tools
- Going live: Include production tools
πΊοΈ Choose your path - all designed to get you production-ready in under 2 hours:
Hour 1: Core Foundations (60 minutes)
# Minutes 0-10: Setup and first agent
python test_setup.py
python chapter1/01_hello_world.py
# Minutes 10-25: Add superpowers with tools
python chapter2/14_simple_tool.py
# Minutes 25-45: Production-ready patterns
cd chapter3/my-agent-project && export PYTHONPATH=$(pwd)
python examples/customer_support_example.py
# Minutes 45-60: Multi-agent teamwork
python chapter5/11_research_team_orchestration.py
Hour 2: Deploy to Production (60 minutes)
# Minutes 60-80: Build and test
pytest # Verify everything works
docker build -f docker/Dockerfile -t my-agent .
# Minutes 80-105: Deploy locally
docker run -p 8000:8000 -e OPENAI_API_KEY=your_key my-agent
curl http://localhost:8000/health # Test it works!
# Minutes 105-120: Scale with Kubernetes (optional)
kubectl apply -f k8s/deployment.yaml
π Result: Production-ready AI agent system deployed and running!
Perfect if you're new to AI agents or want to understand everything:
# 0-30 min: Understanding the basics
python chapter1/01_hello_world.py # Your first agent
python chapter1/02_haiku_writer.py # Creative agents
python chapter1/03_structured_output_agent.py # Structured responses
# 30-60 min: Adding real capabilities
python chapter2/14_simple_tool.py # Tools and functions
python chapter4/01_input_guardrail_minimal.py # Safety first
python chapter8/observability.py # Monitor performance
# 60-90 min: Production deployment
cd chapter3/my-agent-project
python examples/customer_support_example.py
docker build -f docker/Dockerfile -t my-agent .
docker run -p 8000:8000 -e OPENAI_API_KEY=your_key my-agent
You know Python, just want the production patterns:
# 0-15 min: Core concepts
python chapter1/01_hello_world.py
python chapter2/14_simple_tool.py
# 15-30 min: Production framework
cd chapter3/my-agent-project && export PYTHONPATH=$(pwd)
python examples/customer_support_example.py
pytest
# 30-45 min: Deploy
docker build -f docker/Dockerfile -t my-agent .
docker run -p 8000:8000 -e OPENAI_API_KEY=your_key my-agent
For those who want to master every pattern and technique:
- Hour 1: Foundations (Chapters 1-2)
- Hour 2: Production Framework (Chapter 3)
- Hour 3: Safety, Multi-Agents, Tools (Chapters 4-6)
- Hour 4: Security & Monitoring (Chapters 7-8)
π Perfect for: Tech leads, AI teams, or anyone building multiple agent systems
π Location: chapter1/
| π’ Examples: 14 step-by-step tutorials
π― You'll Build:
- Hello World Agent (
01_hello_world.py
) - Your very first AI agent in 10 lines! - Creative Writer (
02_haiku_writer.py
) - An agent that writes poetry - Smart Responder (
03_structured_output_agent.py
) - Returns organized data, not just text - Chat Interface (
04_interactive_demo.py
) - Back-and-forth conversations - Error Handler (
05_error_handling_agent.py
) - Agents that don't crash - Memory Agents (
08-13_memory_*.py
) - Agents that remember previous conversations
π§ What You'll Learn:
- How to create and run agents
- Why some agents remember things and others don't
- How to handle errors gracefully
- Basic Python async patterns (we make it easy!)
β±οΈ Time: 30 minutes (core examples), 2 hours (complete mastery)
π Location: chapter2/
| π’ Examples: 22 power-user techniques
π― You'll Build:
- Dynamic Agents (
01-02_dynamic_*.py
) - Agents that change their behavior based on context - Tool-Using Agents (
14-15_tool_*.py
) - Agents that can search the web, read files, call APIs - Streaming Agents (
13_streaming.py
) - See responses as they're generated (like ChatGPT) - Async Agents (
11-12_async_*.py
) - Handle multiple requests simultaneously - Production Agents (
16-22_production_*.py
) - Security, monitoring, optimization
π§ What You'll Learn:
- The difference between sync and async (and when to use each)
- How to give agents "tools" (superpowers!)
- Streaming responses for better user experience
- Security and performance best practices
β±οΈ Time: 45 minutes (key patterns), 3 hours (all examples)
π Location: chapter3/my-agent-project/
| π― Goal: Production-ready framework you can use at work
π What You Get:
- Complete Starter App - Customer service agent ready to deploy
- Testing Suite - Automated tests so you know things work
- Docker Setup - Deploy anywhere in minutes
- Kubernetes Config - Scale to handle thousands of users
- Monitoring Dashboard - See performance, errors, costs in real-time
π― You'll Build:
- Customer support agent with specialized responses
- Multi-agent system (triage β specialist agents)
- Content safety filters
- Performance monitoring
- Automated testing
π§ What You'll Learn:
- How to structure a real application
- Testing strategies for AI agents
- Docker and Kubernetes deployment
- Monitoring and observability
- Best practices for production systems
πΌ Perfect for: Teams wanting to deploy agents to production
β±οΈ Time: 45 minutes (framework setup), 90 minutes (full deployment)
π Location: chapter4/
| π’ Examples: 7 safety-first patterns
π¨ Why This Matters: AI agents can sometimes generate inappropriate content or respond to malicious inputs. This chapter shows you how to build agents that are safe, responsible, and trustworthy.
π― You'll Build:
- Input Filters (
01-02_input_guardrails_*.py
) - Block harmful requests before they reach your agent - Content Moderator (
03_content_moderation.py
) - Automatically detect and filter inappropriate responses - Custom Safety Rules (
04_custom_guardrails.py
) - Define your own safety policies - Monitoring System (
05-07_monitoring_*.py
) - Track safety violations and trends
π§ What You'll Learn:
- How to prevent agents from generating harmful content
- Input validation techniques
- Building custom safety policies for your use case
- Monitoring and alerting for safety violations
πΌ Critical for: Any public-facing application
β±οΈ Time: 30 minutes (essential safety), 1 hour (comprehensive)
π Location: chapter5/
| π’ Examples: 11 teamwork patterns
π The Big Idea: Instead of one agent doing everything, create teams of specialized agents that work together. Like having a customer service team where different agents handle billing, technical support, and general questions.
π― You'll Build:
- Agent Handoffs (
01-04_handoff_*.py
) - Pass conversations between specialized agents - Research Team (
11_research_team_orchestration.py
) - Agents that work together to research topics - Parallel Processing (
07-10_processing_*.py
) - Multiple agents working simultaneously - Smart Routing (
05-06_orchestration_*.py
) - Automatically direct requests to the right agent
π§ What You'll Learn:
- When to use multiple agents vs. one powerful agent
- How agents can share information and context
- Orchestration patterns for complex workflows
- Building agent "teams" with specialized roles
π‘ Real Example: A research assistant that uses one agent to search the web, another to read academic papers, and a third to write summaries.
β±οΈ Time: 30 minutes (basic handoffs), 90 minutes (complete orchestration)
π Location: chapter6/
| π’ Examples: 6 powerful integrations
β‘ The Magic: Tools turn your agents from "just chatbots" into powerful assistants that can actually DO things - search the web, run code, generate images, read files, and more!
π― You'll Build:
- Code-Running Agent (
03_code_interpreter.py
) - Agent that can write and execute Python code - Image Creator (
05_image_generation.py
) - Agent that generates images with DALL-E - File Assistant (
04_file_search.py
) - Agent that can search through documents - Web-Enabled Agent (
02_hosted_tools.py
) - Agent that can search the internet - Custom Tools (
01_basic_tools.py
) - Build your own tools for specific tasks
π§ What You'll Learn:
- How to give agents access to external systems
- Using OpenAI's built-in tools vs. building custom ones
- Async tool patterns for better performance
- Security considerations when agents use tools
π‘ Real Example: A data analyst agent that can read CSV files, run statistical analysis, and generate charts.
β±οΈ Time: 20 minutes (basic tools), 2 hours (all integrations)
π Location: chapter7/
| π’ Examples: 3 security essentials
π― You'll Build:
- API Key Manager (
01_api_key_manager.py
) - Secure key storage and rotation - Key Validator (
02_key_validation.py
) - Verify and validate API keys - JWT Authentication (
03_jwt.py
) - Token-based user authentication
π§ What You'll Learn:
- How to secure API keys and credentials
- User authentication patterns
- Authorization and access control
- Security best practices for production
β±οΈ Time: 15 minutes (essential security), 45 minutes (complete)
π Location: chapter8/
| π’ Examples: 5 monitoring systems
π Why Monitor? In production, you need to know: Is your agent working? How fast is it? How much is it costing? Are users happy? This chapter shows you how to get those answers.
π― You'll Build:
- Performance Dashboard (
observability.py
) - Track response times, token usage, costs - Smart Logging (
structured_logging.py
) - Logs that actually help you debug - Custom Metrics (
custom_metrics.py
) - Track business-specific metrics - Multi-Modal Monitoring (
simple_multi_modal.py
) - Monitor agents that handle text, images, and files
π§ What You'll Learn:
- Setting up comprehensive monitoring
- Creating useful dashboards and alerts
- Debugging production issues
- Optimizing performance and costs
πΌ Essential for: Production deployments
β±οΈ Time: 20 minutes (basic monitoring), 1 hour (complete observability)
Your First Agent (5 minutes):
# Make sure you're in the project directory
cd openai-agents-blueprint
# Run your first agent
python chapter1/01_hello_world.py
What happens? Your agent writes a haiku about programming! π
Try Some Tools (10 minutes):
# Agent that can check weather and time
python chapter2/14_simple_tool.py
What happens? Your agent can now DO things, not just chat! β‘
Advanced Multi-Agent (20 minutes):
# Watch multiple agents work together
python chapter5/11_research_team_orchestration.py
What happens? A team of specialist agents conducts research for you! π€
Step 1: Enter the Framework
cd chapter3/my-agent-project
# Tell Python where to find the code
export PYTHONPATH=$(pwd) # Linux/Mac
# set PYTHONPATH=%cd% # Windows
Step 2: Try the Examples
# Customer service agent
python examples/customer_support_example.py
# Multi-agent workflow
python examples/multi_agent_workflow_example.py
Step 3: Run the Tests
pytest
# You should see: 9 passed in ~4s β
Build Your Container:
cd chapter3/my-agent-project
# Build the Docker image
docker build -f docker/Dockerfile -t my-agent-project .
Run Your Agent:
# Start the container
docker run -p 8000:8000 \
-e OPENAI_API_KEY=your_actual_key_here \
my-agent-project
Test It:
# Check if it's working
curl http://localhost:8000/health
# Should return: {"status":"healthy"}
# Try the agent
curl -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{"query": "Hello, can you help me?"}'
cd chapter3/my-agent-project
# Create a local cluster for testing
kind create cluster --name agent-test
# Load your image into the cluster
kind load docker-image my-agent-project --name agent-test
# Create your API key secret
kubectl create secret generic agent-secrets \
--from-literal=openai-api-key=your_key_here
# Deploy your agents
kubectl apply -f k8s/deployment.yaml
# Test the deployment
kubectl port-forward service/agent-service 8080:80
curl http://localhost:8080/health
What This Gets You:
- β Load balancing across multiple agent instances
- β Auto-scaling based on demand
- β Health checks and automatic restarts
- β Zero-downtime deployments
python test_setup.py
cd chapter3/my-agent-project
export PYTHONPATH=$(pwd)
pytest
cd chapter3/my-agent-project
pytest tests/test_performance.py -v
cd chapter3/my-agent-project
pytest --cov=src tests/
Based on test results from the production framework:
- Response Time: 2-4 seconds average
- Concurrent Requests: 10+ handled successfully
- Test Coverage: >80% code coverage
- Deployment Success: β Docker, Docker Compose, Kubernetes
- Auto-scaling: β 3-5 replicas tested
- Load Balancing: β Verified across multiple instances
Issue | Solution | Command |
---|---|---|
OPENAI_API_KEY not found |
Set environment variable | export OPENAI_API_KEY=your_key |
ImportError: No module named 'agents' |
Install dependencies | pip install -r requirements.txt |
Module not found |
Set Python path | export PYTHONPATH=$(pwd) |
Tests failing | Verify API key and deps | python test_setup.py |
Issue | Solution | Command |
---|---|---|
Build fails | Check Docker syntax | docker build --no-cache . |
Container won't start | Check environment vars | docker logs <container> |
Health check fails | Verify endpoints | curl http://localhost:8000/health |
Issue | Solution | Command |
---|---|---|
Pods not starting | Check secrets and images | kubectl describe pod <name> |
Service unreachable | Verify endpoints | kubectl get svc,endpoints |
Scaling issues | Check resource limits | kubectl describe hpa <name> |
After completing this blueprint, you will have:
- Mastered OpenAI Agents SDK - From basics to advanced patterns
- Built Production Systems - Complete frameworks with testing and deployment
- Implemented Safety - Guardrails, validation, and security patterns
- Created Multi-Agent Systems - Orchestration and coordination patterns
- Added Observability - Monitoring, logging, and performance tracking
- Deployed at Scale - Docker, Kubernetes, and cloud deployment
- Fork the repository
- Create feature branch:
git checkout -b feature/amazing-feature
- Run tests:
pytest
- Commit changes:
git commit -m 'Add amazing feature'
- Push branch:
git push origin feature/amazing-feature
- Open Pull Request
- OpenAI Agents SDK Documentation: Official SDK documentation
- OpenAI Platform: API documentation and guides
- Pydantic Documentation: Data validation and settings
- pytest Documentation: Testing framework
- Docker Documentation: Containerization
- Kubernetes Documentation: Container orchestration
MIT License - see LICENSE file for details.
Ready to build amazing AI agents? Start with:
- Setup:
python test_setup.py
- Learn:
python chapter1/01_hello_world.py
- Explore:
cd chapter3/my-agent-project && pytest
- Deploy: Follow Docker/Kubernetes guides
- Scale: Implement your own agents using the patterns
Happy building! π