Laravel Prism is an open-source PHP package that gives you one fluent API for working with large language models (LLMs). You write Prism::text() once, and switching from OpenAI to Anthropic, Gemini, or a local Ollama model can be as simple as changing one line. It supports text generation, structured output, tool calling, embeddings, streaming, and testing fakes.

Most Laravel teams start their first AI feature the same way. They install a provider's SDK, wrap it in a service class, and ship the feature. Then a cheaper model launches, or a client asks for a different provider, and that service class needs to be rewritten.

Prism helps avoid that rewrite. In this guide, you'll install Prism, generate text, get structured JSON back, give the model tools, stream responses, and write tests that never hit a real API. We'll finish by comparing Prism with Laravel's own AI SDK.

Key Takeaways

  • Prism (prism-php/prism) is a community Laravel package that provides one API for 13+ providers, including OpenAI, Anthropic, Gemini, Mistral, Groq, DeepSeek, xAI, and Ollama.

  • Switching providers can be a one-line change. Change Provider::OpenAI to Provider::Anthropic while keeping the rest of your code the same.

  • Structured output, tools, and embeddings share the same fluent style, covering use cases such as chatbots, data extraction, and semantic search.

  • Prism::fake() makes AI features easier to test without API keys, network calls, or token costs.

  • Prism is still pre-1.0 (v0.100.x as of October 2026), so pin your version in composer.json.

The developers in this article's examples are illustrative composites based on common Laravel scenarios.

What Is Laravel Prism?

Prism is a Laravel package created by TJ Miller and maintained by the open-source community. It isn't an official Laravel project, but it follows Laravel conventions closely, with a facade, a published configuration file, and chainable builder methods that feel familiar to Laravel developers.

It's also one of the widely used Laravel packages for LLM integration. Packagist shows more than 7 million installs, and the GitHub repository has around 2,400 stars.

Here's what Prism PHP supports:

Capability

Prism method

Text generation

Prism::text()->asText()

Structured (JSON) output

Prism::structured()->asStructured()

Tool or function calling

->withTools([...])

Embeddings

Prism::embeddings()->asEmbeddings()

Streaming

->asStream(), ->asEventStreamResponse()

Testing

Prism::fake([...])

The Prism documentation lists providers for Anthropic, DeepSeek, ElevenLabs, Groq, Gemini, Mistral, Ollama, OpenAI, OpenRouter, Voyage AI, xAI, Perplexity, and Z AI. Amazon Bedrock support is available through a separate package, prism-php/bedrock.

Not every provider supports every feature. Embeddings, for example, require a provider that offers an embeddings model, such as OpenAI or Voyage AI.

How to Install the Prism Laravel Package

Prism requires PHP 8.2+ and Laravel 11 or later. Install it with Composer:

composer require prism-php/prism

Then publish the configuration file:

php artisan vendor:publish --tag=prism-config

This creates config/prism.php, where each provider reads its credentials from your environment. Add the keys you need to .env:

ANTHROPIC_API_KEY=your-key-here
OPENAI_API_KEY=your-key-here

Keep your keys in .env or a secrets manager, never in source control. Because Prism is still pre-1.0 and evolving quickly, the documentation recommends pinning a specific version rather than accepting every update.

Generating Text with Prism PHP

Text generation is the core feature of the Prism Laravel package. Choose a provider and model, add a prompt, and call asText():

use Prism\Prism\Facades\Prism;
use Prism\Prism\Enums\Provider;

$response = Prism::text()
    ->using(Provider::Anthropic, 'claude-sonnet-5-5')
    ->withSystemPrompt('You are a concise support assistant for a SaaS app.')
    ->withPrompt('Summarise this ticket in two sentences: ' . $ticket->body)
    ->asText();

echo $response->text;
echo $response->usage->promptTokens;
echo $response->usage->completionTokens;

The usage object is worth logging from day one. Token counts help you identify rising costs before they show up on your invoice.

Switching Providers in One Line

This is Prism's headline feature. To try the same functionality with OpenAI, change only the using() call:

->using(Provider::OpenAI, 'gpt-4o')

A good practice is to keep the provider and model in your configuration rather than hard-coding them. This makes switching between environments easier:

->using(config('services.llm.provider'), config('services.llm.model'))

Multi-Turn Conversations

For chat features, pass the conversation history as message objects instead of using a single prompt:

use Prism\Prism\ValueObjects\Messages\UserMessage;
use Prism\Prism\ValueObjects\Messages\AssistantMessage;

