Adding a Claude-powered feature to a Laravel app, properly · Part 4 of 6
An assistant that answers from your own data, through tools
Three read-only tools scoped to the company, the SDK's tool runner driving the loop, a saved history for follow-ups, and tests that script the model and keep everything else real.
By Abhishek Fouzdar
This part gives InvoiceMini an assistant. On a new page you ask "Which invoices are overdue, and how much is outstanding in total?" and Claude answers from the company's own data, which it reads through three tools the app provides. It covers what a tool is on the wire, the SDK's tool runner that drives the loop, the authorization boundary that keeps one company's data out of another company's answers, a saved conversation that makes follow-up questions work, and how to test all of it against a real database without the network. Part 3 streamed a reminder into the page.

What a tool is
A tool is a function the app owns and the model can ask for. The request carries a list of tools, each with a name, a description and a JSON schema for its input. When the model decides it needs one, it stops with the reason tool_use and a tool_use block naming the tool and giving the input. The app runs the function, sends the result back as a tool_result block in a user message, and the model continues. It may ask for another tool, or several at once, or answer in text, which ends the turn.
Nothing runs on Anthropic's side. The model never touches the database; it asks, the app decides, the app answers. That is what makes the authorization story simple, and it is the thing to hold on to when the word "agent" starts getting used.
The three tools
app/AI/AssistantTools.php builds the tools for one company. Each is a BetaRunnableTool: a definition array and a closure that runs it. list_invoices in full, the other two trimmed:
<?php
namespace App\AI;
use Anthropic\Lib\Tools\BetaRunnableTool;
use App\Billing\Money;
use App\Enums\InvoiceStatus;
use App\Models\Company;
use App\Models\Invoice;
// The three things the assistant can look up, all read-only and all scoped to one company.
// Every query starts from $company's relations, so there is no input the model could send
// that reaches another company's rows: the boundary is the query, not the prompt.
final class AssistantTools
{
public function __construct(private Company $company) {}
/** @return list<BetaRunnableTool> */
public function all(): array
{
return [$this->listInvoices(), $this->getInvoice(), $this->findClients()];
}
private function listInvoices(): BetaRunnableTool
{
return new BetaRunnableTool(
definition: [
'name' => 'list_invoices',
'description' => 'List the company\'s invoices, newest first, with totals. Filter by status, client name or overdue only. Returns at most 50.',
'inputSchema' => [
'type' => 'object',
'properties' => [
'status' => ['type' => 'string', 'enum' => ['draft', 'sent', 'paid', 'void'], 'description' => 'Only invoices in this status'],
'client' => ['type' => 'string', 'description' => 'Only invoices whose client name contains this text'],
'overdue_only' => ['type' => 'boolean', 'description' => 'Only sent invoices past their due date'],
],
],
],
run: function (array $input): string {
$query = $this->company->invoices()->with('client')->latest('id');
if (isset($input['status'])) {
$status = InvoiceStatus::tryFrom($input['status'])
?? throw new \InvalidArgumentException("Unknown status [{$input['status']}]; use draft, sent, paid or void.");
$query->where('status', $status);
}
if (! empty($input['client'])) {
$query->whereRelation('client', 'name', 'like', '%'.$input['client'].'%');
}
if (! empty($input['overdue_only'])) {
$query->where('status', InvoiceStatus::Sent)->whereDate('due_at', '<', today());
}
$invoices = $query->limit(50)->get();
$outstanding = [];
foreach ($invoices as $invoice) {
if ($invoice->status === InvoiceStatus::Sent) {
$outstanding[$invoice->currency] = ($outstanding[$invoice->currency] ?? 0) + $invoice->total - $invoice->amountPaid();
}
}
return json_encode([
'count' => $invoices->count(),
'outstanding_total' => array_map(fn (int $minor, string $currency) => Money::format($minor, $currency), $outstanding, array_keys($outstanding)),
'invoices' => $invoices->map(fn (Invoice $i) => $this->summary($i))->all(),
]);
},
);
}
private function getInvoice(): BetaRunnableTool // one invoice by number: lines, payments, notes
private function findClients(): BetaRunnableTool // clients by name, with invoice counts and what they owe
}
The rules behind the shape of those tools, each learned the hard way at some point.
Every query starts from $this->company. list_invoices is $this->company->invoices(), never Invoice::query(). There is no input the model can send, by mistake or because a prompt told it to, that reaches another company's rows, because the company is fixed before the model is involved. The test for it asks for another company's invoice number and gets "no such invoice". That is the whole multi-tenant story, and it is a query, not a prompt instruction.
Read-only. Three lookups, no writes. The system prompt tells the model it cannot change anything and where the person can; the tools make that true whatever the prompt says. An assistant that can send invoices is a different feature with a different risk, and it is not this one.
Do the arithmetic in the tool. list_invoices returns outstanding_total, summed per currency in PHP, so "how much is outstanding in total" is a number the tool computed and the model repeats. Models add numbers correctly most of the time; the tool does it every time.
Format the money. Amounts go to the model as €6,120.00, not 612000, and the system prompt says to repeat them as given. A model handed minor units will divide by a hundred, and the yen invoice will be wrong.
Return JSON, and throw for bad input. A result is a string; JSON is the string a model reads most reliably. A not-found is a normal result with an error key, because the model should tell the person. A bad filter value throws, and the runner turns the exception into a tool_result with is_error: true and the message, which the model reads and recovers from. The difference between those two is whether the model should explain or retry.
The runner
app/AI/Assistant.php sends the question and lets the SDK's tool runner drive the loop:
<?php
namespace App\AI;
use Anthropic\Beta\Messages\BetaMessage;
use Anthropic\Beta\Messages\BetaToolUseBlock;
use Anthropic\Client;
use Anthropic\Core\Exceptions\APIConnectionException;
use Anthropic\Core\Exceptions\APIStatusException;
use App\Models\Conversation;
use Illuminate\Support\Facades\Log;
// Answers a question about the company's invoices by letting Claude call the read-only tools
// in AssistantTools. The SDK's tool runner drives the loop: send, run the tools Claude asked
// for, send the results, repeat until Claude answers in text. The whole exchange, tool calls
// included, is saved on the conversation so the next question has the context.
final class Assistant
{
private const MAX_STEPS = 6;
public function __construct(private Client $claude) {}
public function ask(Conversation $conversation, string $question): BetaMessage
{
$model = config('claude.models.default');
$messages = [...$conversation->messages, ['role' => 'user', 'content' => $question]];
$tools = new AssistantTools($conversation->company);
$runner = $this->claude->beta->messages->toolRunner(
maxTokens: 2048,
messages: $messages,
model: $model,
tools: $tools->all(),
maxIterations: self::MAX_STEPS,
extraParams: [
// Cached: identical on every request for the company, and it is the longest
// part. Part 5 shows what that saves.
'system' => [['type' => 'text', 'text' => $this->systemPrompt($conversation), 'cacheControl' => ['type' => 'ephemeral']]],
],
thread: false,
);
$last = null;
$steps = 0;
try {
foreach ($runner as $message) {
$steps++;
$last = $message;
Log::info('claude.assistant', [
'conversation_id' => $conversation->id,
'step' => $steps,
'stop_reason' => $message->stopReason,
'tools' => array_map(fn ($b) => $b->name, array_filter($message->content, fn ($b) => $b instanceof BetaToolUseBlock)),
'input_tokens' => $message->usage->inputTokens,
'cache_read_input_tokens' => $message->usage->cacheReadInputTokens,
'output_tokens' => $message->usage->outputTokens,
'cost' => Cost::of($model, $message->usage),
]);
}
} catch (APIStatusException|APIConnectionException $e) {
throw new AssistantFailed('Claude could not answer: '.$e->getMessage(), previous: $e);
}
if ($last === null || $last->stopReason !== 'end_turn') {
throw new AssistantFailed('Claude did not reach an answer in '.self::MAX_STEPS.' steps.');
}
// The runner's history is the API's message list: the question, each tool request,
// each tool result, the answer. Stored as the API would accept it back.
$conversation->messages = json_decode(json_encode($runner->getParams()['messages']), true);
$conversation->title ??= mb_strimwidth($question, 0, 80, '…');
$conversation->save();
return $last;
}
}
The runner lives in the SDK's beta namespace, $client->beta->messages->toolRunner(), and is iterable: each iteration is one round trip, and it yields the model's message for that step. Between iterations it runs whatever tools the message asked for and appends the results. The loop body above only observes: it logs each step with its stop reason, the tools it called and its tokens, and keeps the last message. When the model answers in text the runner stops, and $last is the answer.
maxIterations is the guard rail. A model can, in principle, keep asking for tools; six steps is more than this app's questions need and small enough that a runaway conversation costs cents. If the loop ends on anything other than end_turn, the assistant failed and says so, rather than showing a half-answer.
thread: false keeps the runner on plain messages. By default it wraps the conversation in the SDK's thread helper, which is useful elsewhere; here the app owns the history, so it opts out.
The system prompt goes through extraParams, and it is marked for caching. Everything about the company that does not change between questions, the instructions and the tool definitions, is the same on every request, and the API can charge a tenth of the input price for the part it has seen before. Part 5 measures it; the log line already shows cache_read_input_tokens so you can see it working today.
$runner->getParams()['messages'] is the history as the runner holds it: the question, the model's tool requests, the tool results, the answer. Saved as JSON on the conversation, it is exactly what the next question sends as messages, which is why a follow-up like "what exactly is on the biggest one?" knows what "the biggest one" is.
The page is a controller and two Blade views with nothing new in them, and a markdown step that deserves one note. The answer is rendered with Str::markdown($text, ['html_input' => 'strip', 'allow_unsafe_links' => false]), so the model's bold and bullets work and any HTML it might emit, or might be tricked into emitting by text in an invoice note, is stripped. The model's output is data, like a client's name; the page treats it the way it treats any user input.
Against the real API
The demo company, two questions, through Assistant directly:
Q: Which invoices are overdue, and how much is outstanding in total?
(5.5 s)
A: Two invoices are overdue, both for Von-Blick, and together they leave **€6,120.00** unpaid.
- **INV-2026-0005**: €6,120.00 still owed. It was due Oct 20, 2026, and nothing has been paid yet.
- **INV-2026-0004**: €0.00 owed. It was due Oct 17, 2026.
INV-2026-0004 looks wrong. Its total is €0.00, but it's still marked as sent and overdue. It may have been sent with no lines on it. It's worth opening it to check whether it should be fixed or voided.
Q: What exactly is on the biggest one?
(4.0 s)
A: INV-2026-0005 for Von-Blick has two lines, both with 20% tax:
- **Design system audit**: 1 × €2,400.00
- **Component library, 3 days**: 3 × €900.00
Before tax that's €5,100.00. The 20% tax adds €1,020.00, which brings it to the €6,120.00 total. It was issued Oct 6, 2026 and due Oct 20, 2026, and no payments have been recorded against it. The invoice has no notes.
stored messages: 8 (conversation 1)
The second invoice really is a seeded one with no lines, left over from the testing series, and the assistant noticed without being asked. The follow-up resolved "the biggest one" from the saved history and called get_invoice for the right number. Eight stored messages: two questions, two tool requests, two tool results, two answers.
The log for those two questions, one line per step:
step 1 stop tool_use tools ["list_invoices"] in 97 cache_read 0 out 53 $0.001448
step 2 stop end_turn tools [] in 416 cache_read 835 out 352 $0.008704
step 1 stop tool_use tools ["get_invoice"] in 784 cache_read 835 out 56 $0.004256
step 2 stop end_turn tools [] in 1063 cache_read 835 out 205 $0.008352
Four requests, a little over two cents. From the second request on, 835 tokens of system prompt and tool definitions were read from cache instead of being charged in full. The cost column is not counting those cached tokens yet; part 5's accounting does.
Testing the loop
The fake gets a reply that asks for a tool:
/** A reply that asks the app to run a tool: one tool_use block and the matching stop reason. */
public static function toolUse(string $name, array $input, string $id = 'toolu_01', int $inputTokens = 10, int $outputTokens = 5): array
{
return [
...self::text('', $inputTokens, $outputTokens),
'id' => 'msg_test_'.$id,
'content' => [['type' => 'tool_use', 'id' => $id, 'name' => $name, 'input' => $input]],
'stop_reason' => 'tool_use',
];
}
Queue a toolUse reply and then a text reply, and the runner does the rest: it runs the real tool against the test database, sends the result in a second request, and takes the text as the answer. The first test checks every link in that chain:
it('answers by calling a tool and saves the whole exchange', function () {
$claude = FakeClaude::bind(
FakeClaude::toolUse('list_invoices', ['overdue_only' => true]),
FakeClaude::text('One invoice is overdue: INV-2026-0042 for Acme GmbH, €1,200.00 outstanding.'),
);
$response = $this->actingAs($this->user)->post(route('assistant.store'), ['question' => 'Which invoices are overdue?']);
$conversation = Conversation::sole();
$response->assertRedirect(route('assistant.show', $conversation));
// The runner sent two requests: the question, then the question plus the tool round trip.
expect($claude->requests)->toHaveCount(2);
$second = $claude->requests[1]['body']['messages'];
expect($second)->toHaveCount(3)
->and($second[0])->toBe(['role' => 'user', 'content' => 'Which invoices are overdue?'])
->and($second[1]['content'][0]['type'])->toBe('tool_use')
->and($second[2]['content'][0]['type'])->toBe('tool_result')
->and($second[2]['content'][0]['tool_use_id'])->toBe('toolu_01');
// The tool ran against the real database, scoped to the company.
$result = json_decode($second[2]['content'][0]['content'], true);
expect($result['count'])->toBe(1)
->and($result['invoices'][0]['number'])->toBe('INV-2026-0042')
->and($result['invoices'][0]['overdue'])->toBeTrue()
->and($result['outstanding_total'])->toBe(['€1,200.00']);
// Saved as the API would accept it back: question, tool request, tool result, answer.
expect($conversation->messages)->toHaveCount(4)
->and($conversation->title)->toBe('Which invoices are overdue?')
->and($conversation->messages[3]['content'][0]['text'])->toContain('INV-2026-0042');
$this->actingAs($this->user)->get(route('assistant.show', $conversation))
->assertSee('Which invoices are overdue?')
->assertSee('One invoice is overdue')
->assertSee('Looked up')
->assertSee('list_invoices');
});
Notice what is and is not faked. The model's decisions are scripted, because they are the one thing a test cannot control. The tools, the database, the saved history and the page are real. That is the right split for any LLM feature: fake the model, test everything around it.
The rest of the file: the request carries the three tools and a cached system prompt naming the company; another company's invoice number comes back as not found; a bad status filter becomes an is_error result starting with Error: Unknown status [bogus]; a follow-up replays the saved history and sends the new question last; six toolUse replies in a row hit the step limit and the person sees a message, not a 500; a stranger gets 403 on the conversation and on asking in it; and <script> in an answer is stripped while **bold** becomes <strong>.
php artisan test --testsuite=Unit,Feature --compact
Tests: 156 passed (422 assertions)
Duration: 22.60s
What went wrong
Cost::of(): Argument #2 ($usage) must be of type Anthropic\Messages\Usage, Anthropic\Beta\Messages\BetaUsage given. The tool runner is a beta feature and returns the beta namespace's classes, which are parallel to the stable ones: BetaMessage, BetaToolUseBlock, BetaUsage. The same fields, a different type. Cost::of() now accepts both.
The Assistant link landed in the middle of the header. The layout's header is a flex row with justify-between and two children; a third child spreads out. It belongs inside the right-hand group.
Bulleted answers rendered without bullets. Tailwind's reset removes list styling, and the project does not use the typography plugin. Eight lines of CSS under .prose give lists and paragraphs their spacing back.
The seeded data had a sent invoice with no lines, which the assistant pointed out before I did. A useful property of a tool that returns the real rows: the model reads what is actually there.
Part 5 takes the assistant and the reminder off the request thread: a monthly summary written in a queued job with retries that respect the API's rate limits, prompt caching measured instead of assumed, token counting before a call, a usage table that puts a price on every call per company, the Batch API at half price, and Haiku for the calls that do not need Opus.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
4 / 6- OverviewAdding a Claude-powered feature to a Laravel app, properly
- Part 1The SDK, one client in the container, and the first call
- Part 2An invoice draft from plain English, through structured outputs
- Part 3A payment reminder streamed into the page
- Part 4An assistant that answers from your own data, through tools
- Part 5Queues, retries, real cost, caching measured, the Batch API and Haiku
- Part 6An eval set, a grader, prompt snapshots and a nightly run