softcreatr / php-openai-sdk
A powerful and easy-to-use PHP SDK for the OpenAI API, allowing seamless integration of advanced AI-powered features into your PHP projects.
Requires
- php: >=8.1
- ext-json: *
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-message: ^1.1 || ^2.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95.27
- guzzlehttp/guzzle: ^7.15.5 || ^8.2.0
- phpstan/phpstan: ^2.3.0
- phpunit/phpunit: ^10.5.66 || ^11.5.57 || ^12.5.38 || ^13.4.1
- vlucas/phpdotenv: ^5.7.0
Suggests
- softcreatr/json-payload-contract: Optional JSON response validation and DTO mapping (PHP 8.3 or newer).
Provides
None
Conflicts
None
Replaces
None
README
A lightweight, underrated PSR-17/PSR-18 client for the current OpenAI API, with examples for every exposed SDK method, SSE streaming, streamed multipart uploads, structured errors, project scoping, endpoint-specific beta headers, and webhook signature verification.
Requirements
- PHP 8.1 or newer. Validation tests PHP 8.1 with the lowest supported dependencies and PHP 8.5 with current dependencies; PHP 8.6 is included as a non-blocking experimental job.
- A PSR-17 request, stream, and URI factory.
- A PSR-18 HTTP client.
- The JSON extension.
Guzzle is used below because it provides both the PSR-17 factories and PSR-18 client implementation. The SDK itself depends only on the PSR interfaces, so other compliant implementations remain supported.
Installation
composer require softcreatr/php-openai-sdk guzzlehttp/guzzle
Client Setup
<?php declare(strict_types=1); require __DIR__ . '/vendor/autoload.php'; use GuzzleHttp\Client; use GuzzleHttp\Psr7\HttpFactory; use SoftCreatR\OpenAI\OpenAI; $factory = new HttpFactory(); $openAI = new OpenAI( requestFactory: $factory, streamFactory: $factory, uriFactory: $factory, httpClient: new Client(['stream' => true]), apiKey: (string) getenv('OPENAI_API_KEY'), organization: (string) getenv('OPENAI_ORGANIZATION_ID'), project: (string) getenv('OPENAI_PROJECT_ID'), );
Keep API keys on the server and out of source control. Organization and project IDs are optional.
Responses API
The Responses API is the default interface for direct model requests, built-in tools, and stateful workflows.
use const JSON_THROW_ON_ERROR; $response = $openAI->createResponse([ 'model' => 'gpt-6-luna', 'input' => 'Give me a one-sentence summary of PSR-18.', ]); $result = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR); foreach ($result['output'] as $item) { foreach ($item['content'] ?? [] as $content) { if (($content['type'] ?? null) === 'output_text') { echo $content['text']; } } }
Endpoint methods return a PSR-7 ResponseInterface, including calls that deliver SSE events to a callback.
To request GPT-6.1 Sol's Ultrafast mode, pass 'service_tier' => 'ultrafast' in the request body. See the
Ultrafast example and check OpenAI's
pricing before choosing this tier.
Agents API
The beta Agents API provides the managed Codex harness, durable sessions, hosted environments, artifacts, subagents,
and vaults. The SDK applies the required OpenAI-Beta: agents=v1 header automatically.
$openAI->createAgentSession( [ 'agent' => [ 'model' => 'gpt-6-astra', 'instructions' => 'Write clean code, run it, and report the actual output.', ], 'environment' => ['type' => 'openai_hosted'], 'input' => 'Create tree.php and use it to print a readable directory tree.', 'stream' => true, ], static function (array $event): void { echo json_encode($event, JSON_THROW_ON_ERROR) . PHP_EOL; }, );
Arguments
Body-only endpoints use a single body array:
$openAI->createEmbedding([ 'model' => 'text-embedding-3-small', 'input' => 'A sentence to embed.', ]);
For endpoints with path parameters, a single combined array is the preferred v4 form. Path fields are separated from the request body using the endpoint template:
$openAI->updateConversation([ 'conversation_id' => 'conv_abc123', 'metadata' => ['customer' => 'acme'], ]);
The v3 two-array form remains supported for existing integrations:
$openAI->updateConversation( ['conversation_id' => 'conv_abc123'], ['metadata' => ['customer' => 'acme']], );
For GET and DELETE methods, non-path values become RFC 3986 query parameters. Path parameter values are URL
encoded. The explicit form is available when method names are determined at runtime:
$response = $openAI->request( 'listFiles', ['limit' => 20, 'after' => 'file_abc123'], customHeaders: ['X-Trace-Id' => 'trace_abc123'], );
Streaming
Set stream to true and pass a callback. The decoder supports arbitrarily split chunks, CRLF and LF delimiters,
comments, multiline data fields, final unterminated frames, and [DONE].
$openAI->createResponse( [ 'model' => 'gpt-6-luna', 'input' => 'Write a short haiku about PHP.', 'stream' => true, ], static function (array $event): void { if ($event['type'] === 'response.output_text.delta') { echo $event['delta']; } }, );
An ordinary JSON response is still returned when a callback is supplied without requesting an SSE stream. Endpoints
that are inherently streaming, such as streamAgentSessionEvents, select a StreamingClientInterface transport
without requiring a body flag.
File Uploads
Multipart endpoints accept readable local file paths. Files are copied as raw bytes into a temporary stream rather than being base64 encoded or assembled in one large PHP string.
$response = $openAI->uploadFile([ 'file' => __DIR__ . '/data.jsonl', 'purpose' => 'user_data', ]);
Repeated upload fields such as image inputs and skill files accept arrays of paths. Nested non-file values are encoded using bracket notation. Multipart fields that are protocol payloads rather than files, such as Realtime SDP, remain ordinary strings.
Errors
4xx and 5xx responses throw OpenAIException. The exception keeps the parsed API error, raw response body, response
headers, status code, and x-request-id for diagnostics.
use SoftCreatR\OpenAI\Exception\OpenAIException; try { $openAI->retrieveModel(['model' => 'missing-model']); } catch (OpenAIException $exception) { error_log(sprintf( 'OpenAI request %s failed (%d): %s', $exception->getRequestId() ?? 'unknown', $exception->getCode(), $exception->getMessage(), )); }
PSR-18 transport failures are wrapped in OpenAIException and retain the original exception as getPrevious().
Response Handling
Endpoint methods return raw PSR-7 responses. Optional wrappers implement ResponseContract and expose
toArray(), getRawBody(), getResponse(), and getRequestId(), as well as JSON serialization. They require PHP 8.1
and add no dependencies.
ModelResponse is a DTO for Responses API model responses. It provides readonly id, model, status, output,
and usage properties, aggregates text from message outputs, and exposes refusals separately:
use SoftCreatR\OpenAI\Response\ModelResponse; $dto = ModelResponse::fromResponse($response); if ($dto->isCompleted()) { echo $dto->getOutputText(); } $refusals = $dto->getRefusals();
The DTO checks common field types but accepts new status strings, output types, and response properties. The original
payload remains available through toArray() and getRawBody(). Missing or null status and usage are preserved as
null. See the live DTO example.
JsonResponse wraps any JSON object or array response. Its map() method passes decoded data to your DTO factory;
mapJson() passes the exact original JSON to a validator or mapper. Seekable response streams retain their original
position. Non-seekable streams are consumed: wrap them before reading, then use the captured getRawBody(). If you
already captured a body, use JsonResponse::fromJson($rawBody, $response) to avoid reading the stream again. Invalid
JSON throws JsonException; invalid wrapper or DTO input throws InvalidArgumentException.
Optional Payload Contracts
JSONPayloadContract can validate and normalize selected fields before constructing application DTOs. Install it explicitly on PHP 8.3 or newer:
composer require softcreatr/json-payload-contract:^1.0
use SoftCreatR\JsonPayloadContract\Contract; use SoftCreatR\JsonPayloadContract\Field; use SoftCreatR\OpenAI\Response\JsonResponse; $contract = Contract::define([ 'responseId' => Field::required('$.id')->string(), 'textParts' => Field::many( '$.output[?(@.type == "message")].content[?(@.type == "output_text")].text', )->string(), ]); $data = JsonResponse::fromResponse($response)->mapJson($contract->applyJson(...));
Using raw JSON lets the contract distinguish objects from arrays and detect duplicate object members. Pass
$contract->extractJson(...) instead to receive a diagnostic Result without throwing for invalid payloads. The
fixture-based contract example also validates generated
JSON and constructs an application DTO without making an API request.
HTTP error handling, SSE JSON decoding, and webhook signature verification remain independent of these wrappers.
Apply application schemas and business rules explicitly. For model-generated JSON, use
Structured Outputs and handle refusals and
incomplete responses before using the generated data. Streaming callbacks remain plain event arrays; contracts can
be applied to selected events with apply() or extract().
Webhooks
Verify the signature against the exact raw request body before decoding or changing it. The verifier follows OpenAI's
webhook guide and supports multiple v1 signatures during
secret rotation.
use SoftCreatR\OpenAI\Webhook\WebhookVerifier; $rawBody = (string) $request->getBody(); $event = (new WebhookVerifier((string) getenv('OPENAI_WEBHOOK_SECRET'))) ->unwrap($rawBody, $request->getHeaders()); if ($event['type'] === 'response.completed') { // Handle the completed response idempotently. }
The default replay tolerance is 300 seconds. Invalid signatures throw InvalidWebhookSignatureException; valid
signatures with invalid JSON throw WebhookException. The Webhooks methods in the endpoint catalog manage project
webhook endpoints, rotate their signing secrets, and send test events.
Examples
Examples load the ignored project-level .env through examples/OpenAIFactory.php:
cp .env.example .env php examples/responses/createResponse.php
Set OPENAI_ADMIN_KEY only when running examples under examples/administration. The Agents vault credential examples
also read MCP_BEARER_TOKEN; the vault update example accepts OPENAI_VAULT_ID. Workload identity examples use their
dedicated identity variables; X.509 examples also require OPENAI_CLIENT_CERT and OPENAI_CLIENT_KEY. Keep all
secrets in .env and never commit it.
Supported Methods
The catalog follows the current OpenAI API reference. Evals and fine-tuning are retained for transitional compatibility and are marked deprecated. Removed APIs and the legacy Completions, Assistants, and Realtime beta session-token routes are intentionally absent. Distinct beta routes are registered separately from their stable counterparts.
Administration
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
activateCertificates |
POST /organization/certificates/activate |
json |
PHP |
activateProjectCertificates |
POST /organization/projects/{project_id}/certificates/activate |
json |
PHP |
addGroupUser |
POST /organization/groups/{group_id}/users |
json |
PHP |
addProjectGroup |
POST /organization/projects/{project_id}/groups |
json |
PHP |
archiveProject |
POST /organization/projects/{project_id}/archive |
none |
PHP |
assignGroupRole |
POST /organization/groups/{group_id}/roles |
json |
PHP |
assignProjectGroupRole |
POST /projects/{project_id}/groups/{group_id}/roles |
json |
PHP |
assignProjectUserRole |
POST /projects/{project_id}/users/{user_id}/roles |
json |
PHP |
assignUserRole |
POST /organization/users/{user_id}/roles |
json |
PHP |
createAdminApiKey |
POST /organization/admin_api_keys |
json |
PHP |
createExternalStorage |
POST /organization/external_storage |
json |
PHP |
createGroup |
POST /organization/groups |
json |
PHP |
createInvite |
POST /organization/invites |
json |
PHP |
createOrganizationRole |
POST /organization/roles |
json |
PHP |
createOrganizationSpendAlert |
POST /organization/spend_alerts |
json |
PHP |
createProject |
POST /organization/projects |
json |
PHP |
createProjectRole |
POST /projects/{project_id}/roles |
json |
PHP |
createProjectServiceAccount |
POST /organization/projects/{project_id}/service_accounts |
json |
PHP |
createProjectServiceAccountApiKey |
POST /organization/projects/{project_id}/service_accounts/{service_account_id}/api_keys |
json |
PHP |
createProjectSpendAlert |
POST /organization/projects/{project_id}/spend_alerts |
json |
PHP |
createProjectUser |
POST /organization/projects/{project_id}/users |
json |
PHP |
deactivateCertificates |
POST /organization/certificates/deactivate |
json |
PHP |
deactivateProjectCertificates |
POST /organization/projects/{project_id}/certificates/deactivate |
json |
PHP |
deleteAdminApiKey |
DELETE /organization/admin_api_keys/{key_id} |
none |
PHP |
deleteCertificate |
DELETE /organization/certificates/{certificate_id} |
none |
PHP |
deleteExternalStorage |
DELETE /organization/external_storage/{external_storage_id} |
none |
PHP |
deleteGroup |
DELETE /organization/groups/{group_id} |
none |
PHP |
deleteInvite |
DELETE /organization/invites/{invite_id} |
none |
PHP |
deleteOrganizationRole |
DELETE /organization/roles/{role_id} |
none |
PHP |
deleteOrganizationSpendAlert |
DELETE /organization/spend_alerts/{alert_id} |
none |
PHP |
deleteOrganizationSpendLimit |
DELETE /organization/spend_limit |
none |
PHP |
deleteProjectApiKey |
DELETE /organization/projects/{project_id}/api_keys/{api_key_id} |
none |
PHP |
deleteProjectModelPermissions |
DELETE /organization/projects/{project_id}/model_permissions |
none |
PHP |
deleteProjectRole |
DELETE /projects/{project_id}/roles/{role_id} |
none |
PHP |
deleteProjectServiceAccount |
DELETE /organization/projects/{project_id}/service_accounts/{service_account_id} |
none |
PHP |
deleteProjectSpendAlert |
DELETE /organization/projects/{project_id}/spend_alerts/{alert_id} |
none |
PHP |
deleteProjectSpendLimit |
DELETE /organization/projects/{project_id}/spend_limit |
none |
PHP |
deleteProjectUser |
DELETE /organization/projects/{project_id}/users/{user_id} |
none |
PHP |
deleteUser |
DELETE /organization/users/{user_id} |
none |
PHP |
getAudioSpeechesUsage |
GET /organization/usage/audio_speeches |
none |
PHP |
getAudioTranscriptionsUsage |
GET /organization/usage/audio_transcriptions |
none |
PHP |
getCertificate |
GET /organization/certificates/{certificate_id} |
none |
PHP |
getCodeInterpreterSessionsUsage |
GET /organization/usage/code_interpreter_sessions |
none |
PHP |
getCompletionsUsage |
GET /organization/usage/completions |
none |
PHP |
getCosts |
GET /organization/costs |
none |
PHP |
getDecisionsUsage |
GET /organization/usage/decisions |
none |
PHP |
getEmbeddingsUsage |
GET /organization/usage/embeddings |
none |
PHP |
getFileSearchCallsUsage |
GET /organization/usage/file_search_calls |
none |
PHP |
getImagesUsage |
GET /organization/usage/images |
none |
PHP |
getModerationsUsage |
GET /organization/usage/moderations |
none |
PHP |
getVectorStoresUsage |
GET /organization/usage/vector_stores |
none |
PHP |
getWebSearchCallsUsage |
GET /organization/usage/web_search_calls |
none |
PHP |
listAdminApiKeys |
GET /organization/admin_api_keys |
none |
PHP |
listAuditLogs |
GET /organization/audit_logs |
none |
PHP |
listCertificates |
GET /organization/certificates |
none |
PHP |
listExternalStorage |
GET /organization/external_storage |
none |
PHP |
listGroupRoles |
GET /organization/groups/{group_id}/roles |
none |
PHP |
listGroupUsers |
GET /organization/groups/{group_id}/users |
none |
PHP |
listGroups |
GET /organization/groups |
none |
PHP |
listInvites |
GET /organization/invites |
none |
PHP |
listOrganizationRoles |
GET /organization/roles |
none |
PHP |
listOrganizationSpendAlerts |
GET /organization/spend_alerts |
none |
PHP |
listProjectApiKeys |
GET /organization/projects/{project_id}/api_keys |
none |
PHP |
listProjectCertificates |
GET /organization/projects/{project_id}/certificates |
none |
PHP |
listProjectGroupRoles |
GET /projects/{project_id}/groups/{group_id}/roles |
none |
PHP |
listProjectGroups |
GET /organization/projects/{project_id}/groups |
none |
PHP |
listProjectRateLimits |
GET /organization/projects/{project_id}/rate_limits |
none |
PHP |
listProjectRoles |
GET /projects/{project_id}/roles |
none |
PHP |
listProjectServiceAccounts |
GET /organization/projects/{project_id}/service_accounts |
none |
PHP |
listProjectSpendAlerts |
GET /organization/projects/{project_id}/spend_alerts |
none |
PHP |
listProjectUserRoles |
GET /projects/{project_id}/users/{user_id}/roles |
none |
PHP |
listProjectUsers |
GET /organization/projects/{project_id}/users |
none |
PHP |
listProjects |
GET /organization/projects |
none |
PHP |
listUserRoles |
GET /organization/users/{user_id}/roles |
none |
PHP |
listUsers |
GET /organization/users |
none |
PHP |
modifyCertificate |
POST /organization/certificates/{certificate_id} |
json |
PHP |
modifyProject |
POST /organization/projects/{project_id} |
json |
PHP |
modifyProjectHostedToolPermissions |
POST /organization/projects/{project_id}/hosted_tool_permissions |
json |
PHP |
modifyProjectModelPermissions |
POST /organization/projects/{project_id}/model_permissions |
json |
PHP |
modifyProjectRateLimit |
POST /organization/projects/{project_id}/rate_limits/{rate_limit_id} |
json |
PHP |
modifyProjectUser |
POST /organization/projects/{project_id}/users/{user_id} |
json |
PHP |
modifyUser |
POST /organization/users/{user_id} |
json |
PHP |
removeGroupUser |
DELETE /organization/groups/{group_id}/users/{user_id} |
none |
PHP |
removeProjectGroup |
DELETE /organization/projects/{project_id}/groups/{group_id} |
none |
PHP |
retrieveAdminApiKey |
GET /organization/admin_api_keys/{key_id} |
none |
PHP |
retrieveExternalStorage |
GET /organization/external_storage/{external_storage_id} |
none |
PHP |
retrieveGroup |
GET /organization/groups/{group_id} |
none |
PHP |
retrieveGroupRole |
GET /organization/groups/{group_id}/roles/{role_id} |
none |
PHP |
retrieveGroupUser |
GET /organization/groups/{group_id}/users/{user_id} |
none |
PHP |
retrieveInvite |
GET /organization/invites/{invite_id} |
none |
PHP |
retrieveOrganizationDataRetention |
GET /organization/data_retention |
none |
PHP |
retrieveOrganizationRole |
GET /organization/roles/{role_id} |
none |
PHP |
retrieveOrganizationSpendAlert |
GET /organization/spend_alerts/{alert_id} |
none |
PHP |
retrieveOrganizationSpendLimit |
GET /organization/spend_limit |
none |
PHP |
retrieveProject |
GET /organization/projects/{project_id} |
none |
PHP |
retrieveProjectApiKey |
GET /organization/projects/{project_id}/api_keys/{api_key_id} |
none |
PHP |
retrieveProjectDataRetention |
GET /organization/projects/{project_id}/data_retention |
none |
PHP |
retrieveProjectGroup |
GET /organization/projects/{project_id}/groups/{group_id} |
none |
PHP |
retrieveProjectGroupRole |
GET /projects/{project_id}/groups/{group_id}/roles/{role_id} |
none |
PHP |
retrieveProjectHostedToolPermissions |
GET /organization/projects/{project_id}/hosted_tool_permissions |
none |
PHP |
retrieveProjectModelPermissions |
GET /organization/projects/{project_id}/model_permissions |
none |
PHP |
retrieveProjectRole |
GET /projects/{project_id}/roles/{role_id} |
none |
PHP |
retrieveProjectServiceAccount |
GET /organization/projects/{project_id}/service_accounts/{service_account_id} |
none |
PHP |
retrieveProjectSpendAlert |
GET /organization/projects/{project_id}/spend_alerts/{alert_id} |
none |
PHP |
retrieveProjectSpendLimit |
GET /organization/projects/{project_id}/spend_limit |
none |
PHP |
retrieveProjectUser |
GET /organization/projects/{project_id}/users/{user_id} |
none |
PHP |
retrieveProjectUserRole |
GET /projects/{project_id}/users/{user_id}/roles/{role_id} |
none |
PHP |
retrieveUser |
GET /organization/users/{user_id} |
none |
PHP |
retrieveUserRole |
GET /organization/users/{user_id}/roles/{role_id} |
none |
PHP |
unassignGroupRole |
DELETE /organization/groups/{group_id}/roles/{role_id} |
none |
PHP |
unassignProjectGroupRole |
DELETE /projects/{project_id}/groups/{group_id}/roles/{role_id} |
none |
PHP |
unassignProjectUserRole |
DELETE /projects/{project_id}/users/{user_id}/roles/{role_id} |
none |
PHP |
unassignUserRole |
DELETE /organization/users/{user_id}/roles/{role_id} |
none |
PHP |
updateGroup |
POST /organization/groups/{group_id} |
json |
PHP |
updateOrganizationDataRetention |
POST /organization/data_retention |
json |
PHP |
updateOrganizationRole |
POST /organization/roles/{role_id} |
json |
PHP |
updateOrganizationSpendAlert |
POST /organization/spend_alerts/{alert_id} |
json |
PHP |
updateOrganizationSpendLimit |
POST /organization/spend_limit |
json |
PHP |
updateProjectDataRetention |
POST /organization/projects/{project_id}/data_retention |
json |
PHP |
updateProjectRole |
POST /projects/{project_id}/roles/{role_id} |
json |
PHP |
updateProjectServiceAccount |
POST /organization/projects/{project_id}/service_accounts/{service_account_id} |
json |
PHP |
updateProjectSpendAlert |
POST /organization/projects/{project_id}/spend_alerts/{alert_id} |
json |
PHP |
updateProjectSpendLimit |
POST /organization/projects/{project_id}/spend_limit |
json |
PHP |
uploadCertificate |
POST /organization/certificates |
json |
PHP |
validateExternalStorage |
POST /organization/external_storage/{external_storage_id}/validate |
none |
PHP |
Agents (Beta)
The SDK automatically sends the required OpenAI-Beta: agents=v1 header for these endpoints.
Creating and listing prewarmed environments requires access to the Agents prewarming beta.
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createAgent |
POST /agents |
json |
PHP |
createAgentEnvironment |
POST /agents/environments |
json |
PHP |
createAgentEnvironmentFile |
POST /agents/environments/{environment_id}/files |
json |
PHP |
createAgentEnvironmentTemplate |
POST /agents/environments/templates |
json |
PHP |
createAgentSession |
POST /agents/sessions |
json |
PHP |
createAgentSessionEvents |
POST /agents/sessions/{session_id}/events |
json |
PHP |
createVault |
POST /vaults |
json |
PHP |
createVaultCredential |
POST /vaults/{vault_id}/credentials |
json |
PHP |
deleteAgent |
DELETE /agents/{agent_id} |
none |
PHP |
deleteAgentEnvironmentTemplate |
DELETE /agents/environments/templates/{environment_template_id} |
none |
PHP |
deleteAgentSession |
DELETE /agents/sessions/{session_id} |
none |
PHP |
deleteAgentSessionArtifact |
DELETE /agents/sessions/{session_id}/artifacts/{artifact_id} |
none |
PHP |
deleteVault |
DELETE /vaults/{vault_id} |
none |
PHP |
deleteVaultCredential |
DELETE /vaults/{vault_id}/credentials/{credential_id} |
none |
PHP |
listAgentEnvironmentFiles |
GET /agents/environments/{environment_id}/files |
none |
PHP |
listAgentEnvironmentTemplates |
GET /agents/environments/templates |
none |
PHP |
listAgentEnvironments |
GET /agents/environments |
none |
PHP |
listAgentSessionArtifacts |
GET /agents/sessions/{session_id}/artifacts |
none |
PHP |
listAgentSessionItems |
GET /agents/sessions/{session_id}/items |
none |
PHP |
listAgentSessionSubagentItems |
GET /agents/sessions/{session_id}/subagents/{subagent_id}/items |
none |
PHP |
listAgentSessionSubagentTurnItems |
GET /agents/sessions/{session_id}/subagents/{subagent_id}/turns/{turn_id}/items |
none |
PHP |
listAgentSessionSubagentTurns |
GET /agents/sessions/{session_id}/subagents/{subagent_id}/turns |
none |
PHP |
listAgentSessionSubagents |
GET /agents/sessions/{session_id}/subagents |
none |
PHP |
listAgentSessionTraces |
GET /agents/sessions/{session_id}/traces |
none |
PHP |
listAgentSessionTurnItems |
GET /agents/sessions/{session_id}/turns/{turn_id}/items |
none |
PHP |
listAgentSessionTurns |
GET /agents/sessions/{session_id}/turns |
none |
PHP |
listAgentSessions |
GET /agents/sessions |
none |
PHP |
listAgents |
GET /agents |
none |
PHP |
listVaultCredentials |
GET /vaults/{vault_id}/credentials |
none |
PHP |
listVaults |
GET /vaults |
none |
PHP |
retrieveAgent |
GET /agents/{agent_id} |
none |
PHP |
retrieveAgentEnvironment |
GET /agents/environments/{environment_id} |
none |
PHP |
retrieveAgentEnvironmentTemplate |
GET /agents/environments/templates/{environment_template_id} |
none |
PHP |
retrieveAgentSession |
GET /agents/sessions/{session_id} |
none |
PHP |
retrieveAgentSessionArtifact |
GET /agents/sessions/{session_id}/artifacts/{artifact_id} |
none |
PHP |
retrieveAgentSessionArtifactContent |
GET /agents/sessions/{session_id}/artifacts/{artifact_id}/content |
none |
PHP |
retrieveAgentSessionSubagent |
GET /agents/sessions/{session_id}/subagents/{subagent_id} |
none |
PHP |
retrieveAgentSessionSubagentTurn |
GET /agents/sessions/{session_id}/subagents/{subagent_id}/turns/{turn_id} |
none |
PHP |
retrieveAgentSessionTurn |
GET /agents/sessions/{session_id}/turns/{turn_id} |
none |
PHP |
retrieveVault |
GET /vaults/{vault_id} |
none |
PHP |
retrieveVaultCredential |
GET /vaults/{vault_id}/credentials/{credential_id} |
none |
PHP |
rotateVaultCredential |
POST /vaults/{vault_id}/credentials/{credential_id} |
json |
PHP |
streamAgentSessionEvents |
GET /agents/sessions/{session_id}/events |
none |
PHP |
updateAgent |
POST /agents/{agent_id} |
json |
PHP |
updateAgentEnvironmentTemplate |
POST /agents/environments/templates/{environment_template_id} |
json |
PHP |
updateAgentSession |
POST /agents/sessions/{session_id} |
json |
PHP |
updateVault |
POST /vaults/{vault_id} |
json |
PHP |
Audio
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createSpeech |
POST /audio/speech |
json |
PHP |
createTranscription |
POST /audio/transcriptions |
multipart |
PHP |
createTranslation |
POST /audio/translations |
multipart |
PHP |
createVoice |
POST /audio/voices |
multipart |
PHP |
createVoiceConsent |
POST /audio/voice_consents |
multipart |
PHP |
deleteVoiceConsent |
DELETE /audio/voice_consents/{consent_id} |
none |
PHP |
listVoiceConsents |
GET /audio/voice_consents |
none |
PHP |
retrieveVoiceConsent |
GET /audio/voice_consents/{consent_id} |
none |
PHP |
updateVoiceConsent |
POST /audio/voice_consents/{consent_id} |
json |
PHP |
Batches
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
cancelBatch |
POST /batches/{batch_id}/cancel |
none |
PHP |
createBatch |
POST /batches |
json |
PHP |
listBatches |
GET /batches |
none |
PHP |
retrieveBatch |
GET /batches/{batch_id} |
none |
PHP |
Chat Completions
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createChatCompletion |
POST /chat/completions |
json |
PHP |
deleteChatCompletion |
DELETE /chat/completions/{completion_id} |
none |
PHP |
getChatCompletion |
GET /chat/completions/{completion_id} |
none |
PHP |
getChatMessages |
GET /chat/completions/{completion_id}/messages |
none |
PHP |
listChatCompletions |
GET /chat/completions |
none |
PHP |
updateChatCompletion |
POST /chat/completions/{completion_id} |
json |
PHP |
ChatKit
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
cancelChatKitSession |
POST /chatkit/sessions/{session_id}/cancel |
none |
PHP |
createChatKitSession |
POST /chatkit/sessions |
json |
PHP |
deleteChatKitThread |
DELETE /chatkit/threads/{thread_id} |
none |
PHP |
listChatKitThreadItems |
GET /chatkit/threads/{thread_id}/items |
none |
PHP |
listChatKitThreads |
GET /chatkit/threads |
none |
PHP |
retrieveChatKitThread |
GET /chatkit/threads/{thread_id} |
none |
PHP |
Containers
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createContainer |
POST /containers |
json |
PHP |
createContainerFile |
POST /containers/{container_id}/files |
multipart |
PHP |
deleteContainer |
DELETE /containers/{container_id} |
none |
PHP |
deleteContainerFile |
DELETE /containers/{container_id}/files/{file_id} |
none |
PHP |
listContainerFiles |
GET /containers/{container_id}/files |
none |
PHP |
listContainers |
GET /containers |
none |
PHP |
retrieveContainer |
GET /containers/{container_id} |
none |
PHP |
retrieveContainerFile |
GET /containers/{container_id}/files/{file_id} |
none |
PHP |
retrieveContainerFileContent |
GET /containers/{container_id}/files/{file_id}/content |
none |
PHP |
Content Provenance
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createContentProvenanceCheck |
POST /content_provenance_checks |
multipart |
PHP |
Conversations
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createConversation |
POST /conversations |
json |
PHP |
createConversationItems |
POST /conversations/{conversation_id}/items |
json |
PHP |
deleteConversation |
DELETE /conversations/{conversation_id} |
none |
PHP |
deleteConversationItem |
DELETE /conversations/{conversation_id}/items/{item_id} |
none |
PHP |
listConversationItems |
GET /conversations/{conversation_id}/items |
none |
PHP |
retrieveConversation |
GET /conversations/{conversation_id} |
none |
PHP |
retrieveConversationItem |
GET /conversations/{conversation_id}/items/{item_id} |
none |
PHP |
updateConversation |
POST /conversations/{conversation_id} |
json |
PHP |
Decisions
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createDecision |
POST /decisions |
json |
PHP |
Embeddings
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createEmbedding |
POST /embeddings |
json |
PHP |
Evals (Deprecated)
The Evals API becomes read-only on October 31, 2026 and is scheduled to shut down on November 30, 2026. These methods remain callable for transitional compatibility until shutdown.
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
cancelEvalRun (deprecated) |
POST /evals/{eval_id}/runs/{run_id}/cancel |
none |
PHP |
createEval (deprecated) |
POST /evals |
json |
PHP |
createEvalRun (deprecated) |
POST /evals/{eval_id}/runs |
json |
PHP |
deleteEval (deprecated) |
DELETE /evals/{eval_id} |
none |
PHP |
deleteEvalRun (deprecated) |
DELETE /evals/{eval_id}/runs/{run_id} |
none |
PHP |
listEvalRunOutputItems (deprecated) |
GET /evals/{eval_id}/runs/{run_id}/output_items |
none |
PHP |
listEvalRuns (deprecated) |
GET /evals/{eval_id}/runs |
none |
PHP |
listEvals (deprecated) |
GET /evals |
none |
PHP |
retrieveEval (deprecated) |
GET /evals/{eval_id} |
none |
PHP |
retrieveEvalRun (deprecated) |
GET /evals/{eval_id}/runs/{run_id} |
none |
PHP |
retrieveEvalRunOutputItem (deprecated) |
GET /evals/{eval_id}/runs/{run_id}/output_items/{output_item_id} |
none |
PHP |
updateEval (deprecated) |
POST /evals/{eval_id} |
json |
PHP |
Files
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
deleteFile |
DELETE /files/{file_id} |
none |
PHP |
listFiles |
GET /files |
none |
PHP |
retrieveFile |
GET /files/{file_id} |
none |
PHP |
retrieveFileContent |
GET /files/{file_id}/content |
none |
PHP |
uploadFile |
POST /files |
multipart |
PHP |
Fine-Tuning (Deprecated)
These routes remain available for transitional compatibility and are deprecated upstream.
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
cancelFineTuning (deprecated) |
POST /fine_tuning/jobs/{fine_tuning_job_id}/cancel |
none |
PHP |
createFineTuningCheckpointPermission (deprecated) |
POST /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions |
json |
PHP |
createFineTuningJob (deprecated) |
POST /fine_tuning/jobs |
json |
PHP |
deleteFineTuningCheckpointPermission (deprecated) |
DELETE /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id} |
none |
PHP |
listFineTuningCheckpointPermissions (deprecated) |
GET /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions |
none |
PHP |
listFineTuningCheckpoints (deprecated) |
GET /fine_tuning/jobs/{fine_tuning_job_id}/checkpoints |
none |
PHP |
listFineTuningEvents (deprecated) |
GET /fine_tuning/jobs/{fine_tuning_job_id}/events |
none |
PHP |
listFineTuningJobs (deprecated) |
GET /fine_tuning/jobs |
none |
PHP |
pauseFineTuning (deprecated) |
POST /fine_tuning/jobs/{fine_tuning_job_id}/pause |
none |
PHP |
resumeFineTuning (deprecated) |
POST /fine_tuning/jobs/{fine_tuning_job_id}/resume |
none |
PHP |
retrieveFineTuningJob (deprecated) |
GET /fine_tuning/jobs/{fine_tuning_job_id} |
none |
PHP |
runFineTuningGrader (deprecated) |
POST /fine_tuning/alpha/graders/run |
json |
PHP |
validateFineTuningGrader (deprecated) |
POST /fine_tuning/alpha/graders/validate |
json |
PHP |
Images
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createImage |
POST /images/generations |
json |
PHP |
createImageEdit |
POST /images/edits |
multipart |
PHP |
Live
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
acceptLiveSession |
POST /live/sessions/{session_id}/accept |
json |
PHP |
createLiveSession |
POST /live/sessions |
json |
PHP |
downloadLiveSessionRecording |
GET /live/sessions/{session_id}/content |
none |
PHP |
forkLiveSession |
POST /live/sessions/{session_id}/fork |
json |
PHP |
hangupLiveSession |
POST /live/sessions/{session_id}/hangup |
none |
PHP |
referLiveSession |
POST /live/sessions/{session_id}/refer |
json |
PHP |
rejectLiveSession |
POST /live/sessions/{session_id}/reject |
json |
PHP |
Models
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
deleteModel |
DELETE /models/{model} |
none |
PHP |
listModels |
GET /models |
none |
PHP |
retrieveModel |
GET /models/{model} |
none |
PHP |
Moderations
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createModeration |
POST /moderations |
json |
PHP |
Realtime
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
acceptRealtimeCall |
POST /realtime/calls/{call_id}/accept |
json |
PHP |
createRealtimeCall |
POST /realtime/calls |
multipart |
PHP |
createRealtimeClientSecret |
POST /realtime/client_secrets |
json |
PHP |
createRealtimeTranslationClientSecret |
POST /realtime/translations/client_secrets |
json |
PHP |
hangupRealtimeCall |
POST /realtime/calls/{call_id}/hangup |
none |
PHP |
referRealtimeCall |
POST /realtime/calls/{call_id}/refer |
json |
PHP |
rejectRealtimeCall |
POST /realtime/calls/{call_id}/reject |
json |
PHP |
Responses
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
cancelResponse |
POST /responses/{response_id}/cancel |
none |
PHP |
compactResponse |
POST /responses/compact |
json |
PHP |
countResponseInputTokens |
POST /responses/input_tokens |
json |
PHP |
createResponse |
POST /responses |
json |
PHP |
deleteResponse |
DELETE /responses/{response_id} |
none |
PHP |
getResponse |
GET /responses/{response_id} |
none |
PHP |
listInputItems |
GET /responses/{response_id}/input_items |
none |
PHP |
Responses (Beta Schema)
These methods select the distinct beta schema by adding ?beta=true; stable Responses methods are unchanged.
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
cancelBetaResponse |
POST /responses/{response_id}/cancel?beta=true |
none |
PHP |
compactBetaResponse |
POST /responses/compact?beta=true |
json |
PHP |
countBetaResponseInputTokens |
POST /responses/input_tokens?beta=true |
json |
PHP |
createBetaResponse |
POST /responses?beta=true |
json |
PHP |
deleteBetaResponse |
DELETE /responses/{response_id}?beta=true |
none |
PHP |
getBetaResponse |
GET /responses/{response_id}?beta=true |
none |
PHP |
listBetaResponseInputItems |
GET /responses/{response_id}/input_items?beta=true |
none |
PHP |
Safety
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
retrieveSafetyAlert |
GET /safety/alerts/{id} |
none |
PHP |
retrieveSafetyCase |
GET /safety/cases/{id} |
none |
PHP |
Skills
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createSkill |
POST /skills |
multipart |
PHP |
createSkillVersion |
POST /skills/{skill_id}/versions |
multipart |
PHP |
deleteSkill |
DELETE /skills/{skill_id} |
none |
PHP |
deleteSkillVersion |
DELETE /skills/{skill_id}/versions/{version} |
none |
PHP |
listSkillVersions |
GET /skills/{skill_id}/versions |
none |
PHP |
listSkills |
GET /skills |
none |
PHP |
retrieveSkill |
GET /skills/{skill_id} |
none |
PHP |
retrieveSkillContent |
GET /skills/{skill_id}/content |
none |
PHP |
retrieveSkillVersion |
GET /skills/{skill_id}/versions/{version} |
none |
PHP |
retrieveSkillVersionContent |
GET /skills/{skill_id}/versions/{version}/content |
none |
PHP |
updateSkill |
POST /skills/{skill_id} |
json |
PHP |
Uploads
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
addUploadPart |
POST /uploads/{upload_id}/parts |
multipart |
PHP |
cancelUpload |
POST /uploads/{upload_id}/cancel |
none |
PHP |
completeUpload |
POST /uploads/{upload_id}/complete |
json |
PHP |
createUpload |
POST /uploads |
json |
PHP |
Vector Stores
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
cancelVectorStoreFileBatch |
POST /vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel |
none |
PHP |
createVectorStore |
POST /vector_stores |
json |
PHP |
createVectorStoreFile |
POST /vector_stores/{vector_store_id}/files |
json |
PHP |
createVectorStoreFileBatch |
POST /vector_stores/{vector_store_id}/file_batches |
json |
PHP |
deleteVectorStore |
DELETE /vector_stores/{vector_store_id} |
none |
PHP |
deleteVectorStoreFile |
DELETE /vector_stores/{vector_store_id}/files/{file_id} |
none |
PHP |
listVectorStoreFiles |
GET /vector_stores/{vector_store_id}/files |
none |
PHP |
listVectorStoreFilesInBatch |
GET /vector_stores/{vector_store_id}/file_batches/{batch_id}/files |
none |
PHP |
listVectorStores |
GET /vector_stores |
none |
PHP |
modifyVectorStore |
POST /vector_stores/{vector_store_id} |
json |
PHP |
retrieveVectorStore |
GET /vector_stores/{vector_store_id} |
none |
PHP |
retrieveVectorStoreFile |
GET /vector_stores/{vector_store_id}/files/{file_id} |
none |
PHP |
retrieveVectorStoreFileBatch |
GET /vector_stores/{vector_store_id}/file_batches/{batch_id} |
none |
PHP |
retrieveVectorStoreFileContent |
GET /vector_stores/{vector_store_id}/files/{file_id}/content |
none |
PHP |
searchVectorStore |
POST /vector_stores/{vector_store_id}/search |
json |
PHP |
updateVectorStoreFileAttributes |
POST /vector_stores/{vector_store_id}/files/{file_id} |
json |
PHP |
Webhooks
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
createWebhookEndpoint |
POST /webhook_endpoints |
json |
PHP |
deleteWebhookEndpoint |
DELETE /webhook_endpoints/{webhook_endpoint_id} |
none |
PHP |
listWebhookEndpoints |
GET /webhook_endpoints |
none |
PHP |
listWebhookEventTypes |
GET /webhook_event_types |
none |
PHP |
retrieveWebhookEndpoint |
GET /webhook_endpoints/{webhook_endpoint_id} |
none |
PHP |
rotateWebhookEndpointSecret |
POST /webhook_endpoints/{webhook_endpoint_id}/rotate_secret |
json |
PHP |
testWebhookEndpoint |
POST /webhook_endpoints/{webhook_endpoint_id}/test |
json |
PHP |
updateWebhookEndpoint |
POST /webhook_endpoints/{webhook_endpoint_id} |
json |
PHP |
Workload Identity Federation
| SDK method | HTTP route | Request body | Example |
|---|---|---|---|
exchangeWorkloadIdentityToken |
POST https://auth.openai.com/oauth/token |
json |
PHP |
exchangeX509WorkloadIdentityToken |
POST https://mtls.auth.openai.com/oauth/token |
json |
PHP |
Custom API Origin
origin accepts either a hostname or an absolute base URL. A hostname uses /v1; an absolute URL keeps its path unless
basePath is supplied explicitly.
$openAI = new OpenAI( requestFactory: $factory, streamFactory: $factory, uriFactory: $factory, httpClient: new Client(['stream' => true]), apiKey: (string) getenv('OPENAI_API_KEY'), origin: 'https://gateway.example/openai/v1', );
Deprecated And Removed APIs
The SDK deliberately does not expose APIs that OpenAI classifies as legacy or has removed: classic Completions, Assistants/Threads/Runs/Messages, deprecated Realtime session-token routes, DALL-E image variations, and the Videos API. Use Responses and Conversations instead of Assistants, and Realtime client-secret methods instead of the old session-token routes.
The self-serve fine-tuning routes remain temporarily available and are marked deprecated because eligible existing customers can still use them during OpenAI's transition. Evals methods are also marked deprecated: the platform becomes read-only on October 31, 2026 and shuts down on November 30, 2026. See OpenAI's deprecation schedule and the migration notes before upgrading.
Development
composer test
composer analyse
vendor/bin/php-cs-fixer fix --dry-run --diff
composer audit