> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praison.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Codex CLI Integration

> Integrate OpenAI's Codex CLI for non-interactive code execution

# Codex CLI Integration

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

## Installation

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Install Codex CLI
npm install -g @openai/codex

# Verify installation
codex --version
```

## Quick Start

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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

| Option          | Type | Default   | Description                                   |
| --------------- | ---- | --------- | --------------------------------------------- |
| `workspace`     | str  | "."       | Working directory for CLI execution           |
| `timeout`       | int  | 300       | Timeout in seconds                            |
| `full_auto`     | bool | False     | Allow file modifications                      |
| `sandbox`       | str  | "default" | Sandbox mode: "default", "danger-full-access" |
| `json_output`   | bool | False     | Enable JSON Lines streaming output            |
| `output_schema` | str  | None      | Path to JSON schema for structured output     |
| `output_file`   | str  | None      | Path to save output                           |

## Examples

### Basic Execution

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
codex = CodexCLIIntegration(
    workspace="/project",
    full_auto=True  # Allow file edits
)

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

### Sandbox Modes

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
codex = CodexCLIIntegration(
    workspace="/project",
    json_output=True
)

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

### Structured Output with Schema

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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:

| Flag              | Description                    |
| ----------------- | ------------------------------ |
| `exec`            | Non-interactive execution mode |
| `--full-auto`     | Allow file modifications       |
| `--sandbox`       | Sandbox mode selection         |
| `--json`          | JSON Lines streaming output    |
| `--output-schema` | Structured output schema       |
| `-o`              | Output file path               |

## JSON Lines Output Format

When `json_output=True`, the output is a stream of JSON events:

```json theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
{"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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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
