Laravel AI SDK: Tool-Calling Agents Guide | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://www.msaied.com) [ Home ](https://www.msaied.com) [ Projects ](https://www.msaied.com/projects) [ Articles  ](https://www.msaied.com/articles) [ Certificates ](https://www.msaied.com/certificates) [ Contact ](https://www.msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://www.msaied.com) [ Projects ](https://www.msaied.com/projects) [ Articles ](https://www.msaied.com/articles) [ Certificates ](https://www.msaied.com/certificates) [ Contact ](https://www.msaied.com#contact-section) 

  [ home ](https://www.msaied.com)    [ articles ](https://www.msaied.com/articles)    Laravel AI SDK: Tool-Calling Agents and Conversation Persistence        On this page       1. [  Laravel AI SDK: Tool-Calling Agents and Conversation Persistence ](#laravel-ai-sdk-tool-calling-agents-and-conversation-persistence)
2. [  Defining Typed Tools ](#defining-typed-tools)
3. [  Running the Agent Loop ](#running-the-agent-loop)
4. [  Persisting Conversation History ](#persisting-conversation-history)
5. [  Guarding Against Prompt Injection ](#guarding-against-prompt-injection)
6. [  Takeaways ](#takeaways)

  ![Laravel AI SDK: Tool-Calling Agents and Conversation Persistence](https://cdn.msaied.com/726/cde0e4e03a15ea0776e82aca8727f660.png)

  #laravel   #ai   #agents   #llm  

 Laravel AI SDK: Tool-Calling Agents and Conversation Persistence 
==================================================================

     1 Oct 2026      3 min read    ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said  

       Table of contents

1. [  01   Laravel AI SDK: Tool-Calling Agents and Conversation Persistence  ](#laravel-ai-sdk-tool-calling-agents-and-conversation-persistence)
2. [  02   Defining Typed Tools  ](#defining-typed-tools)
3. [  03   Running the Agent Loop  ](#running-the-agent-loop)
4. [  04   Persisting Conversation History  ](#persisting-conversation-history)
5. [  05   Guarding Against Prompt Injection  ](#guarding-against-prompt-injection)
6. [  06   Takeaways  ](#takeaways)

 Laravel AI SDK: Tool-Calling Agents and Conversation Persistence
----------------------------------------------------------------

The [Laravel AI SDK](https://github.com/prism-php/prism) (Prism) gives you a first-class, fluent interface for building LLM-powered features without drowning in raw HTTP calls. Once you move beyond simple completions, two challenges dominate real production work: **defining tools the model can call** and **persisting conversation state** so users can resume sessions. This article tackles both concretely.

### Defining Typed Tools

A tool is a PHP class the model can invoke. Prism expects each tool to declare its name, description, and a JSON-schema-compatible parameter list. The cleanest pattern is a dedicated class per tool:

```php
use Prism\Prism\Tool;
use Prism\Prism\Schema\StringSchema;
use Prism\Prism\Schema\ObjectSchema;

class SearchOrdersTool extends Tool
{
    public function __construct(private OrderRepository $orders) {}

    public function name(): string { return 'search_orders'; }

    public function description(): string
    {
        return 'Search customer orders by status or date range.';
    }

    public function parameters(): ObjectSchema
    {
        return new ObjectSchema(
            name: 'search_orders_params',
            description: 'Parameters for order search',
            properties: [
                new StringSchema('status', 'Order status filter'),
                new StringSchema('since', 'ISO-8601 date lower bound'),
            ],
            requiredFields: ['status']
        );
    }

    public function handle(string $status, string $since = ''): string
    {
        $results = $this->orders->search($status, $since);
        return json_encode($results->toArray());
    }
}

```

Bind the tool through the service container so its dependencies are resolved automatically:

```php
// AppServiceProvider
$this->app->bind(SearchOrdersTool::class, fn ($app) =>
    new SearchOrdersTool($app->make(OrderRepository::class))
);

```

### Running the Agent Loop

Tool-calling agents require a loop: the model responds, you execute any requested tools, then feed results back. Prism handles this with `withTools()` and `usingMaxSteps()`:

```php
use Prism\Prism\Prism;
use Prism\Prism\Enums\Provider;
use Prism\Prism\ValueObjects\Messages\UserMessage;

$response = Prism::text()
    ->using(Provider::OpenAI, 'gpt-4o')
    ->withTools([
        app(SearchOrdersTool::class),
    ])
    ->usingMaxSteps(5)
    ->withMessages($conversationHistory)
    ->withPrompt('Find all pending orders placed after 2024-06-01.')
    ->generate();

$reply = $response->text;

```

`usingMaxSteps(5)` prevents runaway loops. Each step either produces a final answer or calls a tool and continues.

### Persisting Conversation History

Stateless completions are fine for one-shot tasks, but agents need memory. Store each turn as a JSON-serialised message array:

```php
// Migration
Schema::create('agent_conversations', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->string('session_id')->index();
    $table->json('messages')->default('[]');
    $table->timestamps();
});

```

A thin service wraps load/save:

```php
class ConversationStore
{
    public function load(string $sessionId): array
    {
        $row = AgentConversation::where('session_id', $sessionId)->first();
        return $row ? $row->messages : [];
    }

    public function append(string $sessionId, array $newMessages): void
    {
        AgentConversation::updateOrCreate(
            ['session_id' => $sessionId],
            ['messages' => array_merge($this->load($sessionId), $newMessages)]
        );
    }
}

```

After each agent run, persist the full step history:

```php
$store->append($sessionId, $response->steps
    ->flatMap(fn ($step) => $step->messages)
    ->all()
);

```

### Guarding Against Prompt Injection

Tool results are injected back into the context verbatim. Sanitise any user-controlled data before it reaches the model:

```php
public function handle(string $status, string $since = ''): string
{
    // Never interpolate raw user input into SQL or shell commands.
    $status = in_array($status, ['pending','shipped','cancelled'])
        ? $status
        : throw new \InvalidArgumentException('Invalid status');

    return json_encode($this->orders->search($status, $since)->toArray());
}

```

### Takeaways

- **One class per tool** keeps parameter schemas and business logic co-located and testable.
- **`usingMaxSteps()`** is a hard safety valve — always set it.
- **Store messages as JSON arrays**, not raw text, so you can replay or audit the full tool-call chain.
- **Validate tool inputs** inside `handle()` before touching any data layer; the model can hallucinate parameter values.
- Bind tools through the **service container** to keep dependencies injectable and mockable in tests.

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.msaied.com%2Farticles%2Flaravel-ai-sdk-tool-calling-agents-and-conversation-persistence-4&text=Laravel+AI+SDK%3A+Tool-Calling+Agents+and+Conversation+Persistence) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.msaied.com%2Farticles%2Flaravel-ai-sdk-tool-calling-agents-and-conversation-persistence-4) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  How do I test a tool-calling agent without hitting the real OpenAI API?        Prism ships with a fake driver. Call `Prism::fake()` in your test, define canned responses including simulated tool-call steps, then assert the tool's handle method was invoked with the expected arguments using standard Pest expectations. 

      Q02  What happens if a tool throws an exception during an agent step?        By default the exception bubbles up and halts the loop. Wrap the `handle()` body in a try/catch and return a structured error string so the model can decide how to recover, rather than crashing the entire request. 

      Q03  Can I use streaming responses with tool-calling agents?        Streaming and tool-calling are mutually exclusive in most providers: the model must finish generating the full tool-call JSON before you can parse and execute it. Use streaming only for final text responses after all tool steps are complete. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://www.msaied.com/articles) 

 [ ![Laravel 14 Adds a defaults() Method to Eloquent Models](https://cdn.msaied.com/725/6d4daa85070ffb81d6a9a3e25a8ed08c.png) Laravel 14 Eloquent Model Defaults 

### Laravel 14 Adds a defaults() Method to Eloquent Models

Laravel 14 introduces a defaults() method for Eloquent models, letting you set dynamic default attribute value...

  ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said 

 30 Sep 2026     3 min read  

  Read    

 ](https://www.msaied.com/articles/laravel-14-adds-a-defaults-method-to-eloquent-models) [ ![Laravel AI SDK and Laravel MCP Security Fixes: Update Now](https://cdn.msaied.com/722/fbe8df92faa32e9b9cee984a18bd4411.png) security laravel-ai laravel-mcp 

### Laravel AI SDK and Laravel MCP Security Fixes: Update Now

Two security advisories were published for laravel/ai and laravel/mcp on September 30, 2026. Both are fixed—ru...

  ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said 

 30 Sep 2026     3 min read  

  Read    

 ](https://www.msaied.com/articles/laravel-ai-sdk-and-laravel-mcp-security-fixes-update-now) [ ![Migrating Pinkary from Laravel Forge to Laravel Cloud: An Engineering Playbook](https://cdn.msaied.com/723/6f9c9010ccb06581b52bcfab81e47dd9.png) Laravel Cloud Laravel Forge MySQL 

### Migrating Pinkary from Laravel Forge to Laravel Cloud: An Engineering Playbook

A code-backed walkthrough of the real issues encountered moving Pinkary from Laravel Forge to Laravel Cloud: S...

  ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said 

 30 Sep 2026     5 min read  

  Read    

 ](https://www.msaied.com/articles/migrating-pinkary-from-laravel-forge-to-laravel-cloud-an-engineering-playbook) 

   [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://www.msaied.com)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

Explore

- [Home](https://www.msaied.com)
- [Projects](https://www.msaied.com/projects)
- [Articles](https://www.msaied.com/articles)
- [Certificates](https://www.msaied.com/certificates)
- [Contact](https://www.msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
