Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
OpenAI PHP for Laravel
https://github.com/openai-php/laravel
Admin
A community-maintained PHP API client for Laravel that allows interaction with the OpenAI API,
...
Tokens:
7,349
Snippets:
56
Trust Score:
7.1
Update:
1 month ago
Context
Skills
Chat
Benchmark
70.6
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# OpenAI PHP for Laravel OpenAI PHP for Laravel is a community-maintained PHP API client that provides seamless integration between Laravel applications and the OpenAI API. Built on top of the framework-agnostic `openai-php/client` package, this library offers a clean Laravel Facade interface, automatic service provider registration, and configuration management through environment variables. It requires PHP 8.2+ and supports Laravel 11 and 12. The package provides access to all OpenAI API resources including chat completions, responses, embeddings, images, audio, assistants, threads, vector stores, fine-tuning, and more. It includes a built-in testing system with fake responses for unit testing, making it easy to mock API calls in your test suite without hitting the actual OpenAI servers. ## Installation Install the package via Composer and run the install command to publish the configuration file and set up environment variables. ```bash # Install the package composer require openai-php/laravel # Run the install command to create config/openai.php and add env variables php artisan openai:install ``` ## Configuration The package is configured through environment variables that control API authentication, base URL, and request timeout settings. ```env # Required: Your OpenAI API key OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxx # Optional: Your OpenAI organization ID OPENAI_ORGANIZATION=org-xxxxxxxxxxxx # Optional: Project ID for legacy user API keys OPENAI_PROJECT=proj_xxxxxxxxxxxx # Optional: Custom base URL (defaults to api.openai.com/v1) OPENAI_BASE_URL= # Optional: Request timeout in seconds (defaults to 30) OPENAI_REQUEST_TIMEOUT=60 ``` ## OpenAI::responses()->create() The responses resource provides access to OpenAI's response generation API for creating AI-powered text completions and conversations. ```php use OpenAI\Laravel\Facades\OpenAI; $response = OpenAI::responses()->create([ 'model' => 'gpt-4o', 'input' => 'Explain quantum computing in simple terms.', ]); echo $response->outputText; // Output: Quantum computing uses quantum bits (qubits) that can exist in multiple states... ``` ## OpenAI::chat()->create() The chat resource enables conversational AI interactions with message-based context, supporting system prompts, user messages, and assistant responses. ```php use OpenAI\Laravel\Facades\OpenAI; $response = OpenAI::chat()->create([ 'model' => 'gpt-4o', 'messages' => [ ['role' => 'system', 'content' => 'You are a helpful assistant.'], ['role' => 'user', 'content' => 'What is the capital of France?'], ], ]); echo $response->choices[0]->message->content; // Output: The capital of France is Paris. ``` ## OpenAI::embeddings()->create() The embeddings resource generates vector representations of text for use in semantic search, clustering, and similarity comparisons. ```php use OpenAI\Laravel\Facades\OpenAI; $response = OpenAI::embeddings()->create([ 'model' => 'text-embedding-3-small', 'input' => 'The quick brown fox jumps over the lazy dog.', ]); $vector = $response->embeddings[0]->embedding; // Returns array of 1536 floating-point numbers representing the text echo 'Vector dimension: ' . count($vector); // Output: Vector dimension: 1536 ``` ## OpenAI::images()->create() The images resource generates images from text descriptions using DALL-E models. ```php use OpenAI\Laravel\Facades\OpenAI; $response = OpenAI::images()->create([ 'model' => 'dall-e-3', 'prompt' => 'A serene mountain landscape at sunset with a calm lake reflection', 'n' => 1, 'size' => '1024x1024', ]); $imageUrl = $response->data[0]->url; // Returns URL to the generated image ``` ## OpenAI::audio()->transcribe() The audio resource provides speech-to-text transcription capabilities using Whisper models. ```php use OpenAI\Laravel\Facades\OpenAI; $response = OpenAI::audio()->transcribe([ 'model' => 'whisper-1', 'file' => fopen('/path/to/audio.mp3', 'r'), 'language' => 'en', ]); echo $response->text; // Output: Transcribed text from the audio file... ``` ## OpenAI::audio()->speech() Generate speech audio from text input using text-to-speech models. ```php use OpenAI\Laravel\Facades\OpenAI; $response = OpenAI::audio()->speech([ 'model' => 'tts-1', 'voice' => 'alloy', 'input' => 'Hello! Welcome to our application.', ]); // Save the audio content to a file file_put_contents('/path/to/output.mp3', $response); ``` ## OpenAI::assistants()->create() Create AI assistants with specific instructions and capabilities for building conversational applications. ```php use OpenAI\Laravel\Facades\OpenAI; $assistant = OpenAI::assistants()->create([ 'model' => 'gpt-4o', 'name' => 'Math Tutor', 'instructions' => 'You are a helpful math tutor. Help users solve math problems step by step.', 'tools' => [ ['type' => 'code_interpreter'], ], ]); echo $assistant->id; // Output: asst_abc123... ``` ## OpenAI::threads()->create() and messages Create conversation threads and add messages for stateful assistant interactions. ```php use OpenAI\Laravel\Facades\OpenAI; // Create a new thread $thread = OpenAI::threads()->create([]); $threadId = $thread->id; // Add a message to the thread $message = OpenAI::threads()->messages()->create($threadId, [ 'role' => 'user', 'content' => 'Can you help me solve 2x + 5 = 15?', ]); // Run the assistant on the thread $run = OpenAI::threads()->runs()->create($threadId, [ 'assistant_id' => 'asst_abc123', ]); // Check run status and retrieve messages when complete $run = OpenAI::threads()->runs()->retrieve($threadId, $run->id); echo $run->status; // Output: completed ``` ## OpenAI::files()->upload() Upload files to OpenAI for use with assistants, fine-tuning, or other features. ```php use OpenAI\Laravel\Facades\OpenAI; $file = OpenAI::files()->upload([ 'purpose' => 'assistants', 'file' => fopen('/path/to/document.pdf', 'r'), ]); echo $file->id; // Output: file-abc123... ``` ## OpenAI::models()->list() List all available models in your OpenAI account. ```php use OpenAI\Laravel\Facades\OpenAI; $models = OpenAI::models()->list(); foreach ($models->data as $model) { echo $model->id . "\n"; } // Output: // gpt-4o // gpt-4o-mini // text-embedding-3-small // dall-e-3 // whisper-1 // ... ``` ## OpenAI::moderations()->create() Check text content for potentially harmful or inappropriate material using the moderation endpoint. ```php use OpenAI\Laravel\Facades\OpenAI; $response = OpenAI::moderations()->create([ 'model' => 'text-moderation-latest', 'input' => 'This is a sample text to check for content policy violations.', ]); $result = $response->results[0]; echo $result->flagged ? 'Content flagged' : 'Content is safe'; // Output: Content is safe // Check specific categories foreach ($result->categories as $category => $flagged) { if ($flagged) { echo "Flagged for: $category\n"; } } ``` ## OpenAI::fineTuning()->createJob() Create fine-tuning jobs to customize models with your own training data. ```php use OpenAI\Laravel\Facades\OpenAI; // First upload your training file $trainingFile = OpenAI::files()->upload([ 'purpose' => 'fine-tune', 'file' => fopen('/path/to/training.jsonl', 'r'), ]); // Create a fine-tuning job $job = OpenAI::fineTuning()->createJob([ 'training_file' => $trainingFile->id, 'model' => 'gpt-4o-mini-2024-07-18', ]); echo $job->id; // Output: ftjob-abc123... // Check job status $job = OpenAI::fineTuning()->retrieveJob($job->id); echo $job->status; // Output: running | succeeded | failed ``` ## OpenAI::vectorStores()->create() Create vector stores for storing and searching document embeddings with the Assistants API. ```php use OpenAI\Laravel\Facades\OpenAI; $vectorStore = OpenAI::vectorStores()->create([ 'name' => 'Product Documentation', ]); echo $vectorStore->id; // Output: vs_abc123... // Add files to the vector store OpenAI::vectorStores()->files()->create($vectorStore->id, [ 'file_id' => 'file-abc123', ]); ``` ## Testing with OpenAI::fake() The facade provides a `fake()` method for mocking API responses in your test suite without making actual API calls. ```php use OpenAI\Laravel\Facades\OpenAI; use OpenAI\Responses\Chat\CreateResponse; // Set up fake responses OpenAI::fake([ CreateResponse::fake([ 'choices' => [ [ 'message' => [ 'content' => 'Paris is the capital of France.', ], ], ], ]), ]); // Make API call (returns fake response) $response = OpenAI::chat()->create([ 'model' => 'gpt-4o', 'messages' => [ ['role' => 'user', 'content' => 'What is the capital of France?'], ], ]); echo $response->choices[0]->message->content; // Output: Paris is the capital of France. // Assert the request was made correctly OpenAI::assertSent(\OpenAI\Resources\Chat::class, function ($method, $parameters) { return $method === 'create' && $parameters['model'] === 'gpt-4o'; }); ``` ## Summary OpenAI PHP for Laravel is ideal for building AI-powered Laravel applications including chatbots, content generation systems, document analysis tools, and semantic search features. The package abstracts away the complexity of HTTP requests and authentication, allowing developers to focus on implementing AI features. Common use cases include building customer support bots with the Assistants API, generating product descriptions with chat completions, transcribing audio content, creating image assets, and implementing RAG (Retrieval-Augmented Generation) systems with vector stores. Integration follows standard Laravel patterns with service container binding, facade access, and environment-based configuration. The package can be dependency-injected via the `OpenAI\Contracts\ClientContract` interface or accessed statically through the `OpenAI` facade. Testing is straightforward with the built-in fake system that allows mocking responses and asserting request parameters. The deferred service provider ensures minimal performance impact when the OpenAI client is not being used in a request lifecycle.