Skip to content
Back to skills

Anthropic Laravel

ASecurity

Use when writing Laravel code that calls the Anthropic Claude API through `mozex/anthropic-laravel` or the underlying `mozex/anthropic-php` SDK, including structured output (JSON answers as a class, an `Illuminate\JsonSchema` type or validation rules, through `structured()`), the Claude-only work laravel/ai doesn't cover (Message Batches, token counting, the Files and Skills APIs, rate-limit headers, refusal fallback, Managed Agents, the Admin and usage reports) and named connections or per-t...

  • 75 stars
  • 0 votes
  • 1 copy
  • 4 views
  • Added September 5, 2026
ai-agentsgophpshellbashreactvuetestingapi

Works with

  • claude code
  • terminal
  • cli
  • api
  • mcp

Security analysis

A100/100

Scanned December 1, 2026

npx -y skills add mozex/anthropic-laravel --skill anthropic-laravel --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Anthropic Laravel?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Anthropic Laravel
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/mozex-anthropic-laravel/badge)](https://www.skillsdirectory.com/skills/mozex-anthropic-laravel)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: anthropic-laravel
description: Use when writing Laravel code that calls the Anthropic Claude API through `mozex/anthropic-laravel` or the underlying `mozex/anthropic-php` SDK, including structured output (JSON answers as a class, an `Illuminate\JsonSchema` type or validation rules, through `structured()`), the Claude-only work laravel/ai doesn't cover (Message Batches, token counting, the Files and Skills APIs, rate-limit headers, refusal fallback, Managed Agents, the Admin and usage reports) and named connections or per-tenant keys. Trigger on any mention of the `Anthropic` facade, `anthropic-laravel`, `Anthropic::messages()`, `Anthropic::batches()`, `Anthropic::models()`, `Anthropic::files()`, `Anthropic::request()`, `Anthropic::fake()`, `CreateResponse`, `FileResponse`, `ErrorException`, or any Claude/Anthropic API work in a Laravel project (controllers, queued jobs, Livewire components). Also trigger on requests to wire Claude into a Laravel app for chat, streaming responses, function calling (tool use), computer and browser toolsets, extended thinking, web search, code execution, the MCP connector, document citations, bulk processing with batches, uploading and referencing files by `file_id`, calling an API endpoint the package doesn't wrap yet, token counting before sending, or testing code that calls the API.
---

# Anthropic Laravel

A Laravel wrapper around the `mozex/anthropic-php` SDK. It adds a Facade, a publishable config, an install command, and a testing fake that replaces the client on the Facade and in the container. Every real call is handed off to the PHP client, so the response DTOs, content block shapes, and streaming events below come straight from the underlying SDK.

## Quick reference

This skill covers the Laravel integration plus the common paths through the SDK. For depth on any specific topic, fetch on demand rather than guessing.

**Preferred: Context7** (when MCP or CLI is configured)

- Laravel wrapper docs: library ID `/mozex/anthropic-laravel`
- Underlying PHP SDK docs: library ID `/mozex/anthropic-php`

**Fallback: direct URL fetch** (when Context7 isn't installed)

The docs site serves AI-friendly markdown for every page. Start at the introduction URL; it returns a markdown table of contents listing every page with its full URL, so one fetch tells you what's available without needing to know the page paths upfront.

- Laravel introduction (with TOC): https://mozex.dev/docs/anthropic-laravel/v1
- PHP SDK introduction (with TOC): https://mozex.dev/docs/anthropic-php/v1
- Anthropic API reference: https://platform.claude.com/docs/en/api

Good things to fetch rather than guess: the full list of content block types, every capability flag on a model, all server tool result block variants, the complete HTTP error status table, every response fake class, the exact shape of obscure streaming delta types. Those are stable reference material where a wrong guess will produce subtle bugs.

## Setup

```bash
composer require mozex/anthropic-laravel
php artisan anthropic:install
```

The install command publishes `config/anthropic.php` and adds `ANTHROPIC_API_KEY=` to `.env` and `.env.example`, with the optional variables commented out. The keys:

```php
return [
    'api_key' => env('ANTHROPIC_API_KEY'),
    'auth_token' => env('ANTHROPIC_AUTH_TOKEN'),
    'workspace_id' => env('ANTHROPIC_WORKSPACE_ID'),
    'request_timeout' => env('ANTHROPIC_REQUEST_TIMEOUT', 30),
    'connect_timeout' => env('ANTHROPIC_CONNECT_TIMEOUT'),
    'max_retries' => env('ANTHROPIC_MAX_RETRIES', 0),
    'middleware' => [], // client middleware class names, e.g. Anthropic\Middleware\OpenTelemetryMiddleware
    'fallback_models' => array_values(array_filter(array_map(
        'trim',
        explode(',', (string) env('ANTHROPIC_FALLBACK_MODELS', ''))
    ))),
    'http' => [
        'middleware' => [],
        'laravel_client' => (bool) env('ANTHROPIC_HTTP_LARAVEL_CLIENT', false),
        'laravel_events' => (bool) env('ANTHROPIC_HTTP_LARAVEL_EVENTS', false),
        'telescope' => (bool) env('ANTHROPIC_HTTP_TELESCOPE', false),
        'nightwatch' => (bool) env('ANTHROPIC_HTTP_NIGHTWATCH', true),
    ],
    'context' => (bool) env('ANTHROPIC_CONTEXT', false),
    'headers' => [],
    'connections' => [], // 'support' => ['api_key' => env('ANTHROPIC_SUPPORT_API_KEY')], inheriting the rest
    'beta' => array_values(array_filter(array_map(
        'trim',
        explode(',', (string) env('ANTHROPIC_BETA', ''))
    ))),
    'api_version' => env('ANTHROPIC_API_VERSION'),
    'base_url' => env('ANTHROPIC_BASE_URL'),
];
```

`api_version` sets the `anthropic-version` header (default `2023-06-01`; `2026-10-21` rejects `temperature`, `top_p` and `top_k` on every model). Prism reads `ANTHROPIC_API_VERSION` too, so setting it switches both. `base_url` takes a proxy or gateway URL the way the official SDKs do, without `/v1`, which the package adds unless the URL ends in it. A shell-exported `ANTHROPIC_BASE_URL` (Claude Code and the SDKs read it too) wins over `.env` for artisan and queue workers, and that host gets the API key. `auth_token` sends `Authorization: Bearer` (a Workload Identity Federation access token) when no key is set, one credential as in the official SDKs (a shell-exported `ANTHROPIC_AUTH_TOKEN`, which Claude Code reads too, reaches an app without a key); `workspace_id` sends `anthropic-workspace-id`, needed by keys not scoped to one workspace; `connect_timeout` is the Guzzle connect timeout, which streamed requests ignore; `max_retries` (default 0; the official SDKs use 2) retries connection failures, timeouts, 408/409/429 and 5xx, waiting what the API asks (one call can then take `max_retries + 1` request timeouts plus those waits, so size a job's `$timeout` and the queue's `retry_after` for it; a job that releases itself on a 429 turns them off with `withOptions(['max_retries' => 0])`); `fallback_models` (`ANTHROPIC_FALLBACK_MODELS=claude-opus-4-8`) retries a refused non-streamed Messages request on those models in order, redeeming the refusal's fallback credit (`Anthropic\Middleware\RefusalFallbackMiddleware`, model names only; one list for every model the app calls, so each name must be a permitted fallback of the refused model: Opus 4.8 or Opus 5 after Fable 5 or Opus 5.5, Sonnet 5 after Sonnet 5.5; no shared `FallbackState`, so each request starts from the requested model: to keep a conversation on the model that accepted, store `$response->model` and request it next turn; a request with `fallbacks` throws while it's set); `http.laravel_client` sends through Laravel's HTTP client stack so `Http::fake()`, `Http::assertSent()` and `Http::preventStrayRequests()` apply whenever they're set (off by default, since an app's catch-all `Http::fake()` would catch them); `http.laravel_events` also dispatches Laravel's `RequestSending` then `ResponseReceived` or `ConnectionFailed`, in pairs and without credential headers, which Telescope and Sentry record; every attempt (retries and fallback hops included) dispatches `Anthropic\Laravel\Events\RequestSending`, `ResponseReceived` (status, decoded JSON body, usage, meta, durationMs), `RequestFailed` (status null and `connection_error`/`client_timeout_error` without an answer) and `RateLimited` (`errorCode` `enforced_spend_limit_reached` for the spend cap), serializable and without credential headers, seen by `Event::fake()`, never under `Anthropic::fake()`; `http.telescope` records each attempt as a Telescope client request tagged `anthropic`, `model:<model>` and `req:<request id>`, credentials removed (turn on this or `laravel_events`, not both, or each call is recorded twice); `http.nightwatch` (on by default) attaches Nightwatch's Guzzle middleware when Nightwatch is installed and `laravel_client` is off; `context` adds each answer's request ID (`anthropic_request_ids`) and a Messages answer's `anthropic_input_tokens` and `anthropic_output_tokens` (a stream's once it ends) to Laravel's Context, so later log lines and dispatched jobs carry them; no event or recording carries a credential, including an MCP server's `authorization_token`; `http.middleware` takes Guzzle middleware class names, resolved from the container, and reaches only the package's own Guzzle client; `headers` (no env variable) go on every request, applied last. A config file published by an older release lacks the newer keys; re-running `anthropic:install` names what's missing.

`Anthropic::withOptions(['workspace_id' => ..., 'betas' => [...], 'headers' => [...], 'query' => [...], 'api_version' => ..., 'user_profile_id' => ..., 'max_retries' => ...])` returns a client for one tenant or feature, leaving the app-wide one unchanged; it's also how ID-only methods (`models()->retrieve()`) get betas. Under `Anthropic::fake()` it shares the fake's queue; assert with `Anthropic::assertSentWithOptions(Messages::class, ['workspace_id' => ...])`.

`ANTHROPIC_BETA` takes a comma-separated list of beta names (`ANTHROPIC_BETA=compact-2026-01-12`). They go out in the `anthropic-beta` header on every request, merged with any `betas` array you pass on a single call.

If the config has neither `api_key` nor `auth_token` (and laravel/ai has no Anthropic key either) when the client resolves, the deferred service provider throws `Anthropic\Laravel\Exceptions\ApiKeyIsMissing`. The binding is a singleton, so `Anthropic::messages()`, `app('anthropic')`, and `app(\Anthropic\Contracts\ClientContract::class)` all resolve the same instance.

Raise `ANTHROPIC_REQUEST_TIMEOUT` to 60+ seconds for extended thinking on high/max effort, code execution with slow scripts, or very large contexts. Streaming only applies the timeout to the initial connection; chunks flow freely after that.

## The Facade

`Anthropic\Laravel\Facades\Anthropic` is the only entry point for application code:

```php
use Anthropic\Laravel\Facades\Anthropic;

Anthropic::messages();     // Messages resource
Anthropic::batches();      // Message Batches
Anthropic::models();       // Models
Anthropic::files();        // Files (upload, list, download, delete)
Anthropic::completions();  // Deprecated Text Completions: the API rejects it on current models
```

Don't instantiate `Anthropic\Client` directly in Laravel code; the container binding already does that. If you need a custom HTTP client or headers, see the factory section at the end.

## Five things that surprise people

These are the pitfalls that actually cause bugs. Internalize them before writing code against the SDK.

### 1. Property casing is inconsistent by design

DTO casing matches the wire format from the API, so different response shapes use different conventions. Don't normalize.

| DTO | Casing | Example |
|-----|--------|---------|
| `CreateResponse` top level | snake_case | `$r->stop_reason`, `$r->stop_sequence` |
| `CreateResponseUsage` (nested) | camelCase | `$r->usage->inputTokens`, `$r->usage->cacheCreationInputTokens`, `$r->usage->inferenceGeo`, `$r->usage->serviceTier` |
| Content blocks | snake_case | `$block->type`, `$block->tool_use_id`, `$block->partial_json` |
| Stream event DTOs | snake_case | `$event->content_block_start`, `$event->delta` |
| `CountTokensResponse` | camelCase | `$r->inputTokens` |
| Batch / Models / Files responses | camelCase | `$r->processingStatus`, `$r->requestCounts`, `$r->displayName`, `$r->maxInputTokens`, `$r->mimeType`, `$r->sizeBytes` |

When in doubt, `dump($response)` or consult `/mozex/anthropic-php` via Context7 or the docs site. Guessing usually produces `PropertyNotFound` errors at runtime.

### 2. Tool dispatchers key on `toolset_name` and `name`

With the computer or browser toolset (`['type' => 'computer_toolset_20260801']`, `['type' => 'browser_toolset_20260801']`), their member tools (`screenshot`, `left_click`, `navigate` ...) arrive as ordinary `tool_use` blocks with `toolset_name` set to `'computer'` or `'browser'`; a custom tool's call has `toolset_name` `null`. A custom tool may share a member's name, so dispatch on the pair, never on `name` alone, and echo `toolset_name` on every member's result (only on those; the API rejects a member result without it):

```php
foreach ($response->content as $block) {
    if ($block->type !== 'tool_use') {
        continue;
    }

    if ($block->toolset_name !== null) {
        $results[] = [
            'type' => 'tool_result',
            'tool_use_id' => $block->id,
            'toolset_name' => $block->toolset_name,
            'content' => app($toolsets[$block->toolset_name])->run($block->name, $block->input),
        ];

        continue;
    }

    $results[] = [
        'type' => 'tool_result',
        'tool_use_id' => $block->id,
        'content' => json_encode(app($toolRegistry[$block->name])->handle($block->input)),
    ];
}
```

Don't skip a `tool_use` whose `$block->caller->type` is `'code_execution_20260120'`. That's programmatic tool calling: code Claude runs in the sandbox called your tool and is paused waiting for the result (it times out after about four minutes). Run it like a direct call. The answering `user` message must hold only `tool_result` blocks (string or `text` content, no text after them), and the request must pass the paused response's `container` id and the same `tools`.

### 3. `pause_turn` is not an error

Long-running turns can return `stop_reason: 'pause_turn'` instead of `'end_turn'`. The response is valid and complete for the work done so far. To resume, echo the content back as the next assistant message. No special parameter needed.

```php
do {
    $response = Anthropic::messages()->create([
        'model' => 'claude-sonnet-5-5',
        'max_tokens' => 8192,
        'messages' => $messages,
    ]);

    $messages[] = [
        'role' => 'assistant',
        'content' => array_map(fn ($block) => $block->toArray(), $response->content),
    ];
} while ($response->stop_reason === 'pause_turn');
```

This pattern fits naturally inside a queued job where each iteration can take a while.

### 4. Refusals return HTTP 200

When safety classifiers intervene, `stop_reason` is `'refusal'` and `stop_details` is populated. The HTTP response is still 200, and no exception is thrown. Branch on `stop_reason` explicitly:

```php
if ($response->stop_reason === 'refusal') {
    Log::warning('Claude refused', [
        'user_id' => auth()->id(),
        'category' => $response->stop_details->category,    // 'cyber', 'bio', 'frontier_llm', 'reasoning_extraction', 'general_harms', or null
        'explanation' => $response->stop_details->explanation,
    ]);
    return back()->with('error', 'Your request could not be processed.');
}
```

`stop_details` is `null` on normal completions, so guard before reading it. Treat `category` as the machine-readable signal; `explanation` text isn't stable between calls, so don't parse it. Re-sending the same conversation usually gets another refusal: drop or rephrase the turn that caused it first.

When streaming, the refusal arrives on the `message_delta` event, possibly after text has already streamed: check `$event->delta->stop_reason === 'refusal'`, read `$event->delta->stop_details?->category`, and discard the partial text (clear it in the UI too).

On Claude Fable 5 and Opus 5 you can pass `'fallbacks' => 'default'` with the `server-side-fallback-2026-07-01` beta so the API retries a refused request on another model. Check `usage->iterations` for a `fallback_message` entry to see which model actually served the turn; see the docs Messages page for the full flow. `ANTHROPIC_FALLBACK_MODELS` does it client-side instead, streams included: a refused stream goes on with the fallback's events behind a `fallback` block (usually carrying on from the refused partial), under one `message_start`.

### 5. Mid-stream errors arrive after HTTP 200

Streamed responses started successfully before the error happened, so the status code is 200, but the client still throws `ErrorException` when the failing event arrives. Always wrap the iteration:

```php
try {
    foreach ($stream as $event) { /* ... */ }
} catch (\Anthropic\Exceptions\ErrorException $e) {
    // log, retry, or surface to the user
}
```

## Messages API

`Anthropic::messages()->create(...)` is the main call. At minimum: `model`, `max_tokens`, and a non-empty `messages` array. Everything is pass-through: the array ships to the API as JSON with no validation, no coercion, no casing rewrites. New API parameters work the day Anthropic ships them.

```php
$response = Anthropic::messages()->create([
    'model' => 'claude-sonnet-5-5',
    'max_tokens' => 1024,
    'messages' => [
        ['role' => 'user', 'content' => 'Hello, world'],
    ],
]);

$response->id;
$response->stop_reason;
collect($response->content)->firstWhere('type', 'text')?->text;
$response->usage->inputTokens;
```

Messages alternate `user` and `assistant`, starting with `user`. `system` is normally a *separate top-level string*. Newer models (Claude 5 except Sonnet 5, and Opus 4.8) also accept a `['role' => 'system', 'content' => '...']` message partway through `messages`, never first and never between a `tool_use` and its `tool_result`.

Every Claude 5 model thinks by default, so a reply can start with a `thinking` block: read the answer with `collect($response->content)->firstWhere('type', 'text')?->text` rather than `content[0]`.

Sampling parameters: Claude 5 models, Opus 4.8 and Opus 4.7 return a 400 for any non-default `temperature`, `top_p` or `top_k`.

### Multi-turn

The API is stateless, so send the full history every request. Typical Laravel pattern pulling from Eloquent:

```php
$messages = $conversation->messages()
    ->latest('id')->take(20)->get()->reverse()
    ->map(fn ($m) => ['role' => $m->is_assistant ? 'assistant' : 'user', 'content' => $m->content])
    ->toArray();
```

### Vision

Pass `content` as an array of content blocks. Supported media types: `image/jpeg`, `image/png`, `image/gif`, `image/webp`. Common pattern with `Storage`:

```php
use Illuminate\Support\Facades\Storage;

['type' => 'image', 'source' => [
    'type' => 'base64',
    'media_type' => Storage::disk('s3')->mimeType('uploads/photo.jpg'),
    'data' => base64_encode(Storage::disk('s3')->get('uploads/photo.jpg')),
]]
```

Or by URL: `['type' => 'image', 'source' => ['type' => 'url', 'url' => '...']]`. Multiple images in one message work; add more blocks.

### User tracking

Pass an opaque identifier (UUID, hash) via `metadata.user_id`. It surfaces in the Anthropic Console for analytics and abuse detection. Never names or emails.

```php
'metadata' => ['user_id' => auth()->user()->uuid],
```

### Long requests belong in queues

Put `new \Anthropic\Laravel\Queue\ThrottlesAnthropic('claude-sonnet-5-5')` in a Claude job's `middleware()`: it fails the job on the monthly spend cap (a 429 with `enforced_spend_limit_reached`, dispatching `SpendCapReached`) and on 400/401/402/403/404/413/422, and releases it on other 429s, 529, 408, 409, 5xx and connection errors for `retry-after` (else the rate-limit reset, else a doubling backoff), holding back every job of the same key meanwhile. One key per rate-limit class; `->budget(20000)` waits for the reset while the last answer left fewer tokens; `->concurrency(5)` caps parallel calls (`Cache::funnel`). Turn the client's retries off in the job (`Anthropic::withOptions(['max_retries' => 0])`), bound it by `retryUntil()` (each release is an attempt) and set `$maxExceptions` (with `retryUntil()`, `--tries` no longer stops a job that throws). On the sync queue or run directly, the error goes to the caller.

Anything with extended thinking, code execution, or large context pushes past typical HTTP timeouts. Dispatch to a queue and raise both `ANTHROPIC_REQUEST_TIMEOUT` and the job's `$timeout`, then make sure the queue connection's `retry_after` in `config/queue.php` is larger than the job's `$timeout`. With a smaller `retry_after`, the worker releases the job to another process while the first is still waiting on Claude: the job runs twice and the call is paid twice. With `ANTHROPIC_MAX_RETRIES` on, count every attempt: up to `max_retries + 1` request timeouts plus the waits between them. Each fallback model gets a whole timeout too. `php artisan anthropic:doctor` checks the default queue connection's `retry_after` against `request_timeout × (max_retries + 1) × (1 + fallback models)` plus the backoff, exits non-zero when it's too short, and warns about a Horizon supervisor `timeout` below it (a job's `$timeout` wins over it). A streamed call's `request_timeout` is only the longest gap between chunks, so size a streaming job's `$timeout` and `retry_after` for the whole answer.

### Compaction

On-demand compaction (beta `compact-2026-09-04`, `'compaction' => ['type' => 'summarize']`) returns one signed `compaction` block with `stop_reason: 'compaction'`; any other stop reason means no summary, so keep the history. On every later request, with the same beta header, send the block exactly as `toArray()` returns it (`signature` included, no extra keys), first in `messages`, and drop the turns it summarized. Threshold compaction (`compact-2026-01-12`, `'context_management' => ['edits' => [['type' => 'compact_20260112']]]`) also expects its `compaction` block back unchanged.

### More request options

- **Mid-conversation tool changes** (beta `mid-conversation-tool-changes-2026-07-01`, or `inline-tools-2026-09-15` on the Claude API for inline definitions): a `role: system` message whose content is `tool_addition` or `tool_removal` blocks (`['type' => 'tool_removal', 'tool' => ['type' => 'tool_reference', 'name' => 'get_weather']]`) adds or removes tools without editing `tools`, which would break the prompt cache.
- **Cache diagnostics** (GA, no header): send `'diagnostics' => ['previous_message_id' => null]` on the first turn and the previous response's `id` after that; `$response->diagnostics?->cache_miss_reason?->type` says why the cache missed (`system_changed`, `tools_changed` ...).
- **Fast mode**: `'speed' => 'fast'` on Opus 5.5 (GA, no header); `$response->usage->speed` reports what served it, `$meta->fastInputTokenLimit` its own rate limit. Not available with batches.
- **Dropped thinking on replay** (beta `thinking-binding-controls-2026-08-01`): `'thinking' => ['type' => 'adaptive', 'block_binding' => ['prefix_mismatch_behavior' => 'drop_block']]` drops replayed thinking blocks that no longer match (another model, an edited history) instead of failing; `$response->input_transformations` lists them (`thinking_dropped` with a `path` and `reason`).

## Streaming

`createStreamed()` takes the same shape as `create()` and returns an iterable `StreamResponse`. The client skips `ping` and ends the loop at `message_stop`. Your loop sees these five event types, plus any type the API adds later, so always branch on `$event->type`:

- `message_start`: full envelope plus initial usage
- `content_block_start`: `$event->index`, `$event->content_block_start->type`
- `content_block_delta`: `$event->delta->type` is `text_delta`, `input_json_delta`, `thinking_delta`, `signature_delta`, or `citations_delta`
- `content_block_stop`: `$event->index`
- `message_delta`: final `stop_reason` and usage; `$event->delta->stop_details` on a refusal, `$event->delta->container` after code execution

```php
foreach ($stream->text() as $delta) {   // text deltas only
    echo $delta;
}

$message = $stream->finalMessage();     // reads the rest; a CreateResponse as create() returns it
```

`finalText()` joins the text blocks; `currentMessage()` is the message so far (`stop_reason` null mid-stream). Callbacks run as events are read, before the loop gets them: `onText(fn (string $delta) => ...)`, `onThinking()`, `onContentBlock(fn (CreateResponseContent $block) => ...)` (a tool call with `input` decoded), `onMessage(fn (CreateResponse $message) => ...)`, `onEvent()`. `Anthropic\Responses\Messages\MessageAccumulator` folds decoded events read another way (`->add($event)`, `->message()`).

Some blocks arrive whole in `content_block_start` with no deltas: an on-demand `compaction` block (its `content` is a string there, with `signature`), `fallback` and `advisor_tool_result`.

### To the browser

Return the stream from a route: `->toEventStream()` for `useEventStream` (`@laravel/stream-react|vue|svelte`; pass `glue: ''`, or deltas are joined with spaces), `->toTextStream()` for `useStream`, `->toVercelStream()` for the AI SDK's `useChat` (header `x-vercel-ai-ui-message-stream: v1`, ends in `data: [DONE]`; server tools aren't sent). Every stream `Anthropic::messages()->createStreamed()` (or a connection's) returns has them, under `Anthropic::fake()` too; an injected `ClientContract`'s stream doesn't, so inject `AnthropicManager` or call `->as(\Anthropic\Laravel\Responses\StreamResponse::class)` before reading. `useStream` and `useChat` POST, so those two go on a `Route::post`.

```php
Route::get('/conversations/{conversation}/reply', fn (Conversation $conversation) => Anthropic::messages()
    ->createStreamed([...])
    ->onMessage(fn (CreateResponse $message) => $conversation->messages()->create(['role' => 'assistant', 'content' => $message->toArray()['content']]))
    ->toEventStream());
```

`EventSource` is GET only: POST the user's message, then stream the reply from a GET route. `toEventStream()` sends each line of a delta on its own `data:` line, and on a failure reports it and sends an `error` event (the API's type and message only), then always the `</stream>` marker, so the browser doesn't reconnect and bill the call again. A stream cut off upstream is reported and sent as an error too. The event streams send `: keep-alive` after 15 quiet seconds while events arrive that the browser isn't sent; with `thinking.display: 'omitted'` nothing arrives while Claude thinks, so the proxy's read timeout must outlast the think. They also send `X-Accel-Buffering: no`. All three stop on `connection_aborted()`, which works under PHP-FPM: under Octane, Swoole runs the reply to the end (billed in full) and RoadRunner buffers a `StreamedResponse` whole. No refusal signal reaches the browser: check `stop_reason` in `onMessage()`. A GET reply route bills on every open, a reload included: stream only when the last stored message is the user's. Never hand-roll a `StreamedResponse` with `ob_flush()`.

### Broadcasting, Livewire and cancel

From a queued job, `$message = $stream->broadcastTo(new PrivateChannel("chat.{$id}"))` sends anonymous broadcasts with `sendNow()`: `claude.delta` (`text`, `sequence`) every 50 ms (`everyMs:`, checked as events arrive) and before anything but text (a tool call, a block start), each payload under 6,000 bytes as Reverb receives it (`maxBytes:`, at least 256) and cut between characters; `claude.fallback` (`from`, `to`) when a fallback takes over a refused stream; `claude.done` (`id`, `stop_reason`); or `claude.error` (`type`, `message`) on a failure or a cut-off stream, then the exception is thrown on (a retried job starts again at `sequence` 0). A failing broadcaster is reported and its later deltas skipped, the stream still read, the closing event still tried. It returns the final message to save and never broadcasts tool calls or the whole message. Echo listens with a leading dot: `useEcho(channel, ['.claude.delta', '.claude.done', ...], ...)`. In a Livewire component, `use Anthropic\Laravel\Livewire\InteractsWithClaudeStreams;` then `$this->answer = $this->streamClaude($stream, to: 'answer')` (the first update replaces the element; `replace: true` sends the text so far each time); it calls `stream()` with named arguments, so Livewire 3 and 4 both work; not under Octane. `broadcastTo()` reads to the end: to cancel mid-generation, loop over `$stream->text()` yourself, check a `Cache::pull("stop-stream-{$id}")` flag and `break`.

`$stream->meta()` returns the same `MetaInformation` object as on a regular response; headers arrive at the start of the stream.

## Tool use

Define tools with JSON Schema `input_schema`. Write clear descriptions: Claude uses them to pick the right tool and the right arguments. Add `'strict' => true` to guarantee schema-conformant output.

```php
'tools' => [[
    'name' => 'get_weather',
    'description' => 'Get the current weather in a given location',
    'input_schema' => [
        'type' => 'object',
        'properties' => [
            'location' => ['type' => 'string', 'description' => 'City and state, e.g. San Francisco, CA'],
        ],
        'required' => ['location'],
    ],
]]
```

Reading the call:

```php
$block = $response->content[1];
$block->type;   // 'tool_use'
$block->id;     // 'toolu_...'
$block->name;
$block->input;  // array
$response->stop_reason; // 'tool_use'
```

Send results back as a new `user` turn containing `tool_result` blocks. `tool_use_id` must match the `id` from the call. Set `'is_error' => true` on failures.

`tool_choice` variants: `['type' => 'auto']` (default), `['type' => 'any']`, `['type' => 'tool', 'name' => '...']`, `['type' => 'none']`. Opus 5.5, Sonnet 5.5, Fable 5.1 and Mythos 5.1 return a 400 for `any` and `tool`, and so does budget-based thinking; use `auto` with `'strict' => true` there.

A tool call with no parameters has `input` as an `ArrayObject` in `toArray()`, which encodes as `{}`; the API rejects a replayed `"input": []`. So send `$response->toArray()['content']` back as is.

See pitfall #2 above for dispatching on `toolset_name` and answering programmatic calls.

Tool classes (`php artisan make:anthropic-tool GetWeather` writes one in `app/Tools`) are invokable: `__invoke()`'s parameters become the input schema (the same types and `#[Description]`/`#[Constraints]`/`#[ListOf]` attributes as structured output classes), and the class's `#[Description]` the description. `Anthropic::tool(GetWeather::class)` resolves it from the container and returns an `Anthropic\Tools\Tool`:

```php
$weather = Anthropic::tool(GetWeather::class);   // or Anthropic::tool(fn (string $location) => ..., name: 'get_weather')
'tools' => [$weather->toArray()],                  // name: get_weather; options: ['strict' => true] sanitizes the schema

foreach ($response->content as $block) {
    if ($weather->handles($block)) {               // name match, never a toolset member
        $results[] = $weather->result($block);     // tool_result with the matching tool_use_id
    }
}
```

