This example demonstrates how to use the Codex CLI provider for basic AI agent orchestration tasks with your OpenAI API key.
- OpenAI Integration: Use your OpenAI API key with CAO
- Basic Agent Creation: Create Codex agents for different development tasks
- Status Detection: Understand how CAO detects Codex CLI states
- Message Extraction: Extract responses from Codex agents
- Multi-Agent Coordination: Simple supervisor-worker patterns
-
OpenAI API Key or ChatGPT Subscription: Authentication for Codex CLI
-
Codex CLI: Install and authenticate:
npm install -g @openai/codex export OPENAI_API_KEY=your-key-here # Or use: codex login codex --version # Verify installation
-
CLI Agent Orchestrator: Installed and running
cao-server # Run in one terminal
# Start cao-server in one terminal
cao-server
# In another terminal, create a Codex session
cao launch --agents codex_developer --provider codex# In the tmux window, paste your prompt at the Codex prompt.
# Optional: print the CAO terminal id (useful for API automation / MCP)
echo "$CAO_TERMINAL_ID"Optional automation from another terminal (send input + get extracted last message):
python3 - <<'PY'
import time
import requests
terminal_id = "<terminal-id>"
requests.post(
f"http://localhost:9889/terminals/{terminal_id}/input",
params={"message": "Write a Python function to validate email addresses using regex"},
).raise_for_status()
# Poll status until completion
while True:
status = requests.get(f"http://localhost:9889/terminals/{terminal_id}").json()["status"]
if status in {"completed", "error", "waiting_user_answer"}:
break
time.sleep(1)
resp = requests.get(
f"http://localhost:9889/terminals/{terminal_id}/output",
params={"mode": "last"},
)
resp.raise_for_status()
print(resp.json()["output"])
PYThe example includes pre-configured agent profiles for different Codex-based tasks:
- General programming and development tasks
- Code writing, debugging, refactoring
- Language: Python, JavaScript, TypeScript
- Code review and security analysis
- Best practices and optimization
- Testing and quality assurance
- Technical writing and documentation
- README files, API docs, tutorials
- Clear, structured communication
When using the codex provider with --agents, CAO loads the specified agent profile and injects its system prompt into Codex as developer_instructions. This means Codex will adopt the role defined in the agent profile (e.g., supervisor, developer, reviewer).
Agent profiles are loaded from:
- Local store:
~/.aws/cli-agent-orchestrator/agent_store/<name>.md - Built-in store:
src/cli_agent_orchestrator/agent_store/<name>.md
# Launch a Codex developer
cao launch --agents codex_developer --provider codex
# In the agent terminal:
"Write a Python function that:
1. Takes a list of URLs
2. Downloads each URL content
3. Extracts all email addresses
4. Returns a unique list of emails
Include proper error handling and docstring."Expected Output:
- Agent will think and process (PROCESSING state)
- Write the Python function with proper structure
- Return completed code (COMPLETED state)
# Launch a Codex reviewer
cao launch --agents codex_reviewer --provider codexPaste this prompt into the Codex CLI:
Please review this Python code for security issues:
import subprocess
def execute_command(user_input):
command = f"ls {user_input}"
return subprocess.run(command, shell=True, capture_output=True)
Focus on:
1. Security vulnerabilities
2. Input validation
3. Safe coding practices
4. Potential improvements
# Launch a Codex documenter
cao launch --agents codex_documenter --provider codex
# Request documentation:
"Create comprehensive README documentation for a Python package that:
- Has functions for data processing
- Includes installation instructions
- Provides usage examples
- Documents API reference
- Includes contribution guidelines
Make it professional and developer-friendly."The Codex provider automatically detects these states:
-
PROCESSING: Codex is thinking or working
[Agent is thinking...] -
WAITING_USER_ANSWER: Waiting for confirmation
Approve this action? (y/n) -
COMPLETED: Task finished with response
❯ # Ready for next command -
ERROR: Error occurred
Error: Invalid input provided
CAO automatically extracts the last assistant response:
# CAO extracts this part
def validate_email(email):
"""Validate email address using regex."""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
# This is the response returned by GET /terminals/{terminal_id}/output?mode=last# Launch developer
cao launch --agents codex_developer --provider codex
# Multi-step task:
"1. First, write a Python class for User with fields: id, name, email, created_at
2. Then, add methods for validation and serialization
3. Finally, write unit tests for the User class
Proceed step by step and show me each part."# Launch reviewer then developer
cao launch --agents codex_reviewer --provider codexPaste this prompt into the Codex CLI:
Review this legacy code and suggest refactoring improvements:
def process_data(data):
result = []
for i in range(len(data)):
if data[i] > 0:
result.append(data[i] * 2)
else:
result.append(0)
return result
Identify:
1. Code smells and anti-patterns
2. Performance improvements
3. Pythonic alternatives
4. Better naming and structure
Then provide a refactored version with explanations.
-
Authentication Failed:
codex logout codex login # Or set API key directly export OPENAI_API_KEY=your-key-here
-
Agent Not Responding:
- Check
tmux list-sessionsfor session status - Verify your OpenAI API key is valid (
codex --version) - Check network connectivity
- Check
-
Status Detection Issues:
- Agent might be in unexpected state
- Check terminal output manually:
tmux attach -t <session-name> - Verify Codex CLI version compatibility
- Clear Tasks: Be specific about what you want
- Step by Step: Break complex tasks into smaller steps
- Context Management: Provide relevant context upfront
- Validation: Ask for explanations of complex logic
After mastering the basics, explore:
- Multi-Agent Patterns: See
examples/assign/for step-by-step patterns you can adapt to Codex - Workflow Integration: Combine with other providers
- Custom Agent Profiles: Create specialized Codex agents
- MCP Integration: Use Codex agents in MCP workflows
For issues:
- Check troubleshooting section
- Review main documentation
- Report issues on GitHub
To contribute Codex examples:
- Fork the repository
- Create new example in
examples/codex-*/ - Follow the established pattern
- Update documentation
- Submit a pull request