Move Laravel AI Logic Out of Controllers into Action Classes

You write a clean, robust controller method that talks to an LLM, processes a JSON payload, and updates a few Eloquent models. It feels like a minor victory. Two weeks later, a product requirement lands on your desk: this exact same prompt-and-parsing logic needs to run inside a queued background job when a batch upload finishes. Then, another requirement: your customer support chat widget needs to stream the exact same tool calls in real time via a Livewire or Inertia-backed agent loop.

Suddenly, your pristine controller is a mess of duplicated prompt builders, hardcoded model parameters, and tightly coupled API responses.

If you copy-paste that logic into your ProcessDocumentJob and your SupportAgent class, you've officially created technical debt that will rot the moment your LLM provider updates its schema or you decide to swap out your model weights.

In modern Laravel development, building maintainable AI features means treating your LLMs and prompt chains as reusable application services, not controller-bound script glue. Let's look at how to architect, structure, and deploy reusable Laravel AI tools that slide seamlessly across controllers, asynchronous queue jobs, and autonomous agent loops without violating the DRY principle or melting your memory limits.


📋 Table of Contents


The Trap of Controller-Coupled AI Logic

When developers first start integrating large language models into Laravel applications via packages like Laravel Prompts, native SDK wrappers, or HTTP clients, they naturally gravitate toward the path of least resistance. They write the integration directly inside the HTTP layer:

// The anti-pattern: Fat controller logic
public function analyze(Request $request, Project $project)
{
    $validated = $request->validate(['prompt' => 'required|string']);

    $client = new \OpenAI\Client(config('services.openai.key'));
    
    $response = $client->chat()->create([
        'model' => 'gpt-4o',
        'messages' => [
            ['role' => 'system', 'content' => 'You are a senior code reviewer.'],
            ['role' => 'user', 'content' => $validated['prompt']],
        ],
    ]);

    $analysis = $response->choices[0]->message->content;

    $project->reviews()->create(['content' => $analysis]);

    return response()->json(['analysis' => $analysis]);
}

This code works fine until your business requirements shift. What happens when a user requests an asynchronous bulk analysis of 500 legacy repositories via a queued job? You cannot pass the HTTP Request object into a queued job. What happens when your testing suite runs? You are suddenly making live network requests to a third-party API during your PHPUnit suite, bloating your test execution time and racking up API costs.

To build genuinely reusable AI tools in Laravel, we need to completely decouple intent (what the AI should do) from transport (how the request arrived: HTTP, CLI, Queue, or WebSockets).


1. The Contract-First Approach: Designing Abstract Tool Interfaces

Scenario: Your application requires multiple AI-driven features: code summarization, automated tagging, and security vulnerability scanning. Each feature needs different system prompts, distinct temperature settings, and specialized output schemas, but they all share a common lifecycle: they take a data payload, communicate with an LLM, and return a typed, predictable result.

Why it matters: If every AI feature implements its own ad-hoc API calls, swapping your underlying AI provider or adding global logging middleware requires refactoring every single file where you instantiated an HTTP client.

Solution: Define a strict contract using a PHP interface and a foundational abstract class that handles boilerplate configuration, model resolution, and response validation.

Code:

namespace App\Contracts\AI;

use App\Support\AI\AIResponse;

interface AIToolInterface
{
    public function handle(array $payload): AIResponse;
    public function toToolDefinition(): array;
}
namespace App\Support\AI;

use App\Contracts\AI\AIToolInterface;
use Illuminate\Support\Facades\Http;

abstract class BaseAITool implements AIToolInterface
{
    protected string $model;
    protected float $temperature;

    public function __construct()
    {
        $this->model = config('ai.default_model', 'gpt-4o');
        $this->temperature = 0.2;
    }

    abstract public function handle(array $payload): AIResponse;
    abstract public function toToolDefinition(): array;