`result()` checks the input against the schema first (a failure is an `is_error` result listing the errors) and turns a thrown `Anthropic\Exceptions\ToolError` into `is_error: true` with its content. Any other exception propagates, so a secret in its message never reaches Claude.

## Structured output

`structured()` asks for JSON matching a schema, checks the reply and returns it: the class built, or the checked array.

```php
$contact = Anthropic::messages()->structured([
    'model' => 'claude-sonnet-5-5',
    'max_tokens' => 1024,
    'messages' => [['role' => 'user', 'content' => $prompt]],
], Contact::class);
```

The schema can be a class (built from its constructor: nullable or defaulted parameters are optional, a backed enum is an `enum`, an `array` needs `#[ListOf(...)]` or a `@param list<...>`), an `Illuminate\JsonSchema` type, a laravel/ai-style array of property types, a validation-rules array (also checked by Laravel's validator, so `exists` and other rules no schema can say still apply; returns `validated()`), or a raw JSON schema array (sent as it is). A reply that fails the check is retried once with what's wrong (a second billed call; `retries: 0` turns it off). A failed reply that also calls a tool isn't retried. A refusal, a `max_tokens` cut-off, no JSON or a second failure throws `Anthropic\Exceptions\StructuredOutputException` (`reason`, `errors`).

For a request built by hand: `'output_config' => ['format' => Anthropic\Laravel\Schema\Schema::format(Contact::class)]`, then `$response->parse(Contact::class)`. Never pass a class name as `output_config.format` itself: parameters go to the API as they are.

## Extended thinking

Two modes:

- **Adaptive**: `'thinking' => ['type' => 'adaptive']`, the default on every Claude 5 model and opt-in on Opus 4.8, 4.7, 4.6 and Sonnet 4.6. Use `'output_config' => ['effort' => 'low'|'medium'|'high'|'xhigh'|'max']` to guide depth; `$model->capabilities?->effort` says which levels a model takes.
- **Budget-based**: `'thinking' => ['type' => 'enabled', 'budget_tokens' => 10000]`, for Opus 4.5, Sonnet 4.5 and Haiku 4.5. Deprecated on Opus 4.6 and Sonnet 4.6; Claude 4.7 and later return a 400.

Turning thinking off: Fable 5.1, Fable 5, Mythos and Opus 5.5 reject `'type' => 'disabled'`; Sonnet 5.5 takes `'type' => 'between_tools'` instead (effort `high` or below).

Response content may include `thinking` (with `signature`), `redacted_thinking` (opaque `data`), and `text` blocks. `display` defaults to `'omitted'` on Claude 5 models, Opus 4.8 and Opus 4.7: the `thinking` field is empty but `signature` is still present. Pass `'display' => 'summarized'` to get the reasoning text.

Preserve `signature` verbatim. The server uses it to verify thinking integrity on follow-up turns. When doing multi-turn with thinking, pass the full content array (including thinking blocks) back as the assistant message: `array_map(fn ($b) => $b->toArray(), $response->content)`.

Interleaved thinking with tools activates automatically when you combine `thinking` (adaptive) and `tools` in the same request.

## Server tools

These run on Anthropic infrastructure; add to `tools` and results come back in the response.

**Web search**: `['type' => 'web_search_20250305', 'name' => 'web_search']`. Options: `max_uses`, `allowed_domains`, `blocked_domains`, `user_location`. Version `web_search_20260209` adds dynamic filtering and requires code execution enabled alongside.

**Code execution**: `['type' => 'code_execution_20250825', 'name' => 'code_execution']`. Version `code_execution_20260120` adds REPL state persistence and programmatic tool calling.

**Container persistence**: the sandbox lives 30 days. Reuse it by passing top-level `'container' => $response->container['id']` on follow-ups. Store the ID on your Eloquent model.

**`container_upload` blocks**: when Claude writes a file inside the container, a block with `file_id` appears. Pair with the Files API to download and forward.

**Server tool errors still return HTTP 200**. The error is inside the result block's `content`: `$block->content['type']` ends in `_error`, `$block->content['error_code']` gives the reason.

Usage counts: `$response->usage->serverToolUse?->webSearchRequests` / `webFetchRequests` / `codeExecutionRequests` / `toolSearchRequests`.

**MCP connector** (beta, `mcp-client-2025-11-20`): `'mcp_servers' => [['type' => 'url', 'url' => 'https://...', 'name' => 'crm', 'authorization_token' => $token]]` plus `['type' => 'mcp_toolset', 'mcp_server_name' => 'crm']` in `tools`. Results come back as `mcp_tool_use` (`server_name`) and `mcp_tool_result` (`is_error`) blocks; your code doesn't run them. Under `mcp-client-2026-09-15` a response can start with an `mcp_tool_listing` block, so don't assume `content[0]` is text.

**Advisor tool** (beta, `advisor-tool-2026-03-01`): `['type' => 'advisor_20260301', 'name' => 'advisor', 'model' => 'claude-opus-5-5']`. Its `advisor_tool_result` blocks (usually encrypted) go back unchanged on later turns, with the beta header.

**Programmatic tool calling**: mark custom tools with `'allowed_callers' => ['code_execution_20260120']`; see pitfall #2 for answering those calls.

For the full list of result block types (`web_search_tool_result`, `bash_code_execution_tool_result`, `text_editor_code_execution_tool_result`, etc.) and the tool version history, fetch `/mozex/anthropic-php` via Context7 or the docs site.

## Citations

Enable per document content block with `'citations' => ['enabled' => true]`. The response splits into multiple text blocks; cited claims have a `citations` array, linking phrases don't.

Five citation types: `char_location`, `page_location`, `content_block_location`, `web_search_result_location`, `search_result_location`. All include `cited_text`. Document-based types include `document_index` (zero-indexed, matching the order you passed documents) and `document_title`.

Web search citations are automatic; you don't enable them explicitly. Streaming delivers citations as `citations_delta` events on the delta object.

For per-type field lists, fetch `/mozex/anthropic-php` via Context7 or the docs site.

## Token counting

Same shape as `create()`. Returns a single `inputTokens` field (camelCase). Include `tools` and `system` if they'll be in the real request, since both contribute to the count. Common use: trim conversation history before hitting context limits.

```php
$parameters = Anthropic::messages()->trimToFit($parameters, 150000); // drops the oldest turns until it fits
Anthropic::messages()->fits($parameters, 150000);                    // true or false
```

Both take `create()`'s parameters as they are (only what `count_tokens` takes is sent) and count input tokens only. `trimToFit()` cuts only before a user turn without a `tool_result`, keeps the system prompt and tools, and throws `Anthropic\Exceptions\InvalidArgumentException` (not SPL's) when even the last turn is over. A thinking conversation needs `thinking.block_binding.prefix_mismatch_behavior: 'drop_block'` (beta `thinking-binding-controls-2026-08-01`) or Claude 5.1 rejects the kept thinking. Validation: `['bail', ..., new \Anthropic\Laravel\Rules\FitsInTokens(4000, 'claude-sonnet-5-5')]` (`->withSystem()`, `->onConnection()`; too large to count fails, another API error throws). CLI: `php artisan anthropic:count-tokens "text" --model=... [--file=] [--system=]`.

## Models

```php
$response = Anthropic::models()->list();

foreach ($response->data as $model) {
    $model->id;              // 'claude-sonnet-5-5'
    $model->displayName;
    $model->maxInputTokens;  // context window
    $model->maxTokens;       // max output
    $model->capabilities?->imageInput->supported;    // capabilities can be null
    $model->capabilities?->thinking->types->adaptive->supported;
    $model->capabilities?->effort->max->supported;
}
```

