PHP code example of neosoftware / openai-codex-sdk

1. Go to this page and download the library: Download neosoftware/openai-codex-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

neosoftware / openai-codex-sdk example snippets


new CodexOptions(codexPathOverride: '/usr/local/bin/codex')


OpenAI\Codex\Codex;
use OpenAI\Codex\Types\Options\CodexOptions;
use OpenAI\Codex\Types\Options\ThreadOptions;

$codex = new Codex(new CodexOptions(
    apiKey: $_ENV['OPENAI_API_KEY'],
));

$thread = $codex->startThread(new ThreadOptions(
    model: 'codex-mini-latest',
    skipGitRepoCheck: true,
));

$turn = $thread->run('Explain what the array_chunk function does in PHP.');

echo $turn->finalResponse;

$codex = new Codex(new CodexOptions(
    apiKey:            'sk-...',             // OpenAI API key (or via the OPENAI_API_KEY env variable)
    baseUrl:           'https://...',        // custom API endpoint (optional)
    codexPathOverride: '/usr/local/bin/codex', // custom binary (optional)
    config: [                                // additional --config flags
        'disable_response_storage' => true,
    ],
    env: [                                   // if set, process env is NOT inherited
        'OPENAI_API_KEY' => 'sk-...',
        'HOME' => '/home/user',
    ],
));

// New thread
$thread = $codex->startThread(new ThreadOptions(...));

// Resume an existing thread by ID
$thread = $codex->resumeThread('019dc15c-a8aa-...', new ThreadOptions(...));

// Get the ID after the first request
echo $thread->getId(); // string|null

$turn = $thread->run('Find a bug in src/Payment.php');

echo $turn->finalResponse;           // final text response from the agent
echo $turn->usage->outputTokens;     // tokens consumed
foreach ($turn->items as $item) {   // all completed items
    // AgentMessageItem | CommandExecutionItem | FileChangeItem | ...
}

$streamed = $thread->runStreamed('Check all tests and fix the errors');

foreach ($streamed->events() as $event) {
    match (true) {
        $event instanceof ThreadStartedEvent  => print("Thread: {$event->threadId}\n"),
        $event instanceof TurnCompletedEvent  => print("Tokens: {$event->usage?->outputTokens}\n"),
        $event instanceof ItemStartedEvent    => print("Started: {$event->item->type}\n"),
        $event instanceof ItemCompletedEvent  => match (true) {
            $event->item instanceof AgentMessageItem     => print($event->item->text . "\n"),
            $event->item instanceof CommandExecutionItem => print("$ {$event->item->command}\n"),
            $event->item instanceof FileChangeItem       => print("Files changed: " . count($event->item->changes) . "\n"),
            default => null,
        },
        default => null,
    };
}

// Simple string
$thread->run('Explain this code');

// Text + images
use OpenAI\Codex\Types\Input\TextInput;
use OpenAI\Codex\Types\Input\LocalImageInput;

$thread->run([
    new TextInput('What is wrong with this screenshot?'),
    new LocalImageInput('/path/to/screenshot.png'),
    new TextInput('Pay attention to the upper-right corner.'),
]);

$item->id;    // string
$item->text;  // string — agent message

$item->id;    // string
$item->text;  // string

$item->id;               // string
$item->command;          // string — command, for example "/bin/zsh -c 'php artisan test'"
$item->aggregatedOutput; // string — full command output
$item->exitCode;         // ?int — return code
$item->status;           // CommandExecutionStatus::InProgress|Completed|Failed

$item->id;      // string
$item->status;  // PatchApplyStatus::Completed|Failed
foreach ($item->changes as $change) {
    $change->path;        // string — file path
    $change->kind;        // PatchChangeKind::Add|Delete|Update
    $change->applyStatus; // PatchApplyStatus::Completed|Failed
}

$item->id;        // string
$item->server;    // string — MCP server name
$item->tool;      // string — tool name
$item->arguments; // mixed — arguments
$item->result;    // mixed — result (after completion)
$item->error;     // ?string — error (if any)
$item->status;    // McpToolCallStatus::InProgress|Completed|Failed

$item->id;     // string
$item->query;  // string — search query

$item->id;  // string
foreach ($item->items as $todo) {
    $todo->id;          // string
    $todo->description; // string
    $todo->completed;   // bool
}

$item->id;      // string
$item->message; // string

use OpenAI\Codex\Types\Options\TurnOptions;

$turn = $thread->run('Task', new TurnOptions(
    outputSchema:   [...],   // JSON Schema for structured output
    timeoutSeconds: 120,     // response wait timeout in seconds
));

