Codex provider forClaif - AI-powered code generation and manipulation through OpenAI Codex CLI
Project description
#claif_cod - Codex Provider forClaif
Quickstart
CLAIF_COD is an async Python wrapper that integrates CLI-based AI code generation tools into theClaif framework. It provides a subprocess-based transport layer that communicates with AI CLIs through JSON streaming, offering both command-line and Python API interfaces for code generation tasks. Version 1.0.5 improves subprocess reliability by switching to native asyncio.
pip install claif_cod && claif-cod query "Write a Python function to calculate fibonacci numbers"
CLAIF_COD is a Python package that provides integration with OpenAI's Codex CLI as part of theClaif (Command-Line Artificial Intelligence Framework) ecosystem. It enables AI-powered code generation, refactoring, and manipulation through both command-line and programmatic interfaces.
Whatclaif_cod Does
CLAIF_COD acts as a specialized provider that creates an async subprocess wrapper around the Codex CLI binary. The package:
- Manages subprocess communication with the Codex CLI binary through async streaming
- Converts betweenClaif and Codex message formats for unified API compatibility
- Provides multiple action modes (review, interactive, full-auto) for code safety
- Handles platform-specific CLI discovery across Windows, macOS, and Linux
- Implements timeout protection and graceful error handling for long operations
- Offers both CLI and Python API interfaces with rich terminal output
- Logs operations with loguru for debugging and monitoring
The transport layer spawns the Codex CLI as a subprocess, streams JSON-formatted messages, and normalizes them into theClaif message format for consistent cross-provider usage.
Installation
Prerequisites
You need to have the Codex CLI binary installed. Set the path via environment variable:
export CODEX_CLI_PATH=/path/to/codex-cli
From PyPI
pip install claif_cod
From Source
git clone https://github.com/twardoch/claif_cod.git
cd claif_cod
pip install -e .
WithClaif Framework
# InstallClaif with Codex support
pip install claif[cod]
# or
pip install claif claif_cod
Development Installation
# Clone and install with development dependencies
git clone https://github.com/twardoch/claif_cod.git
cd claif_cod
pip install -e ".[dev,test]"
# Or using uv for faster installation
uv pip install -e ".[dev,test]"
Command Line Usage
CLAIF_COD provides a Fire-based CLI with rich terminal output:
Basic Commands
# Simple code generation
claif-cod query "Write a Python function to calculate fibonacci numbers"
# Use specific model
claif-cod query "Refactor this code for better performance" --model o4
# Set custom parameters
claif-cod query "Add comprehensive error handling" --temperature 0.2 --max-tokens 2000
Action Modes
Control how code changes are applied:
# Review mode (default) - preview all changes before applying
claif-cod query "Fix the bug in main.py" --action-mode review
# Interactive mode - approve each change individually
claif-cod query "Update all docstrings" --action-mode interactive
# Full-auto mode - apply all changes automatically
claif-cod query "Format all files" --action-mode full-auto --auto-approve
Working with Projects
# Specify project directory
claif-cod query "Run tests and fix failures" --working-dir /path/to/project
# Use current directory
claif-cod query "Add type hints to all functions" --working-dir .
Streaming Responses
# Stream responses in real-time
claif-cod stream "Implement a REST API with FastAPI"
# Stream with specific model
claif-cod stream "Create comprehensive unit tests" --model o4-preview
Model Management
# List available models
claif-cod models
# Show model details
claif-cod model-info o4-mini
# List action modes
claif-cod modes
Configuration
# Show current configuration
claif-cod config show
# Set configuration values
claif-cod config set --codex_cli_path /usr/local/bin/codex-cli
claif-cod config set --default_model o4-mini
claif-cod config set --timeout 300
# Save configuration
claif-cod config save
Additional Commands
# Check service health
claif-cod health
# Show version
claif-cod version
Python API Usage
Basic Usage
import asyncio
from claif_cod import query, CodexOptions
async def main():
# Simple query
async for message in query("Write a sorting algorithm"):
print(message.content)
# With options
options = CodexOptions(
model="o4",
temperature=0.2,
max_tokens=1500,
action_mode="review"
)
async for message in query("Optimize this function", options):
print(message.content)
asyncio.run(main())
Advanced Configuration
from pathlib import Path
from claif_cod import query, CodexOptions
async def generate_code():
options = CodexOptions(
model="o4-preview",
temperature=0.3,
max_tokens=2000,
action_mode="interactive",
working_dir=Path("./src"),
system_prompt="You are an expert Python developer",
auto_approve_everything=False,
timeout=300
)
async for message in query("Create a web scraper", options):
if message.content_type == "code":
print(f"Generated code:\n{message.content}")
elif message.content_type == "error":
print(f"Error: {message.content}")
else:
print(message.content)
Working with Transport Layer
from claif_cod.transport import CodexTransport
from claif_cod.types import CodexOptions
# Create custom transport
transport = CodexTransport(
cli_path="/usr/local/bin/codex-cli",
timeout=600 # 10 minutes for complex operations
)
# Execute query
options = CodexOptions(model="o4", action_mode="review")
async for message in transport.query("Refactor entire module", options):
print(f"{message.message_type}: {message.content}")
Error Handling
from claif.common import ProviderError, TimeoutError
from claif_cod import query, CodexOptions
async def safe_query():
try:
options = CodexOptions(timeout=120)
async for message in query("Complex refactoring", options):
print(message.content)
except TimeoutError:
print("Operation timed out")
except ProviderError as e:
print(f"Codex error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
Whyclaif_cod is Useful
1. Unified Interface
- Consistent API across different AI providers
- Easy switching between Codex, Claude, Gemini, and others
- Standardized message format and error handling
2. Safety Features
- Default review mode prevents unwanted changes
- Timeout protection for long-running operations
- Clear error messages and logging
- Working directory isolation
3. Developer Experience
- Rich CLI with colored output and progress indicators
- Both sync and async APIs
- Type hints and IDE support
- Comprehensive documentation
4. Integration
- Works seamlessly with theClaif framework
- Plugin architecture for easy extension
- Configuration inheritance fromClaif
- Compatible with existing codebases
Howclaif_cod Works
Architecture Overview
┌─────────────────────┐
│ User Code │
├─────────────────────┤
│ Claif Core │ ← Unified interface (Message types)
├─────────────────────┤
│ `claif_cod` │ ← This package (provider adapter)
├─────────────────────┤
│ CodexClient │ ← Client orchestration layer
├─────────────────────┤
│ CodexTransport │ ← Async subprocess management
├─────────────────────┤
│ Codex CLI Binary │ ← External process (JSON I/O)
└─────────────────────┘
Codebase Structure
The package is organized into five main modules:
src/claif_cod/
├── __init__.py # Main entry point, exports query() function
├── cli.py # Fire-based CLI with rich terminal output
├── client.py # Client orchestration and message conversion
├── transport.py # Async subprocess communication layer
└── types.py # Type definitions and data structures
Component Details
__init__.py - Main Entry Point (22 lines)
- Exports the primary
query()async generator function - ConvertsClaif's
ClaifOptionstoCodexOptions - Imports from
claif.commonfor unified Message types - Uses loguru for debug logging
- Version string: "0.1.0"
cli.py - Command Line Interface (334 lines)
CodexCLIclass with Fire-based commands- Rich console output with progress spinners and tables
- Commands implemented:
query: Execute a prompt with optionsstream: Real-time streaming responsesmodels: List available modelsmodel_info: Show model detailsmodes: List action modeshealth: Check service statusconfig: Manage configurationversion: Show version info
- Async execution with
asyncio.run() - Response formatting (text, json, code modes)
client.py - Client Orchestration (55 lines)
CodexClientclass manages transport lifecycle- Module-level
_clientinstance for reuse - Converts
CodexMessagetoClaifMessageformat - Handles connection/disconnection
- Error propagation from transport layer
transport.py - Async Subprocess Layer (171 lines)
CodexTransportclass with anyio for async subprocess- Key methods:
_find_cli_path(): Platform-aware CLI discovery_build_command(): Construct CLI argumentssend_query(): Execute subprocess and stream output_parse_output_line(): JSON line parsing
- Uses
anyio.open_process()for subprocess management - Graceful timeout handling with process termination
- Stderr collection for error reporting
types.py - Type Definitions (142 lines)
- Data classes with
@dataclassdecorator:CodexOptions: All configuration optionsContentBlock(base class)TextBlock,CodeBlock,ErrorBlock: Content typesCodexMessage: Main message structureResultMessage: Completion metadata
- Method
to_claif_message()for format conversion - Comprehensive type hints for IDE support
Message Flow
- User Input → CLI (
fire.Fire) or Python API - Option Conversion →
ClaifOptions→CodexOptionsin__init__.py - Client Layer →
CodexClient.query()manages lifecycle - Transport Layer →
CodexTransport.send_query()spawns subprocess - CLI Discovery → Check env var → PATH → common locations
- Command Building → Construct args:
[cli_path, "query", "--model", model, ...] - Subprocess Execution →
anyio.open_process()with JSON streaming - Output Parsing → Line-by-line JSON parsing in
_parse_output_line() - Message Conversion →
CodexMessage.to_claif_message()normalizes format - Async Yielding → Messages yielded back through async generators
Configuration
Environment variables:
CODEX_CLI_PATH: Path to Codex CLI binaryCODEX_DEFAULT_MODEL: Default model (o4-mini)CODEX_ACTION_MODE: Default action mode (review)CODEX_TIMEOUT: Default timeout in seconds
Configuration file (~/.claif/config.toml):
[providers.codex]
enabled = true
cli_path = "/usr/local/bin/codex-cli"
default_model = "o4-mini"
default_action_mode = "review"
timeout = 180
[providers.codex.models]
available = ["o3.5", "o4-mini", "o4", "o4-preview"]
default = "o4-mini"
Models Available
The package supports any model that the Codex CLI accepts. Common models include:
- o4-mini: Fast, efficient model for quick tasks (default)
- o4: Balanced model for general use
- o4-preview: Latest features and capabilities
- o3.5: Previous generation model
The actual available models depend on your Codex CLI version and API access.
Action Modes
- review (default): Preview changes before applying
- interactive: Approve each change individually
- full-auto: Apply all changes automatically
Best Practices
- Always start with review mode to understand what changes will be made
- Use specific, clear prompts for better results
- Set appropriate timeouts for complex operations (default: 180s)
- Test generated code thoroughly before production use
- Use version control before applying automated changes
- Configure working directory to limit scope of operations
- Check CLI path with
healthcommand if encountering issues - Use verbose mode (
--verbose) for debugging transport issues
Development
Setting Up Development Environment
# Clone the repository
git clone https://github.com/twardoch/claif_cod.git
cd claif_cod
# Install with dev dependencies
pip install -e ".[dev,test]"
# Install pre-commit hooks
pre-commit install
Running Tests
# Run all tests with pytest
pytest
# Run with coverage
pytest --cov=claif_cod --cov-report=html
# Run specific test file
pytest tests/test_package.py -v
Code Quality Tools
# Format code with ruff
ruff format src/claif_cod tests
# Check linting
ruff check src/claif_cod tests --fix
# Type checking with mypy
mypy src/claif_cod
# Run all formatters (as per CLAUDE.md)
fd -e py -x autoflake {}
fd -e py -x pyupgrade --py312-plus {}
fd -e py -x ruff check --output-format=github --fix --unsafe-fixes {}
fd -e py -x ruff format --respect-gitignore --target-version py312 {}
Building and Publishing
# Build distribution
python -m build
# Check distribution
twine check dist/*
# Upload to PyPI (maintainers only)
twine upload dist/*
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Run tests and linting
- Commit with descriptive message
- Push to your fork
- Open a Pull Request
License
MIT License - see LICENSE file for details.
Links
Related Projects
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file claif_cod-1.0.7.tar.gz.
File metadata
- Download URL: claif_cod-1.0.7.tar.gz
- Upload date:
- Size: 32.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: python-httpx/0.28.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
04c16cda3e8e12f31bc3d2a50c97801ac7e16a88a318e0c19af77f9d4c84f294
|
|
| MD5 |
5f079ce6fd94644683fe1c43a6de2bbc
|
|
| BLAKE2b-256 |
3e13d2d6a547459ea4b3d7eac96bee30aa2ea7900adb691d18a0d3878cfa6a83
|
File details
Details for the file claif_cod-1.0.7-py3-none-any.whl.
File metadata
- Download URL: claif_cod-1.0.7-py3-none-any.whl
- Upload date:
- Size: 19.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: python-httpx/0.28.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
011a908154043a508573ea4298b357a8a1b59e8be43f118d7788db3486c79244
|
|
| MD5 |
52ebbd24c51972c7637ac3d0447f6740
|
|
| BLAKE2b-256 |
1779864382a5b1f7d70241a6272e0c57242dae058d5745ef46b274ed2b40832f
|