Pagination: `limit` (default 20, max 1000), `after_id`, `before_id`. `iterate()` (on `models()`, `batches()` and `files()`) walks every page, a generator yielding one item at a time and requesting each page only when the loop reaches it; `LazyCollection::make(fn () => Anthropic::models()->iterate())` gives it collection methods. `['lifecycle' => ['retired']]` filters by stage (up to three of `active`, `deprecated`, `retired`; retired models appear only when asked for). Each list item is a full `RetrieveResponse`. `maxInputTokens`, `maxTokens`, `capabilities`, `firstId` and `lastId` can be `null`.

Lifecycle: `$model->lifecycle` (`'active'`, `'deprecated'`, `'retired'`), `$model->line` (`'sonnet'` ...), `$model->deprecatedAt`, `$model->retiresAt`. A scheduled check that logs a warning when a model the app uses is `deprecated` or `retired` catches retirements early (`lifecycle` is `null` on fakes and when the API doesn't send it).

Cache the list so you're not hitting the API per request:

```php
$models = Anthropic::models()->cached(); // every model, Cache::flexible for 1h fresh, up to a day stale; per connection and key; never under the fake
```

`php artisan anthropic:models` lists them; `php artisan anthropic:ping` checks the key with that call (no tokens); `php artisan anthropic:chat --model=...` chats in the terminal, streamed.

The full capability tree (batch, citations, codeExecution, imageInput, pdfInput, structuredOutputs, thinking types, effort levels, and the versioned contextManagement strategies map) is extensive. Fetch `/mozex/anthropic-php` via Context7 or the docs site for the exact shape.

## Usage ledger

Opt-in: `php artisan vendor:publish --tag=anthropic-migrations`, migrate, `ANTHROPIC_LEDGER=true`. Every billed Messages call, stream (once it ends or is dropped) and `Anthropic::batch()` result writes a row to `anthropic_requests` (`Anthropic\Laravel\Ledger\AnthropicRequest`: tokens by kind, model, connection, request ID, `billable` morph, `feature`; no prices). Bill calls with `Anthropic::for($user, feature: 'summaries')->messages()->create([...])` (hidden Context, so it follows dispatched jobs; never `auth()` in a listener). `php artisan anthropic:usage --by=model|feature|connection|billable|day --days=30`. UUID billables: switch the migration to `nullableUuidMorphs`. `usage.iterations` (compaction, advisor, fallback) is summed. Prune with `Schedule::command('model:prune', ['--model' => [AnthropicRequest::class]])` (plain `model:prune` only scans `app/Models`). `UsageRecorded` fires for each billed call with the ledger on or off; under `Anthropic::fake()` only a batch's poll job dispatches it. A queue that's down, or a `UsageRecorded` listener that throws, on a call or a stream is reported and never fails it.

## Token budgets

`Anthropic::budget('user:'.$id)->perDay(200_000)->enforce()` (`perMinute`/`perHour`/`perDay`; `->counting('rate')` leaves cache reads out) charges every Messages call and batch after it, in the request or job and the jobs it dispatches, and refuses the next one with `Anthropic\Laravel\Exceptions\BudgetExceeded` before it's sent once used up; token counts pass. Several can be enforced at once (a minute and a day budget, a user's and a team's): a call is charged to all and refused when any is used up, and the same key and window enforced again replaces the earlier one. In a loop over users, `->during(fn () => ...)` holds only the callback's calls, then puts back what was enforced before (read a stream inside it). `BudgetExceeded` is a `TooManyRequestsHttpException`: a 429 with `Retry-After`, not reported, its message without the key (`$e->key` has it). Route: `->middleware('anthropic.budget:user,200000,day')` (tokens without `_`; `minute`, `hour` or `day`; `billed` or `rate`) answers 429 at the door or partway. Job: `new \Anthropic\Laravel\Queue\TokenBudget(Anthropic::budget('team:'.$id)->perDay(1_000_000))` releases the job (six hours at most per release, for SQS) before it runs or when it runs out partway (it re-runs from the top), throws on sync or a direct run, and puts the caller's budgets back after; give the job `retryUntil()` past the window, since each release is an attempt. A Claude job dispatched under a budget inherits it: without the middleware a refusal fails the job unreported, so give it `new TokenBudget()` (no budget of its own). `remaining()`, `exceeded()`, `availableIn()`, `charge($response->usage)`, `clear()`. Rate-limiter windows are fixed; calls in flight when it runs out go through. Under `Anthropic::fake()` nothing is charged or refused, except a batch poll job's results: `charge()` the budget in a test to use it up. A cache outage fails budgeted calls.

## Batches

50% of normal cost, up to 24 hours to complete. Each request needs a `custom_id` (your own string) and `params` matching a `messages()->create()` shape.

```php
Anthropic::batches()->create(['requests' => [
    ['custom_id' => 'r1', 'params' => [/* messages create params */]],
]]);
Anthropic::batches()->retrieve($id);
Anthropic::batches()->list(['limit' => 10]);
Anthropic::batches()->cancel($id);
Anthropic::batches()->delete($id); // only after ended
```

Three `processingStatus` values only: `in_progress`, `canceling`, `ended`. **Canceled batches end with `ended`, not `canceled`**. The per-request breakdown lives in `$batch->requestCounts->{processing, succeeded, errored, canceled, expired}`.

Send and handle a batch with `Anthropic::batch($requests)->then(fn (BatchResponse $batch) => ...)->catch(fn (Throwable $e) => ...)->onQueue('batches')->every(120)->dispatch()`: it creates the batch (and returns it, so store `$batch->id`), then a queued poll job (one per batch; it needs a worker, so on a real `sync`, `deferred` or `background` queue `dispatch()` throws before sending anything) releases itself until the batch ends, waiting `every()` seconds first and twice as long each time up to 15 minutes, dispatches a `BatchResultReceived` event per result (`$event->customId`, `$event->result['type']`, `$event->result['message']`), then `BatchEnded`, then runs `then()`. Handle results in a queued `BatchResultReceived` listener; `then()` gets the batch, not its results. Callbacks are serialized: no `$this`. Per connection: `Anthropic::connection('support')->batch(...)`; the job polls with the batch's `withApiKey()` key and `withOptions()` options, encrypted. `->timeout(600)` for a big results file; a timeout while reading results fails the job (`catch()`) with some events already sent, so keep listeners idempotent (`updateOrCreate` by `customId`). `php artisan anthropic:batches {id?}` lists or shows them. In tests, queue the created batch, the ended batch and `BatchResultResponse::fake()`, then `Anthropic::assertBatched(fn (array $requests, string $connection) => ...)`. `$batch->isEnded()` (`canceling` hasn't), and `Anthropic::batches()->wait($id)` blocks until it ends (CLI only). Scheduled alternative: store the ID, check `retrieve($id)->isEnded()` from a scheduled closure.

Results stream JSONL; iterate rather than buffering:

```php
foreach (Anthropic::batches()->results($id) as $individual) {
    if ($individual->result->type === 'succeeded') {
        $message = $individual->result->message; // full CreateResponse shape
        // ...
    }
    if ($individual->result->type === 'errored') {
        Log::error('Batch request failed', [
            'custom_id' => $individual->customId,
            'type' => $individual->result->error->type,
            'request_id' => $individual->result->error->requestId, // can be null
        ]);
    }
}
```

## Files

Upload once, reference by `file_id` on later Messages calls. Good for repeated PDFs/images and for reading outputs the code execution tool or Skills produce. Anthropic flags it beta; the SDK auto-injects `anthropic-beta: files-api-2025-04-14` on every `Anthropic::files()` call, so callers do nothing.