    protected function sendRequest(array $messages, array $tools = []): array
    {
        $payload = [
            'model' => $this->model,
            'messages' => $messages,
            'temperature' => $this->temperature,
        ];

        if (!empty($tools)) {
            $payload['tools'] = $tools;
            $payload['tool_choice'] = 'auto';
        }

        $response = Http::withToken(config('services.openai.key'))
            ->timeout(60)
            ->post('https://api.openai.com/v1/chat/completions', $payload);

        if ($response->failed()) {
            throw new \RuntimeException("AI Provider Error: " . $response->body());
        }

        return $response->json();
    }
}

Why this works: By forcing every tool to implement handle() and toToolDefinition(), you create a polymorphic architecture. Your controllers, queue jobs, and autonomous agents don't need to know how code analysis or tagging works; they only need to know that they can invoke handle() with an array and receive an AIResponse data transfer object (DTO) back.

💡 Practical note: Keep your DTOs (AIResponse) strictly typed. Never pass raw associative arrays of LLM responses deep into your business domain layers.


2. Encapsulating Logic in Invokable AI Action Classes

Scenario: You've built your abstract classes, but you want a clean, idiomatic way to invoke these tools inside your Laravel controllers and jobs without verbose method chaining.

Why it matters: Injecting large configuration objects or client classes directly into controllers creates bloated constructors and messy dependency graphs. Laravel developers prefer single-action, invokable classes that read like plain English.

Solution: Implement your concrete AI tools as single-action invokable classes that leverage Laravel's service container for dependency injection.

Code:

namespace App\AI\Tools;

use App\Support\AI\BaseAITool;
use App\Support\AI\AIResponse;
use App\Models\Repository;

class CodeReviewTool extends BaseAITool
{
    protected float $temperature = 0.1;

    public function __invoke(Repository $repository, string $diff): AIResponse
    {
        return $this->handle([
            'repository_id' => $repository->id,
            'diff' => $diff,
        ]);
    }

    public function handle(array $payload): AIResponse
    {
        $messages = [
            [
                'role' => 'system', 
                'content' => 'You are an expert static analysis tool. Identify bugs, performance bottlenecks, and security flaws in unified diffs. Return a structured JSON summary.'
            ],
            [
                'role' => 'user', 
                'content' => "Review this code diff:\n\n{$payload['diff']}"
            ],
        ];

        $result = $this->sendRequest($messages);
        $content = data_get($result, 'choices.0.message.content');

        return new AIResponse(
            rawContent: $content,
            parsedData: json_decode($content, true) ?? [],
            usage: data_get($result, 'usage', [])
        );
    }

    public function toToolDefinition(): array
    {
        return [
            'type' => 'function',
            'function' => [
                'name' => 'code_review_tool',
                'description' => 'Analyzes code diffs for bugs, security vulnerabilities, and performance issues.',
                'parameters' => [
                    'type' => 'object',
                    'properties' => [
                        'diff' => [
                            'type' => 'string',
                            'description' => 'The unified git diff string to analyze.',
                        ],
                    ],
                    'required' => ['diff'],
                ],
            ],
        ];
    }
}

Now, look at how clean this looks when called inside a standard controller:

namespace App\Http\Controllers;

use App\AI\Tools\CodeReviewTool;
use App\Models\Repository;
use Illuminate\Http\Request;

class RepositoryReviewController extends Controller
{
    public function store(Request $request, Repository $repository, CodeReviewTool $reviewTool)
    {
        $validated = $request->validate(['diff' => 'required|string']);

        $response = $reviewTool($repository, $validated['diff']);

        $repository->reviews()->create([
            'findings' => $response->parsedData,
            'tokens_used' => $response->totalTokens(),
        ]);

        return response()->json($response->parsedData);
    }
}

Why this works: Invokable classes (__invoke) leverage PHP's magical invocation syntax, allowing the class instance to act as a function. Because it's a standard service container binding, you can inject CodeReviewTool directly into a controller method, a queued job constructor, or another service without changing a single line of the internal AI logic.


3. State Management and Context Preservation Across Queued Jobs

Scenario: A user uploads a massive multi-module codebase comprising 40 files. Running an AI code review synchronously in an HTTP request will immediately trigger a 504 Gateway Timeout. You need to push this workload onto Laravel's queue, processing files in chunks and aggregating the state.

