{"slug": "episode-02-getting-started-with-the-laravel-ai-sdk", "title": "Episode 02: Getting Started with the Laravel AI SDK", "summary": "Laravel released the Laravel AI SDK, a first-party package that gives developers a single Laravel-native integration layer for configuring AI providers, defining agents, calling models, using tools, requesting structured output, and tracking usage. The SDK is installed via Composer and provides an agent class pattern, per-environment provider and model configuration, and database-backed conversation storage, with guidance to start from one narrow feature such as support-ticket summarization rather than a general assistant.", "body_md": "The **Laravel AI SDK** is Laravel's first-party package for building AI-powered application features without turning your codebase into a collection of provider-specific HTTP calls.\n\nIt gives Laravel developers one consistent place to configure providers, define agents, call models, use tools, request structured output, and track usage.\n\nThe important mental shift is this: the SDK is not the product feature by itself. It is the integration layer.\n\nYour Laravel application still owns the use case, authorization, validation, persistence, queues, logs, and user experience. The SDK gives you a Laravel-native way to connect those responsibilities to AI providers.\n\n**Start with one narrow feature:** Do not begin by building a general assistant. Begin with a small task such as support-ticket summarization, product description improvement, review classification, or internal document Q&A. A narrow feature makes the prompt, output, fallback, cost, and success criteria much easier to control.\n\nBefore the SDK, many Laravel applications integrated AI with raw HTTP clients, direct provider SDKs, or small wrapper services.\n\nThat works for a prototype, but it becomes messy once the product needs multiple providers, conversation context, structured output, tools, streaming, cost tracking, testing, and failover.\n\nThe SDK gives you several production-friendly building blocks:\n\nA new Laravel AI SDK setup starts like a normal Laravel package:\n\n```\ncomposer require laravel/ai\n\nphp artisan vendor:publish --provider=\"Laravel\\Ai\\AiServiceProvider\"\n\nphp artisan migrate\n```\n\nThe migration step matters because SDK features such as remembered conversations need database tables.\n\nIf your first feature is a stateless classification or summarization endpoint, you may not use conversation storage immediately, but publishing configuration early keeps provider and model choices visible.\n\nProvider credentials should stay in environment variables and configuration, not inside prompts, controllers, jobs, or agent classes.\n\n```\nOPENAI_API_KEY=\nANTHROPIC_API_KEY=\nGEMINI_API_KEY=\nGROQ_API_KEY=\nMISTRAL_API_KEY=\nOPENROUTER_API_KEY=\nOPENAI_COMPATIBLE_API_KEY=\nOPENAI_COMPATIBLE_URL=\n```\n\nA useful first production habit is to define a default provider and model per environment.\n\nLocal development may use a cheap or local model. Staging may use a stable low-cost model. Production may pin a specific model for predictable behavior and pricing.\n\n**Do not hide model choice:** The selected provider and model affect quality, latency, cost, context window, supported tools, and output behavior. Treat model selection like infrastructure configuration, not like a random string inside a controller.\n\nThe SDK's main application-facing concept is the agent.\n\nAn agent is a PHP class with a responsibility. For a first feature, imagine a `SupportSummaryAgent` that turns a long support message into a short internal summary.\n\n```\nphp artisan make:agent SupportSummaryAgent\nphp\n<?php\n\nnamespace App\\Ai\\Agents;\n\nuse Laravel\\Ai\\Attributes\\MaxTokens;\nuse Laravel\\Ai\\Attributes\\Temperature;\nuse Laravel\\Ai\\Contracts\\Agent;\nuse Laravel\\Ai\\Promptable;\n\n#[MaxTokens(600)]\n#[Temperature(0.2)]\nclass SupportSummaryAgent implements Agent\n{\n    use Promptable;\n\n    public function instructions(): string\n    {\n        return <<<'PROMPT'\nYou summarize customer support messages for an internal Laravel support team.\n\nWrite concise summaries.\nKeep facts from the original message.\nDo not invent account status, payment state, or technical causes.\nIf the message is unclear, say what is missing.\nPROMPT;\n    }\n}\n```\n\nNotice that the instructions describe the job and the boundary.\n\nThe agent may summarize and identify missing information, but it must not invent account state or technical root cause. That kind of language is not decoration; it is part of the application contract.\n\nA controller should not become the place where prompts, provider decisions, validation, persistence, and response formatting all mix together.\n\nKeep the HTTP layer thin and call a service or action that owns the use case.\n\n``` php\n<?php\n\nnamespace App\\Services;\n\nuse App\\Ai\\Agents\\SupportSummaryAgent;\nuse App\\Models\\SupportTicket;\n\nclass SummarizeTicket\n{\n    public function handle(SupportTicket $ticket): string\n    {\n        $prompt = <<<TEXT\nSummarize this support ticket for an internal support agent.\n\nSubject: {$ticket->subject}\nMessage:\n{$ticket->message}\nTEXT;\n\n        $response = (new SupportSummaryAgent)->prompt($prompt);\n\n        return trim((string) $response->content);\n    }\n}\n```\n\nThe first Laravel AI SDK request lifecycle usually looks like this:\n\nThe prompt should contain only the data required for the task.\n\nIf the summary does not need billing history, do not send billing history. If the user cannot access a record, the model should not receive that record either.\n\nThe SDK also supports anonymous agents through the `agent()` helper.\n\nThis is useful for experiments, prototypes, and one-off internal scripts. For product features, a named class is usually easier to review, test, version, and observe.\n\n``` php\nuse function Laravel\\Ai\\agent;\n\n$response = agent(\n    instructions: 'You explain Laravel concepts to PHP developers.',\n)->prompt('Explain service containers in three bullet points.');\n```\n\n**Prototype fast, promote carefully:** Anonymous agents are good for learning the SDK. Once a workflow affects users, money, records, support decisions, or private data, move the behavior into a named agent and a domain service.\n\nAI features create a new operational dimension: token usage.\n\nA feature can be correct and still be too expensive. The SDK response exposes usage information reported by the provider, including input tokens, output tokens, and totals.\n\n``` php\n$response = (new SupportSummaryAgent)->prompt($prompt);\n\nlogger()->info('support_ticket_summary.generated', [\n    'ticket_id' => $ticket->id,\n    'input_tokens' => $response->usage?->inputTokens,\n    'output_tokens' => $response->usage?->outputTokens,\n    'total_tokens' => $response->usage?->totalTokens(),\n]);\n\nreturn trim((string) $response->content);\n```\n\nAt minimum, log provider, model, prompt version, feature name, response time, token usage, validation result, and failure reason.\n\nLater, these logs answer practical questions: which customer costs the most, which prompt version became slower, which provider fails most often, and whether a cheaper model is good enough.\n\nA good first Laravel AI SDK feature has a boring boundary.\n\nIt accepts trusted application data, sends minimal context, asks for a limited result, validates or reviews that result, and stores enough metadata to debug it later.\n\nFor example, a ticket summary can safely fail by showing \"summary unavailable\" and letting the support agent read the original ticket.\n\nA payment decision cannot safely fail open. The first feature should teach the team how AI behaves without putting core business state at risk.\n\nOnce the first feature works, the next step is not automatically \"more AI.\"\n\nThe next step is better engineering around the same narrow use case: structured output, tests, retries, provider failover, prompt versioning, queueing, and user feedback.\n\nA sensible learning path:\n\nThis episode gives you the first working shape: install the SDK, configure providers, create an agent, call it from Laravel code, and observe the result.\n\nIn the next episode, we will go deeper into agents themselves: what belongs inside an agent, what belongs in Laravel services, how tools enter the loop, and how to keep agent behavior understandable as the feature grows.\n\nIf you found this useful, follow me for the next article in the **AI Engineering with Laravel** series.", "url": "https://wpnews.pro/news/episode-02-getting-started-with-the-laravel-ai-sdk", "canonical_source": "https://dev.to/kbzaman2/episode-02-getting-started-with-the-laravel-ai-sdk-4p70", "published_at": "2026-09-26 04:42:00+00:00", "updated_at": "2026-09-26 05:30:01.422346+00:00", "lang": "en", "topics": ["ai-tools", "developer-tools", "large-language-models", "ai-agents", "ai-products"], "entities": ["Laravel", "Laravel AI SDK", "OpenAI", "Anthropic", "Gemini", "Groq", "Mistral", "OpenRouter"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/episode-02-getting-started-with-the-laravel-ai-sdk", "markdown": "https://wpnews.pro/news/episode-02-getting-started-with-the-laravel-ai-sdk.md", "text": "https://wpnews.pro/news/episode-02-getting-started-with-the-laravel-ai-sdk.txt", "jsonld": "https://wpnews.pro/news/episode-02-getting-started-with-the-laravel-ai-sdk.jsonld"}}