Skip to content

Complete educational guide with 100+ working code examples for building production-ready AI agents using the OpenAI Agents SDK. Learn to build and deploy scalable multi-agent systems in under 2 hours, going straight from 'Hello World' to enterprise deployment with Docker, Kubernetes, safety guardrails, and monitoring.

Notifications You must be signed in to change notification settings

jkmaina/openai-agents-blueprint

Repository files navigation

The Complete OpenAI Agents SDK Blueprint

Build and Deploy Production-Ready AI Agents in Under 2 Hours

Book Cover

Complete educational code examples and production-ready patterns for building AI agents with the OpenAI Agents SDK

Python 3.8+ OpenAI Agents SDK 100+ Examples Production Ready


πŸ“– What You'll Learn

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.

🎯 Perfect for:

  • 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

πŸš€ What's an AI Agent?

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.

πŸš€ Quick Start

⏱️ Get your first AI agent running in under 5 minutes!

πŸ“‹ What You Need

  • 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!

πŸ› οΈ Installation (Step-by-Step)

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

πŸ§ͺ Test Everything Works

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.

πŸƒβ€β™‚οΈ Try Your First Real Agent

# 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:

  1. Received your request
  2. Thought about it using GPT-4
  3. Generated a creative response
  4. Returned it to your program

This is the foundation of all AI agents! πŸš€


⚑ 2-Hour Challenge: Zero to Production

Can you really build and deploy production-ready AI agents in under 2 hours?

Absolutely! Here's your timed roadmap:

🎯 The 2-Hour Sprint

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

πŸ† What You'll Have Built

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!

πŸ“Š Why This Project is Special

πŸŽ“ Learn by Doing

  • 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!

🏭 Production-Ready Framework

  • 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.

πŸ›‘οΈ Safety First

  • 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.

πŸ“Š See Everything

  • 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.

🀝 Multi-Agent Magic

  • 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.

πŸ› οΈ What's Under the Hood

Don't worry - you don't need to understand all of these! We'll explain them as we go.

🎯 Core AI Technologies

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

πŸ§ͺ Testing Tools (for when you want to be sure things work)

pytest==<latest>          # Runs automated tests
pytest-asyncio            # Tests async code (we'll explain this!)

πŸš€ Production Tools (for real applications)

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

🎯 Your 2-Hour Learning Journey

πŸ—ΊοΈ Choose your path - all designed to get you production-ready in under 2 hours:

⚑ Express Path: 0 to Production in 2 Hours (Most Popular!)

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!


🌱 Beginner Path: Learn the Fundamentals (90 minutes)

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

πŸš€ Developer Fast Track: Skip to Production (45 minutes)

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

πŸ“š Complete Mastery: Everything (3-4 hours)

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

πŸ“š What's in Each Chapter

πŸ“– Chapter 1: Your First AI Agents

πŸ“ 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)

πŸš€ Chapter 2: Supercharge Your Agents

πŸ“ 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)

🏭 Chapter 3: Build a Real Application

πŸ“ 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)

πŸ›‘οΈ Chapter 4: Keep Your Agents Safe

πŸ“ 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)

🀝 Chapter 5: Team Up Multiple Agents

πŸ“ 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)

πŸ› οΈ Chapter 6: Give Agents Superpowers

πŸ“ 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)


πŸ”’ Chapter 7: Secure Your Agents

πŸ“ 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)


πŸ“Š Chapter 8: Monitor Everything

πŸ“ 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)

πŸ”§ How to Run the Examples

πŸƒβ€β™‚οΈ Start Simple (Perfect for beginners)

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! 🀝


🏭 Production Framework (For serious applications)

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 βœ…

🐳 Docker Deployment (Deploy anywhere)

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?"}'

☸️ Kubernetes Deployment (Scale to thousands)

⚠️ Advanced Users Only! This is for production deployments.

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

πŸ§ͺ Testing

Quick Test

python test_setup.py

Full Test Suite

cd chapter3/my-agent-project
export PYTHONPATH=$(pwd)
pytest

Performance Testing

cd chapter3/my-agent-project
pytest tests/test_performance.py -v

Coverage Report

cd chapter3/my-agent-project
pytest --cov=src tests/

πŸ“ˆ Performance Benchmarks

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

πŸ” Troubleshooting

Common Issues

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

Docker Issues

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

Kubernetes Issues

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>

🌟 Key Learning Outcomes

After completing this blueprint, you will have:

  1. Mastered OpenAI Agents SDK - From basics to advanced patterns
  2. Built Production Systems - Complete frameworks with testing and deployment
  3. Implemented Safety - Guardrails, validation, and security patterns
  4. Created Multi-Agent Systems - Orchestration and coordination patterns
  5. Added Observability - Monitoring, logging, and performance tracking
  6. Deployed at Scale - Docker, Kubernetes, and cloud deployment

🀝 Contributing

  1. Fork the repository
  2. Create feature branch: git checkout -b feature/amazing-feature
  3. Run tests: pytest
  4. Commit changes: git commit -m 'Add amazing feature'
  5. Push branch: git push origin feature/amazing-feature
  6. Open Pull Request

πŸ“š Additional Resources

  • 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

πŸ“„ License

MIT License - see LICENSE file for details.

πŸŽ‰ Getting Started

Ready to build amazing AI agents? Start with:

  1. Setup: python test_setup.py
  2. Learn: python chapter1/01_hello_world.py
  3. Explore: cd chapter3/my-agent-project && pytest
  4. Deploy: Follow Docker/Kubernetes guides
  5. Scale: Implement your own agents using the patterns

Happy building! πŸš€

About

Complete educational guide with 100+ working code examples for building production-ready AI agents using the OpenAI Agents SDK. Learn to build and deploy scalable multi-agent systems in under 2 hours, going straight from 'Hello World' to enterprise deployment with Docker, Kubernetes, safety guardrails, and monitoring.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages