### Quick Setup with Facade Source: https://github.com/mozex/anthropic-php/blob/main/CLAUDE.md Use the Anthropic facade for quick setup in Laravel applications. This is the preferred method for Laravel examples. ```php use Anthropic\Laravel\Facades\Anthropic; Anthropic::messages()->create([...]) ``` -------------------------------- ### Install Dev Dependencies Source: https://github.com/mozex/anthropic-php/blob/main/CONTRIBUTING.md Install development dependencies for the project. Run this after cloning your fork. ```bash composer install ``` -------------------------------- ### Install the SDK Source: https://github.com/mozex/anthropic-php/blob/main/docs/introduction.md Use Composer to add the package to your project. ```bash composer require mozex/anthropic-php ``` -------------------------------- ### Installation Source: https://github.com/mozex/anthropic-php/blob/main/README.md Install the library using Composer. ```bash composer require mozex/anthropic-php ``` -------------------------------- ### Create Client with Default Configuration Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Use this method for a quick client setup with auto-discovered defaults. It's sufficient for most projects. ```php $client = Anthropic::client('your-api-key'); ``` -------------------------------- ### Quick Start Source: https://github.com/mozex/anthropic-php/blob/main/README.md Create a client, send a message, and retrieve the response. ```php $client = Anthropic::client('your-api-key'); $response = $client->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? ``` -------------------------------- ### Install Symfony HTTP Client Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Install the Symfony HTTP client component using Composer. This is required if you intend to use it with the Anthropic SDK. ```bash composer require symfony/http-client ``` -------------------------------- ### Install Guzzle HTTP Client Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Install Guzzle using Composer to leverage its capabilities, including automatic streaming support with the Anthropic SDK. ```bash composer require guzzlehttp/guzzle ``` -------------------------------- ### Setup ClientFake for testing Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/testing.md Replace the standard client with ClientFake and provide an array of expected responses to be returned in sequence. ```php use Anthropic\Testing\ClientFake; use Anthropic\Responses\Messages\CreateResponse; $client = new ClientFake([ CreateResponse::fake([ 'content' => [ ['type' => 'text', 'text' => 'Hello! How can I help?'], ], ]), ]); $response = $client->messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Hello!'], ], ]); $response->content[0]->text; // 'Hello! How can I help?' ``` -------------------------------- ### Tool use event structure Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/streaming.md Example of the event structure for tool block initiation and incremental input delivery. ```php // Tool block start [ 'type' => 'content_block_start', 'index' => 1, 'content_block_start' => [ 'id' => 'toolu_01RDFRXpbNUGrZ1xQy443s5Q', 'type' => 'tool_use', 'name' => 'get_weather', 'input' => [], ], ] // Tool input arrives as JSON fragments [ 'type' => 'content_block_delta', 'index' => 1, 'delta' => [ 'type' => 'input_json_delta', 'partial_json' => '{"location": "San Francisco, CA"}', ], ] ``` -------------------------------- ### Configurable Client Factory Source: https://github.com/mozex/anthropic-php/blob/main/CLAUDE.md Utilize the factory method for a more configurable client setup. This provides flexibility for advanced configurations. ```php Anthropic::client($apiKey) ``` -------------------------------- ### Configure Anthropic SDK with Symfony HTTP Client Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Initialize the Anthropic SDK using Symfony's PSR-18 compatible client. Ensure the 'symfony/http-client' package is installed. ```php use Symfony\Component\HttpClient\Psr18Client; $client = Anthropic::factory() ->withApiKey('your-api-key') ->withHttpClient(new Psr18Client()) ->make(); ``` -------------------------------- ### GET /models Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/models.md List all available Claude models with support for cursor-based pagination. ```APIDOC ## GET /models ### Description Lists all available Claude models. Supports cursor-based 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 the next page - **before_id** (string) - Optional - Cursor for the previous page ### Response #### Success Response (200) - **data** (array) - List of model objects - **firstId** (string) - ID of the first item in the current page - **lastId** (string) - ID of the last item in the current page - **hasMore** (boolean) - Indicates if more pages are available ``` -------------------------------- ### GET /v1/files Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/files.md Lists files associated with the API key, supporting cursor-based pagination. ```APIDOC ## GET /v1/files ### Description Returns a cursor-paginated list of files in the workspace. ### Method GET ### Endpoint /v1/files ### Query Parameters - **limit** (integer) - Optional - Number of files to return (default 20, max 1000). - **after_id** (string) - Optional - Cursor for pagination to walk forward. - **before_id** (string) - Optional - Cursor for pagination to walk backward. - **scope_id** (string) - Optional - Filter by session scope. ### Response #### Success Response (200) - **data** (array) - List of file objects. - **firstId** (string) - ID of the first file in the page. - **lastId** (string) - ID of the last file in the page. - **hasMore** (boolean) - Whether more pages are available. ``` -------------------------------- ### Enable Automatic PSR-18 Client Discovery Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Configure Composer to allow the 'php-http/discovery' plugin to automatically install a PSR-18 compatible HTTP client if one is not explicitly provided. This simplifies dependency management. ```bash composer config allow-plugins.php-http/discovery true ``` -------------------------------- ### Full Event Sequence Representation Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/streaming.md Example of the data structure returned by toArray() for various event types during a stream. ```php // 1. message_start [ 'type' => 'message_start', 'message' => [ 'id' => 'msg_01SX1jLtTXgtJwB2EpSRNutG', 'type' => 'message', 'role' => 'assistant', 'content' => [], 'model' => 'claude-sonnet-4-6', 'stop_reason' => null, 'stop_sequence' => null, ], 'usage' => [ 'input_tokens' => 9, 'output_tokens' => 1, 'cache_creation_input_tokens' => null, 'cache_read_input_tokens' => null, ], ] // 2. content_block_start [ 'type' => 'content_block_start', 'index' => 0, 'content_block_start' => [ 'type' => 'text', 'text' => '', ], ] // 3-N. content_block_delta (repeated for each chunk) [ 'type' => 'content_block_delta', 'index' => 0, 'delta' => [ 'type' => 'text_delta', 'text' => 'Hello', ], ] // Final: message_delta [ 'type' => 'message_delta', 'delta' => [ 'stop_reason' => 'end_turn', 'stop_sequence' => null, ], 'usage' => [ 'input_tokens' => null, 'output_tokens' => 12, 'cache_creation_input_tokens' => null, 'cache_read_input_tokens' => null, ], ] ``` -------------------------------- ### GET /v1/files/{file_id} Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/files.md Retrieves metadata for a specific file by its ID. ```APIDOC ## GET /v1/files/{file_id} ### Description Retrieves the metadata for a single file. ### Method GET ### Endpoint /v1/files/{file_id} ### Parameters #### Path Parameters - **file_id** (string) - Required - The unique identifier of the file. ### Response #### Success Response (200) - **filename** (string) - The name of the file. - **mimeType** (string) - The MIME type. - **sizeBytes** (integer) - The size in bytes. - **downloadable** (boolean) - Whether the file is downloadable. - **scope** (object) - Optional - Metadata regarding the file's origin (e.g., session). ``` -------------------------------- ### Configure Client with Factory Options Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Use the factory to customize every aspect of the client, including API key, base URI, HTTP client, headers, query parameters, and stream handler. Chain `with*` methods and call `make()` to create the client. ```php $client = Anthropic::factory() ->withApiKey('your-api-key') ->withBaseUri('anthropic.example.com/v1') ->withHttpClient($httpClient) ->withHttpHeader('X-Custom-Header', 'value') ->withQueryParam('my-param', 'bar') ->withStreamHandler($streamHandler) ->make(); ``` -------------------------------- ### Typical Batch Workflow Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/batches.md Illustrates the complete lifecycle of a batch job, from creation to cleanup. ```APIDOC ## Typical Batch Workflow This section outlines the standard process for using batch jobs: 1. **Create the batch**: Initiate a new batch job with a list of requests. 2. **Poll until complete**: Periodically check the status of the batch job until it reaches the 'ended' state. 3. **Process results**: Retrieve and process the results of the completed batch job. 4. **Clean up**: Delete the batch job once its results have been processed. ### Request Example ```php // 1. Create the batch $batch = $client->batches()->create(['requests' => $requests]); // 2. Poll until complete do { sleep(30); $batch = $client->batches()->retrieve($batch->id); } while ($batch->processingStatus !== 'ended'); // 3. Process results $results = $client->batches()->results($batch->id); foreach ($results as $individual) { if ($individual->result->type === 'succeeded') { processResult($individual->customId, $individual->result->message); } } // 4. Clean up $client->batches()->delete($batch->id); ``` For detailed information on batch limits, pricing, and the full API specification, refer to the [Batch processing guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) on the Anthropic documentation site. ``` -------------------------------- ### GET /models/{model_id} Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/models.md Retrieve detailed information about a specific Claude model by its ID. ```APIDOC ## GET /models/{model_id} ### Description Retrieves details about a specific model, including token limits and supported capabilities. ### 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 - **type** (string) - Resource type - **createdAt** (string) - Creation timestamp - **displayName** (string) - Human-readable name - **maxInputTokens** (integer) - Context window size - **maxTokens** (integer) - Maximum output token limit - **capabilities** (object) - Object containing supported features (batch, citations, codeExecution, imageInput, pdfInput, structuredOutputs, thinking, effort) ``` -------------------------------- ### Run project development commands Source: https://github.com/mozex/anthropic-php/blob/main/CLAUDE.md Use these Composer scripts to manage dependencies, lint code, and execute the full test suite. ```bash composer install # Install dependencies composer lint # Fix code style (Pint) composer test # Run ALL checks (lint, types, type-coverage, unit) composer test:unit # Run unit tests only (Pest) composer test:types # Run PHPStan (level max) composer test:type-coverage # Verify 100% type coverage composer test:lint # Check code style without fixing ``` -------------------------------- ### Configure the client Source: https://github.com/mozex/anthropic-php/blob/main/docs/introduction.md Use the factory to customize the client with specific HTTP settings or API endpoints. ```php $client = Anthropic::factory() ->withApiKey('your-api-key') ->withBaseUri('anthropic.example.com/v1') ->withHttpClient(new \GuzzleHttp\Client(['timeout' => 120])) ->withHttpHeader('X-Custom-Header', 'value') ->withQueryParam('my-param', 'bar') ->withStreamHandler(fn ($request) => $httpClient->send($request, [ 'stream' => true, ])) ->make(); ``` -------------------------------- ### Control tool usage behavior Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/tool-use.md Demonstrates how to use the tool_choice parameter to force specific tools, require any tool, or disable tool usage entirely. ```php // Force Claude to use a specific tool $response = $client->messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'tools' => $tools, 'tool_choice' => ['type' => 'tool', 'name' => 'get_weather'], 'messages' => $messages, ]); // Force Claude to use at least one tool (any tool) 'tool_choice' => ['type' => 'any'] // Let Claude decide (default behavior) 'tool_choice' => ['type' => 'auto'] // Prevent Claude from using any tools 'tool_choice' => ['type' => 'none'] ``` -------------------------------- ### Add Custom Query Parameters Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Append query parameters to every request URL. This is useful for routing or analytics parameters required by proxy setups. ```php ->withQueryParam('my-param', 'bar') ``` -------------------------------- ### Enable Code Execution Tool Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/server-tools.md Provide a sandboxed environment for Claude to write and run code by including the code execution tool. ```php $response = $client->messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 4096, 'tools' => [ ['type' => 'code_execution_20250825', 'name' => 'code_execution'], ], 'messages' => [ ['role' => 'user', 'content' => 'Run this Python code: print(sum(range(1, 101)))'], ], ]); ``` -------------------------------- ### Iterate Through Content Blocks - Anthropic PHP Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/messages.md Process the content of a message response, which is an array of typed blocks. This example shows how to access text content. ```php foreach ($response->content as $block) { $block->type; // 'text' $block->text; // 'Hello! It\'s nice to meet you. How can I assist you today?' } ``` -------------------------------- ### Configure global beta header Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/files.md Sets the required beta header globally on the client factory for all requests. ```php $client = Anthropic::factory() ->withApiKey('your-api-key') ->withHttpHeader('anthropic-beta', 'files-api-2025-04-14') ->make(); ``` -------------------------------- ### Convert Response to Array - Anthropic PHP Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/messages.md Use the toArray() method on a response object to get the raw data as a PHP array. Useful for logging or serialization. ```php $response->toArray(); // ['id' => 'msg_01BSy0WCV7QR2adFBauynAX7', 'type' => 'message', ...] ``` -------------------------------- ### Count Basic Message Tokens Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/token-counting.md Use `countTokens()` with basic message parameters to get the input token count. The response object contains an `inputTokens` field. ```php $response = $client->messages()->countTokens([ 'model' => 'claude-sonnet-4-6', 'messages' => [ ['role' => 'user', 'content' => 'Hello, world'], ], ]); $response->inputTokens; // 2095 ``` -------------------------------- ### Handle streamed responses Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/testing.md Simulate streaming by passing a file resource containing SSE data or use the default fixture. ```php use Anthropic\Testing\ClientFake; use Anthropic\Responses\Messages\CreateStreamedResponse; $client = new ClientFake([ CreateStreamedResponse::fake(fopen('tests/fixtures/stream.txt', 'r')), ]); $stream = $client->messages()->createStreamed([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Hello!'], ], ]); expect($stream->getIterator()->current()) ->type->toBe('message_start'); ``` ```php $client = new ClientFake([ CreateStreamedResponse::fake(), ]); ``` -------------------------------- ### Configure Summarized Thinking Display Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/thinking.md Set the 'display' option to 'summarized' to show a summary of Claude's reasoning. This is the default behavior. ```php 'thinking' => [ 'type' => 'adaptive', 'display' => 'summarized', ] ``` -------------------------------- ### Paginate Through Models (Forward) Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/models.md Demonstrates how to paginate through the list of models using cursor-based pagination. Use 'limit' to set the page size (max 1000) and 'after_id' to fetch the next page of results. ```php // First page $page1 = $client->models()->list(['limit' => 5]); // Next page (if more exist) if ($page1->hasMore) { $page2 = $client->models()->list([ 'limit' => 5, 'after_id' => $page1->lastId, ]); } ``` -------------------------------- ### Retrieve a Specific Claude Model Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/models.md Fetches detailed information for a single Claude model by its unique ID. This is useful for getting specific capabilities or token limits for a known model. ```php $response = $client->models()->retrieve('claude-sonnet-4-6'); $response->id; // 'claude-sonnet-4-6' $response->type; // 'model' $response->createdAt; // '2025-05-14T00:00:00Z' $response->displayName; // 'Claude Sonnet 4.6' $response->maxInputTokens; // 200000 $response->maxTokens; // 64000 ``` -------------------------------- ### Configure Client with Guzzle Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Configure the client to use Guzzle, including setting a timeout and connect timeout. The SDK automatically detects Guzzle and handles streaming without needing a custom stream handler. ```php $client = Anthropic::factory() ->withApiKey('your-api-key') ->withHttpClient(new GuzzleHttp\ Client([ 'timeout' => 120, 'connect_timeout' => 5, ])) ->make(); ``` -------------------------------- ### Cancel a Processing Batch Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/batches.md Initiate the cancellation of a batch that is currently in progress. Any requests already being processed will complete, but new requests will not be started. The batch status will change to `canceling` and eventually `ended`. ```php $response = $client->batches()->cancel('msgbatch_04Rka1yCsMLGPnR7kfPdgR8x'); $response->processingStatus; ``` -------------------------------- ### Run All Tests Source: https://github.com/mozex/anthropic-php/blob/main/CONTRIBUTING.md Execute all tests in the project. This includes unit tests and type checks. ```bash composer test ``` -------------------------------- ### Combine Server and Custom Tools Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/server-tools.md Define both server tools (like web search) and custom tools within the `tools` array in a single request. Claude will automatically execute server tools and return custom tool calls for you to handle. ```php $response = $client->messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 4096, 'tools' => [ // Server tool ['type' => 'web_search_20250305', 'name' => 'web_search'], // Your custom tool [ 'name' => 'save_to_database', 'description' => 'Save research findings to the database', 'input_schema' => [ 'type' => 'object', 'properties' => [ 'title' => ['type' => 'string'], 'content' => ['type' => 'string'], ], 'required' => ['title', 'content'], ], ], ], 'messages' => [ ['role' => 'user', 'content' => 'Research the latest PHP release and save your findings.'], ], ]); ``` -------------------------------- ### Iterate Supported Context Management Strategies Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/models.md Access and iterate through all context management strategies supported by the model. New strategy versions are automatically available via date-suffixed keys. ```php $cm = $model->capabilities->contextManagement; $cm->supported; // true if any strategy is supported // Iterate every strategy the server announced foreach ($cm->strategies as $name => $strategy) { $name; // 'clear_thinking_20251015' $strategy->supported; // true } // Or check a specific strategy by its versioned key $cm->strategies['clear_thinking_20251015']?->supported; $cm->strategies['compact_20260112']?->supported; ``` -------------------------------- ### Send a message Source: https://github.com/mozex/anthropic-php/blob/main/docs/introduction.md Initialize the client and send a request to the Messages API. ```php $client = Anthropic::client('your-api-key'); $response = $client->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? ``` -------------------------------- ### Typical Batch Job Workflow Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/batches.md This snippet illustrates the complete lifecycle of a batch job. It includes creating the batch, polling for completion, processing results, and finally cleaning up by deleting the batch. Ensure you have a list of requests prepared before creating the batch. ```php // 1. Create the batch $batch = $client->batches()->create(['requests' => $requests]); // 2. Poll until complete do { sleep(30); $batch = $client->batches()->retrieve($batch->id); } while ($batch->processingStatus !== 'ended'); // 3. Process results $results = $client->batches()->results($batch->id); foreach ($results as $individual) { if ($individual->result->type === 'succeeded') { processResult($individual->customId, $individual->result->message); } } // 4. Clean up $client->batches()->delete($batch->id); ``` -------------------------------- ### Create a Text Completion Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/completions.md Use this to generate a text completion using the legacy API. Ensure the prompt follows the `\n\nHuman:` / `\n\nAssistant:` format. The response object provides access to the completion text, ID, model, and other metadata. ```php $response = $client->completions()->create([ 'model' => 'claude-2.1', 'prompt' => '\n\nHuman: Hello, Claude\n\nAssistant:', 'max_tokens_to_sample' => 100, 'temperature' => 0, ]); $response->type; // 'completion' $response->id; // 'compl_01EKm5HZ9y6khqaSZjsX44fS' $response->completion; // ' Hello! Nice to meet you.' $response->stop_reason; // 'stop_sequence' $response->model; // 'claude-2.1' $response->stop; // '\n\nHuman:' $response->log_id; // 'compl_01EKm5HZ9y6khqaSZjsX44fS' $response->toArray(); // ['id' => 'compl_01EKm5HZ9y6khqaSZjsX44fS', ...] ``` -------------------------------- ### Provide Custom HTTP Client Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Supply your own PSR-18 compatible HTTP client. If not set, 'php-http/discovery' finds one automatically. ```php ->withHttpClient(new GuzzleHttp\Client(['timeout' => 120])) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/mozex/anthropic-php/blob/main/CONTRIBUTING.md Execute only the unit tests for the project. This focuses on testing individual components. ```bash composer test:unit ``` -------------------------------- ### Set API Key Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Provide your API key, which is sent as an 'x-api-key' header. Leading and trailing whitespace is automatically trimmed. ```php ->withApiKey('your-api-key') ``` -------------------------------- ### Accessing Meta Information Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/meta-information.md Demonstrates how to access the meta information object from a response using the `meta()` method. ```APIDOC ## Accessing Meta Information Call `meta()` on any response object to retrieve meta information. ### Method ```php $response = $client->messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Hello, world'], ], ]); $meta = $response->meta(); ``` ### Response Object Structure The `$meta` object provides access to various details: - **requestId**: Unique identifier for the request. - **requestLimit**: Object containing request limit details (`limit`, `remaining`, `reset`). - **tokenLimit**: Object containing token limit details (`limit`, `remaining`, `reset`). - **inputTokenLimit**: Object for input token limits. - **outputTokenLimit**: Object for output token limits. - **priorityInputTokenLimit**: Optional object for Priority Tier input token limits. - **priorityOutputTokenLimit**: Optional object for Priority Tier output token limits. - **custom**: An object containing any additional, non-standard headers. ``` -------------------------------- ### List files Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/files.md Retrieves a paginated list of files associated with the API key. ```php $response = $client->files()->list(['limit' => 20]); foreach ($response->data as $file) { $file->id; $file->filename; $file->sizeBytes; } $response->firstId; // 'file_011CNha8iCJcU1wXNR6q4V8w' $response->lastId; // 'file_011CPMxVD3fHLUhvTqtsQA5w' $response->hasMore; // false ``` -------------------------------- ### Basic Streaming Implementation Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/streaming.md Use createStreamed() to initiate a stream and iterate over the resulting StreamResponse object to access event types. ```php $stream = $client->messages()->createStreamed([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Hello!'], ], ]); foreach ($stream as $response) { echo $response->toArray()['type']; // event type } ``` -------------------------------- ### Track Server Tool Usage in PHP Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/server-tools.md Access server tool usage counts from the response object. These properties will be null if no server tools were used. ```php $response->usage->serverToolUse?->webSearchRequests; // number of web searches $response->usage->serverToolUse?->webFetchRequests; // number of URL fetches $response->usage->serverToolUse?->codeExecutionRequests; // number of code executions $response->usage->serverToolUse?->toolSearchRequests; // number of tool searches ``` -------------------------------- ### Enable Beta Features Globally Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Set beta features globally on the factory for all requests. This avoids repeating the 'anthropic-beta' header configuration for every call. ```php $client = Anthropic::factory() ->withApiKey('your-api-key') ->withHttpHeader('anthropic-beta', 'interleaved-thinking-2025-05-14') ->make(); ``` -------------------------------- ### Access Code Execution Results Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/server-tools.md Retrieve the tool call and execution output, including stdout and return codes. ```php $response->content[0]->type; // 'server_tool_use' $response->content[0]->name; // 'bash_code_execution' $response->content[1]->type; // 'bash_code_execution_tool_result' $response->content[1]->tool_use_id; // 'srvtoolu_01EWAZ5utP321iRHFdsvbWEV' $response->content[1]->content['type']; // 'bash_code_execution_result' $response->content[1]->content['stdout']; // '5050' $response->content[1]->content['return_code']; // 0 ``` -------------------------------- ### Testing with ClientFake Source: https://github.com/mozex/anthropic-php/blob/main/README.md Demonstrates how to use the built-in test client to mock API responses and assert sent requests. ```php use Anthropic\Testing\ClientFake; use Anthropic\Responses\Messages\CreateResponse; $client = new ClientFake([ CreateResponse::fake([ 'content' => [['type' => 'text', 'text' => 'Paris is the capital of France.']], ]), ]); $response = $client->messages()->create([...]); $client->assertSent(Messages::class, function (string $method, array $parameters): bool { return $parameters['model'] === 'claude-sonnet-4-6'; }); ``` -------------------------------- ### Stream messages with tool use Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/streaming.md Initiates a streamed message request with tool definitions. Tool inputs are received as partial JSON fragments that require concatenation. ```php $stream = $client->messages()->createStreamed([ '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 like in San Francisco?'], ], ]); foreach ($stream as $response) { $response->toArray(); } ``` -------------------------------- ### Handle multiple tool calls Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/tool-use.md Iterates through the response content to identify and execute multiple tool calls provided by Claude in a single turn. ```php foreach ($response->content as $block) { if ($block->type === 'tool_use') { // Execute each tool and collect results $results[] = [ 'type' => 'tool_result', 'tool_use_id' => $block->id, 'content' => executeMyTool($block->name, $block->input), ]; } } ``` -------------------------------- ### Configure Web Search Options Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/server-tools.md Customize web search behavior using optional fields like max_uses, domain filtering, 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', 'region' => 'California', 'country' => 'US', 'timezone' => 'America/Los_Angeles', ], ], ] ``` -------------------------------- ### PHP: Multi-turn Conversation with Thinking Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/thinking.md Demonstrates initiating a multi-turn conversation with Claude using the Anthropic PHP SDK, including enabling the 'thinking' feature. The first turn sends a user query, and the second turn includes the full previous response content (with thinking blocks) and a new user query for continuity. ```php $response = $client->messages()->create([ 'model' => 'claude-opus-4-6', 'max_tokens' => 16000, 'thinking' => ['type' => 'adaptive'], 'messages' => [ ['role' => 'user', 'content' => 'Solve x^2 + 5x + 6 = 0'], ], ]); // Second turn: include the full response content (with thinking blocks) $followUp = $client->messages()->create([ 'model' => 'claude-opus-4-6', 'max_tokens' => 16000, 'thinking' => ['type' => 'adaptive'], 'messages' => [ ['role' => 'user', 'content' => 'Solve x^2 + 5x + 6 = 0'], ['role' => 'assistant', 'content' => $response->toArray()['content']], ['role' => 'user', 'content' => 'Now verify by substitution.'], ], ]); ``` -------------------------------- ### Build a Fake Stream from Text Chunks Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/testing.md Use this helper function to create a fake Server-Sent Events (SSE) stream in memory for testing predictable streamed text responses without needing fixture files. It constructs the full SSE event sequence from an array of text parts. ```php function fakeStream(array $parts) { $events = []; $events[] = [ '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], ], ]; foreach ($parts as $part) { $events[] = [ 'type' => 'content_block_delta', 'index' => 0, 'delta' => ['type' => 'text_delta', 'text' => $part], ]; } $events[] = [ 'type' => 'message_delta', 'delta' => ['stop_reason' => 'end_turn', 'stop_sequence' => null], 'usage' => ['output_tokens' => 12], ]; $events[] = ['type' => 'message_stop']; $body = implode("\n\n", array_map( fn (array $event): string => "event: {$event['type']}\ndata: " . json_encode($event), $events, )); $handle = fopen('php://memory', 'r+'); fwrite($handle, $body); rewind($handle); return $handle; } // Use it in a test $client = new ClientFake([ CreateStreamedResponse::fake(fakeStream(['Hello', ', ', 'world!'])), ]); ``` -------------------------------- ### Stream Text Completions Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/completions.md Use this method to receive completions in chunks as they are generated. This is useful for real-time applications where displaying text progressively is desired. Each iteration of the loop yields the next segment of the completion. ```php $stream = $client->completions()->createStreamed([ 'model' => 'claude-2.1', 'prompt' => 'Hi', 'max_tokens_to_sample' => 70, ]); foreach ($stream as $response) { echo $response->completion; } // 'I' ' am' ' very' ' excited' ... ``` -------------------------------- ### Paginate Through Models (Backward) Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/models.md Shows how to paginate backward through the list of models using the 'before_id' parameter. This is useful for navigating to previous pages of results. ```php $previousPage = $client->models()->list([ 'limit' => 5, 'before_id' => $page2->firstId, ]); ``` -------------------------------- ### Execute specific test files Source: https://github.com/mozex/anthropic-php/blob/main/CLAUDE.md Run individual test files using the Pest test runner. ```bash ./vendor/bin/pest tests/Resources/Messages.php ``` -------------------------------- ### Exporting raw header format Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/meta-information.md Convert meta information into an array using original HTTP header names. ```php $meta->toArray(); // [ // 'anthropic-ratelimit-requests-limit' => 3000, // 'anthropic-ratelimit-tokens-limit' => 250000, // 'anthropic-ratelimit-requests-remaining' => 2999, // 'anthropic-ratelimit-tokens-remaining' => 249983, // 'anthropic-ratelimit-requests-reset' => '2024-05-01T13:29:17Z', // 'anthropic-ratelimit-tokens-reset' => '2024-05-01T13:29:17Z', // 'anthropic-ratelimit-input-tokens-limit' => 20000, // 'anthropic-ratelimit-input-tokens-remaining' => 19500, // 'anthropic-ratelimit-input-tokens-reset' => '2024-05-01T13:29:17Z', // 'anthropic-ratelimit-output-tokens-limit' => 5000, // 'anthropic-ratelimit-output-tokens-remaining' => 4900, // 'anthropic-ratelimit-output-tokens-reset' => '2024-05-01T13:29:17Z', // 'request-id' => 'req_012nTzj6kLoP8vZ1SGANvcgR', // ] ``` -------------------------------- ### Enable Web Search Tool Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/server-tools.md Include the web search tool in the tools array when creating a message to allow Claude to perform internet searches. ```php $response = $client->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?'], ], ]); ``` -------------------------------- ### Read tool calls from response Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/tool-use.md Access tool_use content blocks in the response to retrieve the tool name and input arguments. ```php // Claude often explains what it's about to do $response->content[0]->type; // 'text' $response->content[0]->text; // 'I'll check the weather in San Francisco for you.' // Then the tool call itself $response->content[1]->type; // 'tool_use' $response->content[1]->id; // 'toolu_01RnYGkgJusAzXvcySfZ2Dq7' $response->content[1]->name; // 'get_weather' $response->content[1]->input['location']; // 'San Francisco, CA' $response->content[1]->input['unit']; // 'fahrenheit' ``` -------------------------------- ### Assert No Requests Were Sent At All Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/testing.md Call `assertNothingSent` to ensure that no requests have been made to any resource since the `ClientFake` was initialized or the last assertion. ```php $client->assertNothingSent(); ``` -------------------------------- ### Stream messages with thinking Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/streaming.md Enables adaptive thinking in a stream and demonstrates how to access thinking blocks, signatures, and subsequent text deltas. ```php $stream = $client->messages()->createStreamed([ 'model' => 'claude-opus-4-6', 'max_tokens' => 16000, 'thinking' => [ 'type' => 'adaptive', ], 'messages' => [ ['role' => 'user', 'content' => 'What is the greatest common divisor of 1071 and 462?'], ], ]); foreach ($stream as $response) { // Thinking block start $response->content_block_start->type; // 'thinking' // Thinking content arrives incrementally $response->delta->type; // 'thinking_delta' $response->delta->thinking; // 'I need to find the GCD using the Euclidean algorithm...' // Signature sent before thinking block closes $response->delta->type; // 'signature_delta' $response->delta->signature; // 'EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl...' // Then text content follows $response->delta->type; // 'text_delta' $response->delta->text; // 'The greatest common divisor of 1071 and 462 is **21**.' } ``` -------------------------------- ### List All Batches Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/batches.md Retrieve a list of your message batches using cursor-based pagination. The response includes batch data and pagination metadata like `hasMore`, `firstId`, and `lastId` to facilitate fetching subsequent pages. ```php $response = $client->batches()->list(['limit' => 10]); foreach ($response->data as $batch) { $batch->id; $batch->processingStatus; } $response->hasMore; $response->firstId; $response->lastId; ``` -------------------------------- ### Interleaved Thinking with Tool Use Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/thinking.md Adaptive thinking is automatically enabled when using tool use, allowing Claude to reason between tool calls. No additional configuration is needed beyond including both 'thinking' and 'tools' in your request. -------------------------------- ### Enable Beta Features Per Request Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Opt into beta features for a specific request by including a 'betas' array in the parameters. The SDK automatically converts this to an 'anthropic-beta' header. ```php $response = $client->messages()->create([ 'model' => 'claude-opus-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Hello!'], ], 'betas' => [ 'interleaved-thinking-2025-05-14', 'extended-cache-ttl-2025-04-11', ], ]); ``` -------------------------------- ### Count Tokens with Tools Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/token-counting.md Include tool definitions in the `countTokens()` request to accurately account for their contribution to the token count. This ensures that the estimated token usage reflects the full complexity of the request. ```php $response = $client->messages()->countTokens([ 'model' => 'claude-sonnet-4-6', '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 Paris?'], ], ]); $response->inputTokens; // includes tokens from the tool definition ``` -------------------------------- ### Create a Message - Anthropic PHP Source: https://github.com/mozex/anthropic-php/blob/main/docs/usage/messages.md Use this to send a basic message to Claude. Requires a model, max_tokens, and at least one user message. ```php $response = $client->messages()->create([ 'model' => 'claude-sonnet-4-6', 'max_tokens' => 1024, 'messages' => [ ['role' => 'user', 'content' => 'Hello, world'], ], ]); ``` -------------------------------- ### Configure Anthropic SDK with a Custom PSR-18 Client and Stream Handler Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/configuration.md Integrate the Anthropic SDK with a custom PSR-18 HTTP client. A stream handler is crucial for enabling streaming responses; without it, calling `createStreamed()` will result in an exception. ```php $httpClient = new SomeOtherHttpClient(); $client = Anthropic::factory() ->withApiKey('your-api-key') ->withHttpClient($httpClient) ->withStreamHandler(function (RequestInterface $request) use ($httpClient): ResponseInterface { // Your client's way of returning a streaming response return $httpClient->sendRequest($request); }) ->make(); ``` -------------------------------- ### Configuration Source: https://github.com/mozex/anthropic-php/blob/main/README.md Configure the client with custom settings like base URI, timeouts, and HTTP clients. ```php $client = Anthropic::factory() ->withApiKey('your-api-key') ->withBaseUri('anthropic.example.com/v1') ->withHttpClient(new GuzzleHttp\Client(['timeout' => 120])) ->withHttpHeader('X-Custom-Header', 'value') ->make(); ``` -------------------------------- ### Checking rate limits Source: https://github.com/mozex/anthropic-php/blob/main/docs/reference/meta-information.md Access request and token limit statistics from the meta object. ```php $meta->requestLimit->limit; // 3000 (max requests per period) $meta->requestLimit->remaining; // 2999 (requests left) $meta->requestLimit->reset; // '2024-05-01T13:29:17Z' (when the limit resets) ``` ```php $meta->tokenLimit->limit; // 250000 $meta->tokenLimit->remaining; // 249984 $meta->tokenLimit->reset; // '2024-05-01T13:29:17Z' ``` ```php $meta->inputTokenLimit->limit; // 20000 $meta->inputTokenLimit->remaining; // 19500 $meta->inputTokenLimit->reset; // '2024-05-01T13:29:17Z' $meta->outputTokenLimit->limit; // 5000 $meta->outputTokenLimit->remaining; // 4900 $meta->outputTokenLimit->reset; // '2024-05-01T13:29:17Z' ```