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 | ...
}
// 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.'),
]);
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;
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.