```php
$file = Anthropic::files()->upload(['file' => Storage::disk('local')->readStream('doc.pdf')]);
Anthropic::files()->list(['limit' => 100]);
Anthropic::files()->retrieveMetadata($fileId);
Anthropic::files()->download($fileId);  // raw bytes, only for skills/code-execution outputs
Anthropic::files()->delete($fileId);
```

`FileResponse` fields: `id`, `type`, `filename`, `mimeType`, `sizeBytes`, `createdAt`, `downloadable` (nullable bool), `scope` (nullable `FileResponseScope` with `id` and `type: 'session'`).

**Gotcha: referencing a `file_id` in a Messages call needs the beta on the Messages request too.** Messages is not Files-specific so the SDK doesn't auto-inject there. Pass `'betas' => ['files-api-2025-04-14']` on the Messages call, or set it globally in `config('anthropic.beta')` if every Messages call in the app references files.

```php
Anthropic::messages()->create([
    'model' => 'claude-opus-5-5',
    'max_tokens' => 1024,
    'betas' => ['files-api-2025-04-14'],
    'messages' => [[
        'role' => 'user',
        'content' => [
            ['type' => 'text', 'text' => 'Summarise this.'],
            ['type' => 'document', 'source' => ['type' => 'file', 'file_id' => $file->id]],
        ],
    ]],
]);
```

Block pairing: PDFs and plain text go into `document` blocks; images (`image/jpeg|png|gif|webp`) go into `image` blocks; code execution inputs (CSV, XLSX, JSON, etc.) go into `container_upload` blocks.

User-uploaded files are NOT downloadable (`downloadable: false`). `download()` only works on files produced by Skills or code execution; calling it on a user upload throws `ErrorException` with type `invalid_request_error`.

Uploading a request's file: PHP's temp file lacks the original extension (`phpA1B2.tmp`), so name the stream after the original file (sanitize the browser-supplied name), or the API stores the temp name and misses the type:

```php
$upload = $request->file('pdf');

Anthropic::files()->upload(['file' => \GuzzleHttp\Psr7\Utils::streamFor(
    fopen($upload->getRealPath(), 'r'),
    ['metadata' => ['uri' => $upload->getClientOriginalName()]],
)]);
```

Typical Laravel pattern: store `anthropic_file_id` on an Eloquent model. When done with the file, call `Anthropic::files()->delete($id)` and null the column. For large downloads, queue a job that streams the bytes to S3.

Rate limit: ~100 Files calls per minute per org. Throttle with `RateLimiter::for('anthropic-files', fn () => Limit::perMinute(90))` and a `RateLimited('anthropic-files')` middleware on the job.

## Error handling

Exception hierarchy:

```
ErrorException          (any 4xx/5xx API response, or an error mid-stream)
├── BadRequestException (400), AuthenticationException (401), BillingException (402),
│   PermissionDeniedException (403), NotFoundException (404), ConflictException (409),
│   RequestTooLargeException (413), UnprocessableEntityException (422)
├── RateLimitException  (HTTP 429)
├── InternalServerException (500, other 5xx), ApiTimeoutException (504)
└── OverloadedException (529)
TransporterException    (network, DNS, connection)
└── ConnectionException
    └── TimeoutException (your HTTP client gave up; a 504 from the API is ApiTimeoutException)
UnserializableResponse  (a 2xx response that wasn't valid JSON)
ApiKeyIsMissing         (Laravel wrapper; config-time)
```

On `ErrorException`: `$e->getMessage()`, `$e->getErrorType()` (e.g., `'invalid_request_error'`, `'rate_limit_error'`, `'overloaded_error'`), `$e->getStatusCode()`, `$e->getRequestId()`, `$e->getErrorDetails()`, `$e->getRetryAfter()` (seconds), `$e->response` (PSR-7). A mid-stream error throws the subclass of its error type (status 200). `$e->context()` returns `anthropic_request_id`, `status`, `type`, `retry_after` and `error_code` (only those known), which Laravel's exception handler, Sentry and Flare add to the report on their own: don't copy them into `Log` calls by hand.

Catch the specific subclass first, since `RateLimitException extends ErrorException`:

```php
try {
    Anthropic::messages()->create([...]);
} catch (RateLimitException $e) {
    sleep($e->getRetryAfter() ?? 60);
} catch (ErrorException $e) {
    // other API errors
} catch (TransporterException $e) {
    // network failure; original in getPrevious()
}
```

### Queue retry pattern

Release the job on rate limits and 529 overloads instead of throwing. Overload errors are expected during peak and shouldn't page an on-call engineer. Catch `OverloadedException` (or check `getErrorType()`), never `getStatusCode()`: one that arrives mid-stream carries status 200 and is still an `OverloadedException`. Fail the job on the spend-cap 429: retrying won't help.

```php
class AskClaudeJob implements ShouldQueue {
    use \Illuminate\Foundation\Queue\Queueable;

    public $tries = 5;
    public $backoff = [10, 30, 60, 120, 300];

    public function handle(): void {
        try {
            // the job does its own waiting, so the client doesn't retry
            Anthropic::withOptions(['max_retries' => 0])->messages()->create([...]);
        } catch (RateLimitException $e) {
            if (($e->getErrorDetails()['error_code'] ?? null) === 'enforced_spend_limit_reached') {
                $this->fail($e); // the monthly spend cap carries no Retry-After
                return;
            }
            $this->release($e->getRetryAfter() ?? 60);
            return;
        } catch (\Anthropic\Exceptions\OverloadedException $e) {
            $this->release(30);
            return;
        }
    }
}
```

### Silencing noise

Drop specific errors from the error tracker via `bootstrap/app.php`:

```php
->withExceptions(function (Exceptions $exceptions) {
    $exceptions->dontReport(\Anthropic\Exceptions\OverloadedException::class);
})
```

When the class alone isn't enough, a `reportable` callback returning `false` stops default reporting.

For the full HTTP status code table and the underlying transport details, fetch `/mozex/anthropic-laravel` or `/mozex/anthropic-php` via Context7 or the docs site.

## Meta information

`$response->meta()`, `$stream->meta()`, `$results->meta()` all return `MetaInformation`:

```php
$meta = $response->meta();
$meta->requestId;                                 // log this with every request
$meta->requestLimit->limit / ->remaining / ->reset;  // ISO 8601
$meta->tokenLimit->...;
$meta->inputTokenLimit->...;
$meta->outputTokenLimit->...;
$meta->priorityInputTokenLimit?->...;   // null unless on Priority Tier
$meta->priorityOutputTokenLimit?->...;
$meta->fastInputTokenLimit?->...;       // null unless the request used fast mode
$meta->fastOutputTokenLimit?->...;
$meta->organizationId;
$meta->workspaceId;
$meta->retryAfter;                      // seconds; sent with 429s, so read it with $e->getRetryAfter()
```

Throttle before you hit 429 by stashing a cache flag when remaining drops low:

```php
if ($meta->requestLimit->remaining < 10) {
    Cache::put('anthropic.throttle', true, Carbon::parse($meta->requestLimit->reset));
}
```

Include `requestId` in log context on every response; it's what Anthropic support will ask for.

## Testing

`Anthropic::fake()` replaces the client on the Facade and binds the fake as `Anthropic\Contracts\ClientContract`, so constructor-injected code picks it up too. Type-hint `ClientContract`, never `Anthropic\Client`: the fake isn't a `Client`, so resolving a dependency typed with the class after `fake()` throws a `TypeError`.

```php
use Anthropic\Laravel\Facades\Anthropic;
use Anthropic\Resources\Messages;
use Anthropic\Responses\Messages\CreateResponse;

Anthropic::fake([
    CreateResponse::fake(['content' => [['type' => 'text', 'text' => 'Paris.']]]),
]);

// run code...

Anthropic::assertSent(Messages::class, function (string $method, array $parameters): bool {
    return $method === 'create' && $parameters['model'] === 'claude-sonnet-5-5';
});
```