$turn = $thread->run(
    'Return project data',
    new TurnOptions(
        outputSchema: [
            'type'                 => 'object',
            'additionalProperties' => false,
            'properties' => [
                'name'    => ['type' => 'string'],
                'version' => ['type' => 'string'],
                'license' => ['type' => 'string'],
            ],
            '

use OpenAI\Codex\Types\Enums\SandboxMode;

SandboxMode::ReadOnly        // file system read-only
SandboxMode::WorkspaceWrite  // read + write in the working directory
SandboxMode::DangerFullAccess // full access (no restrictions)

use OpenAI\Codex\Types\Enums\ModelReasoningEffort;

ModelReasoningEffort::Minimal
ModelReasoningEffort::Low
ModelReasoningEffort::Medium
ModelReasoningEffort::High
ModelReasoningEffort::Xhigh

use OpenAI\Codex\Types\Enums\WebSearchMode;

WebSearchMode::Disabled  // web search disabled
WebSearchMode::Cached    // cached results only
WebSearchMode::Live      // live search

use OpenAI\Codex\Types\Enums\ApprovalMode;

ApprovalMode::Never      // run everything without confirmation
ApprovalMode::OnRequest  // ask the user for permission
ApprovalMode::OnFailure  // ask only on failure
ApprovalMode::Untrusted  // strict mode

use OpenAI\Codex\Exceptions\CodexException;
use OpenAI\Codex\Exceptions\SpawnException;
use OpenAI\Codex\Exceptions\TurnFailedException;
use OpenAI\Codex\Exceptions\ParseException;

try {
    $turn = $thread->run('...');
} catch (TurnFailedException $e) {
    // The agent returned an error (API error, invalid schema, etc.)
    echo "Agent error: " . $e->getMessage();
} catch (SpawnException $e) {
    // Startup error or subprocess timeout
    echo "Process error: " . $e->getMessage();
} catch (ParseException $e) {
    // The agent returned invalid JSONL
    echo "Parse error: " . $e->getMessage();
} catch (CodexException $e) {
    // Any other SDK error
    echo "SDK error: " . $e->getMessage();
}


OpenAI\Codex\Codex;
use OpenAI\Codex\Types\Enums\ApprovalMode;
use OpenAI\Codex\Types\Enums\ModelReasoningEffort;
use OpenAI\Codex\Types\Enums\SandboxMode;
use OpenAI\Codex\Types\Events\ItemCompletedEvent;
use OpenAI\Codex\Types\Events\ThreadStartedEvent;
use OpenAI\Codex\Types\Events\TurnCompletedEvent;
use OpenAI\Codex\Types\Input\LocalImageInput;
use OpenAI\Codex\Types\Input\TextInput;
use OpenAI\Codex\Types\Items\AgentMessageItem;
use OpenAI\Codex\Types\Items\CommandExecutionItem;
use OpenAI\Codex\Types\Items\FileChangeItem;
use OpenAI\Codex\Types\Options\CodexOptions;
use OpenAI\Codex\Types\Options\ThreadOptions;
use OpenAI\Codex\Types\Options\TurnOptions;

$codex = new Codex(new CodexOptions(
    apiKey: $_ENV['OPENAI_API_KEY'],
));

$thread = $codex->startThread(new ThreadOptions(
    model:                 'codex-mini-latest',
    sandboxMode:           SandboxMode::WorkspaceWrite,
    workingDirectory:      '/path/to/project',
    modelReasoningEffort:  ModelReasoningEffort::High,
    approvalPolicy:        ApprovalMode::Never,
));

// Streaming with an image
$streamed = $thread->runStreamed(
    [
        new TextInput('What is wrong with this code?'),
        new LocalImageInput('/tmp/screenshot.png'),
    ],
    new TurnOptions(timeoutSeconds: 180),
);

foreach ($streamed->events() as $event) {
    match (true) {
        $event instanceof ThreadStartedEvent  => printf("Thread: %s\n", $event->threadId),
        $event instanceof TurnCompletedEvent  => printf("Tokens: %d\n", $event->usage?->outputTokens ?? 0),
        $event instanceof ItemCompletedEvent  => match (true) {
            $event->item instanceof AgentMessageItem     => printf("%s\n", $event->item->text),
            $event->item instanceof CommandExecutionItem => printf("$ %s\n", $event->item->command),
            $event->item instanceof FileChangeItem       => printf("Files: %d\n", count($event->item->changes)),
            default                                      => null,
        },
        default => null,
    };
}

// Continue the conversation in the same thread
$turn = $thread->run('Now write a test for the fixed code.');
echo $turn->finalResponse;

// Resume the thread in a new session
$resumed = $codex->resumeThread($thread->getId());
$turn = $resumed->run('What did you do last time?');
echo $turn->finalResponse;