$response = Prism::text()
    ->using(Provider::Anthropic, 'claude-sonnet-5-5')
    ->withMessages([
        new UserMessage('What is JSON?'),
        new AssistantMessage('JSON is a lightweight data format...'),
        new UserMessage('Can you show me an example?'),
    ])
    ->asText();

Store messages in your database and rebuild this array with each request. That's all a basic chatbot needs.

Want the scaffolding without the setup? StackMivo generates full Laravel apps from plain-English prompts, so you can focus on AI features instead of boilerplate.

Structured Output: Get Typed JSON Back

Free text works well for summaries. But when your code needs to act on an AI response, you want predictable fields. Prism's structured output feature lets you define a schema and receive structured data:

use Prism\Prism\Facades\Prism;
use Prism\Prism\Enums\Provider;
use Prism\Prism\Schema\ObjectSchema;
use Prism\Prism\Schema\StringSchema;

$schema = new ObjectSchema(
    name: 'ticket_triage',
    description: 'Triage result for a support ticket',
    properties: [
        new StringSchema('category', 'billing, bug, or feature_request'),
        new StringSchema('priority', 'low, medium, or high'),
        new StringSchema('summary', 'One-sentence summary'),
    ],
    requiredFields: ['category', 'priority', 'summary']
);

$response = Prism::structured()
    ->using(Provider::OpenAI, 'gpt-4o')
    ->withSchema($schema)
    ->withPrompt($ticket->body)
    ->asStructured();

$triage = $response->structured;

Always validate the result before trusting it. Parsing can fail, and providers differ in how strictly they follow a schema. Run $triage through Laravel's Validator before saving it.

Leah, a backend developer at a small helpdesk startup in Bristol, used this pattern in August to automatically tag incoming tickets. Her first version parsed free-text replies with regular expressions and broke whenever the model changed its wording. After switching to a Prism schema and a Validator check, misfiled tickets dropped to a handful each week. Her team no longer spent Monday mornings re-sorting the queue.

Tool Calling: Let the Model Use Your Code

Tools let a model call your PHP functions, such as looking up an order or checking stock. You define a tool with a name, description, and parameters:

use Prism\Prism\Facades\Prism;
use Prism\Prism\Enums\Provider;
use Prism\Prism\Facades\Tool;

$orderTool = Tool::as('order_status')
    ->for('Get the current status of a customer order')
    ->withStringParameter('order_number', 'The order number, e.g. ORD-1042')
    ->using(function (string $order_number): string {
        $order = auth()->user()->orders()
            ->where('number', $order_number)
            ->first();

        return $order
            ? "Order {$order->number} is {$order->status}."
            : 'No order found with that number for this customer.';
    });

$response = Prism::text()
    ->using(Provider::Anthropic, 'claude-sonnet-5-5')
    ->withTools([$orderTool])
    ->withMaxSteps(3)
    ->withPrompt('Where is my order ORD-1042?')
    ->asText();

Two details matter here:

  • Set withMaxSteps() appropriately. Prism allows one step by default, so a tool call followed by a final answer requires at least two.

  • Scope every query to the current user. The model chooses the arguments, so treat them as user input. In this example, auth()->user()->orders() prevents one customer from accessing another customer's orders.

Tools must return a string. Wrap external API calls in try/catch and return a helpful message if something fails. This lets the model explain the problem instead of crashing the request.

Embeddings and Streaming

Embeddings for Semantic Search

Embeddings turn text into vectors that you can compare for similarity. They're the foundation of semantic search and retrieval-augmented generation (RAG):

$response = Prism::embeddings()
    ->using(Provider::OpenAI, 'text-embedding-3-large')
    ->fromInput($article->body)
    ->asEmbeddings();

$vector = $response->embeddings[0]->embedding;

Store the vector in a vector-capable database, such as Postgres with pgvector, then find the closest matches to a user's question.

Streaming Responses to the Browser

Long answers can feel slow when users have to wait for the entire response. Prism can return a Server-Sent Events response directly from a route:

Route::get('/chat', function () {
    return Prism::text()
        ->using(Provider::Anthropic, 'claude-sonnet-5-5')
        ->withPrompt(request('message'))
        ->asEventStreamResponse();
});

On the front end, an EventSource listens for text_delta events and appends each chunk. Prism also offers asDataStreamResponse() for the Vercel AI SDK protocol, asBroadcast() for WebSockets over a broadcast channel (which you can pair with Laravel Reverb), and asStream() if you want to process events yourself.

Add authentication and rate-limiting middleware to routes like this. Every request costs tokens.

<!-- TODO BEFORE PUBLISHING: Insert a complete YouTube embed block (opening and closing wp:embed tags) showing Prism setup in a Laravel app, ideally from an official or well-known Laravel channel. If none is available, delete this comment. -->