Every response class has `::fake()` with sensible defaults. Overrides merge recursively, so you can change one nested field without rewriting the parent; a nested item with a different `type` (a `tool_use` block over the default `text` block) replaces it instead. Pass exceptions as fakes to test error branches, built with the subclass's `fake()` (`\Anthropic\Exceptions\OverloadedException::fake()`; `RateLimitException::fake(headers: ['retry-after' => '30'])`; `RateLimitException::fake(['details' => ['error_code' => 'enforced_spend_limit_reached']])`; `ConnectionException::fake()`, `TimeoutException::fake()`): a plain `ErrorException` doesn't reach a `catch (OverloadedException $e)`.

Assertions: `Anthropic::assertSent($resource, $callbackOrCount)`, `assertSentTimes($resource, $n, $callback)`, `assertSentInOrder([[Models::class, 'retrieve'], Messages::class])` (every call, in order), `assertNotSent`, `assertNothingSent`, `sent($resource)` (the `TestRequest`s). Also resource-level: `Anthropic::messages()->assertSent(...)`. Under Pest: `expect($fake)->toHaveSent(...)` on the fake `Anthropic::fake()` returned. An `Anthropic::fake()` with no responses answers every call with its method's default fake; `->preventStrayRequests()` makes an unanswered call throw; `->respondTo([Models::class, 'retrieve'], RetrieveResponse::fake())` answers matching calls ahead of the queue (a closure for a stream).

Test queued jobs with `$job::dispatchSync()` plus `Anthropic::fake()`.

`iterate()` on the fake takes one queued list fake per page: `ListResponse::fake(['has_more' => true, 'last_id' => '...'])`, then `ListResponse::fake()`, whose `has_more` is false.

Stream fakes: `CreateStreamedResponse::fake(CreateResponse::fake([...]))` streams the events the API would for that response, or pass a list of event arrays; `BatchResultResponse::fake([['custom_id' => 'req-1', 'result' => ['type' => 'succeeded', 'message' => CreateResponse::fake()->toArray()]]])` for batch results. `Anthropic\Testing\Blocks::text()`, `toolUse()`, `thinking()`, `serverToolUse()`, `webSearchToolResult()` build content blocks. `Anthropic::record(base_path('tests/cassettes/x.json'))` records the default connection's real calls (the facade and an injected `ClientContract`, not `connection()` or `withApiKey()`) once and replays them after, with no HTTP call or key (`record: true` to record again; one cassette per test, since a replay matches method and path only; no `assertSent()` on a recorded run). Running out of queued fakes throws "No fake responses left", naming the call; a queued response that doesn't fit the method throws too. Use `$fake->addResponses([...])` to add mid-test.

For the full list of fake response classes (`Messages\CountTokensResponse`, `Batches\BatchResultResponse`, `Models\ListResponse`, etc.), streams faked from a `CreateResponse` or from events, and recursive-merge semantics for nested overrides, fetch `/mozex/anthropic-laravel` via Context7 or the docs site.

## Connections and tenants

The facade's root is `Anthropic\Laravel\AnthropicManager`; unknown calls go to the default connection (the top-level config). `Anthropic::connection('support')` resolves a named connection from `connections` (a shallow merge over the top level, cached; a connection that sets `api_key` or `auth_token` inherits neither, and one without a key throws; `Anthropic::forgetConnection()` after a runtime config change; workers and Octane forget them between jobs and requests). The default connection is the container's singleton and keeps the config it was built with: for a key that changes per job, use `withApiKey()` or a named connection. `Anthropic::withApiKey($tenantKey)` builds a client of the default settings with that key (without the default `workspace_id`) on every call, never cached: use it for per-tenant keys. `Anthropic::organization()`, `enterprise()`, `compliance()` use `admin_key`, `enterprise_key`, `compliance_key` (Bearer), which the app adds to `config/anthropic.php` (`'admin_key' => env('ANTHROPIC_ADMIN_KEY')`); they share the default's base URL and headers but not its `workspace_id`, and `connections` can't reuse their names. Type-hint `ClientContract` for the default client, `AnthropicManager` for connections. `Anthropic::fake()` answers every connection; `$fake->assertSentOn('support', Messages::class)` checks which one a call used (an injected `ClientContract` and `withApiKey()` count as `default`; `assertNotSentOn()` and a count form exist too). When this package's config has no key or token (unpublished, say) and laravel/ai has an Anthropic key, the default connection uses `config('ai.providers.anthropic.key')` and its `url`.

## Diagnostics

`php artisan anthropic:doctor [--connection=name] [--offline]` checks the credential, one models-list call (no tokens), the default queue's (and Horizon's queues') `retry_after` against `request_timeout × (max_retries + 1) × (1 + fallback models)` plus the backoff (other queues only warn; a `request_timeout` of 0 fails; a Horizon supervisor `timeout` below it warns), the `fallback_models` lifecycle (retired fails; deprecated warns, overdue included) and warns on Livewire with Octane; any failure exits non-zero, and `--offline` without a key only warns about it. `php artisan about --only=anthropic` lists the versions, the credential's kind (never its value) and what the default client sends. `$client->settings()` on an `Anthropic\Client` returns the base URI, API version, betas, workspace and retries (its timeouts are null here, since the package builds its own Guzzle client: read `config('anthropic.request_timeout')`). A model's `isRetired()` and `isRetiring()` read `lifecycle` (the API's retirement signal: a deprecated model past its date is overdue, `isRetirementOverdue()`, not retired), and `retirementDate()` parses `retiresAt`. Never call the API from `/up`: record the last `ResponseReceived` and check its age in a `DiagnosingHealth` listener.

## Raw requests

For an endpoint the package has no method for yet, `Anthropic::request('GET', 'skills', ['limit' => 100])` returns a `RawResponse` (`->status`, `->data` decoded from JSON or the body's text, `->meta()`); it doesn't follow `next_page`, so pass it back as `page` yourself. GET and DELETE send the parameters in the query, POST and PUT in a JSON body, and `betas` becomes the `anthropic-beta` header; the path works with or without `/v1`. The config, retries and `withOptions()` apply, and errors throw the usual exceptions. Fake it with `RawResponse::fake($body, status: 204)`, which takes the whole body, not overrides, and assert with `Anthropic::assertSent(\Anthropic\Resources\Raw::class, fn (string $method, string $httpMethod, string $path) => ...)`; the fake records the path as passed.

## Direct SDK factory (rare)

Only when you need a custom HTTP client, headers, or stream handler (the API version, base URL, retries, refusal fallback and Guzzle middleware have config keys):

```php
$client = \Anthropic::factory() // the PHP client's class, not the facade
    ->withApiKey(config('anthropic.api_key'))
    ->withApiVersion('2026-10-21')
    ->withBaseUri('proxy.example.com/v1') // the full API root, /v1 included
    ->withHttpClient(new \GuzzleHttp\Client(['timeout' => 120]))
    ->withHttpHeader('X-Custom', 'value')
    ->withQueryParam('region', 'eu')
    ->withStreamHandler($handler) // required for PSR-18 clients other than Guzzle / Symfony
    ->make();
```

To use this as the app-wide client, wrap it in `$this->app->extend(\Anthropic\Contracts\ClientContract::class, fn () => \Anthropic::factory()->...->make())` in a service provider's `register()`. Don't use `singleton()` or `instance()`: the package's provider is deferred and registers its own binding over them when it loads; an extender survives, and `Anthropic::fake()` still wins in tests.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.