Adding AI Features to a Laravel Application

Adding AI Features to a Laravel Application

PHP teams often assume AI features need a separate Python service. For assistants, summaries, classification and drafting, they usually do not. A language model is simply an HTTPS API.

A clean structure

  • One service class that talks to the provider
  • Prompts stored as versioned templates, not scattered strings
  • Slow calls run in queued jobs or stream to the browser
  • Every request and response logged for review and cost tracking

A minimal service class

namespace App\Services;

use Illuminate\Support\Facades\Http;

class AiAssistant
{
    public function answer(string $question, string $context): string
    {
        $response = Http::withToken(config('services.llm.key'))
            ->timeout(60)
            ->retry(2, 500)
            ->post(config('services.llm.url'), [
                'model'    => config('services.llm.model'),
                'messages' => [
                    ['role' => 'system', 'content' => view('prompts.support', compact('context'))->render()],
                    ['role' => 'user', 'content' => $question],
                ],
            ])
            ->throw();

        return $this->extractText($response->json());
    }
}

Keep provider settings in config so you can switch models or providers without touching business logic.

Using your own data

Include relevant context, such as help articles, order details or product data, in the prompt. For larger knowledge bases, use retrieval-augmented generation: embed your documents, store them in a vector database and fetch the most relevant passages for each question.

Before going live

  • Rate-limit per user and cap tokens per request
  • Keep secrets and unnecessary personal data out of prompts
  • Validate JSON output before using it
  • Show sources and offer a route to a person for support features
  • Track cost per feature and per customer

Want this done for you? Find out more about our AI development service.

Keep reading

Related articles

All articles

Need a hand?

Stuck on something similar?
We can fix it with you.

Send us the problem. A senior developer reads every message and replies within one working day.