Skip to main content

Codex CLI Integration

PraisonAI provides integration with OpenAI’s Codex CLI for non-interactive code execution, file modifications, and structured output.

Installation

# Install Codex CLI
npm install -g @openai/codex

# Verify installation
codex --version

Quick Start

from praisonai.integrations import CodexCLIIntegration

# Create integration
codex = CodexCLIIntegration(
    workspace="/path/to/project",
    full_auto=True
)

# Execute a coding task
result = await codex.execute("Fix the authentication bug")
print(result)

Configuration Options

OptionTypeDefaultDescription
workspacestr”.”Working directory for CLI execution
timeoutint300Timeout in seconds
full_autoboolFalseAllow file modifications
sandboxstr”default”Sandbox mode: “default”, “danger-full-access”
json_outputboolFalseEnable JSON Lines streaming output
output_schemastrNonePath to JSON schema for structured output
output_filestrNonePath to save output

Examples

Basic Execution

from praisonai.integrations import CodexCLIIntegration

codex = CodexCLIIntegration(workspace="/project")

result = await codex.execute("Explain the main.py file")
print(result)

Full Auto Mode

Enable file modifications:
codex = CodexCLIIntegration(
    workspace="/project",
    full_auto=True  # Allow file edits
)

result = await codex.execute("Refactor the utils module")

Sandbox Modes

# Default sandbox (restricted)
codex = CodexCLIIntegration(
    workspace="/project",
    sandbox="default"
)

# Full access (for network operations)
codex = CodexCLIIntegration(
    workspace="/project",
    sandbox="danger-full-access"
)

JSON Streaming Output

codex = CodexCLIIntegration(
    workspace="/project",
    json_output=True
)

result = await codex.execute("Analyze the codebase")
# Result is parsed from JSON Lines

Structured Output with Schema

# Create a schema file
schema = {
    "type": "object",
    "properties": {
        "summary": {"type": "string"},
        "issues": {
            "type": "array",
            "items": {"type": "string"}
        },
        "recommendations": {
            "type": "array",
            "items": {"type": "string"}
        }
    }
}

# Save schema
import json
with open("schema.json", "w") as f:
    json.dump(schema, f)

# Use with Codex
codex = CodexCLIIntegration(
    workspace="/project",
    output_schema="schema.json"
)

result = await codex.execute_with_schema(
    "Analyze code quality",
    schema_path="schema.json"
)
print(result)
# {'summary': '...', 'issues': [...], 'recommendations': [...]}

Streaming Output

codex = CodexCLIIntegration(
    workspace="/project",
    json_output=True
)

async for event in codex.stream("Add comprehensive tests"):
    event_type = event.get("type")
    
    if event_type == "thread.started":
        print("Task started")
    elif event_type == "item.completed":
        item = event.get("item", {})
        if item.get("type") == "agent_message":
            print(f"Agent: {item.get('text')}")
    elif event_type == "turn.completed":
        print("Task completed")

As Agent Tool

from praisonai import Agent
from praisonai.integrations import CodexCLIIntegration

codex = CodexCLIIntegration(
    workspace="/project",
    full_auto=True
)

# Create tool
tool = codex.as_tool()

# Use with agent
agent = Agent(
    name="Code Fixer",
    role="Bug Fixer",
    goal="Find and fix bugs in code",
    tools=[tool]
)

result = agent.start("Fix all bugs in the authentication module")

Environment Variables

# API Key (for exec mode)
export CODEX_API_KEY=your-key
# or use ChatGPT authentication

CLI Flags Used

The integration uses the following Codex CLI flags:
FlagDescription
execNon-interactive execution mode
--full-autoAllow file modifications
--sandboxSandbox mode selection
--jsonJSON Lines streaming output
--output-schemaStructured output schema
-oOutput file path

JSON Lines Output Format

When json_output=True, the output is a stream of JSON events:
{"type":"thread.started","thread_id":"abc123"}
{"type":"item.completed","item":{"type":"agent_message","text":"Analyzing..."}}
{"type":"item.completed","item":{"type":"tool_use","name":"read_file"}}
{"type":"turn.completed"}

Error Handling

from praisonai.integrations import CodexCLIIntegration

codex = CodexCLIIntegration(timeout=120)

try:
    result = await codex.execute("Complex refactoring")
except TimeoutError:
    print("Task timed out")
except Exception as e:
    print(f"Error: {e}")

Best Practices

  1. Use full_auto=True only when file modifications are needed
  2. Use structured output for CI/CD pipelines
  3. Set appropriate sandbox mode based on security requirements
  4. Use JSON output for programmatic processing
  5. Set timeouts appropriate for task complexity