Laravel AI SDK: Tool-Calling Agents Guide | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Laravel AI SDK: Tool-Calling Agents and Conversation Persistence

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

 Build reliable tool-calling AI agents in Laravel using the AI SDK, with typed tool definitions, structured responses, and durable conversation history stored in your database.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 1 Oct 2026 · Updated 1 Oct 2026 · 3 min read

ShareCopy linkCopied

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

  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
----------------------------------------------------------------

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.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [ai](https://www.msaied.com/public/articles?search=ai)
- [agents](https://www.msaied.com/public/articles?search=agents)
- [llm](https://www.msaied.com/public/articles?search=llm)

 Frequently asked questions 
---------------------------

  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.

   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.

   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.

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

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

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articlePostcodes for Laravel: GB Postcode Lookup and Geography Data](https://www.msaied.com/public/articles/postcodes-for-laravel-gb-postcode-lookup-and-geography-data) [Next articleWhenMounted and BigInt Props in Inertia.js v3.8](https://www.msaied.com/public/articles/whenmounted-and-bigint-props-in-inertiajs-v38)  

   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)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
