Introduction
Laravel AI SDK provides a unified, expressive API for interacting with AI providers such as OpenAI, Anthropic, Gemini, and more. With the AI SDK you can build intelligent agents with tools and structured output, generate images, synthesize and transcribe audio, create vector embeddings, and much more — all using a consistent, Laravel-friendly interface.Laravel AI SDK is an official package (
laravel/ai) available in Laravel 13.Installation
1
Install the package
2
Publish config and migrations
3
Run migrations
agent_conversations and agent_conversation_messages tables used to persist conversation history.Configuration
Set your API keys in.env. Only add keys for providers you plan to use:
config/ai.php. For example, to default to GPT-4o for text generation and dall-e-3 for image generation:
Custom base URLs
If you route requests through a proxy, configure a custom URL per provider inconfig/ai.php:
OpenAI-compatible providers
For APIs compatible with OpenAI, such as LM Studio, vLLM, Together, Fireworks, or a local gateway, configure a provider with theopenai-compatible driver. The url is required. If you specify a key, it is sent as a bearer token.
Lab enum
Use theLab enum to reference providers without hardcoding strings:
Agents
Agents are the fundamental building block of the Laravel AI SDK. Each agent is a PHP class that encapsulates a system prompt, conversation context, tools, and an optional structured output schema.Creating an agent
--structured for agents that return structured JSON output:
Prompting
Instantiate the agent and callprompt:
make to resolve the agent from the service container:
Conversation context
ImplementConversational and define a messages() method to supply previous messages to the agent.
Manual history
Automatic DB storage with RemembersConversations
The RemembersConversations trait stores and retrieves history automatically using the published migrations:
Structured output
ImplementHasStructuredOutput and define a schema() method:
Nested objects
Arrays of objects
anyOf
If a value may match one of several schemas, use theanyOf method:
Attachments
Attach documents or images to a prompt:Files\Image:
Streaming
Return a stream from a route to deliver the response as Server-Sent Events (SSE):then callback to run after streaming completes:
Vercel AI SDK protocol
Broadcasting
Broadcast each streamed event over a Laravel channel:broadcastOnQueue to broadcast asynchronously:
Skipping oversized events
Some broadcasting platforms limit WebSocket messages to approximately 10 KB. Data-heavy stream events, such as large tool results, can exceed that limit and fail to broadcast. Use theWithoutBroadcasting attribute to exclude specific event types.
agent_conversation_messages table. The frontend can retrieve the complete tool data after streaming finishes. This works for queued broadcasting with broadcastOnQueue and synchronous broadcasting with broadcast or broadcastNow.
Queueing
Run the agent in the background:Tools
Tools extend what an agent can do — query databases, call external APIs, perform calculations, etc.tools method:
Similarity search tool
Use the built-inSimilaritySearch tool to query a vector-enabled Eloquent model:
File storage tools
TheFileStorage tool factory gives an agent access to a Laravel filesystem disk. The all method returns tools for listing, reading, generating URLs for, writing, deleting, and copying files on the selected disk.
readOnly to provide read-only access:
Illuminate\Support\Collection, so you can further restrict the tools you expose:
MCP Tools
If your application uses Laravel MCP, you may give your agents tools exposed by Model Context Protocol servers. Using the Laravel MCP client, you may connect to a remote or local MCP server and pass its tools directly to your agent.MCP tools require the Laravel MCP package to be installed in your application.
tools method returns a collection, spread it into your agent’s tools array using the ... operator:
Provider tools
Provider tools are implemented natively by AI providers.Web Search
Supported: Anthropic, OpenAI, Gemini, OpenRouterWeb Fetch
Supported: Anthropic, GeminiFile Search
Supported: OpenAI, GeminiSubagents
You can return another agent from an agent’stools() method. Registering an agent as a tool lets the parent delegate a specific task to the subagent and incorporate the result into its original response. This is useful when a general-purpose agent needs access to specialists with their own instructions, tools, model, and provider settings.
For example, a customer support agent can delegate refund policy questions to a refund specialist:
CanActAsTool and define its tool name and description:
CanActAsTool, Laravel derives the tool name from its class and generates a generic description. Each subagent invocation is isolated and does not inherit the parent’s conversation history.
Middleware
Agent middleware lets you inspect or modify prompts and responses before and after they are sent.then:
Anonymous agents
Create a one-off agent inline with theagent() helper:
Agent configuration via PHP attributes
Use PHP attributes to configure an agent’s default provider, model, and behaviour:Provider options
Pass provider-specific options by implementingHasProviderOptions:
Image generation
Generate images with theImage class. Supported providers: OpenAI, Gemini, xAI, Azure, Bedrock, OpenRouter.
Storing generated images
Queuing image generation
Audio (TTS)
Generate speech from text with theAudio class. Supported providers: OpenAI, ElevenLabs, Gemini.
Storing generated audio
Queuing audio generation
Transcription (STT)
Transcribe audio files with theTranscription class. Supported providers: OpenAI, ElevenLabs, Mistral, Gemini.
Queuing transcription
Embeddings
Generate embeddings using theEmbeddings class or the Str macro.
Querying embeddings (pgvector)
Add the vector column in your migration:Caching embeddings
Enable caching globally inconfig/ai.php:
Reranking
Rerank a list of documents by relevance to a query. Supported providers: Cohere, Jina, VoyageAI.Reranking Eloquent collections
Rerank by a single field:Files
Upload files to AI providers for use in subsequent prompts or vector stores.Provider-specific options
UsewithProviderOptions to pass provider-specific upload options, such as OpenAI’s file purpose:
Vector stores
Manage vector stores for file-search tools.Adding files to a store
Failover
Pass an array of providers to automatically fall back when one is unavailable:Testing
The AI SDK provides fake implementations for every capability so you can test without real API calls.Agents
If you call
fake() for a structured-output agent without explicitly providing fake data, Laravel automatically generates data that matches the agent’s schema.Images
Audio
Transcriptions
Embeddings
Reranking
Files
Vector stores
Events
The Laravel AI SDK dispatches the following events. You can listen for them using standard Laravel event listeners.Agent events
Agent events
Image, audio, and transcription events
Image, audio, and transcription events
Embeddings and reranking events
Embeddings and reranking events
Files and vector store events
Files and vector store events