Why it matters: Queued jobs serialize their constructor arguments into database records or Redis strings. If your AI tool holds un-serializable state—like open database connections, closure definitions, or live HTTP client instances—your job will fail immediately upon serialization or throw unhelpful Exception payloads when picked up by a worker on a different server node.

Solution: Keep your AI tools strictly stateless services, and pass lightweight primitive data or Eloquent IDs into your queued jobs. Use Laravel's built-in SerializesModels trait to hydrate models safely inside the worker.

Code:

namespace App\Jobs;

use App\AI\Tools\CodeReviewTool;
use App\Models\Repository;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public int $tries = 3;
    public int $timeout = 120;

    public function __construct(
        public Repository $repository,
        public string $fileDiff
    ) {}

    public function handle(CodeReviewTool $reviewTool): void
    {
        // The tool is resolved fresh from the container inside the worker
        $response = $reviewTool($this->repository, $this->fileDiff);

        $this->repository->reviews()->create([
            'findings' => $response->parsedData,
            'tokens_used' => $response->totalTokens(),
            'status' => 'completed',
        ]);
    }

    public function failed(\Throwable $exception): void
    {
        $this->repository->update(['status' => 'failed']);
    }
}

Why this works: By resolving CodeReviewTool directly inside the handle() method of the job via dependency injection, Laravel's container instantiates a clean, fresh instance of the tool on the worker node. There is zero state pollution between jobs, and because models are handled via IDs via SerializesModels, you avoid stale database state bugs.


4. Building Reusable Tool Definitions for Function Calling

Scenario: You are building an autonomous agent that helps users manage their cloud infrastructure. The agent needs to decide when to run a database migration check, when to query server health logs, and when to execute your CodeReviewTool.

Why it matters: Writing manual JSON schemas for OpenAI or Anthropic function calling inside your agent loops leads to massive arrays of duplicate boilerplate code, typos in parameter names, and desynchronization between what the schema says and what your PHP code actually accepts.

Solution: Centralize your tool definitions inside the tool classes themselves, and create an aggregator service that compiles these tool definitions into a unified format for agent loops.

Code:

namespace App\AI\Agents;

use App\AI\Tools\CodeReviewTool;
use App\AI\Tools\DatabaseHealthTool;
use App\AI\Tools\ServerLogQueryTool;

class InfrastructureAgent
{
    protected array $tools;

    public function __construct(
        CodeReviewTool $codeReview,
        DatabaseHealthTool $dbHealth,
        ServerLogQueryTool $logQuery
    ) {
        // Collect all reusable tools into a single registry
        $this->tools = [
            'code_review_tool' => $codeReview,
            'database_health_tool' => $dbHealth,
            'server_log_query_tool' => $logQuery,
        ];
    }

    public function getToolDefinitions(): array
    {
        return array_map(
            fn($tool) => $tool->toToolDefinition(), 
            array_values($this->tools)
        );
    }

    public function executeStep(array $messages): array
    {
        $payload = [
            'model' => 'gpt-4o',
            'messages' => $messages,
            'tools' => $this->getToolDefinitions(),
            'tool_choice' => 'auto',
        ];

        $response = Http::withToken(config('services.openai.key'))
            ->post('https://api.openai.com/v1/chat/completions', $payload)
            ->json();

        $message = data_get($response, 'choices.0.message');

        // Check if the model decided to call a tool
        if (isset($message['tool_calls'])) {
            return $this->handleToolCalls($message, $messages);
        }

        return ['type' => 'text', 'content' => $message['content']];
    }

    protected function handleToolCalls(array $assistantMessage, array $messages): array
    {
        $messages[] = $assistantMessage;

        foreach ($assistantMessage['tool_calls'] as $toolCall) {
            $functionName = $toolCall['function']['name'];
            $arguments = json_decode($toolCall['function']['arguments'], true);

            // Map the tool call string directly back to our service container instance
            if (!isset($this->tools[$functionName])) {
                throw new \BadMethodCallException("Tool [{$functionName}] is not registered.");
            }

            $toolInstance = $this->tools[$functionName];
            $result = $toolInstance->handle($arguments);

            // Append tool execution result back into conversation history
            $messages[] = [
                'role' => 'tool',
                'tool_call_id' => $toolCall['id'],
                'name' => $functionName,
                'content' => json_encode($result->parsedData),
            ];
        }

        // Recursively continue the conversation loop with the tool outputs
        return $this->executeStep($messages);
    }
}

