advanced 18 min read

AI SDK

The official Laravel AI SDK for LLM integration, text generation, embeddings, and RAG pipelines.

Laravel AI SDK

Laravel 13 introduces laravel/ai, the official first-party AI SDK supporting OpenAI, Anthropic, Gemini, Azure, Groq, xAI, DeepSeek, Mistral, Ollama, and more.

// Install: composer require laravel/ai

use Illuminate\Support\Facades\AI;

// Text generation
$response = AI::chat()->create([
"model" => "gpt-4o",
"messages" => [
["role" => "system", "content" => "You are a helpful tutor."],
["role" => "user", "content" => "Explain Eloquent relationships."],
],
]);

echo $response->choices[0]->message->content;

// Streaming
$stream = AI::chat()->createStreamed([
"model" => "gpt-4o",
"messages" => [["role" => "user", "content" => "Write a poem about Laravel."]],
]);

foreach ($stream as $chunk) {
echo $chunk->choices[0]->delta->content;
}

Embeddings & RAG

// Generate embeddings
$embeddings = AI::embeddings()->create([
"model" => "text-embedding-3-small",
"input" => "Laravel is a PHP framework.",
]);

// RAG with vector stores
$results = AI::vectorStore("documents")
->similaritySearch("How do I create a model?");

Tool Calling & Agents

use Laravel\Ai\Tools\Tool;

$tool = Tool::as("get_weather")
->for("Get the weather for a city")
->withParameter("city", "string", "The city name")
->using(fn (string $city) => ["temp" => 22, "condition" => "sunny"]);

$response = AI::chat()->create([
"model" => "gpt-4o",
"messages" => [...],
"tools" => [$tool],
]);

Examples

<?php
use Illuminate\Support\Facades\AI;

\$response = AI::chat()->create([
    'model' => 'gpt-4o',
    'messages' => [
        ['role' => 'user', 'content' => 'What is Laravel 13?'],
    ],
]);

echo \$response->choices[0]->message->content;

Your Notes

Sign in to take notes for this lesson.

Quiz

Laravel 13 New Features Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.