Search by

creativecrafts / laravel-ai-assistant

rockblings

A handy package to access and interact with OpenAi endpoint

Package info

github.com/CreativeCrafts/laravel-ai-assistant

Homepage

pkg:composer/creativecrafts/laravel-ai-assistant

Statistics

Installs: 2 339

Dependents: 0

Suggesters: 0

Stars: 14

Open Issues: 0

3.0.31-beta 2025-10-21 09:40 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

The complete OpenAI API for Laravel. A fluent, Laravel-native way to generate text, stream answers, call your own PHP functions as tools, transcribe and diarize audio, create images and videos, search your documents, run batches and fine-tunes, build realtime voice agents and manage your OpenAI organisation.

use CreativeCrafts\LaravelAiAssistant\Facades\Ai;

echo Ai::responses()
    ->model('gpt-5-mini')
    ->input()
    ->message('Explain Laravel queues in two sentences.')
    ->send()
    ->text;

Read the full documentation →

Highlights

  • One fluent builder, Ai::responses(), for text, vision, audio and images, routed to the right endpoint automatically
  • Every OpenAI endpoint: Responses, Conversations, Chat Completions, Audio, Images, Videos (Sora), Embeddings, Files, Uploads, Vector stores, Batches, Fine-tuning, Evals, Realtime, Agents, Skills, Containers, ChatKit, Webhooks and the Administration API
  • Streaming to the CLI, the browser (SSE, Inertia + React) or websockets (Laravel Reverb)
  • Tool calling with plain PHP callables registered in a ToolRegistry
  • Speaker diarization: who spoke when, with named speakers, transcripts and WebVTT captions
  • Production-ready: retries with backoff, idempotency keys, signed webhooks, health checks, observability, caching
  • Testable: every API is a container-bound contract you can mock
  • New OpenAI parameters work without a package update: payloads are passed through untouched

Requirements

PHP 8.2+ and Laravel 10, 11, 12 or 13 (Laravel 13 requires PHP 8.3+). The test suite runs on Laravel 12 and 13.

Installation

composer require creativecrafts/laravel-ai-assistant
php artisan ai:install
OPENAI_API_KEY=sk-...

Check your setup with php artisan ai:test-connection. See Getting started for all options.

Quick start

Text

$response = Ai::responses()
    ->model('gpt-5-mini')
    ->instructions('You are a concise Laravel expert.')
    ->input()
    ->message('When should I use events instead of jobs?')
    ->send();

$response->text;

Structured output

$response = Ai::responses()
    ->model('gpt-5-mini')
    ->responseFormat([
        'type' => 'json_schema',
        'name' => 'invoice',
        'strict' => true,
        'schema' => [
            'type' => 'object',
            'properties' => ['vendor' => ['type' => 'string'], 'total' => ['type' => 'number']],
            'required' => ['vendor', 'total'],
            'additionalProperties' => false,
        ],
    ])
    ->input()
    ->message("Extract the vendor and total:\n" . $invoiceText)
    ->send();

$invoice = json_decode($response->text, true);

Streaming

foreach (Ai::stream('Tell me about Laravel Reverb') as $event) {
    if ($event->type === 'response.output_text.delta') {
        echo $event->data['delta'];
    }
}

The Streaming guide covers streaming to Inertia + React and over Laravel Reverb.

Multi-turn conversations

$conversationId = Ai::conversations()->start(['user_id' => (string) $user->id]);

Ai::responses()->inConversation($conversationId)->model('gpt-5-mini')
    ->input()->message('My name is Ada.')->send();

Ai::responses()->inConversation($conversationId)->model('gpt-5-mini')
    ->input()->message('What is my name?')->send()->text;   // "Your name is Ada."

Tool calling

use CreativeCrafts\LaravelAiAssistant\Services\ToolRegistry;

// AppServiceProvider::boot(): the PHP implementation
app(ToolRegistry::class)->register('get_order_status', fn (array $args) => Order::statusFor($args['order_number']));

// Describe the tool; send() runs the calls the model makes and returns the final answer
$answer = Ai::chat('Where is my order A-1042?')
    ->includeFunctionCallTool('get_order_status', 'Look up an order by number', [
        'properties' => ['order_number' => ['type' => 'string']],
        'required' => ['order_number'],
    ])
    ->send()
    ->text;

