Refactor Complex Inline Logic into Dedicated Classes

πŸ“– 2 minutes read

When agent() calls become complex with large schemas, extract them into dedicated Agent classes. This improves readability, enables reuse, and makes testing easier.

❌ Before: Inline Complexity

public function processData(string $url): ?array
{
    $response = agent(
        instructions: 'Extract structured data from URL...',
        tools: [new WebFetch, new WebSearch],
        schema: fn (JsonSchema $schema) => [
            'name' => $schema->string()->required(),
            'items' => $schema->array()->items(
                $schema->object([
                    'title' => $schema->string()->required(),
                    'value' => $schema->integer()->min(0)->nullable(),
                ])
            ),
        ]
    )->prompt("Extract from: {$url}");
}

βœ… After: Dedicated Agent Class

// app/Ai/Agents/DataExtractor.php
class DataExtractor implements Agent, HasStructuredOutput
{
    public function instructions(): string
    {
        return 'Extract structured data from URL...';
    }

    public function tools(): iterable
    {
        return [new WebFetch, new WebSearch];
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'name' => $schema->string()->required(),
            'items' => $schema->array()->items(
                $schema->object([
                    'title' => $schema->string()->required(),
                    'value' => $schema->integer()->min(0)->nullable(),
                ])
            ),
        ];
    }
}

// Usage:
public function processData(string $url): ?array
{
    return DataExtractor::prompt("Extract from: {$url}");
}

Why This Matters

Laravel AI SDK’s agent() helper is great for quick prototypes, but production code benefits from structure. Dedicated Agent classes:

  • Improve readability β€” separate concerns into focused files
  • Enable reuse β€” use the same agent across multiple controllers
  • Make testing easier β€” mock or test agents in isolation
  • Follow Laravel conventions β€” single responsibility principle

If your agent() call spans more than ~10 lines, it’s time to extract a class.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *