Adding a Claude-powered feature to a Laravel app, properly · Part 3 of 6

AI12 min read

A payment reminder streamed into the page

The SDK's event stream, Laravel's server-sent events response, an EventSource that never reconnects into a second reminder, and tests that decode the stream back into the email.

By Abhishek Fouzdar

This part puts the API on the other side of the screen. On a sent invoice, "Write with Claude" asks for a payment reminder and the email appears in the page as it is written, word by word, with a Stop button that works and a status line that ends with what it cost. It covers the SDK's streaming interface, Laravel's server-sent events response, a browser-side EventSource that never reconnects into a second reminder, and tests that decode the stream back into the email. Part 2 built the invoice draft through structured outputs.

The reminder box on a sent invoice, mid-stream: the subject and the first paragraph written, the status reading Writing…, a Stop button

Why stream at all

A reminder email takes Opus 5.5 about four and a half seconds to write. Four and a half seconds behind a spinner feels broken; four and a half seconds of text arriving feels like someone typing. That is the whole case for streaming on the user-facing side, and it is a stronger case than it sounds, because the alternative is not only slower-feeling but more fragile: a request that holds a PHP worker for five seconds and then times out at the proxy has nothing to show for it, while a stream that drops at second four has most of an email on the screen.

There is a second reason that matters more as outputs grow. Non-streaming requests have to fit inside HTTP timeouts, and the SDK refuses large maxTokens without streaming for exactly that reason. Part 5's monthly summary is long; it streams on the server even though no browser is watching.

The writer

app/AI/ReminderWriter.php is a generator. It yields each piece of text the moment it arrives and returns the complete message at the end, so one method serves both the live page and the bookkeeping:

<?php

namespace App\AI;

use Anthropic\Client;
use Anthropic\Core\Exceptions\APIConnectionException;
use Anthropic\Core\Exceptions\APIStatusException;
use Anthropic\Lib\Streaming\MessageAccumulator;
use Anthropic\Messages\Message;
use Anthropic\Messages\RawContentBlockDeltaEvent;
use Anthropic\Messages\TextDelta;
use App\Billing\Money;
use App\Models\Invoice;
use Illuminate\Support\Facades\Log;

// Writes a payment reminder for a sent invoice and streams it as it is written. The
// generator yields each piece of text the moment it arrives and returns the complete
// message at the end, so the caller gets both the live stream and the final usage.
final class ReminderWriter
{
    public function __construct(private Client $claude) {}

    /** @return \Generator<int, string, mixed, Message> */
    public function stream(Invoice $invoice): \Generator
    {
        $model = config('claude.models.default');
        $accumulator = MessageAccumulator::forMessages();

        try {
            $events = $this->claude->messages->createStream(
                model: $model,
                maxTokens: 1024,
                system: $this->systemPrompt($invoice),
                messages: [['role' => 'user', 'content' => 'Write the reminder email.']],
            );

            foreach ($events as $event) {
                $accumulator->accumulate($event);

                // Thinking arrives first, as deltas with no text; only the text is for the page.
                if ($event instanceof RawContentBlockDeltaEvent && $event->delta instanceof TextDelta) {
                    yield $event->delta->text;
                }
            }
        } catch (APIStatusException|APIConnectionException $e) {
            throw new ReminderFailed('Claude could not write the reminder: '.$e->getMessage(), previous: $e);
        }

        $message = $accumulator->message();

        Log::info('claude.reminder', [
            'invoice_id' => $invoice->id,
            'model' => $model,
            'stop_reason' => $message->stopReason,
            'input_tokens' => $message->usage->inputTokens,
            'output_tokens' => $message->usage->outputTokens,
            'cost' => Cost::of($model, $message->usage),
        ]);

        return $message;
    }
    // systemPrompt() below
}

createStream() takes the same arguments as create() and returns an iterator of events instead of a message. The events are the API's own: message_start, then for each content block a content_block_start, some content_block_deltas and a content_block_stop, then message_delta with the stop reason and the output token count, then message_stop. The SDK gives each one a class, and the only one the page cares about is a RawContentBlockDeltaEvent whose delta is a TextDelta.

The instanceof TextDelta check is not decoration. Opus 5.5 thinks before it writes, and the thinking arrives as its own content block of deltas before the text does. With the default display setting those deltas carry empty text, so a loop that yielded every delta would send the page a burst of nothing and then the email. The page below shows "Thinking…" until the first real delta and "Writing…" after it, which is the honest version of what is happening.

MessageAccumulator is the SDK's way of getting the final Message out of a stream without assembling it yourself. Feed it every event and ask for message() at the end: the content blocks, the stop reason and the usage are all there, the usage being the input count from message_start and the output count from message_delta. Without it you would be summing deltas by hand and still not have the token counts.