Why this works: Your tools are completely self-contained. Adding a brand-new capability to your autonomous agent requires writing one class that implements AIToolInterface, binding it in the service container, and adding it to the agent's constructor array. The agent doesn't need to change its prompt evaluation logic.


5. Streaming Responses from Jobs to UI via WebSockets and Livewire

Scenario: Large language models take several seconds to generate rich analytical responses. If your user is waiting for a queued background job or a complex agent multi-step loop to finish, a blank screen will cause them to abandon the page. You need real-time streaming tokens right down to the browser.

Why it matters: Standard HTTP request-response cycles terminate connections once data is flushed. If you execute a job asynchronously on the queue, the UI cannot receive streaming byte chunks directly unless you bridge your queue workers with real-time broadcasting channels (like Laravel Reverb or Pusher).

Solution: Emit broadcasting events from inside your AI tool's execution loop or your queue job as chunks stream in, allowing your frontend Livewire component or Vue SPA to render tokens character by character.

Code:

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class AIChatTokenStreamed implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(
        public string $conversationId,
        public string $tokenChunk
    ) {}

    public function broadcastOn(): Channel
    {
        return new Channel('chat.' . $this->conversationId);
    }
}
namespace App\AI\Tools;

use App\Events\AIChatTokenStreamed;
// ... abstract imports

class StreamingCodeReviewTool extends BaseAITool
{
    public function handleStreamed(array $payload, string $conversationId): void
    {
        $response = Http::withToken(config('services.openai.key'))
            ->withOptions(['stream' => true])
            ->post('https://api.openai.com/v1/chat/completions', [
                'model' => $this->model,
                'messages' => $payload['messages'],
                'stream' => true,
            ]);

        $stream = $response->toPsrResponse()->getBody();

        while (!$stream->eof()) {
            $line = trim($stream->read(1024));
            if (str_starts_with($line, 'data: ')) {
                $jsonStr = substr($line, 6);
                if ($jsonStr === '[DONE]') break;
                
                $data = json_decode($jsonStr, true);
                $token = data_get($data, 'choices.0.delta.content', '');

                if (!empty($token)) {
                    broadcast(new AIChatTokenStreamed($conversationId, $token));
                }
            }
        }
    }
}

Why this works: By tapping into PSR-7 streaming bodies via Laravel's HTTP client (->withOptions(['stream' => true])), you parse Server-Sent Events (SSE) directly inside PHP and rebroadcast them instantly using ShouldBroadcastNow. This bypasses queue serialization delays for the streaming channel while keeping the core business logic completely isolated inside your reusable AI tool class.


6. Handling Retries, Rate Limits, and Provider Failovers Gracefully

Scenario: You hit OpenAI's rate limits (HTTP 429) during a peak traffic window. Your controllers crash, throwing unhandled exceptions to your users, or your background jobs burn through all their retry attempts in thirty seconds because they lack intelligent backoff strategies.

Why it matters: AI providers are notoriously fickle. Network timeouts, rate limits, and sudden service degradation are standard operating conditions, not edge cases. If your AI tools don't handle these gracefully, your entire application availability plummets.

Solution: Leverage Laravel's built-in HTTP client retry mechanisms combined with custom exception handlers inside your base AI tool class.

Code:

namespace App\Support\AI;

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

abstract class BaseAITool
{
    protected function sendRequestWithRetry(array $payload): array
    {
        $response = Http::withToken(config('services.openai.key'))
            ->timeout(60)
            ->retry(3, 2000, function (\Exception $exception, $request) {
                // Retry only on connection timeouts or 429/5xx server errors
                if ($exception instanceof \Illuminate\Http\Client\RequestException) {
                    return $exception->response->status() === 429 || 
                           $exception->response->serverError();
                }
                return true;
            })
            ->post('https://api.openai.com/v1/chat/completions', $payload);

        if ($response->failed()) {
            $this->handleProviderFailure($response);
        }

        return $response->json();
    }