More in Tool calling.

Audio

// Speech to text
$text = Ai::responses()->input()
    ->audio(['file' => storage_path('app/meeting.mp3'), 'action' => 'transcribe'])
    ->send()->text;

// Text to speech
Ai::responses()->input()
    ->audio(['text' => 'Your order has shipped!', 'action' => 'speech', 'voice' => 'nova'])
    ->send()->saveAudio(storage_path('app/audio/shipped.mp3'));

// Who spoke when
$call = Ai::diarize(storage_path('app/calls/support.mp3'))
    ->knownSpeaker('agent', storage_path('app/voices/agent.wav'))
    ->send();

$call->speakingShare();   // ['agent' => 61.2, 'A' => 38.8]
$call->toTranscript();

Images and video

Ai::responses()->input()
    ->image(['prompt' => 'A watercolor lighthouse at dawn'])
    ->send()->saveImages(storage_path('app/images'));

$video = Ai::videos()->create(['model' => 'sora-2', 'prompt' => 'A drone shot over Lagos at sunset']);

Embeddings and document search

$vector = Ai::embeddings()->create(['model' => 'text-embedding-3-small', 'input' => 'Refund policy'])['data'][0]['embedding'];

$answer = Ai::chat('How long do refunds take?')
    ->includeFileSearchTool(['vs_help_centre'])
    ->send()
    ->text;

Documentation

Basics Getting started · Core concepts · Configuration
Generating content Responses · Chat sessions & tools · Streaming · Conversations · Chat Completions
Media Audio · Speaker diarization · Images · Videos
Knowledge & data Embeddings & vector stores · Files & uploads · Batches · Fine-tuning & evals · Models & moderation
Realtime & platform Realtime & Live · Agents, skills & containers · Webhooks · Administration
Production Error handling · Testing · Operations · API reference

OpenAI API coverage

Every endpoint is available through a repository on the Ai facade. Methods take the API's JSON body and query parameters as arrays and return the decoded response.

API Accessor Guide
Responses Ai::responses() Responses
Conversations Ai::conversations() Conversations
Chat Completions / Completions Ai::chatCompletions(), Ai::completions() Chat Completions
Embeddings Ai::embeddings() Embeddings
Audio Ai::audio(), Ai::diarize() Audio, Diarization
Images Ai::images() Images
Videos (Sora) Ai::videos() Videos
Models Ai::models() Models
Moderations, Decisions, Content provenance, Safety Ai::moderations(), Ai::decisions(), Ai::contentProvenanceChecks(), Ai::safety() Moderation
Files, Uploads Ai::files(), Ai::uploads() Files
Vector stores Ai::vectorStores(), Ai::vectorStoreFiles(), Ai::vectorStoreFileBatches() Vector stores
Batches Ai::batches() Batches
Fine-tuning, Graders, Evals Ai::fineTuningJobs(), Ai::fineTuningCheckpointPermissions(), Ai::graders(), Ai::evals(), Ai::evalRuns() Fine-tuning & evals
Realtime, Live Ai::realtime(), Ai::realtimeSessions(), Ai::live() Realtime
Agents (beta), Skills, Containers, ChatKit (beta) Ai::agents(), Ai::agentSessions(), Ai::agentEnvironments(), Ai::vaults(), Ai::skills(), Ai::containers(), Ai::containerFiles(), Ai::chatKit() Agents
Webhook endpoints Ai::webhookEndpoints() Webhooks
Administration Ai::admin()->… Administration
Assistants (deprecated) Ai::assistants() OpenAI is shutting it down on August 26, 2026; use Responses + Conversations

Anything newer can be called through the transport directly:

app(\CreativeCrafts\LaravelAiAssistant\Transport\OpenAITransport::class)
    ->request('GET', '/v1/some/new/endpoint', ['query' => ['limit' => 10]]);

Testing

composer test        # Pest
composer analyse     # PHPStan
composer format      # Pint

Integration tests under tests/Integration are skipped unless a valid API key is configured. To fake the package in your own application's tests, see Testing your application.

Upgrading

Contributing

See CONTRIBUTING.md.

License

The MIT License (MIT). See LICENSE.md.