Complete Agent Example¶
"Putting it all together: A production-inspired agentic system"
๐ Overview¶
This example demonstrates how to combine multiple agentic patterns into a cohesive, production-ready system inspired by Codex's architecture.
๐ฏ Patterns Integrated¶
This complete example integrates:
- โ Prompt Chaining - Multi-turn conversation
- โ Routing - Dynamic tool dispatch
- โ Parallelization - Concurrent tool execution
- โ Tool Use - External system integration
- โ Memory Management - Conversation persistence
- โ Exception Handling - Retry logic and recovery
- โ Human-in-the-Loop - Approval workflows
- โ Guardrails - Safety checks and sandboxing
๐๏ธ Architecture¶
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Codex-Inspired Agent โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Conversation Manager โ โ
โ โ โข Turn-based execution loop โ โ
โ โ โข History management โ โ
โ โ โข State persistence โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Tool Router & Safety Layer โ โ
โ โ โข Intent classification โ โ
โ โ โข Safety assessment โ โ
โ โ โข Approval requests โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโ โ
โ โ โ โ โ
โ โโโโโโโโผโโโโโ โโโโโโโโผโโโโโ โโโโโโโโผโโโโโโโโโ โ
โ โ File Ops โ โ Shell โ โ Calculator โ ... โ
โ โ Tools โ โ Tools โ โ Tools โ โ
โ โโโโโโโโโโโโโ โโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Error Handler & Retry Logic โ โ
โ โ โข Exponential backoff โ โ
โ โ โข Circuit breaker โ โ
โ โ โข Graceful degradation โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ Files¶
agent_core.py
: Core agent implementationtool_system.py
: Tool registry and executionsafety_layer.py
: Safety checks and approvalsconversation_manager.py
: State and history managementerror_handling.py
: Retry logic and recoveryexample_usage.py
: Demo scenarios
๐ Quick Start¶
# Install dependencies
pip install openai aiohttp
# Set API key
export OPENAI_API_KEY="your-key-here"
# Run the complete example
python example_usage.py
๐ก Key Features¶
1. Multi-Turn Conversations¶
Like Codex, maintains context across turns:
agent = CodexInspiredAgent()
agent.run("Analyze the codebase")
# Turn 1: Reads files
# Turn 2: Analyzes code
# Turn 3: Generates report
2. Safe Tool Execution¶
Multiple layers of safety:
# Whitelist checking
# Sandboxing simulation
# User approval for dangerous ops
# Output truncation
# Timeout enforcement
3. Intelligent Routing¶
Automatically routes to appropriate tools:
# "What time is it?" โ time tool
# "Calculate 2+2" โ calculator tool
# "Read main.py" โ file tool
4. Error Recovery¶
Handles failures gracefully:
5. Conversation Persistence¶
Saves and resumes sessions:
๐ Example Scenarios¶
Scenario 1: Code Analysis Task¶
query = "Analyze main.py, find bugs, and suggest fixes"
# Turn 1: Read file
# Turn 2: Analyze for bugs (uses analysis tool)
# Turn 3: Generate fixes (uses code generation)
# Turn 4: Present recommendations
Scenario 2: Data Processing¶
query = "Process sales.csv and create a summary report"
# Turn 1: Read CSV (file tool)
# Turn 2: Calculate statistics (calculator tool)
# Turn 3: Generate visualizations (visualization tool)
# Turn 4: Write report (file tool)
Scenario 3: System Administration¶
query = "Check disk usage and clean up old logs"
# Turn 1: Check disk (shell tool)
# Approval requested: "Execute 'du -sh'?"
# Turn 2: Identify old files (shell tool)
# Approval requested: "Delete 500MB of logs?"
# Turn 3: Clean up (shell tool)
# Turn 4: Verify space freed
๐ Safety Features¶
Command Whitelisting¶
Approval Workflow¶
if is_dangerous_operation(tool_call):
approval = request_user_approval(tool_call)
if not approval:
return "Operation denied by user"
Sandboxing¶
# Network disabled
# File access limited to workspace
# Process timeout: 30s
# Output truncated: 10KB max
๐ Performance Considerations¶
Parallel Tool Execution¶
# Some tools run in parallel
results = await asyncio.gather(
execute_tool("read_file", {"path": "a.py"}),
execute_tool("read_file", {"path": "b.py"}),
execute_tool("read_file", {"path": "c.py"}),
)
Context Window Management¶
# Automatically compress old history
if len(history) > MAX_TURNS:
history = compress_history(history)
Caching¶
๐งช Testing¶
# Run unit tests
python -m pytest test_agent.py
# Run integration tests
python -m pytest test_integration.py
# Run safety tests
python -m pytest test_safety.py
๐ Learning Objectives¶
After studying this example, you should understand:
- โ How to architect a multi-pattern agent system
- โ State management across async operations
- โ Safety-first design principles
- โ Error handling and recovery strategies
- โ Tool orchestration and routing
- โ User interaction patterns
- โ Performance optimization techniques
๐ Codex Comparison¶
Feature | This Example | Codex |
---|---|---|
Language | Python | Rust |
Sandboxing | Simulated | Real (Seatbelt/Landlock) |
MCP Support | No | Yes |
TUI | No | Yes (Ratatui) |
State Persistence | JSON | Binary rollout files |
Error Handling | Basic retry | Advanced with backoff |
Tool Parallelization | Yes | Yes |
Approval System | Yes | Yes |
๐ Extension Ideas¶
- Add MCP Support: Integrate with external MCP servers
- Implement Streaming: Stream tool output in real-time
- Add Telemetry: OpenTelemetry integration
- Build TUI: Terminal UI like Codex
- Enhance Sandboxing: Use Docker or similar
- Add Planning: Explicit planning tool like Codex
- Multi-Agent: Coordination between multiple agents
๐ License¶
Educational example for learning purposes.
Start with: example_usage.py
to see it in action!