    protected function handleProviderFailure(Response $response): void
    {
        Log::error('AI Provider Failure', [
            'status' => $response->status(),
            'body' => $response->body(),
        ]);

        // Fallback option: Try secondary provider (e.g., Anthropic or local Ollama)
        if (config('ai.fallback_provider_enabled', false)) {
            // Implement fallback routing here
        }

        throw new \RuntimeException("AI service unavailable. Status: " . $response->status());
    }
}

⚠️ Gotcha: When using exponential backoff with queues, ensure your queue worker timeout is significantly higher than your total retry duration window, otherwise Laravel's queue supervisor will kill the job mid-retry.


7. Testing AI Tools Without Battering OpenAI or Anthropic Rate Limits

Scenario: Your CI/CD pipeline runs on every pull request. If your integration tests make real API calls to OpenAI, your test suite will take 15 minutes to run, become flaky due to network jitter, and cost you hundreds of dollars in API tokens every month.

Why it matters: Mocking third-party HTTP responses manually using PHPUnit or Pest mocks can become tedious when dealing with streaming data, complex function calling JSON structures, and deep tool loops.

Solution: Leverage Laravel's Http::fake() facade to intercept outgoing requests inside your test cases and return deterministic JSON fixtures that match your AI tool's expected output schema.

Code:

namespace Tests\Feature;

use App\AI\Tools\CodeReviewTool;
use App\Models\Repository;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class CodeReviewToolTest extends TestCase
{
    /** @test */
    public function it_correctly_parses_ai_code_review_responses()
    {
        // Arrange: Mock the OpenAI endpoint response
        Http::fake([
            'api.openai.com/v1/chat/completions' => Http::response([
                'choices' => [
                    [
                        'message' => [
                            'role' => 'assistant',
                            'content' => json_encode([
                                'risk_level' => 'low',
                                'bugs_found' => 0,
                                'recommendations' => ['Looks clean!'],
                            ]),
                        ],
                    ],
                ],
                'usage' => [
                    'prompt_tokens' => 120,
                    'completion_tokens' => 45,
                    'total_tokens' => 165,
                ],
            ], 200),
        ]);

        $repository = Repository::factory()->create();
        $tool = app(CodeReviewTool::class);

        // Act
        $response = $tool($repository, 'diff --git a/file.php b/file.php...');

        // Assert
        $this->assertEquals('low', $response->parsedData['risk_level']);
        $this->assertEquals(165, $response->totalTokens());
        
        Http::assertSent(function ($request) {
            return str_contains($request['model'], 'gpt-4o') &&
                   count($request['messages']) === 2;
        });
    }
}

Why this works: By asserting against intercepted requests rather than live infrastructure, your test execution drops from minutes to milliseconds, runs entirely offline, and remains completely deterministic.


Production Architecture Decision Guide

When evaluating where and how to execute your reusable Laravel AI tools in production, consult this architectural decision matrix:

Execution Context Best For Latency Tolerance State Management Recommended Approach
Synchronous Controller Real-time form validations, quick data extractions Low (< 3 seconds) Stateless / Request-bound Inject AIToolInterface directly into controller method.
Queued Background Job Bulk document processing, heavy codebase analysis, reporting High (Asynchronous) Serialized Models via IDs Dispatch Job, resolve tool via container inside handle().
Livewire / Reverb Stream Interactive chat interfaces, multi-step autonomous agents Medium (Streaming) Session / Database persistent history Stream SSE chunks directly via broadcasting events.

By breaking away from procedural controller scripts and treating your AI prompts as encapsulated, testable, dependency-injected service classes, you insulate your Laravel application against breaking provider changes, make your test suites blazing fast, and ensure your AI logic scales effortlessly from a simple web request to heavy distributed queue workers.

Post a Comment

Previous Post Next Post