Build Conversational AI Agents With Laravel’s AI SDK

📖 2 minutes read

Laravel 12’s AI SDK lets you build agents that maintain conversation context and use tools. This is perfect for multi-step decision-making workflows where the agent needs to query your database or call APIs based on previous responses.

Define an agent with conversation memory and custom tools:

use Laravel\Ai\Agent;
use Laravel\Ai\Conversations\Conversational;
use Laravel\Ai\Conversations\RemembersConversations;

class DataValidator extends Agent implements Conversational
{
    use RemembersConversations;
    
    protected function instructions(): string
    {
        return 'Check if data already exists. Use canonical values from database when found.';
    }
    
    protected function tools(): array
    {
        return [new SearchDatabase()];
    }
    
    protected function timeout(): int
    {
        return 60;
    }
}

Invoke the agent with conversation context:

$response = app(DataValidator::class)
    ->forUser($conversationId)
    ->withSchema(DataSchema::schema())
    ->invoke($inputData);

$validated = $response->output();

The agent remembers previous interactions within the same conversation ID, letting it build up context across multiple invocations. This is powerful for workflows like data enrichment pipelines where each step informs the next.

For example, a data import pipeline could use an agent to validate and deduplicate records. The first invocation establishes canonical values, and subsequent invocations reference those decisions:

// First record - agent searches database and establishes canonical form
$result1 = $agent->forUser('import-batch-123')
    ->invoke(['name' => 'John Doe', 'email' => '[email protected]']);

// Second record - agent remembers the previous decision
$result2 = $agent->forUser('import-batch-123')
    ->invoke(['name' => 'J. Doe', 'email' => '[email protected]']);
// Agent recognizes this as the same person and reuses the canonical form

The Conversational interface and RemembersConversations trait handle the complexity of managing conversation history, while your tools provide the agent with the capabilities it needs to make informed decisions.

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 *