Integrating LLM APIs into a Laravel Application

A practical pattern for calling large language model APIs from Laravel: a provider-neutral service class, config-based keys, queues for slow calls, caching, timeouts, logging and cost control.

Adding a language model feature to a Laravel application often starts with a few lines in a controller: build a prompt, call the provider's API, show the answer. It works in a demo. In production, the same code causes slow page loads, API keys in the wrong places, surprise bills, and errors that nobody can trace because nothing was logged.

LLM calls behave differently from most API calls. They can take many seconds, they cost money per token, they occasionally fail or time out, and the response is text you cannot fully predict. This article shows a structure that keeps these concerns under control using standard Laravel features: configuration, the HTTP client, queues, the cache and logging. The examples stay provider-neutral, assuming a chat-completions style endpoint that accepts a list of messages and returns a choice with a message.

Keep keys and endpoints in configuration

Never hard-code an API key or endpoint. Put them in .env and read them through a config file, so that php artisan config:cache works and you can switch provider or model without touching code.

// config/services.php
'llm' => [
    'url'     => env('LLM_API_URL'),
    'key'     => env('LLM_API_KEY'),
    'model'   => env('LLM_MODEL'),
    'timeout' => (int) env('LLM_TIMEOUT', 30),
    'max_tokens' => (int) env('LLM_MAX_TOKENS', 500),
],

Your .env then holds LLM_API_URL, LLM_API_KEY and LLM_MODEL. Keep .env out of version control, use separate keys for staging and production, and set a spending limit in the provider's dashboard if one is offered.

Wrap the API in a service class

All LLM calls should go through one class. That gives you a single place for timeouts, retries, logging and future changes such as switching provider. Laravel's HTTP client keeps the code short:

namespace App\Services;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class LlmClient
{
    public function chat(array $messages, ?int $maxTokens = null): string
    {
        $response = Http::withToken(config('services.llm.key'))
            ->timeout(config('services.llm.timeout'))
            ->retry(2, 1000, fn ($e) => $e instanceof ConnectionException)
            ->post(config('services.llm.url'), [
                'model'      => config('services.llm.model'),
                'messages'   => $messages,
                'max_tokens' => $maxTokens ?? config('services.llm.max_tokens'),
            ])
            ->throw();

        Log::info('llm.call', ['usage' => $response->json('usage')]);

        return (string) $response->json('choices.0.message.content', '');
    }
}

A few details are worth noting. timeout() stops a request from hanging a worker indefinitely. retry() here only retries connection failures, not every error; retrying a 400 response caused by a bad request just wastes time and money. throw() turns a 4xx or 5xx response into an exception, so failures are visible instead of silently returning empty text. Inject the class through Laravel's container wherever you need it, which also makes it easy to replace with a fake in tests.

Move slow calls to queues

A user should not wait twenty seconds for a page while a model writes a summary. For anything that is not strictly interactive, such as summarising a support ticket, classifying an enquiry or drafting product descriptions, dispatch a queued job and store the result.

class SummariseTicket implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public array $backoff = [30, 120];
    public int $timeout = 90;

    public function __construct(public Ticket $ticket) {}

    public function handle(LlmClient $llm): void
    {
        $summary = $llm->chat([
            ['role' => 'system', 'content' => 'Summarise this support ticket in three lines.'],
            ['role' => 'user', 'content' => $this->ticket->body],
        ]);

        $this->ticket->update(['ai_summary' => $summary]);
    }
}

Dispatch it with SummariseTicket::dispatch($ticket). Make sure the job's $timeout is longer than the HTTP timeout, and that your queue connection's retry_after value is longer than the job timeout, otherwise the same job may be picked up twice. On shared hosting where long-running workers are not allowed, a cron-driven queue:work --stop-when-empty can be a workable compromise for low volumes.

For chat-style interfaces where the user must see the answer, keep the call synchronous but show a loading state, or use streaming if your provider and front end support it.

Cache repeated requests

Many prompts repeat: the same product description translated, the same FAQ answered, the same document summarised. Caching identical requests saves both time and money.

$key = 'llm:' . hash('sha256', json_encode($messages));

$answer = Cache::remember($key, now()->addDay(), fn () => $llm->chat($messages));

Only cache where a repeated answer is acceptable, and be careful with prompts that contain personal data. Cached responses are stored in plain form in your cache backend, which matters under the DPDP Act 2023 if the text identifies a person.

Logging, errors and observability

When a customer says "the AI gave a strange answer", you need to be able to find that request. Log at least:

  • A request ID and the feature that made the call.
  • Model name, response time and token usage returned by the provider.
  • Errors with status code and a trimmed response body.

Avoid logging full prompts and responses if they may contain personal or confidential data; log a hash or a truncated version instead, or log full text only in a restricted channel with short retention. Handle exceptions where the job or controller calls the service, and decide what the user sees when the model is unavailable: a fallback message, a retry button, or the feature quietly hidden.

Control cost before it controls you

LLM pricing is usually per token, for both input and output. Costs grow with traffic, prompt length and misuse. Practical controls include:

  • Set max_tokens on every request so a single response cannot run long.
  • Trim input. Send only the relevant part of a document, not the whole thing.
  • Rate limit per user with Laravel's RateLimiter or the throttle middleware on AI-backed routes.
  • Use a smaller model for simple tasks such as classification, and a larger one only where quality demands it. Keeping the model in config makes this a one-line change.
  • Track usage from the logged token counts, grouped by feature, and review it weekly.
  • Set billing alerts with the provider so an unexpected spike is noticed within hours, not at month end.

Finally, write tests with Http::fake() so your test suite never calls the real API, and treat model output as untrusted input: escape it in Blade with the standard escaped echo rather than the raw {!! !!} form, validate any structured data before saving, and never execute it.

How NextWebGen can help

NextWebGen builds and maintains Laravel and PHP applications, including integrations with third-party AI services. If you want to add summarisation, search, classification or a chat assistant to an existing system with sensible cost and security controls, see our web development services or ask us for an estimate.