Skip to main content

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

This creates the 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:
The default models for each capability (text, images, audio, transcription, embeddings) may also be configured in 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 in config/ai.php:
Custom base URLs are supported for OpenAI, Anthropic, Gemini, Groq, Cohere, DeepSeek, xAI, and OpenRouter.

OpenAI-compatible providers

For APIs compatible with OpenAI, such as LM Studio, vLLM, Together, Fireworks, or a local gateway, configure a provider with the openai-compatible driver. The url is required. If you specify a key, it is sent as a bearer token.
Use the configured provider name like any other provider:
Configure a default text model to avoid specifying it for every request:
OpenAI-compatible providers support text generation, streaming, tools, structured output, and image attachments. If the endpoint requires additional request body fields, use provider options.

Lab enum

Use the Lab 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

Add --structured for agents that return structured JSON output:
A full agent implementing all available interfaces:

Prompting

Instantiate the agent and call prompt:
Use make to resolve the agent from the service container:
Override the provider, model, or timeout per request:

Conversation context

Implement Conversational 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

Implement HasStructuredOutput and define a schema() method:

Nested objects

Arrays of objects

anyOf

If a value may match one of several schemas, use the anyOf method:

Attachments

Attach documents or images to a prompt:
For image attachments use Files\Image:

Streaming

Return a stream from a route to deliver the response as Server-Sent Events (SSE):
Register a then callback to run after streaming completes:
Iterate the stream manually:

Vercel AI SDK protocol

Broadcasting

Broadcast each streamed event over a Laravel channel:
Or use 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 the WithoutBroadcasting attribute to exclude specific event types.
Excluded events are not broadcast, but they are still stored in the 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.
Register tools in the agent’s tools method:

Similarity search tool

Use the built-in SimilaritySearch tool to query a vector-enabled Eloquent model:
With additional options:
Using a custom closure:
Provide a custom description shown to the model:

File storage tools

The FileStorage 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.
Use readOnly to provide read-only access:
These methods return an 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.
Because an MCP client’s tools method returns a collection, spread it into your agent’s tools array using the ... operator:
The AI SDK automatically wraps each MCP tool so the agent can call it like any other tool. You may also use a named MCP client:
Or connect to a local MCP server:
For more information on creating and authenticating MCP clients, including bearer tokens and OAuth, consult the MCP client documentation.

Provider tools

Provider tools are implemented natively by AI providers. Supported: Anthropic, OpenAI, Gemini, OpenRouter
With options:

Web Fetch

Supported: Anthropic, Gemini
Supported: OpenAI, Gemini

Subagents

You can return another agent from an agent’s tools() 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:
To customize how the subagent appears to its parent, implement CanActAsTool and define its tool name and description:
If a subagent does not implement 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.
Implement the middleware on the agent:
A middleware class:
Inspect the response after it is generated using then:

Anonymous agents

Create a one-off agent inline with the agent() helper:
With structured output:

Agent configuration via PHP attributes

Use PHP attributes to configure an agent’s default provider, model, and behaviour:
Two convenience attributes automatically select the cheapest or most capable model available:

Provider options

Pass provider-specific options by implementing HasProviderOptions:

Image generation

Generate images with the Image class. Supported providers: OpenAI, Gemini, xAI, Azure, Bedrock, OpenRouter.
Specify quality and aspect ratio:
Generate from a reference image:

Storing generated images

Queuing image generation

Audio (TTS)

Generate speech from text with the Audio class. Supported providers: OpenAI, ElevenLabs, Gemini.
Select a voice:

Storing generated audio

Queuing audio generation

Transcription (STT)

Transcribe audio files with the Transcription class. Supported providers: OpenAI, ElevenLabs, Mistral, Gemini.
Enable speaker diarization:

Queuing transcription

Embeddings

Generate embeddings using the Embeddings class or the Str macro.
Specify dimensions and model:

Querying embeddings (pgvector)

Add the vector column in your migration:
Cast the column to an array on the model:
Query by vector similarity:
Lower-level query methods:

Caching embeddings

Enable caching globally in config/ai.php:
Or enable per request:

Reranking

Rerank a list of documents by relevance to a query. Supported providers: Cohere, Jina, VoyageAI.

Reranking Eloquent collections

Rerank by a single field:
Rerank by multiple fields (concatenated as JSON):
Using a closure:
With additional options:

Files

Upload files to AI providers for use in subsequent prompts or vector stores.
Upload raw content or a form upload:
Reference a previously stored file in a prompt:
Retrieve file metadata:
Delete a stored file:
Specify the provider explicitly:

Provider-specific options

Use withProviderOptions to pass provider-specific upload options, such as OpenAI’s file purpose:
Pass a closure to configure different options for each provider:

Vector stores

Manage vector stores for file-search tools.

Adding files to a store

With metadata:
Remove a file from 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

Queued prompt assertions:
Prevent real prompts from being sent during tests:
For agents that return structured output, pass an array as a fake response:
If you call fake() for a structured-output agent without explicitly providing fake data, Laravel automatically generates data that matches the agent’s schema.
For anonymous agents:

Images

Audio

Transcriptions

Embeddings

Reranking

Files

Vector stores

File operations on a store:
Always call fake() in tests to prevent real API calls, unexpected charges, and rate-limit errors.

Events

The Laravel AI SDK dispatches the following events. You can listen for them using standard Laravel event listeners.
Last modified on July 20, 2026