The system prompt is the invoice, in sentences:

private function systemPrompt(Invoice $invoice): string
{
    $invoice->loadMissing('company', 'client');
    $today = $invoice->company->freshTimestamp();
    $days = (int) $invoice->due_at->diffInDays($today, absolute: true);
    $when = $invoice->due_at->isPast()
        ? "{$days} days overdue"
        : ($days === 0 ? 'due today' : "due in {$days} days");
    $outstanding = Money::format($invoice->total - $invoice->amountPaid(), $invoice->currency);
    $paid = $invoice->amountPaid() > 0
        ? Money::format($invoice->amountPaid(), $invoice->currency).' has been paid so far.'
        : 'Nothing has been paid so far.';

    return <<<PROMPT
        You write payment reminder emails on behalf of {$invoice->company->name}, a small business, to its client {$invoice->client->name}.

        The invoice:
        - Number {$invoice->number}, issued {$invoice->issued_at->toFormattedDateString()}, due {$invoice->due_at->toFormattedDateString()} ({$when}).
        - Outstanding amount: {$outstanding}. {$paid}
        - Today is {$today->toFormattedDateString()}.

        Write a short, courteous email in plain text: a subject line first ("Subject: ..."), then the body. State the invoice number, the amount and the due date. Ask for payment or for a date by which it will be made. If it is overdue, say so plainly without threatening anything. Mention that the reminder can be ignored if payment has already been sent. Sign off as {$invoice->company->name}. No markdown, no placeholders in square brackets, nothing but the email.
        PROMPT;
}

The arithmetic is done in PHP. The model is told "13 days overdue" and "€6,120.00"; it is not handed a due date and a total and asked to work them out. Models can do date arithmetic, and sometimes do it wrong, and a reminder with the wrong number of days in it is worse than no reminder. Anything the app can compute, the app computes, and the prompt gets the answer.

ReminderFailed is the same two-line exception as part 2's DraftFailed, for the same reason: the controller never imports the SDK.

Server-sent events from Laravel

The route answers with an event stream. Laravel has had response()->eventStream() since version 11, and it does exactly the plumbing a stream needs:

Route::get('/invoices/{invoice}/reminder', InvoiceReminderController::class)->name('invoices.reminder');
class InvoiceReminderController extends Controller
{
    public function __invoke(Invoice $invoice, ReminderWriter $writer): StreamedResponse
    {
        Gate::authorize('remind', $invoice);

        return response()->eventStream(function () use ($invoice, $writer) {
            $stream = $writer->stream($invoice);

            try {
                foreach ($stream as $delta) {
                    yield new StreamedEvent('delta', $delta);
                }
            } catch (ReminderFailed $e) {
                report($e);
                yield new StreamedEvent('error', 'The reminder could not be written. Try again in a moment.');

                return;
            }

            $message = $stream->getReturn();

            yield new StreamedEvent('done', json_encode([
                'stopReason' => $message->stopReason,
                'cost' => Cost::format(Cost::of($message->model, $message->usage)),
            ]));
        }, endStreamWith: null);
    }
}

What eventStream() does with each yielded StreamedEvent: writes event: <name>, then data: <text> with every newline in the text turned into a further data: line, then a blank line, and flushes. That is the server-sent events format, and the newline rule is why an email with paragraphs survives the trip. It also sets Content-Type: text/event-stream, Cache-Control: no-cache and X-Accel-Buffering: no, the last of which tells nginx not to buffer the response, without which a stream behind nginx arrives all at once at the end.

Three design points. The three event names are the whole protocol: delta carries text, done carries the stop reason and the cost as JSON, error carries a sentence for the person. endStreamWith: null switches off Laravel's default closing event, because done already says the stream is over. And a failure mid-stream becomes an error event rather than silence: eventStream() catches any exception, reports it and ends the response, which to the browser looks like a stream that stopped for no reason. The try inside the generator turns that into a message on the page.

Cancellation falls out of the design. eventStream() checks connection_aborted() before each event; when the person presses Stop, the browser closes the connection, the next flush notices, the loop breaks, the generator is destroyed, and the SDK's stream is closed with it. The API stops being read, and the app stops paying for output it will not use.

remind is a new policy method: the invoice must belong to the user's company and be in the Sent state. A draft has nothing to remind about, and a paid one would be rude.

The page

The page script is thirty lines on EventSource, the browser API made for this:

const reminder = document.getElementById('reminder');
if (reminder) {
    const text = document.getElementById('reminder-text');
    const status = document.getElementById('reminder-status');
    const write = document.getElementById('reminder-write');
    const stop = document.getElementById('reminder-stop');
    const copy = document.getElementById('reminder-copy');
    let source = null;

    const finish = (note) => {
        source?.close();
        source = null;
        status.textContent = note;
        stop.classList.add('hidden');
        write.disabled = false;
        if (text.value) copy.classList.remove('hidden');
    };

    write.addEventListener('click', () => {
        text.value = '';
        text.classList.remove('hidden');
        copy.classList.add('hidden');
        stop.classList.remove('hidden');
        write.disabled = true;
        status.textContent = 'Thinking…';

        source = new EventSource(reminder.dataset.url);
        source.addEventListener('delta', (event) => {
            if (!text.value) status.textContent = 'Writing…';
            text.value += event.data;
        });
        source.addEventListener('done', (event) => {
            const { stopReason, cost } = JSON.parse(event.data);
            finish(stopReason === 'end_turn' ? `Done, ${cost}.` : `Stopped early (${stopReason}), ${cost}.`);
        });
        source.addEventListener('error', (event) => {
            // Our own error event carries data; a dropped connection does not.
            finish(event.data ?? 'Connection lost.');
        });
    });
    stop.addEventListener('click', () => finish('Stopped.'));
    copy.addEventListener('click', () => navigator.clipboard.writeText(text.value).then(() => { status.textContent = 'Copied.'; }));
}

EventSource sends the session cookie, so the route is protected by the normal login and the policy, with no token to manage. It parses the event: and data: lines and joins multi-line data with newlines, which is why text.value += event.data is enough to rebuild the email.

The one thing to know about EventSource is that it reconnects by itself. If the connection drops, or if the server simply ends the response, the browser opens the URL again a few seconds later, and here that would mean a second reminder being written and paid for. Every exit path in the script, done, error, Stop, goes through finish(), and finish() closes the source first. The native error event fires for both a dropped connection and our own error event; ours carries data, the browser's does not, and the script tells them apart on that.

A stream that stops before end_turn is shown as such. If the reply hit maxTokens the status says "Stopped early (max_tokens)" next to a truncated email, and the person knows to try again rather than send half a letter.

The reminder box when the stream has finished: the full email, a Copy button, and the status Done, $0.006308

Against the real API

The demo invoice is INV-2026-0005 for Von-Blick, €6,120.00, due on 20 October 2026 and thirteen days overdue when this ran. Through ReminderWriter directly, printing the first deltas with a timer:

 2453 ms  delta #1: "Subject: Payment re"
 2479 ms  delta #2: "minder:"
 2536 ms  delta #3: " Invoice INV-2026"
 2592 ms  delta #4: "-0005 (overdue"
 2640 ms  delta #5: ")\n\nDear Von-"
 2687 ms  delta #6: "Blick team"
 3465 ms  delta #20: " and we have not yet received any"
 4377 ms  delta #40: "y to help.\n\nK"
 4498 ms  done: 42 deltas, stop end_turn, in 287, out 245, $0.006048

Two and a half seconds of thinking before the first word, then the whole email in two seconds more, in pieces that cut words in half because tokens do not respect them. Forty-two deltas, 245 output tokens, six tenths of a cent. The email:

Subject: Payment reminder: Invoice INV-2026-0005 (overdue)

Dear Von-Blick team,

I hope you are well. This is a friendly reminder that invoice INV-2026-0005, issued on October 6, 2026, for €6,120.00 was due on October 20, 2026. As of today it is 13 days overdue, and we have not yet received any payment toward it.

Could you please arrange payment at your earliest convenience? If that is not possible right away, we would be grateful if you could let us know the date by which payment will be made.

If you have already sent the payment, please disregard this message, and thank you.

If you have any questions about the invoice, just reply to this email and we will be happy to help.

Kind regards,
Acme Studio

Every number in it came from the prompt, not from the model's arithmetic. In the browser, driven by Playwright, the status went from "Thinking…" to "Writing…" with the first delta and ended on "Done, $0.006308." after a slightly longer email, which is what the two screenshots show.

Testing a stream

The fake from part 1 learns to answer a streaming request. The SDK decides a request is streaming by its Accept: text/event-stream header and sends it through the same transport, so the fake only needs a response whose body is a server-sent event stream in the API's order:

public static function stream(string $text, int $inputTokens = 10, int $outputTokens = 5, string $model = 'claude-opus-5-5', ?int $errorAfter = null): array
{
    $message = ['id' => 'msg_test_stream', 'type' => 'message', 'role' => 'assistant', 'model' => $model, 'content' => [],
        'stop_reason' => null, 'stop_sequence' => null, 'usage' => ['input_tokens' => $inputTokens, 'output_tokens' => 1]];
    $events = [
        ['message_start', ['type' => 'message_start', 'message' => $message]],
        ['content_block_start', ['type' => 'content_block_start', 'index' => 0, 'content_block' => ['type' => 'text', 'text' => '']]],
    ];
    foreach (preg_split('/(?<=\s)/', $text) as $i => $piece) {
        if ($errorAfter !== null && $i >= $errorAfter) {
            $events[] = ['error', ['type' => 'error', 'error' => ['type' => 'overloaded_error', 'message' => 'Overloaded']]];
            break;
        }
        $events[] = ['content_block_delta', ['type' => 'content_block_delta', 'index' => 0, 'delta' => ['type' => 'text_delta', 'text' => $piece]]];
    }
    if ($errorAfter === null) {
        $events[] = ['content_block_stop', ['type' => 'content_block_stop', 'index' => 0]];
        $events[] = ['message_delta', ['type' => 'message_delta', 'delta' => ['stop_reason' => 'end_turn', 'stop_sequence' => null], 'usage' => ['output_tokens' => $outputTokens]]];
        $events[] = ['message_stop', ['type' => 'message_stop']];
    }

    $body = '';
    foreach ($events as [$name, $data]) {
        $body .= "event: {$name}\ndata: ".json_encode($data)."\n\n";
    }

    return ['__sse' => $body];
}

The text is split after each whitespace so a piece can end in a newline, which is the case the SSE format has to handle. $errorAfter injects the API's error event after a number of pieces, because the API can fail in the middle of a stream and the SDK turns that event into the same typed exception as a failed request.

The tests, in tests/Feature/AI/InvoiceReminderTest.php, read the response with Laravel's streamedContent() and decode it the way the browser would:

/** Decode an event-stream body the way EventSource does and return the text of the delta events. */
function deltaText(string $body): string
{
    $text = '';
    foreach (explode("\n\n", trim($body)) as $event) {
        $lines = explode("\n", $event);
        if (array_shift($lines) !== 'event: delta') {
            continue;
        }
        $text .= implode("\n", array_map(fn (string $line) => substr($line, strlen('data: ')), $lines));
    }

    return $text;
}

it('streams the reminder as server-sent events and finishes with the cost', function () use ($email) {
    FakeClaude::bind(FakeClaude::stream($email, inputTokens: 300, outputTokens: 60));

    $response = $this->actingAs($this->user)->get(route('invoices.reminder', $this->invoice));

    $response->assertOk()->assertHeader('Content-Type', 'text/event-stream; charset=utf-8');
    $body = $response->streamedContent();

    expect($body)->toContain("event: delta\ndata: Subject: ")
        ->toContain("event: delta\ndata: client, ")
        ->toContain('event: done')
        ->toContain('"stopReason":"end_turn"')
        ->toContain('"cost":"$0.002400"'); // 300 × $4 + 60 × $20, per million

    // Joined back together, the deltas are the whole email, newlines included: a newline inside
    // a piece of text travels as a second data: line, which is what the SSE format requires.
    expect(deltaText($body))->toBe($email);
});

The request test freezes the clock with travelTo() and asserts the prompt said "10 days overdue" and "Today is Nov 3, 2026", that the request asked for a stream (stream: true in the body, text/event-stream in the Accept header), and that the user message was the one fixed sentence. Two failure tests cover the API dying mid-stream and before the stream, both of which must reach the page as an error event and never as a done. The policy tests cover a draft, another company's invoice, and the box not appearing where a reminder makes no sense.

php artisan test --testsuite=Unit,Feature --compact
  Tests:    148 passed (381 assertions)
  Duration: 19.61s

What went wrong

Header [Content-Type] ... value [text/event-stream; charset=utf-8] does not match [text/event-stream]. Symfony appends the charset to text types. Assert the value it actually sends.

A delta with a newline arrived as two events in the test. The fake splits after whitespace, so "overdue\n\nDear" is three pieces: overdue\n, \n and Dear. My first assertion expected one data: block for it. The fix was the better test: decode the whole stream with deltaText() and compare it to the email, which is what the browser does and what the feature promises.

Every path had to close the EventSource. The first version closed it on done only; a stream ended by an error reconnected after three seconds and wrote a second reminder. finish() exists so there is one place that closes it.

The demo data had totals of zero. The seeded invoices from the testing series had no lines, so the first real reminder politely asked for €0.00. Nothing wrong with the code; a reminder for a real-looking invoice needed a real-looking invoice.

Part 4 gives the app an assistant: a question about the account, answered by Claude with tools that read the company's own invoices and clients, the tool runner that drives the loop, and the authorization boundary that keeps one company's data out of another company's answers.

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.