Testing Laravel Prism Features Without API Calls

This is where Prism earns its place in a serious codebase. Prism::fake() replaces real provider calls with predefined responses, making tests fast, free, and deterministic:

use Prism\Prism\Facades\Prism;
use Prism\Prism\Enums\Provider;
use Prism\Prism\ValueObjects\Usage;
use Prism\Prism\Testing\TextResponseFake;

it('summarises a support ticket', function () {
    $fake = Prism::fake([
        TextResponseFake::make()
            ->withText('Customer cannot log in after a password reset.')
            ->withUsage(new Usage(10, 20)),
    ]);

    $response = Prism::text()
        ->using(Provider::Anthropic, 'claude-sonnet-5-5')
        ->withPrompt('Summarise: I reset my password and now I cannot log in.')
        ->asText();

    expect($response->text)->toBe('Customer cannot log in after a password reset.');
    $fake->assertPrompt('Summarise: I reset my password and now I cannot log in.');
});

No API key is needed, and your CI pipeline never has to contact a provider. For more testing patterns, see our guide to Laravel testing with AI.

Arjun, a freelance Laravel developer in Bengaluru, inherited a client app in June with an AI feature built on a raw HTTP client. Its tests either called OpenAI on every run or were skipped entirely. He moved the feature to Prism and had a full Pest test suite running with fakes in one afternoon. The following month, the client wanted to try Anthropic. The switch took one configuration change, and every test still passed.

Laravel Prism vs. the Laravel AI SDK

Laravel now has a first-party option, too: the Laravel AI SDK (laravel/ai). Which one should you use?

Prism

Laravel AI SDK

Maintainer

Community (TJ Miller and contributors)

Laravel team

Package

prism-php/prism

laravel/ai

Laravel versions

11, 12, 13

12, 13

Providers

13 in core, plus a Bedrock package

17, including Azure, Bedrock, and Cohere

Maturity

Pre-1.0, widely installed

First-party, newer

Best for

Laravel 11 apps and fine-grained LLM calls

Teams that want an official, agent-focused API

Both solve the same core problem: providing one API across multiple providers. If you're starting fresh on Laravel 13 and prefer first-party packages, read our Laravel 13 AI SDK guide.

If you're using Laravel 11, need Perplexity or Z AI, or already have Prism in production, there's no urgent reason to switch.

For a broader comparison, our roundup of the best Laravel AI agents and packages in 2026 compares Prism with five other options.

Building an AI-powered Laravel app from scratch? Describe it in plain English and generate a working codebase with models, authentication, and an admin panel, ready for your Prism features. Start free with StackMivo →

Frequently Asked Questions

What is Laravel Prism used for?

Laravel Prism adds LLM features to Laravel applications through a single API. Common use cases include chatbots, summarisation, structured data extraction, semantic search with embeddings, and agents that call your code through tools.

Is Prism PHP an official Laravel package?

No. Prism is a community package created by TJ Miller. It follows Laravel conventions and the Laravel Code of Conduct, but it isn't affiliated with Laravel. The official option is the Laravel AI SDK (laravel/ai).

Which LLM providers does Prism support?

Prism's documentation lists Anthropic, OpenAI, Gemini, Mistral, Groq, DeepSeek, xAI, Ollama, OpenRouter, Perplexity, Voyage AI, ElevenLabs, and Z AI. Amazon Bedrock is available through the separate prism-php/bedrock package.

Can I use Prism with local models?

Yes. Prism supports Ollama, allowing you to run open models on your own machine or server. This can be useful for development, privacy-sensitive data, and cost control.

How do I test code that uses Prism?

Use Prism::fake() with fake responses such as TextResponseFake. Your code runs normally, but no request reaches a provider. Your tests therefore need no API key and incur no API costs.

Should I use Prism or the Laravel AI SDK?

Use the Laravel AI SDK if you want a first-party package on Laravel 12 or 13. Use Prism if you're running Laravel 11 or PHP 8.2, need Perplexity or Z AI, or already have Prism in production.

The Bottom Line

Laravel Prism takes one of the messiest parts of AI development—provider-specific SDKs—and hides it behind a clean API. You get text generation, structured output, tools, embeddings, and streaming through the same fluent interface, along with fakes that keep your test suite fast and free.

Start small. Install Prism, ship one feature with structured output, log token usage, and write a test with Prism::fake(). Once that pattern works, every new AI feature becomes a variation on it.

Generate your next Laravel app with StackMivo and add Prism on day one →