Docs / AI / laraflare AI SDK
laraflare AI SDK
Introduction
The laraflare AI SDK (@laraflare/ai) 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, laraflare-friendly interface.
Installation
You can install the laraflare AI SDK via npm:
npm install @laraflare/ai
Next, you should publish the AI SDK configuration and migration files using the vendor:publish Artisan command:
npx artisan vendor:publish --provider="AiServiceProvider"
Finally, you should run your application's database migrations. This will create a agent_conversations and agent_conversation_messages table that the AI SDK uses to power its conversation storage:
npx artisan migrate
Configuration
You may define your AI provider credentials in your application's config/ai.ts configuration file or as environment variables in your application's .env file (and, like every other setting, in .env.staging and .env.production):
ANTHROPIC_API_KEY=
AZURE_OPENAI_API_KEY=
COHERE_API_KEY=
DEEPSEEK_API_KEY=
ELEVENLABS_API_KEY=
GEMINI_API_KEY=
GROQ_API_KEY=
MISTRAL_API_KEY=
OLLAMA_API_KEY=
OPENAI_API_KEY=
OPENAI_COMPATIBLE_API_KEY=
OPENAI_COMPATIBLE_URL=
OPENROUTER_API_KEY=
JINA_API_KEY=
TYPESAFE_API_KEY=
VOYAGEAI_API_KEY=
XAI_API_KEY=
The default models used for text, images, audio, transcription, and embeddings may also be configured in your application's config/ai.ts configuration file.
Custom Base URLs
By default, the laraflare AI SDK connects directly to each provider's public API endpoint. However, you may need to route requests through a different endpoint - for example, when using a proxy service to centralize API key management, implement rate limiting, or route traffic through a corporate gateway.
You may configure custom base URLs by adding a url parameter to your provider configuration:
providers: {
openai: {
driver: 'openai',
key: env('OPENAI_API_KEY'),
url: env('OPENAI_URL'),
},
anthropic: {
driver: 'anthropic',
key: env('ANTHROPIC_API_KEY'),
url: env('ANTHROPIC_URL'),
},
},
This is useful when routing requests through a proxy service (such as LiteLLM or Azure OpenAI Gateway) or using alternative endpoints.
Custom base URLs are supported for the following providers: OpenAI, Anthropic, Gemini, Groq, Cohere, DeepSeek, xAI, OpenRouter, and TypeSafe.
OpenAI-Compatible Providers
If you are using an OpenAI-compatible API, such as LM Studio, vLLM, Together, Fireworks, or a local gateway, you may configure an openai-compatible provider. The url option is required, while the key option is optional and will be sent as a bearer token when present:
providers: {
local: {
driver: 'openai-compatible',
url: env('LOCAL_AI_URL'),
key: env('LOCAL_AI_API_KEY'),
},
},
Once configured, you may use the named provider like any other provider:
import { agent } from '@laraflare/ai';
await agent().prompt('What is laraflare?', { provider: 'local', model: 'local-model' });
You may also configure a default text model for the provider so that you do not need to pass a model explicitly:
local: {
driver: 'openai-compatible',
url: env('LOCAL_AI_URL'),
key: env('LOCAL_AI_API_KEY'),
models: {
text: {
default: env('LOCAL_AI_MODEL'),
},
},
},
You may add custom HTTP headers to every outgoing request for the provider by defining a headers object in its configuration. This is useful when an endpoint requires an additional identifying or authentication header beyond the bearer token:
local: {
driver: 'openai-compatible',
url: env('LOCAL_AI_URL'),
key: env('LOCAL_AI_API_KEY'),
headers: {
'X-Tenant-Id': env('LOCAL_AI_TENANT_ID'),
},
},
OpenAI-compatible providers support text generation, streaming, tools, structured output, image attachments, embeddings, transcription, and classification. If your endpoint requires additional request body fields, provide them using provider options.
OpenAI-Compatible Embeddings
Since arbitrary endpoints have no known models, you must configure a default embeddings model to use Embeddings with an OpenAI-compatible provider. You may also configure a fixed dimensions value; if omitted, the request is sent without a dimensions parameter and the model's native dimensions are used.
local: {
driver: 'openai-compatible',
url: env('LOCAL_AI_URL'),
key: env('LOCAL_AI_API_KEY'),
models: {
embeddings: {
default: 'text-embedding-qwen3-embedding-0.6b',
dimensions: 1024, // optional
},
},
},
OpenAI-Compatible Transcriptions
Likewise, you must configure a default transcription model to use Transcription with an OpenAI-compatible provider. The audio will be uploaded to the endpoint's /audio/transcriptions route as a standard multipart request:
local: {
driver: 'openai-compatible',
url: env('LOCAL_AI_URL'),
key: env('LOCAL_AI_API_KEY'),
models: {
transcription: {
default: 'whisper-1',
},
},
},
Note
OpenAI-compatible and Groq providers do not support diarization. Invoking the
diarizemethod when using these providers will throw an exception.
OpenAI-Compatible Classification
If your endpoint implements OpenAI's decisions endpoint, you may use classification with an OpenAI-compatible provider. The SDK sends questions to the endpoint's /decisions route and supports image attachments. Since the SDK does not know which models your endpoint supports, configure a default classification model or pass a model to the classify method:
local: {
driver: 'openai-compatible',
url: env('LOCAL_AI_URL'),
key: env('LOCAL_AI_API_KEY'),
models: {
classification: {
default: env('LOCAL_AI_MODEL'),
},
},
},
Workers AI
Because laraflare apps run on Cloudflare Workers, the AI SDK also has a workers-ai driver that reaches Cloudflare Workers AI through your Worker's AI binding. It needs no URL and no API key:
providers: {
'workers-ai': {
driver: 'workers-ai',
binding: 'AI',
},
},
The driver supports text generation, tool calls, streaming, structured output, and embeddings.
Cloudflare AI Gateway
Cloudflare AI Gateway puts your providers behind one gateway, with its logs, caching, rate limits and cost tracking. Create a gateway in the Cloudflare dashboard, then set your account ID and the gateway's name:
CLOUDFLARE_AI_GATEWAY_ACCOUNT_ID=your-account-id
CLOUDFLARE_AI_GATEWAY=your-gateway
CLOUDFLARE_AI_GATEWAY_TOKEN=
Every provider that AI Gateway supports (OpenAI, Anthropic, Gemini, Groq, Mistral, Cohere, DeepSeek, xAI, OpenRouter and ElevenLabs) then sends its requests to the gateway instead of the provider's own address; your code and your provider keys stay the same. If the gateway has authentication turned on, set CLOUDFLARE_AI_GATEWAY_TOKEN too, and it is sent as the cf-aig-authorization header. Workers AI goes through the gateway on its binding, so it needs only the gateway's name.
These values are the gateway section of config/ai.ts. A provider may set its own gateway option to false to skip the gateway, or to the name of another gateway:
providers: {
ollama: {
driver: 'ollama',
url: env('OLLAMA_BASE_URL', 'http://localhost:11434'),
gateway: false,
},
},
When a provider goes through the gateway, the gateway's address replaces the provider's url.
On-Demand Providers
Sometimes you may need to use provider credentials that are not defined in your application's configuration file, such as API keys that are stored in your database for each tenant of a multi-tenant application. You may use the Ai.build method to create a provider from a configuration object. The object should have the same structure as a provider entry in your application's config/ai.ts configuration file:
import { SalesCoach } from '../Ai/Agents/SalesCoach';
import { Ai } from '@laraflare/ai';
const response = await new SalesCoach().prompt('Analyze this sales transcript...', {
provider: [
Ai.build({
driver: 'anthropic',
key: user.anthropic_key,
}),
],
});
On-demand providers may be used anywhere a provider is accepted, including failover lists and when generating images, audio, transcriptions, and embeddings. To specify a model for an on-demand provider, include a models object in its configuration:
const response = await new SalesCoach().prompt('Analyze this sales transcript...', {
provider: [
Ai.build({ driver: 'anthropic', key: user.anthropic_key }),
Ai.build({
driver: 'openai',
key: user.openai_key,
models: { text: { default: 'gpt-6' } },
}),
],
});
When an agent should always use an on-demand provider, you may return the provider from the agent's provider method. Since the provider is rebuilt when the agent is used, this approach also works well for queued agents:
import { Ai, type Provider } from '@laraflare/ai';
provider(): Provider {
return Ai.build(this.user.aiConfiguration());
}
Note
You should pass on-demand providers within an array, as shown in the examples above. If you give an on-demand provider a
namein its configuration object, the name may not match a built-in provider or a provider defined in yourconfig/ai.tsconfiguration file.
Provider Support
The AI SDK supports a variety of providers across its features. The following table summarizes which providers are available for each feature:
| Feature | Providers |
|---|---|
| Text | OpenAI, OpenAI Compatible, Anthropic, Gemini, Azure, Bedrock, Groq, xAI, DeepSeek, Mistral, Ollama, OpenRouter, Cohere, Workers AI |
| Images | OpenAI, Gemini, xAI, Azure, Bedrock, OpenRouter |
| TTS | OpenAI, ElevenLabs, Gemini, Mistral, OpenRouter |
| STT | OpenAI, OpenAI Compatible, ElevenLabs, Groq, Mistral, Gemini, OpenRouter |
| Embeddings | OpenAI, OpenAI Compatible, Gemini, Azure, Bedrock, Cohere, Mistral, Jina, VoyageAI, Ollama, OpenRouter, Workers AI |
| Reranking | Cohere, Jina, VoyageAI, Bedrock, OpenRouter |
| Classification | OpenAI, OpenAI Compatible, Gemini, TypeSafe, OpenRouter |
| Files | OpenAI, Anthropic, Gemini, Azure, OpenRouter |
The Lab enum may be used to reference providers throughout your code instead of using plain strings:
import { Lab } from '@laraflare/ai';
Lab.Anthropic;
Lab.OpenAI;
Lab.OpenAICompatible;
Lab.Gemini;
// ...
Agents
Agents are the fundamental building block for interacting with AI providers in the laraflare AI SDK. Each agent is a dedicated TypeScript class that encapsulates the instructions, conversation context, tools, and output schema needed to interact with a large language model. Think of an agent as a specialized assistant — a sales coach, a document analyzer, a support bot — that you configure once and prompt as needed throughout your application.
You can create an agent via the make:agent Artisan command:
npx artisan make:agent SalesCoach
npx artisan make:agent SalesCoach --structured
Within the generated agent class, you can define the system prompt / instructions, message context, available tools, and output schema (if applicable):
import { RetrievePreviousTranscripts } from '../Ai/Tools/RetrievePreviousTranscripts';
import { History } from '../Models/History';
import { User } from '../Models/User';
import type { Agent, Conversational, HasStructuredOutput, HasTools, JsonSchemaTypeFactory, Tool, Type } from '@laraflare/ai';
import { Message, Promptable } from '@laraflare/ai';
export class SalesCoach extends Promptable() implements Agent, Conversational, HasTools, HasStructuredOutput {
static readonly agentClass = 'SalesCoach';
constructor(public user: User) {
super();
}
/**
* Get the instructions that the agent should follow.
*/
instructions(): string {
return 'You are a sales coach, analyzing transcripts and providing feedback and an overall sales strength score.';
}
/**
* Get the list of messages comprising the conversation so far.
*/
async messages(): Promise<Message[]> {
const history = await History.query()
.where('user_id', this.user.id)
.latest()
.limit(50)
.get();
return history
.reverse()
.map((message) => new Message(message.role, message.content))
.all();
}
/**
* Get the tools available to the agent.
*/
tools(): Iterable<Tool> {
return [
new RetrievePreviousTranscripts(),
];
}
/**
* Get the agent's structured output schema definition.
*/
schema(schema: JsonSchemaTypeFactory): Record<string, Type> {
return {
feedback: schema.string().required(),
score: schema.integer().min(1).max(10).required(),
};
}
}
Prompting
To prompt an agent, first create an instance using the make method or standard instantiation, then call prompt:
const response = await new SalesCoach(user)
.prompt('Analyze this sales transcript...');
return String(response);
The make method resolves your agent from the container, allowing automatic dependency injection. When you pass arguments, they are given to the agent's constructor in order:
const agent = SalesCoach.make(user);
By passing an options object to the prompt method, you may override the default provider, model, or HTTP timeout when prompting:
const response = await new SalesCoach(user).prompt('Analyze this sales transcript...', {
provider: Lab.Anthropic,
model: 'claude-sonnet-5',
timeout: 120,
});
Raw HTTP Responses
Every response returned from a text-generating agent exposes the raw HTTP response from the underlying provider API call via a raw property. This gives you access to provider-specific information that isn't part of the AI SDK's generic response - rate-limit headers, request IDs, or other exact payload fields:
const response = await new SalesCoach(user).prompt('Analyze this sales transcript...');
response.raw; // The HTTP client response, or null
response.raw?.header('X-RateLimit-Remaining-Requests');
response.raw?.json('id');
In a tool-call loop, each step retains the raw response of its own request:
for (const step of response.steps) {
step.raw?.header('X-RateLimit-Remaining-Requests');
}
Image, transcription, embeddings, reranking, classification, and file responses expose the same raw property. For example, you may read the cost that OpenRouter reports for a request:
import { Embeddings } from '@laraflare/ai';
const response = await Embeddings.for(['Hello world']).generate('openrouter');
response.raw?.json('usage.cost');
Note
The
rawproperty isnullwhen streaming a response, when using the Bedrock provider (which performs its API calls via the AWS SDK instead of an HTTP client), on embeddings that were entirely served from the cache, on serialized responses, and on faked responses unless one is provided explicitly viawithRawResponse.
Conversation Context
If your agent implements the Conversational interface, you may use the messages method to return the previous conversation context, if applicable:
/**
* Get the list of messages comprising the conversation so far.
*/
async messages(): Promise<Message[]> {
const history = await this.user.history()
.latest()
.limit(50)
.get();
return history
.reverse()
.map((message) => new Message(message.role, message.content))
.all();
}
If your agent does not implement the Conversational interface, you may use the withMessages method to provide the conversation history for a single run, such as a history posted by your application's frontend:
import { Message } from '@laraflare/ai';
const response = await new SalesCoach(user)
.withMessages([
new Message('user', 'Analyze this sales transcript...'),
new Message('assistant', 'The rep never asked for the close.'),
])
.prompt('What should they say next time?');
Agents that implement the Conversational interface load their own history, so combining the two approaches will throw a LogicException.
Remembering Conversations
Warning
Before using the
RemembersConversationsmixin, you should publish and run the AI SDK migrations using thevendor:publishArtisan command. These migrations will create the necessary database tables to store conversations.
If you would like laraflare to automatically store and retrieve conversation history for your agent, you may use the RemembersConversations mixin. This mixin provides a simple way to persist conversation messages to the database without manually implementing the Conversational interface:
import type { Agent, Conversational } from '@laraflare/ai';
import { Promptable, RemembersConversations } from '@laraflare/ai';
export class SalesCoach extends RemembersConversations(Promptable()) implements Agent, Conversational {
static readonly agentClass = 'SalesCoach';
/**
* Get the instructions that the agent should follow.
*/
instructions(): string {
return 'You are a sales coach...';
}
}
When using the RemembersConversations mixin, do not manually define a messages method in your agent class. If a messages method is present, it will take precedence over the mixin's implementation and conversation history will not be loaded from the database.
To start a new conversation for a user, call the forUser method before prompting:
const response = await new SalesCoach().forUser(user).prompt('Hello!');
const conversationId = response.conversationId;
The conversation ID is returned on the response and can be stored for future reference. If you would like to retrieve all of a user's conversations using Eloquent, you may wrap your user model with the HasConversations mixin:
import { HasConversations } from '@laraflare/ai/Concerns/HasConversations';
import { Model } from '@laraflare/framework/Database/Eloquent/Model';
export class User extends HasConversations(Model) {
//
}
Once the mixin has been added to your model, you may retrieve and query the user's conversations via the conversations relationship:
const conversations = await user.conversations()
.latest('updated_at')
.paginate(20);
To continue an existing conversation, use the continue method:
const response = await new SalesCoach()
.continue(conversationId, user)
.prompt('Tell me more about that.');
The continueOrStart method may be used to continue the given conversation, or start a new conversation if the given ID is null:
const response = await new SalesCoach()
.continueOrStart(conversationId, user)
.prompt('Hello!');
When using the RemembersConversations mixin, previous messages are automatically loaded and included in the conversation context when prompting. New messages (both user and assistant) are automatically stored after each interaction. Each response also contains the IDs of the conversation and messages that were stored:
response.conversationId;
response.userMessageId;
response.assistantMessageId;
Conversation Participants
Although users are the most common conversation participants, conversations may belong to any Eloquent model. Use the forParticipant method to start a conversation for another type of model:
const response = await new SalesCoach()
.forParticipant(team)
.prompt('Review our latest sales results.');
The participant's morph class and primary key are stored with the conversation. Therefore, models of different types that have the same primary key, such as User ID 1 and Team ID 1, have separate conversation histories. The forUser method is an alias for forParticipant.
You may continue the participant's most recent conversation with the agent using the continueLastConversation method. Conversations are scoped to the agent, so only conversations that the agent participated in will be continued:
const agent = await new SalesCoach().continueLastConversation(team);
const response = await agent.prompt('Tell me more about that.');
When continuing a specific conversation, pass the participant to the continue method:
const response = await new SalesCoach()
.continue(conversationId, team)
.prompt('Tell me more about that.');
The HasConversations mixin may be added to any Eloquent model that participates in conversations. The resulting conversations relationship is a polymorphic relationship scoped to that model's type and primary key.
If your application uses multiple participant model types, you should consider defining an Eloquent morph map so that stored participant types are not coupled to your model class names.
Warning
The
continueandcontinueOrStartmethods do not verify that the given participant owns the conversation. Your application should authorize access to the conversation before continuing it.
Inspecting Stored Conversations
When displaying a conversation to your users, you often need details such as message IDs, timestamps, and tool calls. You may resolve the conversation store from the service container to read the stored messages without querying the AI SDK's tables directly:
import { ConversationStore } from '@laraflare/ai';
const store = app(ConversationStore);
Messages are paginated newest first using a cursor and are returned as StoredMessage instances, which contain each message's ID, timestamps, usage, metadata, and attachments:
const messages = await store.paginateConversationMessages(conversationId, 25);
for (const message of messages) {
message.id;
message.role;
message.content;
message.createdAt;
message.usage;
message.status;
}
Each turn, which consists of a user prompt and the assistant's reply, is stored as a list of steps. A step is a single request to the provider, so a turn in which the model calls tools will contain several steps. Each tool result is recorded on the tool call that produced it. The toolCalls, providerToolCalls, and toolResults methods flatten these steps in order, so you do not need to traverse them yourself:
message.steps;
message.toolCalls();
message.providerToolCalls();
message.toolResults();
A tool call contains a result once it has been executed. Tool calls that contain an approval_reason but no result are still awaiting a tool approval.
The status property contains a MessageStatus value. A turn that failed partway through is stored as Failed along with the steps it had already completed, so tool calls that ran before the failure remain in the history. When the conversation continues, any tool call without a recorded result is sent to the model marked as interrupted, since laraflare cannot determine whether it ran.
Before continuing a conversation via an ID provided by your application's frontend, you should verify that the conversation was stored for the given participant:
if (! await store.conversationBelongsTo(conversationId, user.getMorphClass(), user.getKey())) {
abort(403);
}
If the most recent turn is paused awaiting tool approval, you may render its pending tool calls after a page reload without resuming the run:
for (const approval of await store.pendingApprovalsFor(conversationId)) {
// approval.id, approval.tool, approval.arguments, approval.reason...
}
These methods are defined by the PaginatesConversations, VerifiesConversationOwnership, and ResolvesPendingApprovals contracts. The included database store implements all three, while a custom store may implement only the contracts it needs.
Structured Output
If you would like your agent to return structured output, implement the HasStructuredOutput interface, which requires that your agent define a schema method:
import type { Agent, HasStructuredOutput, JsonSchemaTypeFactory, Type } from '@laraflare/ai';
import { Promptable } from '@laraflare/ai';
export class SalesCoach extends Promptable() implements Agent, HasStructuredOutput {
// ...
/**
* Get the agent's structured output schema definition.
*/
schema(schema: JsonSchemaTypeFactory): Record<string, Type> {
return {
score: schema.integer().required(),
};
}
}
When prompting an agent that returns structured output, you can access the returned StructuredAgentResponse like an object:
const response = await new SalesCoach().prompt('Analyze this sales transcript...');
return response['score'];
Nested Objects
To define nested structured output, use the object method with a closure:
schema(schema: JsonSchemaTypeFactory): Record<string, Type> {
return {
score: schema.integer().required(),
metadata: schema.object((schema) => ({
confidence: schema.string().enum(['low', 'medium', 'high']).required(),
language: schema.string().required(),
})).required(),
};
}
Arrays of Objects
If your agent should return a list of structured items, combine the array and object methods:
schema(schema: JsonSchemaTypeFactory): Record<string, Type> {
return {
feedback: schema.array()
.items(
schema.object((schema) => ({
comment: schema.string().required(),
score: schema.integer().required(),
})),
)
.required(),
};
}
If a value may match one of several schemas, use the anyOf method:
schema(schema: JsonSchemaTypeFactory): Record<string, Type> {
return {
content: schema.anyOf([
schema.object((schema) => ({
type: schema.string().enum(['article']).required(),
title: schema.string().required(),
})),
schema.object((schema) => ({
type: schema.string().enum(['image']).required(),
url: schema.string().required(),
})),
]).required(),
};
}
Attachments
When prompting, you may also pass attachments with the prompt to allow the model to inspect images and documents:
import { SalesCoach } from '../Ai/Agents/SalesCoach';
import { Document } from '@laraflare/ai';
const response = await new SalesCoach(user).prompt('Analyze the attached sales transcript...', {
attachments: [
Document.fromStorage('transcript.pdf'), // Attach a document from a filesystem disk...
Document.fromPath('./storage/transcript.md'), // Attach a document from a local path...
request.file('transcript'), // Attach an uploaded file...
],
});
Likewise, the Image class may be used to attach images to a prompt:
import { ImageAnalyzer } from '../Ai/Agents/ImageAnalyzer';
import { Image } from '@laraflare/ai';
const response = await new ImageAnalyzer().prompt('What is in this image?', {
attachments: [
Image.fromStorage('photo.jpg'), // Attach an image from a filesystem disk...
Image.fromPath('./storage/photo.jpg'), // Attach an image from a local path...
request.file('photo'), // Attach an uploaded file...
],
});
Streaming
You may stream an agent's response by invoking the stream method. The returned StreamableAgentResponse may be returned from a route to automatically send a streaming response (SSE) to the client:
import { SalesCoach } from '../Ai/Agents/SalesCoach';
Route.get('/coach', () => {
return new SalesCoach().stream('Analyze this sales transcript...');
});
The then method may be used to provide a closure that will be invoked when the entire response has been streamed to the client:
import { SalesCoach } from '../Ai/Agents/SalesCoach';
import type { StreamedAgentResponse } from '@laraflare/ai';
Route.get('/coach', () => {
return new SalesCoach()
.stream('Analyze this sales transcript...')
.then((response: StreamedAgentResponse) => {
// response.text, response.events, response.usage...
});
});
Alternatively, you may iterate through the streamed events manually:
const stream = new SalesCoach().stream('Analyze this sales transcript...');
for await (const event of stream) {
// ...
}
The response also contains the model's reasoning and any sources it cited. Both are stored with the assistant message when using the RemembersConversations mixin:
new SalesCoach()
.stream('Analyze this sales transcript...')
.then((response: StreamedAgentResponse) => {
response.reasoning; // '' unless the model returned reasoning text...
response.meta.citations;
});
Reasoning is also available on responses returned by the prompt method.
Stream Protocols
By default, streamed responses use the AI SDK's own event format. However, you may use a frontend streaming protocol instead, which allows you to pair your agent with an existing chat interface rather than building your own.
You may stream the events using the Vercel AI SDK stream protocol by invoking the usingVercelDataProtocol method on the streamable response:
Route.get('/coach', () => {
return new SalesCoach()
.stream('Analyze this sales transcript...')
.usingVercelDataProtocol();
});
You may pass a message ID if your application's frontend assigns its own:
.usingVercelDataProtocol(request.string('messageId'));
Alternatively, the usingAgentUserInteractionProtocol method may be used to stream using the Agent User Interaction (AG-UI) protocol:
Route.post('/coach', (request: Request) => {
return new SalesCoach()
.forUser(request.user())
.stream(request.string('prompt'))
.usingAgentUserInteractionProtocol();
});
The threadId and runId arguments are optional and default to the conversation ID and the invocation ID:
.usingAgentUserInteractionProtocol(
request.input('threadId'),
request.input('runId'),
);
To use a protocol that the AI SDK does not implement, you may pass your own StreamProtocol implementation to the usingProtocol method:
import { CustomProtocol } from '../Ai/Protocols/CustomProtocol';
return new SalesCoach()
.stream('Analyze this sales transcript...')
.usingProtocol(new CustomProtocol());
Frontend Integration
Chat interfaces built with libraries such as Vercel's useChat or CopilotKit already render messages, tool calls, and approval prompts, so your application only needs to handle the requests they send. Each request contains the conversation history, the newest user message, and any tool approval responses.
The Vercel.chat and AgentUserInteraction.chat methods convert such a request into an object that may be passed directly to an agent's stream method:
import { Vercel } from '@laraflare/ai/Vercel/Vercel';
Route.post('/chat', (request: Request) => {
const chat = Vercel.chat(request);
return new SupportAgent()
.withMessages(chat.history())
.stream(chat)
.usingProtocol(chat.protocol());
});
If the request contains approval decisions, the agent will resume using those decisions. Otherwise, the agent is prompted with the request's newest user message and attachments. The protocol method returns the protocol used by the client.
Note
Agents that implement the
Conversationalinterface load their own history, so thewithMessagesmethod may be omitted.
The AgentUserInteraction.chat method provides the same API for AG-UI clients, in addition to the request's thread and run IDs:
import { AgentUserInteraction } from '@laraflare/ai/AgentUserInteraction/AgentUserInteraction';
const chat = AgentUserInteraction.chat(request);
chat.threadId();
chat.runId();
You may also convert stored messages back into the format a client expects, allowing the client to display a previous conversation, such as after a page reload:
const messages = await conversation.messages().oldest().get();
return { messages: await Vercel.toUiMessages(messages) };
The AgentUserInteraction.toClientState method performs the same conversion for AG-UI clients, in addition to returning any pending approval interrupts:
return AgentUserInteraction.toClientState(messages);
Broadcasting
You may broadcast streamed events in a few different ways. First, you can simply invoke the broadcast or broadcastNow method on a streamed event:
import { SalesCoach } from '../Ai/Agents/SalesCoach';
import { Channel } from '@laraflare/framework/Broadcasting/Channel';
const stream = new SalesCoach().stream('Analyze this sales transcript...');
for await (const event of stream) {
event.broadcast(new Channel('channel-name'));
}
Or, you can invoke an agent's broadcastOnQueue method to queue the agent operation and broadcast the streamed events as they are available:
await new SalesCoach().broadcastOnQueue(
'Analyze this sales transcript...',
new Channel('channel-name'),
);
Each event is broadcast under its type, such as stream_start, text_delta, tool_call, tool_result, and stream_end. Errors returned by the provider are always broadcast as error, and the provider's own error code is available in the payload's type key. When a queued broadcast fails, a stream_failed event is broadcast so your frontend can stop waiting for the response. Since these are custom broadcast names, you should prefix them with a . when listening with Echo:
Echo.channel('channel-name')
.listen('.text_delta', (event) => {
// event.delta...
})
.listen('.error', (event) => {
// event.type, event.message...
})
.listen('.stream_failed', (event) => {
// ...
});
Skipping Oversized Events
Some broadcasting platforms limit WebSocket messages to around 10KB. Data-heavy stream events, like large tool results, can exceed this limit and cause broadcasting to fail. You may exclude specific event types from broadcasting using the WithoutBroadcasting attribute. Since TypeScript has no attributes, you attach it to the agent class:
import { WithoutBroadcasting } from '@laraflare/ai/Attributes/WithoutBroadcasting';
import type { Agent, HasTools } from '@laraflare/ai';
import { Promptable, StreamEvents } from '@laraflare/ai';
export class SearchAgent extends Promptable() implements Agent, HasTools {
// ...
}
WithoutBroadcasting.attach(SearchAgent, StreamEvents.ToolCall, StreamEvents.ToolResult);
The excluded events are never broadcast, but they are still persisted to the agent_conversation_messages table, so your frontend can load the full tool data after the stream completes. This works for both queued (broadcastOnQueue) and synchronous (broadcast / broadcastNow) broadcasting.
Queueing
Using an agent's queue method, you may prompt the agent, but allow it to process the response in the background, keeping your application feeling fast and responsive. The andThen method may be used to register a closure that will be invoked when a response is available:
import type { AgentResponse } from '@laraflare/ai';
Route.post('/coach', async (request: Request) => {
const queued = await new SalesCoach().queue(request.input('transcript'));
await queued.andThen((response: AgentResponse) => {
// ...
});
return back();
});
Tools
Tools may be used to give agents additional functionality that they can utilize while responding to prompts. Tools can be created using the make:tool Artisan command:
npx artisan make:tool RandomNumberGenerator
The generated tool will be placed in your application's app/Ai/Tools directory. Each tool contains a handle method that will be invoked by the agent when it needs to utilize the tool:
import { randomInt } from 'node:crypto';
import type { JsonSchemaTypeFactory, Tool, ToolRequest, Type } from '@laraflare/ai';
export class RandomNumberGenerator implements Tool {
/**
* Get the description of the tool's purpose.
*/
description(): string {
return 'This tool may be used to generate cryptographically secure random numbers.';
}
/**
* Execute the tool.
*/
handle(request: ToolRequest): string {
return String(randomInt(request['min'], request['max']));
}
/**
* Get the tool's schema definition.
*/
schema(schema: JsonSchemaTypeFactory): Record<string, Type> {
return {
min: schema.integer().min(0).required(),
max: schema.integer().required(),
};
}
}
Once you have defined your tool, you may return it from the tools method of any of your agents:
import { RandomNumberGenerator } from '../Ai/Tools/RandomNumberGenerator';
/**
* Get the tools available to the agent.
*/
tools(): Iterable<Tool> {
return [
new RandomNumberGenerator(),
];
}
Runtime Tool Overrides
The withTools method may be used to replace the tools declared by an agent instance. This is useful for per-tenant or feature-flagged tool sets:
const response = await new SupportAgent()
.withTools([new LookupOrder()])
.prompt('Where is order 12345?');
You may also pass a closure, which receives the agent's declared tools, allowing you to append to or filter them:
const response = await new SupportAgent()
.withTools((tools) => [...tools, new LookupOrder()])
.prompt('Where is order 12345?');
Validating Tool Arguments
Although your tool's schema constrains the arguments a model may provide, you may validate the incoming arguments using the request's validate method:
async handle(request: ToolRequest): Promise<string> {
const validated = await request.validate({
city: 'required|string',
days: 'required|integer|max:7',
});
return this.forecast(validated.city, validated.days);
}
When validation fails, the validation messages are returned to the model as the tool's result, allowing it to correct the arguments and call the tool again.
Repairing Tool Calls
Use the RepairToolCalls attribute to let an agent recover when a model calls an unknown local tool. laraflare returns the failed call to the model with the names of the available local tools, allowing it to correct the call. Attach it to the agent class:
import { RepairToolCalls } from '@laraflare/ai/Attributes/RepairToolCalls';
import type { Agent, HasTools } from '@laraflare/ai';
import { Promptable } from '@laraflare/ai';
export class SupportAgent extends Promptable() implements Agent, HasTools {
// ...
}
RepairToolCalls.attach(SupportAgent);
When laraflare derives the maximum number of steps automatically, this attribute adds one step for the repaired call. Explicit MaxSteps limits are unchanged.
Handling Tool Failures
When a tool throws an exception, the agent's run continues. The exception is reported to your application's exception handler, a ToolFailed event is dispatched, and the model receives the failure as the tool's result, allowing it to explain what went wrong or try another approach. For example, if a tool throws an exception with the message "Order 1234 can no longer be refunded.", the model receives:
The tool call failed: Order 1234 can no longer be refunded.
The failed result is available through the response's toolResults, and streamed responses emit it as a failed tool_result event. Sub-agents used as tools are handled the same way when they throw.
Similarity Search
The SimilaritySearch tool allows agents to search for documents similar to a given query using vector embeddings stored in your database. This is useful for retrieval-augmented generation (RAG) when you want to give agents access to search your application's data.
The simplest way to create a similarity search tool is using the usingModel method with an Eloquent model that has vector embeddings:
import { Document } from '../Models/Document';
import { SimilaritySearch } from '@laraflare/ai/Tools/SimilaritySearch';
tools(): Iterable<Tool> {
return [
SimilaritySearch.usingModel(Document, 'embedding'),
];
}
The first argument is the Eloquent model class, and the second argument is the column containing the vector embeddings.
You may also provide a minimum similarity threshold between 0.0 and 1.0 and a closure to customize the query:
SimilaritySearch.usingModel(
Document,
'embedding',
0.7,
10,
(query) => query.where('published', true),
),
For more control, you may create a similarity search tool with a custom closure that returns the search results:
import { Document } from '../Models/Document';
import { SimilaritySearch } from '@laraflare/ai/Tools/SimilaritySearch';
tools(): Iterable<Tool> {
return [
new SimilaritySearch(async (query: string) => {
return Document.query()
.where('user_id', this.user.id)
.whereVectorSimilarTo('embedding', query)
.limit(10)
.get();
}),
];
}
You may customize the tool's description using the withDescription method:
SimilaritySearch.usingModel(Document, 'embedding')
.withDescription('Search the knowledge base for relevant articles.'),
Deferred Tool Loading
By default, every tool an agent exposes is sent to the provider with each request. When an agent provides a large number of tools, this consumes tokens and may reduce the accuracy of the model's tool selection. Using the ToolSearch provider tool with OpenAI, Azure, or Anthropic, you may defer tool definitions so that the provider only loads them when they are needed:
import { RefundOrder } from '../Ai/Tools/RefundOrder';
import { SearchInvoices } from '../Ai/Tools/SearchInvoices';
import { Weather } from '../Ai/Tools/Weather';
import { ToolSearch } from '@laraflare/ai';
tools(): Iterable<Tool> {
return [
new Weather(),
new ToolSearch({
tools: [
new SearchInvoices(),
new RefundOrder(),
],
}),
];
}
The wrapped tools do not require any modification. The provider will search for and load them when they are relevant to the prompt, after which the agent may call them like any other tool.
When using Anthropic, the strategy option may be used to determine how the provider should search for deferred tools. The supported strategies are regex (default) and bm25:
new ToolSearch({ tools: [new SearchInvoices()], strategy: 'bm25' }),
When using Anthropic, additional provider-specific options may be passed to the search tool using the withProviderOptions method:
new ToolSearch({ tools: [new SearchInvoices()] })
.withProviderOptions({ cache_control: { type: 'ephemeral' } }),
Warning
Providers that do not support tool search will throw an exception rather than silently discarding the deferred tools. In addition, Anthropic requires that at least one tool is provided outside of the
ToolSearchwrapper.
File Storage Tools
The FileStorage tool factory allows you to give agents access to a filesystem disk. The all method returns tools that allow the agent to list, read, inspect, generate URLs for, write, delete, copy, and move files on the given disk:
import { FileStorage } from '@laraflare/ai/Tools/FileStorage';
tools(): Iterable<Tool> {
return FileStorage.all('local');
}
If your agent should only be able to inspect files, use the readOnly method:
return FileStorage.readOnly('local');
These methods return a Collection, allowing you to further filter the tools that are provided to the agent:
import { DeleteFile } from '@laraflare/ai/Tools/Filesystem/DeleteFile';
return FileStorage.all('s3')
.reject((tool) => tool instanceof DeleteFile);
MCP Tools
If your application uses the MCP package (@laraflare/mcp), you may give your agents tools exposed by Model Context Protocol servers. Using the MCP client, you may connect to a remote or local MCP server and pass its tools directly to your agent.
Note
MCP tools require the
@laraflare/mcppackage to be installed in your application.
Because an MCP client's tools method returns a collection, spread its items into your agent's tools array:
import { RandomNumberGenerator } from '../Ai/Tools/RandomNumberGenerator';
import { Client } from '@laraflare/mcp';
/**
* Get the tools available to the agent.
*/
async tools(): Promise<Tool[]> {
const mcpTools = await Client.web('https://mcp.example.com')
.withToken(token)
.tools();
return [
...mcpTools,
new RandomNumberGenerator(),
];
}
The AI SDK automatically wraps each MCP tool so the agent can call it like any other tool. Or connect to a local MCP server:
import { Client } from '@laraflare/mcp';
async tools(): Promise<Tool[]> {
return [
...await Client.local('npx', ['artisan', 'mcp:start']).tools(),
];
}
Skills
Agent Skills are folders of instructions and supporting files that teach an agent how to perform a specific task. Because skills follow an open standard, the same skill may be shared between your application's agents and the coding agents you use to build your application.
Each skill is a directory within your application's resources/skills directory that contains a SKILL.md file. Any other files in the directory, such as reference documents, are bundled with the skill:
resources/skills/
└── refund-policy/
├── SKILL.md
└── references/EDGE-CASES.md
The SKILL.md file begins with YAML frontmatter containing the skill's name and a description of when the skill should be used, followed by the skill's instructions:
---
name: refund-policy
description: Use when a customer asks for a refund or disputes a charge.
---
# Refund Policy
Customers may request a full refund within 30 days of purchase...
If the name is omitted, the name of the skill's directory will be used. Skills without a description are ignored.
To give an agent access to your skills, implement the HasSkills interface and return your skill sources from the skills method:
import type { Agent, HasSkills } from '@laraflare/ai';
import { Promptable } from '@laraflare/ai';
import { Skill } from '@laraflare/ai/Skills/Skill';
import { base_path, resource_path } from '@laraflare/framework/Support/helpers';
export class SupportAgent extends Promptable() implements Agent, HasSkills {
skills() {
return [
resource_path('skills'),
base_path('.agents/skills'),
new Skill('house-style', 'Use when you write copy for a customer.', 'Write short, friendly sentences.'),
() => this.user.team.skills.map(
(skill) => new Skill(skill.name, skill.description, skill.instructions),
),
];
}
}
Sources may be directories, Skill instances, or closures returning skills, which are only invoked once the agent needs them. When two skills share a name, the source listed first takes precedence.
Note
Skill directories are read from the filesystem, which a Worker does not have. Use
Skillinstances or closures for skills in a deployed Worker, and directories when the agent runs from the Node CLI.
The agent receives a LoadSkill tool that lists each skill's name and description, loading a skill's full instructions and bundled text files only when a prompt calls for it. Binary files and files larger than 256 KB are not returned.
Provider Tools
Provider tools are special tools implemented natively by AI providers, offering capabilities like web searching, URL fetching, and file searching. Unlike regular tools, provider tools are executed by the provider itself rather than your application.
Provider tools can be returned by your agent's tools method.
Web Search
The WebSearch provider tool allows agents to search the web for real-time information. This is useful for answering questions about current events, recent data, or topics that may have changed since the model's training cutoff.
Supported providers: Anthropic, OpenAI, Azure, Gemini, xAI, Groq, OpenRouter
import { WebSearch } from '@laraflare/ai';
tools(): Iterable<Tool | ProviderTool> {
return [
new WebSearch(),
];
}
You may configure the web search tool to limit the number of searches or restrict results to specific domains:
new WebSearch().max(5).allow(['laraflare.com', 'developer.mozilla.org']),
To refine search results based on user location, use the location method:
new WebSearch().location({
city: 'New York',
region: 'NY',
country: 'US',
});
Note
Groq only supports web search on its GPT-OSS models, and ignores the
max,allow, andlocationmethods.
Web Fetch
The WebFetch provider tool allows agents to fetch and read the contents of web pages. This is useful when you need the agent to analyze specific URLs or retrieve detailed information from known web pages.
Supported providers: Anthropic, Gemini, OpenRouter
import { WebFetch } from '@laraflare/ai';
tools(): Iterable<Tool | ProviderTool> {
return [
new WebFetch(),
];
}
You may configure the web fetch tool to limit the number of fetches or restrict to specific domains:
new WebFetch().max(3).allow(['laraflare.com']),
File Search
The FileSearch provider tool allows agents to search through files stored in vector stores. This enables retrieval-augmented generation (RAG) by allowing the agent to search your uploaded documents for relevant information.
Supported providers: OpenAI, Azure, Gemini, xAI
import { FileSearch } from '@laraflare/ai';
tools(): Iterable<Tool | ProviderTool> {
return [
new FileSearch({ stores: ['store_id'] }),
];
}
You may provide multiple vector store IDs to search across multiple stores:
new FileSearch({ stores: ['store_1', 'store_2'] });
If your files have metadata, you may filter the search results by providing a where option. For simple equality filters, pass an object:
new FileSearch({
stores: ['store_id'],
where: {
author: 'Taylor Otwell',
year: 2026,
},
});
For more complex filters, you may pass a closure that receives a FileSearchQuery instance:
import { FileSearch, type FileSearchQuery } from '@laraflare/ai';
new FileSearch({
stores: ['store_id'],
where: (query: FileSearchQuery) => query
.where('author', 'Taylor Otwell')
.whereNot('status', 'draft')
.whereIn('category', ['news', 'updates']),
});
Code Execution
The CodeExecution provider tool allows agents to run code in a sandbox hosted by the AI provider. This is useful for performing calculations and analyzing data.
Supported providers: Anthropic, OpenAI, Azure, Gemini, xAI, Groq
import { CodeExecution } from '@laraflare/ai';
tools(): Iterable<Tool | ProviderTool> {
return [new CodeExecution()];
}
When using OpenAI or Azure, you may make stored files available to the sandbox via provider options:
new CodeExecution().withProviderOptions({
container: { type: 'auto', file_ids: ['file_123'] },
});
Note
Groq only supports code execution on its GPT-OSS models.
Sub-Agents
Agents may also be returned from another agent's tools method. When an agent is returned as a tool, the parent agent may delegate a specific task to the sub-agent and use the sub-agent's response while answering the original prompt. This is useful when a general-purpose agent needs access to specialized agents with their own instructions, tools, model configuration, or provider preferences.
For example, a customer support agent could delegate refund eligibility questions to a dedicated refunds agent:
import type { Agent, HasTools } from '@laraflare/ai';
import { Promptable } from '@laraflare/ai';
export class CustomerSupportAgent extends Promptable() implements Agent, HasTools {
/**
* Get the instructions that the agent should follow.
*/
instructions(): string {
return 'You help customers with account, order, and billing questions. Delegate refund policy questions to the refunds specialist.';
}
/**
* Get the tools available to the agent.
*/
tools(): Iterable<Tool | Agent> {
return [
new RefundsAgent(),
];
}
}
To customize how the sub-agent is exposed to the parent agent, implement the CanActAsTool interface on the sub-agent and define a tool-facing name and description:
import type { Agent, CanActAsTool, HasTools } from '@laraflare/ai';
import { Lab, Promptable } from '@laraflare/ai';
export class RefundsAgent extends Promptable() implements Agent, CanActAsTool, HasTools {
static provider = Lab.Anthropic;
/**
* Get the agent's tool name.
*/
name(): string {
return 'refunds_specialist';
}
/**
* Get the agent's tool description.
*/
description(): string {
return 'Determine whether an order is eligible for a refund and explain the next step.';
}
// ...
}
If a sub-agent does not implement CanActAsTool, laraflare will use the agent's class name as the tool name and a generic description that asks the parent agent to pass a clear, self-contained task description. Each sub-agent invocation runs in isolation and does not receive the parent agent's conversation history.
Warning
Sub-agents do not currently support tools that require human approval. If a sub-agent's tool requires approval, the sub-agent pauses. However, the parent agent receives a normal tool result and continues its run without notifying your application of the pending approval. Register tools that require approval on the top-level agent.
When the parent agent is streaming, its sub-agents stream as well, unless they produce structured output. For streaming sub-agents, the parent agent emits preliminary ToolResult events containing the text the sub-agent has produced so far. The tool call's final result follows these events, so you may skip preliminary events when iterating events manually:
import { StreamEvents } from '@laraflare/ai';
for await (const event of stream) {
if (event instanceof StreamEvents.ToolResult && event.preliminary) {
continue;
}
// ...
}
Response values such as text, usage, and toolResults ignore preliminary events. The Vercel protocol renders them as native streaming tool output, so useChat displays the progress without any custom code, while the AG-UI protocol reports them as activity snapshots. The sub-agent's final text becomes the tool call's result, which is available through the completed response's toolResults. The completed response's text, reasoning, citations, and usage only include the parent agent's own output. To track the usage of a sub-agent, you may listen for the AgentStreamed event and compare the event's prompt.parentInvocationId with the parent response's invocationId.
Middleware
Agents support middleware, allowing you to intercept and modify each generation step before it is sent to the provider. Middleware is invoked once per step, so a run that takes three steps will invoke it three times. Middleware can be created using the make:agent-middleware Artisan command:
npx artisan make:agent-middleware LogPrompts
The generated middleware will be placed in your application's app/Ai/Middleware directory. To add middleware to an agent, implement the HasMiddleware interface and define a middleware method that returns an array of middleware:
import { LogPrompts } from '../Ai/Middleware/LogPrompts';
import type { Agent } from '@laraflare/ai';
import type { HasMiddleware } from '@laraflare/ai/Contracts/HasMiddleware';
import { Promptable } from '@laraflare/ai';
export class SalesCoach extends Promptable() implements Agent, HasMiddleware {
// ...
/**
* Get the agent's middleware.
*/
middleware(): unknown[] {
return [
new LogPrompts(),
];
}
}
Each middleware class should define a handle method that receives a PendingStep and a function that passes the step to the next middleware:
import { Log } from '@laraflare/framework/Support/Facades/Log';
import type { PendingStep } from '@laraflare/ai';
export class LogPrompts {
/**
* Handle the pending generation step.
*/
handle(step: PendingStep, next: (step: PendingStep) => unknown) {
Log.info('Prompting agent', { model: step.model });
return next(step);
}
}
In addition to the provider, model, instructions, messages, and tools that are about to be sent, the step exposes the steps that have already completed, their combined usage, and the progress of the run:
step.steps;
step.usage;
step.number;
step.isFirstStep();
step.isFinalStep;
The withModel, withInstructions, withMessages, withTools, onlyTools, withoutTools, withToolChoice, withMaxTokens, and withProviderOptions methods each return a copy of the step. For example, you may remove an expensive tool once the agent has used it:
handle(step: PendingStep, next: (step: PendingStep) => unknown) {
if (! step.isFirstStep()) {
step = step.withoutTools('SearchDocumentation');
}
return next(step);
}
Or, you may keep a long tool calling loop within the context window by summarizing the middle of the conversation:
import { Summarizer } from '../Ai/Agents/Summarizer';
import { UserMessage } from '@laraflare/ai';
async handle(step: PendingStep, next: (step: PendingStep) => unknown) {
if (step.messages.length > 40) {
const summary = (await new Summarizer().prompt(
step.messages.slice(1, -10).map((message) => message.content).join('\n'),
)).text;
step = step.withMessages([
step.messages[0],
new UserMessage(`Summary of the conversation so far: ${summary}`),
...step.messages.slice(-10),
]);
}
return next(step);
}
Messages passed to the withMessages method only change what is sent for the current step. Later steps and the stored conversation continue to use the full, unsummarized history.
You may use the then method to execute code once the model has answered the step, before its tool calls are executed. This works for both synchronous and streaming responses:
import type { StepResponse } from '@laraflare/ai';
handle(step: PendingStep, next: (step: PendingStep) => any) {
return next(step).then((response: StepResponse) => {
Log.info('Agent responded', { text: response.text });
});
}
Middleware must return the result of next, a StepResponse, or StepResult.stop(). Return a StepResponse to answer the step without invoking the model, such as when serving a cached response. Return StepResult.stop() to end the run. Any other return value causes a LogicException.
Stopping Runs
To end an agent's run before its next model call, use the Stop middleware. For example, you may stop a run when a user presses a "stop" button or the run reaches an input-token budget. The response retains the completed steps and their combined usage:
import { Cache } from '@laraflare/framework/Support/Facades/Cache';
import { Stop, type PendingStep } from '@laraflare/ai';
middleware(): unknown[] {
return [
// Stop when the user has pressed the "stop" button...
Stop.when((step: PendingStep) => Cache.has(`chat:${this.user.id}:stopped`)),
// Stop when the run has used at least 50,000 input tokens...
Stop.unless((step: PendingStep) => step.usage.inputTokens < 50_000),
];
}
Before each step, when stops the run if the condition is true, and unless stops the run if the condition is false. A stopped streaming run has a cancelled finish reason.
Custom middleware may also end the run by returning StepResult.stop() instead of the result of next:
import { StepResult } from '@laraflare/ai';
handle(step: PendingStep, next: (step: PendingStep) => unknown) {
return this.cancelled(step) ? StepResult.stop() : next(step);
}
Anonymous Agents
Sometimes you may want to quickly interact with a model without creating a dedicated agent class. You can create an ad-hoc, anonymous agent using the agent function:
import { agent } from '@laraflare/ai';
const response = await agent({
instructions: 'You are an expert at software development.',
messages: [],
tools: [],
}).prompt('Tell me about laraflare');
Anonymous agents may also produce structured output:
import { agent, type JsonSchemaTypeFactory } from '@laraflare/ai';
const response = await agent({
schema: (schema: JsonSchemaTypeFactory) => ({
number: schema.integer().required(),
}),
}).prompt('Generate a random number less than 100');
Agent Configuration
TypeScript has no attributes, so you configure text generation options for an agent with static properties on the agent class. The following options are available:
maxSteps: The maximum number of steps the agent may take when using tools.maxTokens: The maximum number of tokens the model may generate.model: The model the agent should use.provider: The AI provider (or providers for failover) to use for the agent.temperature: The sampling temperature to use for generation (0.0 to 1.0).timeout: The HTTP timeout in seconds for agent requests (default: 60).topP: The nucleus sampling probability to use for generation (0.0 to 1.0).useCheapestModel: Use the provider's cheapest text model for cost optimization.useSmartestModel: Use the provider's most capable text model for complex tasks.
import type { Agent } from '@laraflare/ai';
import { Lab, Promptable } from '@laraflare/ai';
export class SalesCoach extends Promptable() implements Agent {
static provider = Lab.Anthropic;
static model = 'claude-sonnet-5';
static maxSteps = 10;
static maxTokens = 4096;
static temperature = 0.7;
static timeout = 120;
static topP = 0.9;
// ...
}
The useCheapestModel and useSmartestModel options allow you to automatically select the most cost-effective or most capable model for a given provider without specifying a model name. This is useful when you want to optimize for cost or capability across different providers:
export class SimpleSummarizer extends Promptable() implements Agent {
static useCheapestModel = true;
// Will use the cheapest model (e.g., Haiku)...
}
export class ComplexReasoner extends Promptable() implements Agent {
static useSmartestModel = true;
// Will use the most capable model (e.g., Opus)...
}
Note
The underlying model selected by
useCheapestModelanduseSmartestModelmay change between releases of the AI SDK as providers release new models. Switching models can introduce behavioral changes, deprecated parameters, and significant cost differences. If you need a stable, predictable model and pricing, specify the model explicitly using themodeloption.
Provider Options
If your agent needs to pass provider-specific options (such as OpenAI reasoning effort or penalty settings), implement the HasProviderOptions contract and define a providerOptions method:
import type { Agent, HasProviderOptions } from '@laraflare/ai';
import { Lab, Promptable } from '@laraflare/ai';
export class SalesCoach extends Promptable() implements Agent, HasProviderOptions {
// ...
/**
* Get provider-specific generation options.
*/
providerOptions(provider: Lab | string): Record<string, unknown> {
switch (provider) {
case Lab.OpenAI:
return {
reasoning: { effort: 'low' },
frequency_penalty: 0.5,
presence_penalty: 0.3,
};
case Lab.Anthropic:
return {
thinking: { budget_tokens: 1024 },
cache_control: { type: 'ephemeral' },
};
default:
return {};
}
}
}
The providerOptions method receives the provider currently being used (Lab value or string), allowing you to return different options per provider. This is especially useful when using failover, since each fallback provider can receive its own configuration.
The Anthropic example above also enables prompt caching via cache_control.
The image, audio, transcription, embedding, and reranking builders accept provider options as well:
import { Audios } from '@laraflare/ai';
const audio = await Audios.of('I love coding with laraflare.')
.withProviderOptions({ speed: 1.25 })
.generate();
You may also pass a closure instead of an object, which will receive the provider currently being used.
Custom HTTP Headers
Headers configured for a provider within your application's config/ai.ts configuration file are sent with every request that provider makes. To send headers on a per-request basis, such as metadata used by an AI gateway, you may use the withHeaders method, which is available on the image, audio, transcription, embedding, and reranking builders, as well as on file uploads:
import { Embeddings } from '@laraflare/ai';
const embeddings = await Embeddings.for(chunks)
.withHeaders({ 'cf-aig-metadata': JSON.stringify({ team: team.id }) })
.withProviderOptions({ dimensions: 1024 })
.generate();
Headers may also be given as a closure, which receives the provider currently being used. Headers are not included in the request body and do not affect embedding cache keys.
Prompt Caching
Most providers cache repeated prompt prefixes automatically and bill the cached portion at a discount. OpenAI, Gemini, Groq, DeepSeek, and xAI require no configuration, and you may inspect the savings via the response's usage:
response.usage.cacheReadInputTokens;
response.usage.cacheWriteInputTokens;
Both of these counts are subsets of the input token total, which is discussed further in the usage documentation.
The anthropic and bedrock providers only cache when asked. The static cacheInstructions and cacheToolDefinitions properties place a cache breakpoint at the end of your agent's instructions and tool definitions, so every conversation reads that prefix from the cache instead of writing it again:
import { CacheInstructions } from '@laraflare/ai/Attributes/CacheInstructions';
import { CacheToolDefinitions } from '@laraflare/ai/Attributes/CacheToolDefinitions';
export class SalesCoach extends Promptable() implements Agent {
static cacheInstructions = new CacheInstructions();
static cacheToolDefinitions = new CacheToolDefinitions();
// ...
}
If your instructions change on every request, such as when they embed the current date, use cacheToolDefinitions alone. Caching a prefix that changes on every request creates a new cache entry each time, so you pay to write it to the cache without ever reusing it.
Providers that do not support these options ignore them, so an agent may safely declare them while using failover.
Cached prefixes are retained for five minutes by default. Anthropic may retain them for an hour if you pass a TTL:
static cacheInstructions = new CacheInstructions('1h');
static cacheToolDefinitions = new CacheToolDefinitions('1h');
Alternatively, Anthropic's automatic caching may be enabled via a top-level cache_control provider option. This places a single breakpoint after the last block of the request, so the breakpoint advances as the conversation grows and each turn reads the previous turns from the cache. Both mechanisms may be combined.
Warning
Because providers build prompts in the order tools, instructions, and messages, caching instructions for an hour also requires caching tool definitions for an hour. Mixing the two throws an
InvalidArgumentException.
Human Tool Approval
Warning
Tool approval requires the paused turn's history to be available when the run is resumed. You should either use a
Conversationalagent, such as one using theRemembersConversationsmixin, or provide the history from your application's frontend using thewithMessagesmethod. Agents that do neither will throw anApprovalNotResumableExceptionwhen a tool pauses.
Tools that perform sensitive or irreversible actions may require human approval before they are executed. To make a tool approvable, implement the Approvable contract and use the InteractsWithApprovals mixin. Approvable tools require approval by default:
import type { JsonSchemaTypeFactory, Tool, ToolRequest, Type } from '@laraflare/ai';
import { InteractsWithApprovals } from '@laraflare/ai';
import type { Approvable } from '@laraflare/ai/Contracts/Approvable';
import { Storage } from '@laraflare/framework/Support/Facades/Storage';
export class DeleteFile extends InteractsWithApprovals(Object) implements Approvable, Tool {
/**
* Get the description of the tool's purpose.
*/
description(): string {
return 'Delete a file from storage.';
}
/**
* Execute the tool.
*/
async handle(request: ToolRequest): Promise<string> {
await Storage.delete(request['path']);
return `Deleted [${request['path']}].`;
}
/**
* Get the tool's schema definition.
*/
schema(schema: JsonSchemaTypeFactory): Record<string, Type> {
return {
path: schema.string().required(),
};
}
}
To determine whether approval is needed based on the tool call's arguments, define a needsApproval method on the tool. This method may return a boolean or an Approval instance that includes a reason for the approval request:
import { Approval } from '@laraflare/ai';
/**
* Determine whether the tool needs approval for the given request.
*/
protected needsApproval(request: ToolRequest): Approval | boolean {
return request['path'].startsWith('temporary/')
? false
: Approval.required('This will permanently delete a file.');
}
You may override a tool's approval requirement when returning it from an agent's tools method:
tools(): Iterable<Tool> {
return [
new SendNotification().withoutApproval(),
new DeleteFile().requireApproval('Deletion review required.'),
];
}
When an approvable tool is called, the agent pauses before executing it. You may inspect the response's pending approvals, which contain each tool call's ID, tool name, arguments, and approval reason:
const response = await new FileAssistant()
.forUser(user)
.prompt('Delete the old invoice.');
if (response.hasPendingApprovals()) {
for (const approval of response.pendingApprovals) {
// approval.id
// approval.tool
// approval.arguments
// approval.reason
}
}
To resume the agent, continue the conversation and provide a Decisions instance containing a decision for each pending tool call. Decisions may approve the call, reject it, or edit its arguments before execution:
import { Decision, Decisions } from '@laraflare/ai';
const response = await new FileAssistant()
.continue(conversationId, user)
.prompt(Decisions.from({
call_abc: Decision.approve(),
call_ghi: Decision.reject('The invoice must be retained.'),
}));
Warning
Paused turns are matched by their conversation and pending tool calls, not by the participant that paused them. Therefore, your application should authorize access to the conversation before resuming it, as demonstrated in the complete approval flow, or verify access using the conversation store's
conversationBelongsTomethod.
The boolean values true and false may be used as shorthand for approval and rejection. Every pending tool call must receive a decision. Unknown, missing, or previously resolved tool call IDs will cause an ApprovalMismatchException to be thrown. You may provide a default for calls without an explicit decision using the approveRemaining or rejectRemaining methods:
const decisions = Decisions.from({
call_abc: true,
}).rejectRemaining('Not approved.');
const response = await new FileAssistant()
.continue(conversationId, user)
.prompt(decisions);
A rejection with a result, such as Decision.reject('Not approved.'), is returned to the model so it may continue responding. A rejection without a result stops the generation loop after recording the rejection.
Tool approval is supported by the prompt, stream, queue, broadcast, broadcastNow, and broadcastOnQueue methods.
During streaming and broadcasting, a pause is represented by a tool_approval_request event. When using the Vercel AI SDK stream protocol, approval requests and results are emitted using the protocol's native tool approval parts, and the Agent User Interaction protocol reports them as interrupts.
Clients that use either protocol post their decisions along with the rest of the conversation, so a chat request may be passed directly to the agent:
const chat = Vercel.chat(request);
return new FileAssistant()
.continue(conversationId, request.user())
.stream(chat)
.usingProtocol(chat.protocol());
When a paused turn is resumed, the resumed steps are merged into that turn, so each turn is stored as a single assistant message. The response's assistantMessageId contains the ID of the paused message, and that message's usage includes both the pause and the resume.
For queued agents, the resulting response is passed to the andThen callback, and laraflare also dispatches a ToolApprovalRequested event.
laraflare stores the result of an approved tool before asking the model to continue. If generation then fails, the approval has already been resolved. Continue the conversation with a normal text prompt instead of submitting the same approval decisions again.
Complete Approval Flow
The following route demonstrates a complete approval flow, accepting either a new text prompt or approval decisions from the chat screen. This example assumes the application's User model uses the HasConversations mixin:
import { FileAssistant } from '../Ai/Agents/FileAssistant';
import { Decision, Decisions } from '@laraflare/ai';
import { Conversation } from '@laraflare/ai/Models/Conversation';
import { Gate } from '@laraflare/framework/Support/Facades/Gate';
Route.post('/chat/{conversation}', async (request: Request, conversation: Conversation) => {
await Gate.authorize('view', conversation);
const validated = await request.validate({
message: ['nullable', 'string', 'required_without:decisions', 'prohibits:decisions'],
decisions: ['nullable', 'array', 'required_without:message', 'prohibits:message'],
'decisions.*.action': ['required_with:decisions', 'in:approve,reject'],
'decisions.*.result': ['nullable', 'string'],
});
const prompt = validated.decisions
? Decisions.from(Object.fromEntries(
Object.entries(validated.decisions as Record<string, { action: string; result?: string }>).map(
([id, decision]) => [
id,
decision.action === 'approve' ? Decision.approve() : Decision.reject(decision.result ?? null),
],
),
))
: validated.message;
const response = await new FileAssistant()
.continue(conversation.id, request.user())
.prompt(prompt);
return {
conversation_id: response.conversationId,
status: response.hasPendingApprovals() ? 'awaiting_approval' : 'complete',
message: response.text,
approvals: response.pendingApprovals,
};
}).middleware('auth');
When the response status is awaiting_approval, the chat screen should render the pending approvals and submit the user's choices to the same endpoint using the tool call ID as each decision's key. Otherwise, the screen may submit a plain message value:
{
"decisions": {
"call_abc": {
"action": "approve"
},
"call_def": {
"action": "reject",
"result": "The invoice must be retained."
}
}
}
Images
The Images class may be used to generate images using the openai, gemini, or xai providers:
import { Images } from '@laraflare/ai';
const image = await Images.of('A donut sitting on the kitchen counter').generate();
const rawContent = String(image);
Note
The
ImageandAudionames belong to the file classes used for attachments, so the generators are namedImagesandAudios.
The square, portrait, and landscape methods may be used to control the aspect ratio of the image, while the quality method may be used to guide the model on final image quality (high, medium, low). The timeout method may be used to specify the HTTP timeout in seconds:
const image = await Images.of('A donut sitting on the kitchen counter')
.quality('high')
.landscape()
.timeout(120)
.generate();
You may attach reference images using the attachments method:
import { Image, Images } from '@laraflare/ai';
const image = await Images.of('Update this photo of me to be in the style of an impressionist painting.')
.attachments([
Image.fromStorage('photo.jpg'),
// Image.fromPath('./storage/photo.jpg'),
// Image.fromUrl('https://example.com/photo.jpg'),
// request.file('photo'),
])
.landscape()
.generate();
Some providers may generate multiple images in a single request. OpenAI, Azure, and xAI accept an n provider option, and the response will contain every image that was returned:
const response = await Images.of('A donut sitting on the kitchen counter')
.withProviderOptions({ n: 4 })
.generate();
response.images; // A collection of generated images...
response.firstImage(); // The first generated image...
Generated images may be easily stored on the default disk configured in your application's config/filesystems.ts configuration file:
const image = await Images.of('A donut sitting on the kitchen counter').generate();
const path = await image.store();
const path2 = await image.storeAs('image.jpg');
const path3 = await image.storePublicly();
const path4 = await image.storePubliclyAs('image.jpg');
Image generation may also be queued:
import { Images, type ImageResponse } from '@laraflare/ai';
const queued = await Images.of('A donut sitting on the kitchen counter')
.portrait()
.queue();
await queued.andThen(async (image: ImageResponse) => {
const path = await image.store();
// ...
});
Audio
The Audios class may be used to generate audio from the given text:
import { Audios } from '@laraflare/ai';
const audio = await Audios.of('I love coding with laraflare.').generate();
const rawContent = String(audio);
You may also generate audio from a string using the toAudio method available via the Stringable class:
import { Str } from '@laraflare/framework/Support/Str';
const audio = await Str.of('I love coding with laraflare.').toAudio();
The male, female, and voice methods may be used to determine the voice of the generated audio:
const audio = await Audios.of('I love coding with laraflare.')
.female()
.generate();
const audio2 = await Audios.of('I love coding with laraflare.')
.voice('voice-id-or-name')
.generate();
Similarly, the instructions method may be used to dynamically coach the model on how the generated audio should sound:
const audio = await Audios.of('I love coding with laraflare.')
.female()
.instructions('Said like a pirate')
.generate();
Generated audio may be easily stored on the default disk configured in your application's config/filesystems.ts configuration file:
const audio = await Audios.of('I love coding with laraflare.').generate();
const path = await audio.store();
const path2 = await audio.storeAs('audio.mp3');
const path3 = await audio.storePublicly();
const path4 = await audio.storePubliclyAs('audio.mp3');
Audio generation may also be queued:
import { Audios, type AudioResponse } from '@laraflare/ai';
const queued = await Audios.of('I love coding with laraflare.').queue();
await queued.andThen(async (audio: AudioResponse) => {
const path = await audio.store();
// ...
});
Transcriptions
The Transcription class may be used to generate a transcript of the given audio:
import { Transcription } from '@laraflare/ai';
const transcript = await Transcription.fromPath('./storage/audio.mp3').generate();
const transcript2 = await Transcription.fromStorage('audio.mp3').generate();
const transcript3 = await (await Transcription.fromUpload(request.file('audio'))).generate();
return String(transcript);
The diarize method may be used to indicate you would like the response to include the diarized transcript in addition to the raw text transcript, allowing you to access the segmented transcript by speaker:
const transcript = await Transcription.fromStorage('audio.mp3')
.diarize()
.generate();
Transcription generation may also be queued:
import { Transcription, type TranscriptionResponse } from '@laraflare/ai';
const queued = await Transcription.fromStorage('audio.mp3').queue();
await queued.andThen((transcript: TranscriptionResponse) => {
// ...
});
Text Summarization
You may summarize text using the summarize method available via the Stringable class. By default, the summary will contain no more than three sentences and will be generated using the configured provider's cheapest text model:
import { Str } from '@laraflare/framework/Support/Str';
const summary = await Str.of(article).summarize();
You may specify the maximum number of sentences, provider, model, and timeout used to generate the summary, in that order. The Str class also offers a static version of the method:
import { Lab } from '@laraflare/ai';
const summary = await Str.of(article).summarize(4, Lab.Anthropic, 'claude-sonnet-5', 30);
const summary2 = await Str.summarize(article, 4);
Embeddings
You may easily generate vector embeddings for any given string using the toEmbeddings method available via the Stringable class:
import { Str } from '@laraflare/framework/Support/Str';
const embeddings = await Str.of('Napa Valley has great wine.').toEmbeddings();
Alternatively, you may use the Embeddings class to generate embeddings for multiple inputs at once:
import { Embeddings } from '@laraflare/ai';
const response = await Embeddings.for([
'Napa Valley has great wine.',
'laraflare is a TypeScript framework.',
]).generate();
response.embeddings; // [[0.123, 0.456, ...], [0.789, 0.012, ...]]
You may specify the dimensions and provider for the embeddings:
const response = await Embeddings.for(['Napa Valley has great wine.'])
.dimensions(1536)
.generate(Lab.OpenAI, 'text-embedding-3-small');
Multimodal Embeddings
In addition to strings, the Embeddings.for method accepts image, audio, document, and video inputs, allowing you to generate embeddings for non-text content. Gemini supports image, audio, document, and video embeddings, while VoyageAI supports image and video embeddings:
import { Embeddings, Image, Lab, Video } from '@laraflare/ai';
const response = await Embeddings.for([
'A vineyard at sunset.',
Image.fromStorage('vineyard.jpg'),
Video.fromPath('./storage/tour.mp4'),
]).generate(Lab.Gemini);
Multimodal inputs use the same file classes used for attachments. These files may be created from a local path, a filesystem disk, a remote URL, or Base64-encoded content. Images, documents, and videos may also be created from uploaded files, while documents may be created from raw string content:
import { Audio, Document, Image, Video } from '@laraflare/ai';
Image.fromPath('./storage/photo.jpg');
Image.fromStorage('photo.jpg');
Image.fromUpload(request.file('photo'));
Audio.fromPath('./storage/clip.mp3');
Audio.fromStorage('clip.mp3');
Video.fromPath('./storage/video.mp4');
Video.fromStorage('video.mp4');
Video.fromUpload(request.file('video'));
Document.fromUrl('https://example.com/report.pdf');
Document.fromString('laraflare is a TypeScript framework.', 'text/plain');
Document.fromUpload(request.file('report'));
Note
VoyageAI does not allow remote URL media and Base64-encoded media to be mixed in a single request. Local, stored, and uploaded files are sent as Base64-encoded content, and text inputs may be combined with either media source. Consult your provider's documentation to determine which multimodal models and inputs are available.
Querying Embeddings
Once you have generated embeddings, you will typically store them in a vector column in your database for later querying. laraflare provides native support for vector columns on PostgreSQL via the pgvector extension and MariaDB, and stores them as JSON text on SQLite and D1. To get started, define a vector column in your migration, specifying the number of dimensions:
await Schema.ensureVectorExtensionExists();
await Schema.create('documents', (table: Blueprint) => {
table.id();
table.string('title');
table.text('content');
table.vector('embedding', 1536);
table.timestamps();
});
You may also add a vector index to speed up similarity searches. When calling index on a vector column, laraflare will automatically create an HNSW index with cosine distance:
table.vector('embedding', 1536).index();
On your Eloquent model, you should cast the vector column using the AsVector cast:
import { AsVector } from '@laraflare/framework/Database/Eloquent/Casts/AsVector';
static casts() {
return {
embedding: AsVector,
};
}
To query for similar records, use the whereVectorSimilarTo method. This method filters results by a minimum cosine similarity (between 0.0 and 1.0, where 1.0 is identical) and orders the results by similarity:
import { Document } from '../Models/Document';
const documents = await Document.query()
.whereVectorSimilarTo('embedding', queryEmbedding, 0.4)
.limit(10)
.get();
The queryEmbedding may be an array of numbers or a plain string. When a string is given, laraflare will automatically generate embeddings for it:
const documents = await Document.query()
.whereVectorSimilarTo('embedding', 'best wineries in Napa Valley')
.limit(10)
.get();
If you need more control, you may use the lower-level whereVectorDistanceLessThan, selectVectorDistance, and orderByVectorDistance methods independently:
const documents = await Document.query()
.select('*')
.selectVectorDistance('embedding', queryEmbedding, 'distance')
.whereVectorDistanceLessThan('embedding', queryEmbedding, 0.3)
.orderByVectorDistance('embedding', queryEmbedding)
.limit(10)
.get();
If you would like to give an agent the ability to perform similarity searches as a tool, check out the Similarity Search tool documentation.
Note
Vector queries are supported on PostgreSQL connections using the
pgvectorextension, on MariaDB 11.7 or later using its native vector support, and on SQLite and D1, where the vector is stored as JSON text.
Caching Embeddings
Embedding generation can be cached to avoid redundant API calls for identical inputs. To enable caching, set the ai.caching.embeddings.cache configuration option to true:
caching: {
embeddings: {
cache: true,
store: env('CACHE_STORE', 'database'),
individually: true,
// ...
},
},
When caching is enabled, embeddings are cached for 30 days. The cache key is based on the provider, model, dimensions, and input content, ensuring that identical requests return cached results while different configurations generate fresh embeddings.
By default, each input's embedding is cached under its own key, so a later request may hit the cache for inputs it has seen before even when the set of inputs or their order has changed. To instead cache the entire set of inputs under a single key, set the ai.caching.embeddings.individually configuration option to false.
You may also enable caching for a specific request using the cache method, even when global caching is disabled:
const response = await Embeddings.for(['Napa Valley has great wine.'])
.cache()
.generate();
You may specify a custom cache duration in seconds:
const response = await Embeddings.for(['Napa Valley has great wine.'])
.cache(3600) // Cache for 1 hour
.generate();
The toEmbeddings Stringable method also accepts a cache option:
// Cache with default duration...
const embeddings = await Str.of('Napa Valley has great wine.').toEmbeddings({ cache: true });
// Cache for a specific duration...
const embeddings2 = await Str.of('Napa Valley has great wine.').toEmbeddings({ cache: 3600 });
Reranking
Reranking allows you to reorder a list of documents based on their relevance to a given query. This is useful for improving search results by using semantic understanding.
The Reranking class may be used to rerank documents:
import { Reranking } from '@laraflare/ai';
const response = await Reranking.of([
'Django is a Python web framework.',
'laraflare is a TypeScript web application framework.',
'React is a JavaScript library for building user interfaces.',
]).rerank('TypeScript frameworks');
// Access the top result...
response.first().document; // "laraflare is a TypeScript web application framework."
response.first().score; // 0.95
response.first().index; // 1 (original position)
The limit method may be used to restrict the number of results returned, while the timeout method may be used to specify the HTTP timeout in seconds, which defaults to 30:
const response = await Reranking.of(documents)
.limit(5)
.timeout(60)
.rerank('search query');
Reranking Collections
For convenience, collections may be reranked using the rerank macro. The first argument specifies which field(s) to use for reranking, and the second argument is the query:
// Rerank by a single field...
const posts = await (await Post.all())
.rerank('body', 'laraflare tutorials');
// Rerank by multiple fields (sent as JSON)...
const reranked = await posts.rerank(['title', 'body'], 'laraflare tutorials');
// Rerank using a closure to build the document...
const reranked2 = await posts.rerank(
(post) => `${post.title}: ${post.body}`,
'laraflare tutorials',
);
You may also limit the number of results and specify a provider, in the order by, query, limit, provider, model, timeout:
const reranked = await posts.rerank(
'content',
'laraflare tutorials',
10,
Lab.Cohere,
null,
60,
);
Classification
Warning
Classification is currently experimental and its API may change in future minor releases of the AI SDK.
Classification allows you to ask a fixed set of questions about a given string or array of data and receive a typed answer, backed by a probability, for each question instead of free-form text. This is useful for routing, moderation, and scoring, where you need to compare an answer against a threshold or make assertions about it in your tests.
The Classification class may be used to classify content. Each question is given a key, and the corresponding answer may be retrieved from the response using that key:
import { Boolean, Choice, Classification, Score } from '@laraflare/ai';
const result = await Classification.of(supportRequest)
.questions({
urgent: new Boolean('Does this request need an immediate response?', {
true: 'Explicitly time-sensitive',
false: 'No urgency expressed',
}),
department: new Choice('Which team should handle this request?', {
billing: 'Payments, invoices, and refunds',
technical: 'Bugs, outages, and integrations',
sales: 'Pricing, plans, and upgrades',
}),
frustration: new Score('How frustrated is the customer?', [
'Calm',
'Frustrated',
'Very angry',
]),
})
.classify();
Boolean questions return the probability that the answer is "true". The isTrue method may be used to determine whether that probability meets a given threshold, which defaults to 0.5:
result['urgent'].probability; // 0.94
result['urgent'].isTrue(0.8); // true
Choice questions return one of the given options along with the probability of each option. The confidence property indicates how certain the provider is across the full set of probabilities, and will be null when the provider is unable to measure it:
result['department'].choice; // 'technical'
result['department'].probabilityOf('technical'); // 0.87
result['department'].probabilities; // { billing: 0.08, technical: 0.87, sales: 0.05 }
result['department'].confidence; // 0.82
Score questions return a position on the ordered levels that were provided. The score property is probability-weighted and may fall between two levels, while the level and label methods describe the most probable level:
result['frustration'].score; // 1.24, the probability-weighted level
result['frustration'].level(); // 1, the most probable level
result['frustration'].label(); // 'Frustrated'
result['frustration'].normalized(); // 0.62, the score as a fraction of the highest level
result['frustration'].probabilities; // [0.12, 0.52, 0.36]
The criteria given to a Boolean question, the option descriptions given to a Choice question, and the levels given to a Score question may each be an array when a single sentence is not sufficient. Choice questions require at least two options, while Score questions require at least two levels.
The response may be iterated, counted, and accessed like an object. In addition, the answer method may be used to retrieve a single answer, while the collect method returns all of the answers as a collection:
result.answer('urgent');
result.collect();
result.usage;
result.meta.provider;
Note
The question classes are named
Boolean,Choice, andScore. ImportingBooleanshadows JavaScript's globalBooleanin that file, so you may preferimport { Boolean as BooleanQuestion } from '@laraflare/ai'.
Classifying Images
When using the OpenAI, OpenAI-compatible, Gemini, TypeSafe, or OpenRouter providers, images may be classified alongside the given content by passing them as the second argument to the of method. Images may be created using the same file classes used for attachments:
import { Boolean, Classification, Image } from '@laraflare/ai';
const result = await Classification.of('Inspect the product in this photo.', [
Image.fromPath(photo),
])
.question('damaged', new Boolean('Does the product have visible damage?'))
.classify('openai');
To refer to a specific image in a question, attach images with string keys. The SDK sends each image's key to the provider as its name:
const result = await Classification.of('Inspect the products in these photos.', {
front: Image.fromPath(front),
back: Image.fromPath(back),
})
.question('damaged', new Boolean('Is the product in `front` or `back` damaged?'))
.classify();
Yes or No Decisions
For a single yes or no decision, you may use the decide method available via the Stringable class, which returns a boolean instead of a full response. You may describe what a "yes" and a "no" mean, and specify the probability the answer must reach, which defaults to 0.5:
import { Str } from '@laraflare/framework/Support/Str';
if (await Str.of(message).decide('Is this spam?')) {
// ...
}
const spam = await Str.of(message).decide('Is this spam?', {
true: 'Unsolicited bulk mail.',
false: 'A genuine message from a customer.',
}, 0.9);
Choosing From Collections
To quickly choose a single item from a list of options, you may use the decide method available on the Collection class. The method accepts a question and the text to classify, and returns the chosen item from the collection.
Collections of strings and enums may be used directly, while other items should be named using the by argument. You may also provide a field, array of fields, or closure via the describe argument to give the model more detail about each option:
const department = await collect(['billing', 'technical', 'sales'])
.decide('Which team should handle this request?', ticket.body);
const priority = await collect(Object.values(Priority))
.decide('How urgent is this request?', ticket.body);
const department2 = await (await Department.all()).decide(
'Which department should handle this request?',
ticket.body,
'name',
'description',
);
The description defined via the describe argument serves as the criteria the model uses to determine whether the text matches that option, which is helpful when an option's name alone is ambiguous. When a closure is provided to the describe argument, it receives each item and should return a string or array describing it:
const priority = await collect(Object.values(Priority)).decide(
'How urgent is this request?',
ticket.body,
null,
(priority) => describePriority(priority),
);
When a collection of strings is keyed by strings, its keys are used as the options and its values as their descriptions, and the chosen key is returned. If a threshold is given and the probability of the chosen option is below it, null is returned:
const department = await collect({
billing: 'Payments, invoices, and refunds',
technical: 'Bugs, outages, and integrations',
}).decide('Which team should handle this request?', ticket.body, null, null, 0.6) ?? 'triage';
Files
The Files class or the individual file classes may be used to store files with your AI provider for later use in conversations. This is useful for large documents or files you want to reference multiple times without re-uploading:
import { Document, Image } from '@laraflare/ai';
// Store a file from a local path...
let response = await Document.fromPath('./storage/document.pdf').put();
response = await Image.fromPath('./storage/photo.jpg').put();
// Store a file that is stored on a filesystem disk...
response = await Document.fromStorage('document.pdf', 'local').put();
response = await Image.fromStorage('photo.jpg', 'local').put();
// Store a file that is stored on a remote URL...
response = await Document.fromUrl('https://example.com/document.pdf').put();
response = await Image.fromUrl('https://example.com/photo.jpg').put();
return response.id;
You may also store raw content or uploaded files:
import { Document } from '@laraflare/ai';
// Store raw content...
const stored = await Document.fromString('Hello, World!', 'text/plain').put();
// Store an uploaded file...
const stored2 = await Document.fromUpload(request.file('document')).put();
Once a file has been stored, you may reference the file when generating text via agents instead of re-uploading the file:
import { SalesCoach } from '../Ai/Agents/SalesCoach';
import { Document } from '@laraflare/ai';
const response = await new SalesCoach(user).prompt('Analyze the attached sales transcript...', {
attachments: [
Document.fromId('file-id'), // Attach a stored document...
],
});
To retrieve a previously stored file, use the get method on a file instance:
import { Document } from '@laraflare/ai';
const file = await Document.fromId('file-id').get();
file.id;
file.mimeType();
To delete a file from the provider, use the delete method:
await Document.fromId('file-id').delete();
By default, the Files class uses the default AI provider configured in your application's config/ai.ts configuration file. For most operations, you may specify a different provider using the provider argument:
const response = await Document.fromPath('./storage/document.pdf')
.put(null, null, Lab.Anthropic);
You may pass provider-specific upload options using the withProviderOptions method. For example, you may set OpenAI's file purpose:
const response = await Document.fromPath('./storage/knowledge.txt')
.withProviderOptions({ purpose: 'assistants' })
.put();
To scope options per provider, pass a closure that receives the current provider:
import { Document, Lab } from '@laraflare/ai';
const response = await Document.fromPath('./storage/training.jsonl')
.withProviderOptions((provider: Lab | string) => provider === Lab.OpenAI ? { purpose: 'fine-tune' } : {})
.put();
Using Stored Files in Conversations
Once a file has been stored with a provider, you may reference it in agent conversations using the fromId method on the Document or Image classes:
import { DocumentAnalyzer } from '../Ai/Agents/DocumentAnalyzer';
import { Document } from '@laraflare/ai';
const stored = await Document.fromPath('./storage/report.pdf').put();
const response = await new DocumentAnalyzer().prompt('Summarize this document.', {
attachments: [
Document.fromId(stored.id),
],
});
Similarly, stored images may be referenced using the Image class:
import { Image } from '@laraflare/ai';
const stored = await Image.fromPath('./storage/photo.jpg').put();
const response = await new ImageAnalyzer().prompt('What is in this image?', {
attachments: [
Image.fromId(stored.id),
],
});
Vector Stores
Vector stores allow you to create searchable collections of files that can be used for retrieval-augmented generation (RAG). The Stores class provides methods for creating, retrieving, and deleting vector stores:
import { Stores } from '@laraflare/ai';
// Create a new vector store...
const store = await Stores.create('Knowledge Base');
// Create a store with additional options...
const store2 = await Stores.create(
'Knowledge Base',
'Documentation and reference materials.',
null,
days(30),
);
return store.id;
To retrieve an existing vector store by its ID, use the get method:
import { Stores } from '@laraflare/ai';
const store = await Stores.get('store_id');
store.id;
store.name;
store.fileCounts;
store.ready;
To delete a vector store, use the delete method on the Stores class or the store instance:
// Delete by ID...
await Stores.delete('store_id');
// Or delete via a store instance...
const store = await Stores.get('store_id');
await store.delete();
Adding Files to Stores
Once you have a vector store, you may add files to it using the add method. Files added to a store are automatically indexed for semantic searching using the file search provider tool:
import { Document, Stores } from '@laraflare/ai';
const store = await Stores.get('store_id');
// Add a file that has already been stored with the provider...
let document = await store.add('file_id');
document = await store.add(Document.fromId('file_id'));
// Or, store and add a file in one step...
document = await store.add(Document.fromPath('./storage/document.pdf'));
document = await store.add(Document.fromStorage('manual.pdf'));
document.id;
document.fileId;
Note
Typically, when adding previously stored files to vector stores, the returned document ID will match the file's previously assigned ID; however, some vector storage providers may return a new, different "document ID". Therefore, it's recommended that you always store both IDs in your database for future reference.
When adding a file to a Gemini store, laraflare waits for the import to finish so that the document is searchable once the call returns. An AiException will be thrown if the import fails or exceeds five minutes, so you may wish to add Gemini files from a queued job.
You may attach metadata to files when adding them to a store. This metadata can later be used to filter search results when using the file search provider tool:
await store.add(Document.fromPath('./storage/document.pdf'), {
author: 'Taylor Otwell',
department: 'Engineering',
year: 2026,
});
To remove a file from a store, use the remove method:
await store.remove('file_id');
Removing a file from a vector store does not remove it from the provider's file storage. To remove a file from the vector store and delete it permanently from file storage, use the deleteFile argument:
await store.remove('file_abc123', true);
Usage
Every response contains a usage property containing the token counts reported by the provider. The input and output counts are totals, so tokens counted as cached or reasoning tokens are also included in the total they belong to:
const response = await new SalesCoach(user).prompt('Analyze this sales transcript...');
response.usage.inputTokens;
response.usage.outputTokens;
response.usage.totalTokens();
Text generation returns a TextUsage instance, which breaks these totals down further. Each of these values will be null, rather than 0, when the provider does not report it:
response.usage.cacheReadInputTokens; // Subset of the input tokens read from a prompt cache...
response.usage.cacheWriteInputTokens; // Subset of the input tokens written to a prompt cache...
response.usage.reasoningTokens; // Subset of the output tokens spent on reasoning...
response.usage.uncachedInputTokens(); // Input tokens that were neither read from nor written to the cache...
Cache reads, cache writes, and uncached input are billed at different rates, so you should price these three counts separately instead of using the input total alone.
The remaining capabilities return a usage object containing the counts specific to them:
| Capability | Usage object | Adds |
|---|---|---|
| Text, classification | TextUsage |
Cache read, cache write, and reasoning tokens |
| Images | ImageUsage |
imageInputTokens and imageOutputTokens |
| Transcription | TranscriptionUsage |
audioSeconds, the duration of the transcribed audio |
| Reranking | RerankingUsage |
searchUnits, which some providers bill instead of tokens |
| Audio, embeddings | Usage |
Not every provider reports every count, and counts that a provider does not report will be null:
import { Images, Transcription } from '@laraflare/ai';
(await Images.of('A donut sitting on the kitchen counter').generate()).usage.imageOutputTokens;
(await Transcription.fromPath('./storage/meeting.mp3').generate()).usage.audioSeconds;
Failover
When prompting or generating other media, you may provide an array of providers / models to automatically failover to a backup provider / model if a service interruption or rate limit is encountered on the primary provider:
import { SalesCoach } from '../Ai/Agents/SalesCoach';
import { Images, Lab } from '@laraflare/ai';
const response = await new SalesCoach(user).prompt('Analyze this sales transcript...', {
provider: [Lab.OpenAI, Lab.Anthropic],
});
const image = await Images.of('A donut sitting on the kitchen counter')
.generate([Lab.Gemini, Lab.xAI]);
Failover only occurs when a FailoverableException is thrown — such as a rate limit (RateLimitedException), an overloaded or unavailable provider (ProviderOverloadedException), or insufficient credits (InsufficientCreditsException). Ordinary errors, like a validation or bad request error, will not trigger failover.
When you pass a plain list of providers, such as [Lab.OpenAI, Lab.Anthropic], each provider uses its default model. To specify a particular model for each provider in the failover chain, pass an object keyed by the provider:
import { Lab } from '@laraflare/ai';
const response = await new SalesCoach(user).prompt('Analyze this sales transcript...', {
provider: {
[Lab.Gemini]: 'gemini-3-flash-preview',
[Lab.DeepSeek]: 'deepseek-v4-pro',
},
});
Testing
When faking queued image, audio, transcription, or embeddings generation, any andThen callback registered on the queued generation will be invoked with the faked response, allowing you to test the logic contained within the callback. If you would prefer that these callbacks are not invoked, you may fake the queue using Queue.fake() as well.
Agents
To fake an agent's responses during tests, call the fake method on the agent class. You may optionally provide an array of responses or a closure:
import { SalesCoach } from '../Ai/Agents/SalesCoach';
import type { AgentPrompt } from '@laraflare/ai';
// Automatically generate a fixed response for every prompt...
SalesCoach.fake();
// Provide a list of prompt responses...
SalesCoach.fake([
'First response',
'Second response',
]);
// Dynamically handle prompt responses based on the incoming prompt...
SalesCoach.fake((prompt: AgentPrompt) => {
return `Response for: ${prompt.prompt}`;
});
When faking an agent that returns structured output, you may provide objects as responses. The agent will return a structured response containing the given data:
SalesCoach.fake([
{ score: 87 },
]);
You may also fake a response that is awaiting tool approval:
import { AgentResponse, PendingApproval } from '@laraflare/ai';
FileAssistant.fake([
AgentResponse.fakeWithPendingApprovals([
new PendingApproval('call_abc', 'DeleteFile', { path: 'invoice.pdf' }, 'This will permanently delete a file.'),
]),
]);
const response = await new FileAssistant().prompt('Delete the invoice.');
response.hasPendingApprovals(); // true
In addition, you can fake a response that includes reasoning. The fake emits reasoning events, so the reasoning is reported on streamed runs as well:
import { AgentResponse } from '@laraflare/ai';
SalesCoach.fake([
AgentResponse.fakeWithReasoning('They asked about pricing.', 'Plans start at $10.'),
]);
const response = new SalesCoach().stream('What does it cost?');
for await (const event of response) {
// ...
}
response.reasoning; // 'They asked about pricing.'
Note
When
Agent.fake()is invoked on an agent that returns structured output and fake output was not explicitly provided, laraflare will automatically generate fake data that matches your agent's defined output schema.
After prompting the agent, you may make assertions about the prompts that were received:
import type { AgentPrompt } from '@laraflare/ai';
SalesCoach.assertPrompted('Analyze this...');
SalesCoach.assertPrompted((prompt: AgentPrompt) => {
return prompt.contains('Analyze');
});
SalesCoach.assertPromptedTimes(3);
SalesCoach.assertNotPrompted('Missing prompt');
SalesCoach.assertNeverPrompted();
When asserting an approval continuation, you may inspect the prompt's approval decisions:
import { Decisions, type AgentPrompt } from '@laraflare/ai';
FileAssistant.fake();
await new FileAssistant().prompt(Decisions.from({
call_abc: true,
}));
FileAssistant.assertPrompted((prompt: AgentPrompt) => {
return prompt.hasApprovalDecisions()
&& prompt.approvalDecisions.get('call_abc').isApproved();
});
For queued agent invocations, use the queued assertion methods:
import type { QueuedAgentPrompt } from '@laraflare/ai';
SalesCoach.assertQueued('Analyze this...');
SalesCoach.assertQueued((prompt: QueuedAgentPrompt) => {
return prompt.contains('Analyze');
});
SalesCoach.assertNotQueued('Missing prompt');
SalesCoach.assertNeverQueued();
To ensure all agent invocations have a corresponding fake response, you may use preventStrayPrompts. If an agent is invoked without a defined fake response, an exception will be thrown:
SalesCoach.fake().preventStrayPrompts();
Images
Image generations may be faked by invoking the fake method on the Images class. Once image has been faked, various assertions may be performed against the recorded image generation prompts:
import { Images, type ImagePrompt, type QueuedImagePrompt } from '@laraflare/ai';
// Automatically generate a fixed response for every prompt...
Images.fake();
// Provide a list of prompt responses...
Images.fake([
Buffer.from(firstImage).toString('base64'),
Buffer.from(secondImage).toString('base64'),
]);
// Dynamically handle prompt responses based on the incoming prompt...
Images.fake((prompt: ImagePrompt) => {
return Buffer.from('...').toString('base64');
});
After generating images, you may make assertions about the prompts that were received:
Images.assertGenerated((prompt: ImagePrompt) => {
return prompt.contains('sunset') && prompt.isLandscape();
});
Images.assertNotGenerated(
(prompt: ImagePrompt) => prompt.contains('Missing prompt'),
);
Images.assertNothingGenerated();
For queued image generations, use the queued assertion methods:
Images.assertQueued(
(prompt: QueuedImagePrompt) => prompt.contains('sunset'),
);
Images.assertNotQueued(
(prompt: QueuedImagePrompt) => prompt.contains('Missing prompt'),
);
Images.assertNothingQueued();
To ensure all image generations have a corresponding fake response, you may use preventStrayImages. If an image is generated without a defined fake response, an exception will be thrown:
Images.fake().preventStrayImages();
Audio
Audio generations may be faked by invoking the fake method on the Audios class. Once audio has been faked, various assertions may be performed against the recorded audio generation prompts:
import { Audios, type AudioPrompt, type QueuedAudioPrompt } from '@laraflare/ai';
// Automatically generate a fixed response for every prompt...
Audios.fake();
// Provide a list of prompt responses...
Audios.fake([
Buffer.from(firstAudio).toString('base64'),
Buffer.from(secondAudio).toString('base64'),
]);
// Dynamically handle prompt responses based on the incoming prompt...
Audios.fake((prompt: AudioPrompt) => {
return Buffer.from('...').toString('base64');
});
After generating audio, you may make assertions about the prompts that were received:
Audios.assertGenerated((prompt: AudioPrompt) => {
return prompt.contains('Hello') && prompt.isFemale();
});
Audios.assertNotGenerated(
(prompt: AudioPrompt) => prompt.contains('Missing prompt'),
);
Audios.assertNothingGenerated();
For queued audio generations, use the queued assertion methods:
Audios.assertQueued(
(prompt: QueuedAudioPrompt) => prompt.contains('Hello'),
);
Audios.assertNotQueued(
(prompt: QueuedAudioPrompt) => prompt.contains('Missing prompt'),
);
Audios.assertNothingQueued();
To ensure all audio generations have a corresponding fake response, you may use preventStrayAudio. If audio is generated without a defined fake response, an exception will be thrown:
Audios.fake().preventStrayAudio();
Transcriptions
Transcription generations may be faked by invoking the fake method on the Transcription class. Once transcription has been faked, various assertions may be performed against the recorded transcription generation prompts:
import { Transcription, type QueuedTranscriptionPrompt, type TranscriptionPrompt } from '@laraflare/ai';
// Automatically generate a fixed response for every prompt...
Transcription.fake();
// Provide a list of prompt responses...
Transcription.fake([
'First transcription text.',
'Second transcription text.',
]);
// Dynamically handle prompt responses based on the incoming prompt...
Transcription.fake((prompt: TranscriptionPrompt) => {
return 'Transcribed text...';
});
After generating transcriptions, you may make assertions about the prompts that were received:
Transcription.assertGenerated((prompt: TranscriptionPrompt) => {
return prompt.language === 'en' && prompt.isDiarized();
});
Transcription.assertNotGenerated(
(prompt: TranscriptionPrompt) => prompt.language === 'fr',
);
Transcription.assertNothingGenerated();
For queued transcription generations, use the queued assertion methods:
Transcription.assertQueued(
(prompt: QueuedTranscriptionPrompt) => prompt.isDiarized(),
);
Transcription.assertNotQueued(
(prompt: QueuedTranscriptionPrompt) => prompt.language === 'fr',
);
Transcription.assertNothingQueued();
To ensure all transcription generations have a corresponding fake response, you may use preventStrayTranscriptions. If a transcription is generated without a defined fake response, an exception will be thrown:
Transcription.fake().preventStrayTranscriptions();
Embeddings
Embeddings generations may be faked by invoking the fake method on the Embeddings class. Once embeddings has been faked, various assertions may be performed against the recorded embeddings generation prompts:
import { Embeddings, type EmbeddingsPrompt, type QueuedEmbeddingsPrompt } from '@laraflare/ai';
// Automatically generate fake embeddings of the proper dimensions for every prompt...
Embeddings.fake();
// Provide a list of prompt responses...
Embeddings.fake([
[firstEmbeddingVector],
[secondEmbeddingVector],
]);
// Dynamically handle prompt responses based on the incoming prompt...
Embeddings.fake((prompt: EmbeddingsPrompt) => {
return prompt.inputs.map(
() => Embeddings.fakeEmbedding(prompt.dimensions),
);
});
After generating embeddings, you may make assertions about the prompts that were received:
Embeddings.assertGenerated((prompt: EmbeddingsPrompt) => {
return prompt.contains('laraflare') && prompt.dimensions === 1536;
});
Embeddings.assertNotGenerated(
(prompt: EmbeddingsPrompt) => prompt.contains('Other'),
);
Embeddings.assertNothingGenerated();
For queued embeddings generations, use the queued assertion methods:
Embeddings.assertQueued(
(prompt: QueuedEmbeddingsPrompt) => prompt.contains('laraflare'),
);
Embeddings.assertNotQueued(
(prompt: QueuedEmbeddingsPrompt) => prompt.contains('Other'),
);
Embeddings.assertNothingQueued();
To ensure all embeddings generations have a corresponding fake response, you may use preventStrayEmbeddings. If embeddings are generated without a defined fake response, an exception will be thrown:
Embeddings.fake().preventStrayEmbeddings();
Reranking
Reranking operations may be faked by invoking the fake method on the Reranking class:
import { RankedDocument, Reranking, type RerankingPrompt } from '@laraflare/ai';
// Automatically generate a fake reranked responses...
Reranking.fake();
// Provide custom responses...
Reranking.fake([
[
new RankedDocument(0, 'First', 0.95),
new RankedDocument(1, 'Second', 0.80),
],
]);
After reranking, you may make assertions about the operations that were performed:
Reranking.assertReranked((prompt: RerankingPrompt) => {
return prompt.contains('laraflare') && prompt.limit === 5;
});
Reranking.assertNotReranked(
(prompt: RerankingPrompt) => prompt.contains('Django'),
);
Reranking.assertNothingReranked();
Classification
Classification may be faked by invoking the fake method on the Classification class. If no custom responses are provided, laraflare will automatically generate answers that match the shape of each question:
import { BooleanAnswer, ChoiceAnswer, Classification, type ClassificationPrompt } from '@laraflare/ai';
// Automatically generate fake answers...
Classification.fake();
// Provide answers for specific questions...
Classification.fake([
{
urgent: new BooleanAnswer(0.94),
department: new ChoiceAnswer('technical', {
billing: 0.08,
technical: 0.87,
sales: 0.05,
}, 0.82),
},
]);
// Build answers from the prompt...
Classification.fake((prompt: ClassificationPrompt) => ({
urgent: new BooleanAnswer(prompt.contains('ASAP') ? 1.0 : 0.0),
}));
Questions that are omitted from a fake response will still receive a generated answer, so your tests only need to provide the answers they make assertions against.
After classifying, you may make assertions about the operations that were performed:
Classification.assertClassified((prompt: ClassificationPrompt) => {
return prompt.contains('refund') && prompt.asks('department');
});
Classification.assertNotClassified(
(prompt: ClassificationPrompt) => prompt.asks('sentiment'),
);
Classification.assertNothingClassified();
Files
File operations may be faked by invoking the fake method on the Files class:
import { Files } from '@laraflare/ai';
Files.fake();
Once file operations have been faked, you may make assertions about the uploads and deletions that occurred:
import { Document, Files } from '@laraflare/ai';
// Store files...
await Document.fromString('Hello, laraflare!', 'text/plain')
.as('hello.txt')
.put();
// Make assertions...
await Files.assertStored(async (file) =>
String(file) === 'Hello, laraflare!' &&
file.mimeType() === 'text/plain',
);
await Files.assertNotStored(async (file) =>
String(file) === 'Hello, World!',
);
Files.assertNothingStored();
For asserting against file deletions, you may pass a file ID:
await Files.assertDeleted('file-id');
await Files.assertNotDeleted('file-id');
Files.assertNothingDeleted();
Vector Stores
Vector store operations may be faked by invoking the fake method on the Stores class. Faking stores will also fake file operations automatically:
import { Stores } from '@laraflare/ai';
Stores.fake();
Once store operations have been faked, you may make assertions about the stores that were created or deleted:
import { Stores } from '@laraflare/ai';
// Create store...
const store = await Stores.create('Knowledge Base');
// Make assertions...
Stores.assertCreated('Knowledge Base');
Stores.assertCreated((name: string, description?: string | null) =>
name === 'Knowledge Base',
);
Stores.assertNotCreated('Other Store');
Stores.assertNothingCreated();
For asserting against store deletions, you may provide the store ID:
Stores.assertDeleted('store_id');
Stores.assertNotDeleted('other_store_id');
Stores.assertNothingDeleted();
To assert files were added or removed from a store, use the assertion methods on a given Store instance:
Stores.fake();
const store = await Stores.get('store_id');
// Add / remove files...
await store.add('added_id');
await store.remove('removed_id');
// Make assertions...
store.assertAdded('added_id');
store.assertRemoved('removed_id');
store.assertNotAdded('other_file_id');
store.assertNotRemoved('other_file_id');
If a file is stored in the provider's file storage and added to a vector store in the same request, you may not know the file's provider ID. In this case, you can pass a closure to the assertAdded method to assert against the content of the added file:
import { Document } from '@laraflare/ai';
await store.add(Document.fromString('Hello, World!', 'text/plain').as('hello.txt'));
store.assertAdded((file) => file.name() === 'hello.txt');
store.assertAdded(async (file) => await file.content() === 'Hello, World!');
Events
The laraflare AI SDK dispatches a variety of events, exported as AiEvents from @laraflare/ai, including:
AddingFileToStoreAddingFileToStoreFailedAgentFailedAgentFailedOverAgentPromptedAgentStreamedAudioFailedAudioGeneratedClassificationFailedClassifiedClassifyingCreatingStoreCreatingStoreFailedEmbeddingsFailedEmbeddingsGeneratedFileAddedToStoreFileDeletedFileRemovedFromStoreFileStoredGeneratingAudioGeneratingEmbeddingsGeneratingImageGeneratingTranscriptionImageFailedImageGeneratedInvokingToolPromptingAgentProviderFailedOverRemovingFileFromStoreRemovingFileFromStoreFailedRerankedRerankingRerankingFailedStartingStepStepCompletedStepFailedStoreCreatedStoreDeletedStoringFileStoringFileFailedStreamingAgentToolApprovalRequestedToolApprovalResolvedToolFailedToolInvokedTranscriptionFailedTranscriptionGenerated
You can listen to any of these events to log or store AI SDK usage information.