### Install development dependencies Source: https://github.com/mozex/anthropic-laravel/blob/main/CONTRIBUTING.md Run this command after cloning the repository to install necessary dependencies. ```bash composer install ``` -------------------------------- ### Install Anthropic Laravel Package Source: https://github.com/mozex/anthropic-laravel/blob/main/resources/boost/skills/anthropic-laravel/SKILL.md Install the package using Composer and run the artisan command to publish configuration and set up the .env file. ```bash composer require mozex/anthropic-laravel php artisan anthropic:install ``` -------------------------------- ### Run Anthropic Install Command Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/introduction.md After installing the package, run this Artisan command to publish the configuration file and set up the .env entry for your API key. ```bash php artisan anthropic:install ``` -------------------------------- ### Install Anthropic Laravel Package Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/introduction.md Install the Anthropic Laravel package using Composer. This command fetches and installs the necessary files for the package. ```bash composer require mozex/anthropic-laravel ``` -------------------------------- ### Install Anthropic Laravel Package Source: https://context7.com/mozex/anthropic-laravel/llms.txt Install the package using Composer and run the artisan command to publish configuration and set up environment variables. ```bash composer require mozex/anthropic-laravel php artisan anthropic:install ``` -------------------------------- ### Set environment variables Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/configuration.md Example of required and optional environment variables for the package. ```env ANTHROPIC_API_KEY=sk-ant-... ANTHROPIC_REQUEST_TIMEOUT=30 ANTHROPIC_BETA=files-api-2025-04-14,extended-cache-ttl-2025-04-11 ``` -------------------------------- ### Set up Fake Client with Mocked Responses Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/testing.md Use `Anthropic::fake()` in your tests to replace the real client with a fake one. Provide an array of `CreateResponse::fake()` instances to simulate API responses. This setup is useful for verifying that your application correctly handles expected API outputs. ```php use Anthropic\Laravel\Facades\Anthropic; use Anthropic\Responses\Messages\CreateResponse; Anthropic::fake([ CreateResponse::fake([ 'content' => [['type' => 'text', 'text' => 'Hello! How can I help?']], ]), ]); $response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Hello!'], ], ]); expect($response->content[0]->text)->toBe('Hello! How can I help?'); ``` -------------------------------- ### Test Queued Jobs with Mocked Anthropic Responses Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/testing.md This example shows how to test a queued job that uses the Anthropic API. Using `dispatchSync` and faking responses allows you to test the job's logic and its interaction with the API. ```php it('processes a Claude job', function () { Anthropic::fake([ CreateResponse::fake([ 'content' => [['type' => 'text', 'text' => 'Answer']], ]), ]); AskClaudeJob::dispatchSync('What is 2+2?'); expect(Answer::count())->toBe(1); expect(Answer::first()->content)->toBe('Answer'); Anthropic::assertSent(Messages::class); }); ``` -------------------------------- ### GET /models Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/models.md List all available Claude models with support for pagination. ```APIDOC ## GET /models ### Description Retrieve a list of available Claude models. Supports pagination using limit, after_id, and before_id parameters. ### Method GET ### Endpoint /models ### Parameters #### Query Parameters - **limit** (integer) - Optional - Number of models to return (default 20, max 1000). - **after_id** (string) - Optional - Cursor for forward pagination. - **before_id** (string) - Optional - Cursor for backward pagination. ### Response #### Success Response (200) - **data** (array) - List of model objects. - **firstId** (string) - ID of the first model in the list. - **lastId** (string) - ID of the last model in the list. - **hasMore** (boolean) - Indicates if more models are available. ``` -------------------------------- ### Select Model by Capability at Runtime Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/models.md A practical Laravel pattern to select a model at runtime based on its capabilities, such as PDF input support. This example caches the model list for a day and defaults to 'claude-sonnet-4-6' if no suitable model is found. ```php use Illuminate\Support\Facades\Cache; $model = Cache::remember('anthropic.pdf_model', now()->addDay(), function () { $models = Anthropic::models()->list()->data; foreach ($models as $model) { if ($model->capabilities->pdfInput->supported) { return $model->id; } } return 'claude-sonnet-4-6'; }); ``` -------------------------------- ### Test Controller Actions with Mocked Anthropic Responses Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/testing.md This example demonstrates how to test a controller action that interacts with the Anthropic API. By faking the responses, you can isolate the controller logic and verify its behavior. ```php it('asks Claude a question', function () { Anthropic::fake([ CreateResponse::fake([ 'content' => [['type' => 'text', 'text' => 'Paris is the capital of France.']], ]), ]); $response = $this->post('/ask', ['question' => 'What is the capital of France?']); $response->assertOk(); $response->assertSee('Paris'); Anthropic::assertSent(Messages::class, function (string $method, array $parameters) { return $parameters['messages'][0]['content'] === 'What is the capital of France?'; }); }); ``` -------------------------------- ### Create a Message with Anthropic Facade Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/introduction.md Use the Anthropic Facade to send a message to the Claude API. This example demonstrates creating a simple text-based message and accessing the response. ```php use Anthropic\Laravel\Facades\Anthropic; $response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Hello!'], ], ]); echo $response->content[0]->text; // Hello! How can I assist you today? ``` -------------------------------- ### Accessing Citation Data from Response Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/citations.md After receiving a response with citations, you can access the citation details from the content blocks. The example shows how to get the text, type, cited text, and character indices. ```php $response->content[1]->text; // 'the grass is green' $response->content[1]->citations[0]['type']; // 'char_location' $response->content[1]->citations[0]['cited_text']; // 'The grass is green.' $response->content[1]->citations[0]['start_char_index']; // 0 $response->content[1]->citations[0]['end_char_index']; // 20 ``` -------------------------------- ### Combine global and per-request beta features Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/configuration.md Demonstrates how global configuration and per-request beta flags are merged. ```php // config/anthropic.php 'beta' => ['files-api-2025-04-14'], // always on // Specific call adds another beta for this request only Anthropic::messages()->create([ 'model' => 'claude-opus-4-6', 'max_tokens' => 1024, 'messages' => [...], 'betas' => ['interleaved-thinking-2025-05-14'], ]); // Sends: anthropic-beta: files-api-2025-04-14,interleaved-thinking-2025-05-14 ``` -------------------------------- ### GET /models/{model_id} Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/models.md Retrieve details and capabilities for a specific Claude model. ```APIDOC ## GET /models/{model_id} ### Description Retrieve specific details for a single model, including its capabilities like image input, PDF support, and thinking features. ### Method GET ### Endpoint /models/{model_id} ### Parameters #### Path Parameters - **model_id** (string) - Required - The unique identifier of the model. ### Response #### Success Response (200) - **id** (string) - Model identifier. - **displayName** (string) - Human-readable name. - **createdAt** (string) - Creation timestamp. - **maxInputTokens** (integer) - Maximum input token limit. - **maxTokens** (integer) - Maximum output token limit. - **capabilities** (object) - Object containing supported features (batch, citations, codeExecution, imageInput, pdfInput, structuredOutputs, thinking, contextManagement). ``` -------------------------------- ### Create a completion Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/completions.md Generates a text completion using the Anthropic facade. Requires the specific prompt format with Human and Assistant markers. ```php use Anthropic\Laravel\Facades\Anthropic; $response = Anthropic::completions()->create([ 'model' => 'claude-2.1', 'prompt' => "\n\nHuman: Hello, Claude\n\nAssistant:", 'max_tokens_to_sample' => 100, 'temperature' => 0, ]); $response->completion; // ' Hello! Nice to meet you.' $response->stop_reason; // 'stop_sequence' $response->model; // 'claude-2.1' ``` -------------------------------- ### Configure budget-based thinking for older models Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/thinking.md Specify a fixed token budget for reasoning when using legacy models like Sonnet 3.7 or Opus 4.5. ```php $response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-5', 'max_tokens' => 16000, 'thinking' => [ 'type' => 'enabled', 'budget_tokens' => 10000, ], 'messages' => [...], ]); ``` -------------------------------- ### Run project tests Source: https://github.com/mozex/anthropic-laravel/blob/main/CONTRIBUTING.md Execute the test suite to verify project integrity. ```bash composer test ``` ```bash composer test:types ``` ```bash composer test:unit ``` -------------------------------- ### Perform basic streaming with Anthropic Laravel Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/streaming.md Iterate through the stream to capture and output text chunks as they arrive. ```php use Anthropic\Laravel\Facades\Anthropic; $stream = Anthropic::messages()->createStreamed([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Tell me a short story.'], ], ]); foreach ($stream as $response) { if ($response->type === 'content_block_delta' && $response->delta->type === 'text_delta') { echo $response->delta->text; } } ``` -------------------------------- ### Run All Project Checks Source: https://github.com/mozex/anthropic-laravel/blob/main/CLAUDE.md Execute all project checks including linting, type checking with PHPStan, and unit tests with Pest. ```bash composer test ``` -------------------------------- ### Trim Conversation History Based on Token Count Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/token-counting.md This example demonstrates a common pattern for managing conversation history in Laravel. It counts tokens for recent messages and trims older ones if the count exceeds a specified limit before creating a new response. ```php $messages = $conversation->messages() ->latest('id') ->take(50) ->get() ->reverse() ->map(fn ($message) => [ 'role' => $message->is_assistant ? 'assistant' : 'user', 'content' => $message->content, ]) ->toArray(); $count = Anthropic::messages()->countTokens([ 'model' => 'claude-sonnet-4-6', 'messages' => $messages, ]); if ($count->inputTokens > 180000) { // Drop the oldest pairs until we're under the limit $messages = array_slice($messages, 4); } $response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => $messages, ]); ``` -------------------------------- ### List and inspect available models Source: https://github.com/mozex/anthropic-laravel/blob/main/resources/boost/skills/anthropic-laravel/SKILL.md Retrieve a list of available models and access their specific capabilities such as image input support or thinking modes. ```php $response = Anthropic::models()->list(); foreach ($response->data as $model) { $model->id; // 'claude-sonnet-4-6' $model->displayName; $model->maxInputTokens; // context window $model->maxTokens; // max output $model->capabilities->imageInput->supported; $model->capabilities->thinking->types->adaptive->supported; $model->capabilities->effort->max->supported; } ``` -------------------------------- ### Create a Custom Anthropic SDK Client Source: https://github.com/mozex/anthropic-laravel/blob/main/resources/boost/skills/anthropic-laravel/SKILL.md Instantiate a custom Anthropic client using the factory when specific configurations like a custom HTTP client, base URI, headers, or stream handler are required. This is a rare use case, typically for advanced integration scenarios. ```php $client = Anthropic::factory() ->withApiKey(config('anthropic.api_key')) ->withBaseUri('proxy.example.com/v1') ->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(); ``` -------------------------------- ### Define global beta features Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/configuration.md Configure beta features globally using environment variables or the config array. ```env ANTHROPIC_BETA=files-api-2025-04-14,extended-cache-ttl-2025-04-11 ``` ```php // config/anthropic.php 'beta' => [ 'files-api-2025-04-14', 'extended-cache-ttl-2025-04-11', ], ``` -------------------------------- ### Create a streamed completion Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/completions.md Streams completion tokens as they are generated by the model. ```php $stream = Anthropic::completions()->createStreamed([ 'model' => 'claude-2.1', 'prompt' => 'Hi', 'max_tokens_to_sample' => 70, ]); foreach ($stream as $response) { echo $response->completion; } ``` -------------------------------- ### List, Cancel, and Delete Batches Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/batches.md Manage existing batches using these methods. `list` supports pagination, `cancel` stops in-progress batches, and `delete` removes completed batches. ```php // List with pagination $response = Anthropic::batches()->list(['limit' => 10]); // Cancel in-progress Anthropic::batches()->cancel('msgbatch_04Rka1yCsMLGPnR7kfPdgR8x'); // Delete after completion Anthropic::batches()->delete('msgbatch_04Rka1yCsMLGPnR7kfPdgR8x'); ``` -------------------------------- ### Access Context Management Strategies Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/models.md Iterates through the available context management strategies for a model, which are versioned and exposed as a map. This allows the package to adapt to new Anthropic releases without requiring an update. ```php foreach ($model->capabilities->contextManagement->strategies as $name => $strategy) { $name; // 'clear_thinking_20251015' $strategy->supported; // true } ``` -------------------------------- ### Check Code Style Without Fixing Source: https://github.com/mozex/anthropic-laravel/blob/main/CLAUDE.md Run Pint to check code style compliance without making any automatic fixes. ```bash composer test:lint ``` -------------------------------- ### Download a File Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/files.md Downloads a file produced by the code execution tool or Skills. User-uploaded files are not downloadable. The `download()` method returns raw bytes as a string. ```php use Illuminate\Support\Facades\Storage; $bytes = Anthropic::files()->download('file_011CPMxVD3fHLUhvTqtsQA5w'); Storage::disk('local')->put('outputs/chart.png', $bytes); ``` -------------------------------- ### Mocking streamed responses with a file Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/testing.md Use a file resource to simulate a streamed response in tests. ```php use Anthropic\Responses\Messages\CreateStreamedResponse; Anthropic::fake([ CreateStreamedResponse::fake(fopen('tests/fixtures/stream.txt', 'r')), ]); ``` -------------------------------- ### Configure Anthropic Client Source: https://context7.com/mozex/anthropic-laravel/llms.txt Configure the Anthropic client by setting the API key and request timeout in the configuration file or environment variables. ```php env('ANTHROPIC_API_KEY'), // Request timeout in seconds (default: 30) 'request_timeout' => env('ANTHROPIC_REQUEST_TIMEOUT', 30), ]; ``` ```dotenv # .env ANTHROPIC_API_KEY=sk-ant-api03-... ANTHROPIC_REQUEST_TIMEOUT=60 ``` -------------------------------- ### Run Pest Unit Tests Source: https://github.com/mozex/anthropic-laravel/blob/main/CLAUDE.md Execute all unit tests for the project using the Pest testing framework. ```bash composer test:unit ``` -------------------------------- ### Configure Web Search Tool Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/server-tools.md Add the web search tool to the tools array in the messages request. ```php use Anthropic\Laravel\Facades\Anthropic; $response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'tools' => [ ['type' => 'web_search_20250305', 'name' => 'web_search'], ], 'messages' => [ ['role' => 'user', 'content' => 'When was Claude Shannon born?'], ], ]); ``` -------------------------------- ### Creating a stream helper for tests Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/testing.md Define a helper function to generate a stream from an array of text chunks for testing purposes. ```php // In tests/Pest.php or a test helper file function fakeStream(array $parts) { $events = collect($parts) ->map(fn (string $part) => [ 'type' => 'content_block_delta', 'index' => 0, 'delta' => ['type' => 'text_delta', 'text' => $part], ]) ->prepend([ 'type' => 'message_start', 'message' => [ 'id' => 'msg_test', 'type' => 'message', 'role' => 'assistant', 'model' => 'claude-sonnet-4-6', 'content' => [], 'stop_reason' => null, 'stop_sequence' => null, 'usage' => ['input_tokens' => 10, 'output_tokens' => 1], ], ]) ->add([ 'type' => 'message_delta', 'delta' => ['stop_reason' => 'end_turn', 'stop_sequence' => null], 'usage' => ['output_tokens' => 12], ]) ->add(['type' => 'message_stop']) ->map(fn (array $event) => "event: {$event['type']}\ndata: " . json_encode($event)) ->join("\n\n"); $handle = fopen('php://memory', 'r+'); fwrite($handle, $events); rewind($handle); return $handle; } ``` -------------------------------- ### Execute Code in Sandbox Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/server-tools.md Enable the code execution tool to allow Claude to run Python or bash code. ```php $response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 4096, 'tools' => [ ['type' => 'code_execution_20250825', 'name' => 'code_execution'], ], 'messages' => [ ['role' => 'user', 'content' => 'Calculate the compound interest on $1000 at 5% for 10 years.'], ], ]); ``` -------------------------------- ### Configure Web Search Options Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/server-tools.md Define search constraints such as max uses, allowed domains, and user location. ```php 'tools' => [ [ 'type' => 'web_search_20250305', 'name' => 'web_search', 'max_uses' => 5, 'allowed_domains' => ['example.com', 'docs.php.net'], 'blocked_domains' => ['untrusted.com'], 'user_location' => [ 'type' => 'approximate', 'city' => 'San Francisco', 'country' => 'US', 'timezone' => 'America/Los_Angeles', ], ], ] ``` -------------------------------- ### Configure Anthropic API Key and Timeout Source: https://github.com/mozex/anthropic-laravel/blob/main/resources/boost/skills/anthropic-laravel/SKILL.md The configuration file allows setting the API key and request timeout using environment variables. Ensure ANTHROPIC_API_KEY is set to avoid an ApiKeyIsMissing exception. ```php return [ 'api_key' => env('ANTHROPIC_API_KEY'), 'request_timeout' => env('ANTHROPIC_REQUEST_TIMEOUT', 30), ]; ``` -------------------------------- ### Create a Message Batch Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/batches.md Use this to initiate a batch of message requests. Each request requires a `custom_id` and `params` object, which accepts standard message creation parameters. The response includes batch details like ID and status. ```php use Anthropic\Laravel\Facades\Anthropic; $response = Anthropic::batches()->create([ 'requests' => [ [ 'custom_id' => 'request-1', 'params' => [ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'What is the capital of France?'], ], ], ], [ 'custom_id' => 'request-2', 'params' => [ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'What is the capital of Germany?'], ], ], ], ], ]); $response->id; $response->processingStatus; $response->requestCounts->processing; $response->createdAt; $response->expiresAt; ``` -------------------------------- ### Testing Batch Operations and Model Listing Source: https://context7.com/mozex/anthropic-laravel/llms.txt Mock responses for batch operations and model listing to validate specific resource methods. ```php use Anthropic\Laravel\Facades\Anthropic; use Anthropic\Resources\Batches; use Anthropic\Resources\Models; use Anthropic\Responses\Batches\BatchResponse; use Anthropic\Responses\Models\ListResponse as ModelsListResponse; // Test batches Anthropic::fake([ BatchResponse::fake([ 'id' => 'msgbatch_test_123', 'processing_status' => 'ended', ]), ]); $batch = Anthropic::batches()->retrieve('msgbatch_test_123'); expect($batch->id)->toBe('msgbatch_test_123'); Anthropic::assertSent(Batches::class, function (string $method, string $id): bool { return $method === 'retrieve' && $id === 'msgbatch_test_123'; }); // Test models Anthropic::fake([ ModelsListResponse::fake(), ]); $models = Anthropic::models()->list(['limit' => 10]); Anthropic::assertSent(Models::class, function (string $method, array $parameters): bool { return $method === 'list' && $parameters === ['limit' => 10]; }); ``` -------------------------------- ### Build Multi-turn Conversations Source: https://context7.com/mozex/anthropic-laravel/llms.txt Construct conversational applications by providing the complete message history with alternating user and assistant roles. The model maintains context from previous turns. ```php use Anthropic\Laravel\Facades\Anthropic; $result = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'system' => 'You are a helpful coding assistant specialized in PHP.', 'messages' => [ ['role' => 'user', 'content' => 'How do I create a Laravel controller?'], ['role' => 'assistant', 'content' => 'You can create a controller using: php artisan make:controller UserController'], ['role' => 'user', 'content' => 'How do I add a method to handle POST requests?'], ], ]); echo $result->content[0]->text; // Claude continues the conversation with context from previous messages ``` -------------------------------- ### Configure Vision Content Blocks Source: https://github.com/mozex/anthropic-laravel/blob/main/resources/boost/skills/anthropic-laravel/SKILL.md Uses Laravel Storage to encode images as base64 for API requests. ```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')), ]] ``` -------------------------------- ### Fake Anthropic Client for Testing Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/introduction.md In your tests, use `Anthropic::fake()` to replace the real client with a mock. This allows you to queue responses and assert sent requests. ```php use Anthropic\Laravel\Facades\Anthropic; use Anthropic\Resources\Messages; use Anthropic\Responses\Messages\CreateResponse; Anthropic::fake([ CreateResponse::fake([ 'content' => [['type' => 'text', 'text' => 'Paris is the capital of France.']], ]), ]); // Run your code... $this->post('/ask', ['question' => 'What is the capital of France?']); // Then assert what was sent Anthropic::assertSent(Messages::class, function (string $method, array $parameters): bool { return $method === 'create' && $parameters['model'] === 'claude-sonnet-4-6'; }); ``` -------------------------------- ### Paginate Model List Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/models.md Demonstrates how to paginate through the list of Claude models. You can specify a limit (default 20, max 1000) and use `after_id` or `before_id` for forward or backward pagination, respectively. ```php $page1 = Anthropic::models()->list(['limit' => 5]); if ($page1->hasMore) { $page2 = Anthropic::models()->list([ 'limit' => 5, 'after_id' => $page1->lastId, ]); } ``` -------------------------------- ### Publish Anthropic Configuration File Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/configuration.md Command to manually publish the Anthropic package's configuration file. This is useful for updating or customizing configuration settings. ```bash php artisan vendor:publish --tag=config --provider="Anthropic\Laravel\ServiceProvider" ``` -------------------------------- ### Create a message Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/messages.md Use the Anthropic Facade to send a message and receive a typed response object. ```php use Anthropic\Laravel\Facades\Anthropic; $response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Hello, world'], ], ]); ``` -------------------------------- ### Enable Adaptive Thinking Source: https://context7.com/mozex/anthropic-laravel/llms.txt Configure the messages API to allocate thinking tokens for complex reasoning. Requires a temperature setting of 1. ```php use Anthropic\Laravel\Facades\Anthropic; $result = Anthropic::messages()->create([ 'model' => 'claude-opus-4-6', 'max_tokens' => 16000, 'temperature' => 1, // Required for thinking 'thinking' => [ 'type' => 'enabled', 'budget_tokens' => 10000, // Allow up to 10k tokens for thinking ], 'messages' => [ ['role' => 'user', 'content' => 'Explain quantum entanglement and its implications for quantum computing.'], ], ]); // Access thinking content if available foreach ($result->content as $block) { if ($block->type === 'thinking') { echo "Thinking: " . $block->thinking . "\n"; } elseif ($block->type === 'text') { echo "Response: " . $block->text . "\n"; } } ``` -------------------------------- ### Allow Any Tool Use in Claude API Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/tool-use.md Use this to ensure Claude uses at least one tool if available and appropriate. This is useful when multiple tools might be relevant. ```php 'tool_choice' => ['type' => 'any'] ``` -------------------------------- ### Enable beta features per request Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/configuration.md Pass a betas array to specific resource methods to enable features for a single request. ```php use Anthropic\Laravel\Facades\Anthropic; $response = Anthropic::messages()->create([ 'model' => 'claude-opus-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Hello!'], ], 'betas' => ['interleaved-thinking-2025-05-14'], ]); ``` -------------------------------- ### Configure timeout and queue job for thinking Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/thinking.md Increase request timeouts and process thinking-heavy requests within background jobs to prevent execution failures. ```env ANTHROPIC_REQUEST_TIMEOUT=120 ``` ```php class AnalyzeJob implements ShouldQueue { public $timeout = 150; public function handle(): void { $response = Anthropic::messages()->create([ 'model' => 'claude-opus-4-6', 'max_tokens' => 16000, 'thinking' => ['type' => 'adaptive'], 'output_config' => ['effort' => 'max'], 'messages' => $this->messages, ]); // Save the final answer (skip thinking blocks for display) $text = collect($response->content) ->firstWhere('type', 'text') ->text; $this->result->update(['content' => $text]); } } ``` -------------------------------- ### Define Tools with JSON Schema Source: https://github.com/mozex/anthropic-laravel/blob/main/resources/boost/skills/anthropic-laravel/SKILL.md Configures tool definitions for Claude, including input schemas and descriptions. ```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'], ], ]] ``` -------------------------------- ### Manage Models API Source: https://context7.com/mozex/anthropic-laravel/llms.txt List available models or retrieve specific model details including capabilities and pricing. ```php use Anthropic\Laravel\Facades\Anthropic; // List all available models $models = Anthropic::models()->list(); foreach ($models->data as $model) { echo $model->id . "\n"; // claude-opus-4-6 // claude-sonnet-4-6 // claude-haiku-3-5-20241022 // ... } // Retrieve a specific model $model = Anthropic::models()->retrieve('claude-sonnet-4-6'); echo $model->id; // claude-sonnet-4-6 echo $model->display_name; // Claude Sonnet 4 (6) echo $model->created_at; // 2025-01-01T00:00:00Z ``` -------------------------------- ### Handling Missing API Key Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/error-handling.md Catch ApiKeyIsMissing if the ANTHROPIC_API_KEY environment variable is not configured. This is typically a deployment-time check. ```php use Anthropic\Laravel\Exceptions\ApiKeyIsMissing; try { $response = Anthropic::messages()->create([...]); } catch (ApiKeyIsMissing $e) { // API key not configured } ``` -------------------------------- ### Handle pause_turn stop reasons Source: https://github.com/mozex/anthropic-laravel/blob/main/resources/boost/skills/anthropic-laravel/SKILL.md Resume long-running turns by echoing the assistant's content back in the next request when the stop reason is pause_turn. ```php do { $response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 8192, 'messages' => $messages, ]); $messages[] = [ 'role' => 'assistant', 'content' => array_map(fn ($block) => $block->toArray(), $response->content), ]; } while ($response->stop_reason === 'pause_turn'); ``` -------------------------------- ### Set system messages Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/messages.md Provide persona or context instructions using the system parameter, which is separate from the messages array. ```php $response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'system' => 'You are a helpful PHP expert. Answer concisely.', 'messages' => [ ['role' => 'user', 'content' => 'What is the null coalescing operator?'], ], ]); ``` -------------------------------- ### Configure Global Beta Header Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/files.md If all Messages calls in your application reference uploaded files, you can configure the Files API beta header globally in `config/anthropic.php` to avoid per-call configuration. ```php // config/anthropic.php 'beta' => ['files-api-2025-04-14'], ``` -------------------------------- ### Manage Anthropic Batches Source: https://github.com/mozex/anthropic-laravel/blob/main/resources/boost/skills/anthropic-laravel/SKILL.md Use these methods to create, retrieve, list, cancel, and delete batch jobs. Batches offer a cost-effective way to process requests with a longer completion time. ```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 ``` -------------------------------- ### Testing with Anthropic Facade Source: https://github.com/mozex/anthropic-laravel/blob/main/README.md Use the fake method to mock API responses and assert that specific requests were sent during testing. ```php use Anthropic\Laravel\Facades\Anthropic; use Anthropic\Resources\Messages; use Anthropic\Responses\Messages\CreateResponse; Anthropic::fake([ CreateResponse::fake([ 'content' => [['type' => 'text', 'text' => 'Paris is the capital of France.']], ]), ]); // Run your code... Anthropic::assertSent(Messages::class, function (string $method, array $parameters) { return $parameters['model'] === 'claude-sonnet-4-6'; }); ``` -------------------------------- ### Accessing meta on batch results Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/meta-information.md Retrieve meta information from batch processing results. ```php $results = Anthropic::batches()->results('msgbatch_...'); foreach ($results as $individual) { // Process results } $results->meta(); ``` -------------------------------- ### Configure Anthropic API Key Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/introduction.md Add your Anthropic API key to your .env file. This key is required for the package to authenticate with the Anthropic API. ```env ANTHROPIC_API_KEY=sk-ant-... ``` -------------------------------- ### Configure thinking effort levels Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/thinking.md Adjust the reasoning depth by setting the effort parameter within the output configuration. ```php $response = Anthropic::messages()->create([ 'model' => 'claude-opus-4-6', 'max_tokens' => 16000, 'thinking' => ['type' => 'adaptive'], 'output_config' => [ 'effort' => 'medium', ], 'messages' => [...], ]); ``` -------------------------------- ### Check Model Capabilities Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/models.md Retrieves a specific model and checks its supported capabilities, such as batch processing, citations, code execution, image/PDF input, structured outputs, and thinking. This helps determine if a model is suitable for a particular task. ```php $model = Anthropic::models()->retrieve('claude-sonnet-4-6'); $model->capabilities->batch->supported; $model->capabilities->citations->supported; $model->capabilities->codeExecution->supported; $model->capabilities->imageInput->supported; $model->capabilities->pdfInput->supported; $model->capabilities->structuredOutputs->supported; $model->capabilities->thinking->supported; ``` -------------------------------- ### Injecting the Anthropic Client Source: https://context7.com/mozex/anthropic-laravel/llms.txt Inject the ClientContract directly into classes for dependency injection instead of using the facade. ```php use Anthropic\Contracts\ClientContract; class ChatController extends Controller { public function __construct( private ClientContract $anthropic ) {} public function chat(Request $request) { $result = $this->anthropic->messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => $request->input('message')], ], ]); return response()->json([ 'response' => $result->content[0]->text, ]); } } ``` -------------------------------- ### Manage Files with Anthropic SDK Source: https://github.com/mozex/anthropic-laravel/blob/main/resources/boost/skills/anthropic-laravel/SKILL.md Upload, list, retrieve metadata, download, and delete files using the Anthropic SDK. Files can be referenced in Messages API calls for context. ```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); ``` -------------------------------- ### Define Tools for Claude Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/tool-use.md Define custom tools with their names, descriptions, and input schemas. Claude uses these to decide when to call a tool. ```php use Anthropic\Laravel\Facades\Anthropic; $response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'tools' => [ [ 'name' => 'get_weather', 'description' => 'Get the current weather in a given location', 'input_schema' => [ 'type' => 'object', 'properties' => [ 'location' => [ 'type' => 'string', 'description' => 'The city and state, e.g. San Francisco, CA', ], ], 'required' => ['location'], ], ], ], 'messages' => [ ['role' => 'user', 'content' => 'What is the weather in San Francisco?'], ], ]); ``` -------------------------------- ### Run a Single Pest Test File Source: https://github.com/mozex/anthropic-laravel/blob/main/CLAUDE.md Execute Pest tests located in a specific file, useful for targeted testing during development. ```bash ./vendor/bin/pest tests/Facades/Anthropic.php ``` -------------------------------- ### Track Tool Usage Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/server-tools.md Access usage statistics for various server tools from the response object. ```php $response->usage->serverToolUse?->webSearchRequests; $response->usage->serverToolUse?->webFetchRequests; $response->usage->serverToolUse?->codeExecutionRequests; $response->usage->serverToolUse?->toolSearchRequests; ``` -------------------------------- ### Execute Message Batches Source: https://context7.com/mozex/anthropic-laravel/llms.txt Create and manage asynchronous batch requests to process large volumes of messages efficiently. ```php use Anthropic\Laravel\Facades\Anthropic; // Create a batch $batch = Anthropic::batches()->create([ 'requests' => [ [ 'custom_id' => 'request-1', 'params' => [ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Summarize the benefits of cloud computing.'], ], ], ], [ 'custom_id' => 'request-2', 'params' => [ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Explain microservices architecture.'], ], ], ], ], ]); echo $batch->id; // msgbatch_01HzcWVHnPbrh3... // Retrieve batch status $batch = Anthropic::batches()->retrieve('msgbatch_01HzcWVHnPbrh3...'); echo $batch->processing_status; // in_progress, ended, etc. // List all batches $batches = Anthropic::batches()->list(); // Get batch results when complete $results = Anthropic::batches()->results('msgbatch_01HzcWVHnPbrh3...'); // Cancel a batch Anthropic::batches()->cancel('msgbatch_01HzcWVHnPbrh3...'); // Delete a batch Anthropic::batches()->delete('msgbatch_01HzcWVHnPbrh3...'); ``` -------------------------------- ### Tool Use with Anthropic API Source: https://github.com/mozex/anthropic-laravel/blob/main/README.md Define tools for the AI to use by specifying their name, description, and input schema. Execute the tool in your code and send results back to the model. ```php $response = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'tools' => [ [ 'name' => 'get_weather', 'description' => 'Get the current weather in a given location', 'input_schema' => [ 'type' => 'object', 'properties' => [ 'location' => ['type' => 'string'], ], 'required' => ['location'], ], ], ], 'messages' => [ ['role' => 'user', 'content' => 'What is the weather in San Francisco?'], ], ]); $response->content[1]->name; // 'get_weather' $response->content[1]->input['location']; // 'San Francisco' ``` -------------------------------- ### Build Model Selector with Caching Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/models.md Caches the list of Claude models for one hour to avoid repeated API calls when building UI elements like a model selector dropdown. Requires `Illuminate\Support\Facades\Cache`. ```php use Illuminate\Support\Facades\Cache; $models = Cache::remember('anthropic.models', now()->addHour(), function () { return Anthropic::models()->list()->data; }); // In a Blade form ``` -------------------------------- ### Resolve Anthropic Client Instance Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/configuration.md Demonstrates three ways to resolve the same Anthropic client instance from the Laravel service container. The client is instantiated only when first used due to deferred provider registration. ```php app(\Anthropic\Contracts\ClientContract::class); app('anthropic'); \Anthropic\Laravel\Facades\Anthropic::messages(); ``` -------------------------------- ### Dispatch Tool Calls to Services Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/tool-use.md Map tool names to Laravel service classes for clean execution. Use `caller?->type === 'direct'` to distinguish custom tools from server-handled ones. ```php $toolRegistry = [ 'get_weather' => WeatherService::class, 'search_products' => ProductSearchService::class, 'send_email' => EmailService::class, ]; foreach ($response->content as $block) { if ($block->type === 'tool_use' && $block->caller?->type === 'direct') { $service = app($toolRegistry[$block->name]); $result = $service->handle($block->input); $results[] = [ 'type' => 'tool_result', 'tool_use_id' => $block->id, 'content' => json_encode($result), ]; } } ``` -------------------------------- ### Resource-Level Assertions for Sent Requests Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/testing.md You can also make assertions directly on resource instances, such as `Anthropic::messages()`. This allows for more granular testing of specific resource interactions. ```php Anthropic::messages()->assertSent(function (string $method, array $parameters): bool { return $method === 'create'; }); ``` -------------------------------- ### Throttling based on remaining limits Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/reference/meta-information.md Monitor remaining request limits to proactively cache a throttle flag before hitting 429 errors. ```php $response = Anthropic::messages()->create([...]); $meta = $response->meta(); if ($meta->requestLimit->remaining < 10) { $reset = Carbon::parse($meta->requestLimit->reset); Cache::put('anthropic.throttle', true, $reset); } ``` -------------------------------- ### Fix Code Style with Pint Source: https://github.com/mozex/anthropic-laravel/blob/main/CLAUDE.md Use Composer to run Pint, a tool for automatically fixing code style according to the default Laravel ruleset. ```bash composer lint ``` -------------------------------- ### Use Legacy Completions API Source: https://context7.com/mozex/anthropic-laravel/llms.txt Access the legacy completions endpoint for text completion tasks. The Messages API is preferred for new implementations. ```php use Anthropic\Laravel\Facades\Anthropic; $completion = Anthropic::completions()->create([ 'model' => 'claude-2.1', 'prompt' => "\n\nHuman: Explain PHP in one sentence.\n\nAssistant:", 'max_tokens_to_sample' => 256, ]); echo $completion->completion; // "PHP is a widely-used server-side scripting language..." ``` -------------------------------- ### Accessing Anthropic API Resources via Facade Source: https://github.com/mozex/anthropic-laravel/blob/main/resources/boost/skills/anthropic-laravel/SKILL.md Use the Anthropic facade as the primary entry point for interacting with the Anthropic API within your Laravel application. This facade provides access to various API resources. ```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(); // Legacy Text Completions ``` -------------------------------- ### Mocking API Responses and Assertions Source: https://context7.com/mozex/anthropic-laravel/llms.txt Use the fake() method to define mock responses and verify API calls using assertion methods. ```php use Anthropic\Laravel\Facades\Anthropic; use Anthropic\Resources\Messages; use Anthropic\Responses\Messages\CreateResponse; // Set up fake responses Anthropic::fake([ CreateResponse::fake([ 'id' => 'msg_test_123', 'content' => [ ['type' => 'text', 'text' => 'This is a mocked response!'], ], ]), ]); // Make the API call - returns the fake response $result = Anthropic::messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Hello!'], ], ]); // Verify the response expect($result->id)->toBe('msg_test_123'); expect($result->content[0]->text)->toBe('This is a mocked response!'); // Assert specific requests were made Anthropic::assertSent(Messages::class, function (string $method, array $parameters): bool { return $method === 'create' && $parameters['model'] === 'claude-sonnet-4-6' && $parameters['messages'][0]['content'] === 'Hello!'; }); // Assert on specific resource Anthropic::messages()->assertSent(function (string $method, array $parameters): bool { return $method === 'create'; }); ``` -------------------------------- ### Default Tool Use Behavior in Claude API Source: https://github.com/mozex/anthropic-laravel/blob/main/docs/usage/tool-use.md This is the default behavior where Claude decides whether to use a tool. No explicit configuration is needed. ```php 'tool_choice' => ['type' => 'auto'] ```