"Putting it all together: A production-inspired agentic system"
This example demonstrates how to combine multiple agentic patterns into a cohesive, production-ready system inspired by Codex's architecture.
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
┌─────────────────────────────────────────────────────────────┐
│ 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 │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
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
# Install dependencies
pip install openai aiohttp
# Set API key
export OPENAI_API_KEY="your-key-here"
# Run the complete example
python example_usage.pyLike Codex, maintains context across turns:
agent = CodexInspiredAgent()
agent.run("Analyze the codebase")
# Turn 1: Reads files
# Turn 2: Analyzes code
# Turn 3: Generates reportMultiple layers of safety:
# Whitelist checking
# Sandboxing simulation
# User approval for dangerous ops
# Output truncation
# Timeout enforcementAutomatically routes to appropriate tools:
# "What time is it?" → time tool
# "Calculate 2+2" → calculator tool
# "Read main.py" → file toolHandles failures gracefully:
# Automatic retry with backoff
# Fallback to alternative approaches
# User notification of issuesSaves and resumes sessions:
agent.save_session("session_123.json")
# Later...
agent.load_session("session_123.json")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 recommendationsquery = "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)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 freedSAFE_COMMANDS = ["ls", "cat", "grep", "find"]
DANGEROUS_COMMANDS = ["rm", "dd", "mkfs", "shutdown"]if is_dangerous_operation(tool_call):
approval = request_user_approval(tool_call)
if not approval:
return "Operation denied by user"# Network disabled
# File access limited to workspace
# Process timeout: 30s
# Output truncated: 10KB max# 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"}),
)# Automatically compress old history
if len(history) > MAX_TURNS:
history = compress_history(history)# Cache file reads
# Cache tool results
# Cache LLM responses (deterministic queries)# 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.pyAfter 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
| 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 |
- 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
Educational example for learning purposes.
Start with: example_usage.py to see it in action!