### Send a Message with System Prompt and Tools Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/MessagesService.md This example demonstrates sending a message with a system prompt to guide the model's behavior and defining tools for the model to use. The system prompt specifies the desired output format for dates and times, and the 'get_time' tool is provided. ```php $message = $client->messages->create( maxTokens: 1024, messages: [ ['role' => 'user', 'content' => 'What time is it?'], ], model: 'claude-opus-4-6', system: 'You are a helpful assistant. Always use ISO 8601 format for dates and times.', tools: [ [ 'name' => 'get_time', 'description' => 'Get the current time', 'input_schema' => [ 'type' => 'object', 'properties' => [], 'required' => [], ], ], ], ); ``` -------------------------------- ### Install Project Dependencies with Composer Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/CONTRIBUTING.md Run this command to install the project's dependencies using Composer. ```sh $ composer install ``` -------------------------------- ### Run Bootstrap Script Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/CONTRIBUTING.md Execute the bootstrap script for initial project setup. ```sh $ ./scripts/bootstrap ``` -------------------------------- ### Complete Structured Output Example Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/StructuredOutputModel.md This example demonstrates a full implementation of a `StructuredOutputModel` for a blog post, including JSON serialization and deserialization, and its usage with the Anthropic client. ```php jsonSerialize(), JSON_UNESCAPED_SLASHES); } public static function fromArray(array $data): static { $instance = new static(); $instance->title = $data['title'] ?? ''; $instance->content = $data['content'] ?? ''; $instance->tags = $data['tags'] ?? []; $instance->author = $data['author'] ?? null; return $instance; } public function jsonSerialize(): array { return [ 'title' => $this->title, 'content' => $this->content, 'tags' => $this->tags, 'author' => $this->author, ]; } } $client = new Client(); $message = $client->messages->create( maxTokens: 2048, messages: [ [ 'role' => 'user', 'content' => 'Write a blog post about PHP 8.3 features', ], ], model: 'claude-opus-4-6', outputConfig: ['format' => BlogPost::class], ); // Access the parsed structured output $post = $message->content[0]->parsed; echo "Title: {$post->title}\n"; echo "Author: {$post->author}\n"; echo "Tags: " . implode(', ', $post->tags) . "\n"; echo "Content:\n{$post->content}\n"; ``` -------------------------------- ### Tool Definition Example Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/types.md Provides an example of defining a tool with its name, description, and input schema, including specifying properties and required fields. ```php $tools = [ [ 'name' => 'get_weather', 'description' => 'Get current weather for a location', 'input_schema' => [ 'type' => 'object', 'properties' => [ 'location' => [ 'type' => 'string', 'description' => 'City name', ], 'unit' => [ 'type' => 'string', 'enum' => ['celsius', 'fahrenheit'], ], ], 'required' => ['location'], ], ], ]; ``` -------------------------------- ### Install Claude SDK for PHP Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/README.md Use Composer to install the SDK. Ensure you are using a version compatible with your project. ```sh composer require "anthropic-ai/sdk:^0.33.0" ``` -------------------------------- ### Response Example with Tool Use Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Message.md Shows the JSON format for a response that includes a tool use request. ```json { "id": "msg_0123456789", "type": "message", "role": "assistant", "content": [ { "type": "tool_use", "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "name": "get_stock_price", "input": { "ticker": "AAPL" } } ], "model": "claude-opus-4-6", "stop_reason": "tool_use", "stop_sequence": null, "usage": { "input_tokens": 20, "output_tokens": 50 } } ``` -------------------------------- ### With Custom Request Options Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/BedrockClient.md Example of initializing the Bedrock Client with custom request options, such as timeout and maximum retries, to fine-tune request behavior. ```APIDOC ## With Custom Request Options ```php $client = \Anthropic\Bedrock\Client::fromEnvironment( region: 'us-east-1', requestOptions: [ 'timeout' => 120.0, 'maxRetries' => 5, ] ); $message = $client->messages->create( maxTokens: 1024, messages: [['role' => 'user', 'content' => 'What is 2+2?']], model: 'claude-opus-4-6', ); ``` ``` -------------------------------- ### Multiple Files Upload Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/FileParam.md Example demonstrating how to upload multiple files in a single request. ```APIDOC ## Multiple Files ```php $files = [ FileParam::fromString("data1", "file1.txt", "text/plain"), FileParam::fromString("data2", "file2.txt", "text/plain"), ]; foreach ($files as $file) { $response = $client->beta->files->upload(file: $file); // Process response } ``` ``` -------------------------------- ### MessageParam Example Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/types.md Illustrates the structure of a MessageParam, showing how to format user and assistant messages, including text and image content blocks. ```php $messages = [ ['role' => 'user', 'content' => 'Hello, Claude'], [ 'role' => 'assistant', 'content' => 'Hi! How can I help you?', ], ['role' => 'user', 'content' => [ ['type' => 'text', 'text' => 'Can you help with...'], ['type' => 'image', 'source' => [...]], ]], ]; ``` -------------------------------- ### Configuring Structured Output Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/types.md Shows examples of configuring the output format for messages, including plain text, JSON, or a custom StructuredOutputModel class. ```php // JSON output $message = $client->messages->create( // ... outputConfig: ['format' => 'json'] ); // Typed output (requires StructuredOutputModel) class Article extends StructuredOutputModel { /* ... */ } $message = $client->messages->create( // ... outputConfig: ['format' => Article::class] ); ``` -------------------------------- ### Upload from File on Disk Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/FileParam.md Example of uploading a file from a disk resource using FileParam::fromResource. ```APIDOC ## Upload from File on Disk ```php use Anthropic\Core\FileParam; $fd = fopen('/path/to/document.pdf', 'r'); try { $response = $client->beta->files->upload( file: FileParam::fromResource( $fd, filename: 'report.pdf', contentType: 'application/pdf' ) ); echo "Uploaded file ID: " . $response->id; } finally { fclose($fd); } ``` ``` -------------------------------- ### Generated JSON Schema Example Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/StructuredOutputModel.md This is an example of the JSON schema that the SDK would generate from the Product class, used by the API for structured output. ```json { "type": "object", "properties": { "name": {"type": "string"}, "price": {"type": "number"}, "tags": { "type": "array", "items": {"type": "string"} } }, "required": ["name", "price", "tags"] } ``` -------------------------------- ### Implementing StructuredOutputModel with description() Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/StructuredOutputModel.md Example of implementing the StructuredOutputModel interface, including the static description() method to provide metadata for the generated JSON schema. ```php class Article implements StructuredOutputModel { public string $title; public string $content; public static function description(): ?string { return 'A blog article with title and content'; } } ``` -------------------------------- ### Transformations in Structured Output Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/StructuredOutputModel.md Add methods to your structured output model to transform or derive data. This example shows how to get a Unix timestamp from an ISO 8601 string. ```php class DateTime implements StructuredOutputModel { public string $iso8601; public function getTimestamp(): int { return (new \DateTime($this->iso8601))->getTimestamp(); } } ``` -------------------------------- ### Simple Text Response Example Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Message.md Illustrates the JSON structure for a basic text response from the API. ```json { "id": "msg_0123456789", "type": "message", "role": "assistant", "content": [ { "type": "text", "text": "The capital of France is Paris." } ], "model": "claude-opus-4-6", "stop_reason": "end_turn", "stop_sequence": null, "usage": { "input_tokens": 10, "output_tokens": 15 } } ``` -------------------------------- ### Basic Message Creation Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/BedrockClient.md Example of creating a basic message using the Bedrock Client. This demonstrates sending a user message and receiving a text response. ```APIDOC ## Basic Message Creation ```php $client = \Anthropic\Bedrock\Client::fromEnvironment(); $message = $client->messages->create( maxTokens: 1024, messages: [['role' => 'user', 'content' => 'Hello, Claude']], model: 'claude-opus-4-6', ); echo $message->content[0]->text; ``` ``` -------------------------------- ### Basic Message Creation Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/BedrockClient.md Example of creating a basic message using the Bedrock client. Ensure you have configured authentication, typically via environment variables. ```php $client = \Anthropic\Bedrock\Client::fromEnvironment(); $message = $client->messages->create( maxTokens: 1024, messages: [['role' => 'user', 'content' => 'Hello, Claude']], model: 'claude-opus-4-6', ); echo $message->content[0]->text; ``` -------------------------------- ### Implement Middleware Interface Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Client.md Implement the `Middleware` interface to create a reusable middleware class. This example adds a trace ID header to requests. ```php final class TracingMiddleware implements Middleware { public function handle(RequestInterface $request, \Closure $next): ResponseInterface { return $next($request->withHeader('x-trace-id', bin2hex(random_bytes(8)))); } } ``` -------------------------------- ### Token Counting Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/BedrockClient.md Example of counting tokens for a given message using the Bedrock Client. This is useful for estimating costs and managing input/output lengths. ```APIDOC ## Token Counting ```php $client = \Anthropic\Bedrock\Client::fromEnvironment(); $tokens = $client->messages->countTokens( messages: [['role' => 'user', 'content' => 'Hello']], model: 'claude-opus-4-6', ); echo "Tokens: " . $tokens->inputTokens; ``` ``` -------------------------------- ### Accessing Message Content Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Message.md Examples demonstrating how to access different types of content within a Message object, such as text, tool calls, and thinking content. ```APIDOC ## Accessing Message Content ### Text Content ```php // Assuming $message is a Message object obtained from an API call $text = null; foreach ($message->content as $block) { if ('text' === $block->type) { $text = $block->text; break; } } echo "Text Content: " . $text; ``` ### Tool Calls ```php // Assuming $message is a Message object obtained from an API call if ('tool_use' === $message->stopReason) { foreach ($message->content as $block) { if ('tool_use' === $block->type) { echo "Tool Name: " . $block->name . "\n"; echo "Tool ID: " . $block->id . "\n"; echo "Tool Input: " . json_encode($block->input) . "\n"; } } } ``` ### Thinking Content When extended thinking is enabled: ```php // Assuming $message is a Message object obtained from an API call foreach ($message->content as $block) { if ('thinking' === $block->type) { echo "Model Thinking:\n{$block->thinking}\n"; } elseif ('text' === $block->type) { echo "Response:\n{$block->text}\n"; } } ``` ### Structured Output When `outputConfig` specifies a structured output format: ```php // Assuming Article is a class extending StructuredOutputModel // Example of creating a message with structured output configuration (actual client call not shown here) // $message = $client->messages->create( // // ... other parameters // outputConfig: ['format' => Article::class] // ); // Accessing the parsed structured output // if (isset($message->content[0]->parsed)) { // $article = $message->content[0]->parsed; // $article will be an instance of Article // // You can now access properties of the $article object // } ``` ``` -------------------------------- ### Error Handling with Anthropic SDK for PHP Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/README.md Provides an example of how to catch specific API exceptions, such as rate limiting or authentication errors, and general API exceptions. Ensure necessary exception classes are imported. ```php use Anthropic\Core\Exceptions\ APIException, Anthropic\Core\Exceptions\ APIConnectionException, Anthropic\Core\Exceptions\ RateLimitException, Anthropic\Core\Exceptions\ AuthenticationException; try { $message = $client->messages->create(...); } catch (RateLimitException $e) { // Handle rate limiting } catch (AuthenticationException $e) { // Handle authentication errors } catch (APIException $e) { // Handle other API errors } ``` -------------------------------- ### Initialize Client with Constructor Options Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/configuration.md Instantiate the `Client` class with various configuration parameters such as API key, authentication token, webhook key, base URL, request options, and credentials. ```php $client = new Client( apiKey: $apiKey, authToken: $authToken, webhookKey: $webhookKey, baseUrl: $baseUrl, requestOptions: $requestOptions, credentials: $credentials, ); ``` -------------------------------- ### Implement Custom Middleware Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/RequestOptions.md Add custom middleware to intercept and modify requests or responses. This example demonstrates caching GET requests. ```php $cachedClient = new \Anthropic\Client( requestOptions: RequestOptions::with( middleware: [ function (\Psr\Http\Message\RequestInterface $req, $next) { // Cache GET requests for 60 seconds if ('GET' === $req->getMethod()) { $cached = $cache->get((string)$req->getUri()); if ($cached) return $cached; } $response = $next($req); if ('GET' === $req->getMethod()) { $cache->set((string)$req->getUri(), $response, 60); } return $response; }, ] ) ); ``` -------------------------------- ### Set up Mock Server with Prism Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/CONTRIBUTING.md Use npx prism to set up a mock server against your OpenAPI specification. This is required for running most tests. ```sh $ npx prism mock path/to/your/openapi.yml ``` -------------------------------- ### Run Project Tests Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/CONTRIBUTING.md Execute the project's test suite. Ensure the mock server is set up before running tests. ```sh $ ./scripts/test ``` -------------------------------- ### Upload from String Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/FileParam.md Example of uploading file content from a string using FileParam::fromString. ```APIDOC ## Upload from String ```php use Anthropic\Core\FileParam; $csvData = "id,value\n1,100\n2,200"; $response = $client->beta->files->upload( file: FileParam::fromString( $csvData, filename: 'data.csv', contentType: 'text/csv' ) ); ``` ``` -------------------------------- ### Configure Bedrock Client with Request Options Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/BedrockClient.md Instantiate the Bedrock Client using environment variables and customize request options like timeout, max retries, and extra headers. ```php $client = \Anthropic\Bedrock\Client::fromEnvironment( requestOptions: RequestOptions::with() ->withTimeout(120.0) ->withMaxRetries(5) ->withExtraHeaders(['X-Custom' => 'value']) ); ``` -------------------------------- ### Upload with Default Content Type Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/FileParam.md Example of uploading files using the default content type. ```APIDOC ## Upload with Default Content Type // Uses DEFAULT_CONTENT_TYPE (application/octet-stream) $fileParam = FileParam::fromString('binary data', 'binary.dat'); // Or from a resource with default content type $fd = fopen('/path/to/file', 'r'); $fileParam = FileParam::fromResource($fd); fclose($fd); ``` -------------------------------- ### Initialize Vertex AI Client Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/configuration.md Use the `Anthropic\Vertex\Client` for Google Vertex AI. Specify the region and project ID. ```php $client = new \Anthropic\Vertex\Client( region: 'us-central1', projectID: 'my-project', ); ``` -------------------------------- ### Create Bedrock Client from Environment Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/BedrockClient.md Instantiate a Bedrock client by automatically detecting AWS credentials and region from the environment. This is useful for local development or when AWS configuration is already set up. ```php $client = \Anthropic\Bedrock\Client::fromEnvironment(); // Or specify region explicitly $client = \Anthropic\Bedrock\Client::fromEnvironment(region: 'us-west-2'); ``` -------------------------------- ### Create RequestOptions Instance Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/RequestOptions.md Instantiate RequestOptions directly. It's generally recommended to use the static `with()` method for creating instances with specific configurations. ```php public function __construct() ``` -------------------------------- ### Create a Message Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/MessagesService.md Send a message and get a response from Claude. This is the primary method for interacting with the Messages API. ```APIDOC ## POST /v1/messages ### Description Send a message and get a response from Claude. This is the primary method for interacting with the Messages API. ### Method POST ### Endpoint /v1/messages ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **maxTokens** (int) - Required - Maximum tokens to generate. Set to `0` to warm the prompt cache without generating. - **messages** (array) - Required - List of message objects with `role` (user/assistant) and `content` (string or array of content blocks) - **model** (Model|string) - Required - Model identifier (e.g., `claude-opus-4-6`) - **cacheControl** (CacheControlEphemeral|array|null) - Optional - Enables prompt caching on the last block - **container** (?string) - Optional - Container identifier for code execution tool reuse - **inferenceGeo** (?string) - Optional - Geographic region for processing (e.g., `us` or `eu`) - **metadata** (Metadata|array|null) - Optional - Custom metadata about the request - **outputConfig** (OutputConfig|array|null) - Optional - Output configuration (e.g., JSON format) - **serviceTier** (ServiceTier|string|null) - Optional - Service tier (standard or priority) - **stopSequences** (?array) - Optional - Custom strings that trigger model stop - **system** (string|array|null) - Optional - System prompt (string or array of blocks) - **temperature** (?float) - Optional - Randomness (0.0 = deterministic, 1.0 = creative) - **thinking** (ThinkingConfigEnabled|array|ThinkingConfigDisabled|ThinkingConfigAdaptive|null) - Optional - Extended thinking configuration - **toolChoice** (ToolChoiceAuto|array|ToolChoiceAny|ToolChoiceTool|ToolChoiceNone|null) - Optional - How the model should use tools - **tools** (?array) - Optional - Tool definitions for model to use - **topK** (?int) - Optional - Sample only from top K tokens - **topP** (?float) - Optional - Nucleus sampling parameter - **userProfileID** (?string) - Optional - User profile ID for attribution - **requestOptions** (RequestOptions|array|null) - Optional - Per-request configuration ### Request Example ```php $message = $client->messages->create( maxTokens: 1024, messages: [ ['role' => 'user', 'content' => 'What is the capital of France?'], ], model: 'claude-opus-4-6', ); echo $message->content[0]->text; // "The capital of France is Paris." ``` ### Response #### Success Response (200) - **content** (array) - The content of the message - **id** (string) - The ID of the message - **model** (string) - The model used to generate the response - **role** (string) - The role of the message sender (assistant) - **stopReason** (string) - The reason the model stopped generating text - **stopSequence** (string|null) - The stop sequence that was triggered, if any - **type** (string) - The type of the message - **usage** (object) - Information about token usage #### Response Example ```json { "id": "msg_01aBcDeFgHiJkLmNoPqRsTuVw", "type": "message", "role": "assistant", "model": "claude-opus-4-6", "content": [ { "type": "text", "text": "The capital of France is Paris." } ], "stop_reason": "end_turn", "stop_sequence": null, "usage": { "input_tokens": 10, "output_tokens": 7 } } ``` **Advanced Example with System Prompt and Tools:** ```php $message = $client->messages->create( maxTokens: 1024, messages: [ ['role' => 'user', 'content' => 'What time is it?'], ], model: 'claude-opus-4-6', system: 'You are a helpful assistant. Always use ISO 8601 format for dates and times.', tools: [ [ 'name' => 'get_time', 'description' => 'Get the current time', 'input_schema' => [ 'type' => 'object', 'properties' => [], 'required' => [], ], ], ], ); ``` ``` -------------------------------- ### Streaming Messages Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/BedrockClient.md Example of streaming message responses from the Bedrock Client. This allows for real-time processing of text as it is generated. ```APIDOC ## Streaming Messages ```php $client = \Anthropic\Bedrock\Client::fromEnvironment(region: 'us-west-2'); $stream = $client->messages->createStream( maxTokens: 1024, messages: [['role' => 'user', 'content' => 'Tell me a story']], model: 'claude-opus-4-6', ); foreach ($stream as $event) { if (isset($event->delta->type) && 'text_delta' === $event->delta->type) { echo $event->delta->text; } } ``` ``` -------------------------------- ### Client Initialization with API Key Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Client.md Initialize the Anthropic client using an API key for authentication. The API key is sent in the 'X-Api-Key' header. ```APIDOC ## Client Initialization with API Key ### Description Initialize the Anthropic client using an API key for authentication. The API key is sent in the 'X-Api-Key' header. ### Method ```php $client = new Client(apiKey: 'sk-ant-...'); ``` ``` -------------------------------- ### Token Counting Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/BedrockClient.md Example of counting tokens for a given message payload. This is useful for estimating costs and managing token limits. ```php $client = \Anthropic\Bedrock\Client::fromEnvironment(); $tokens = $client->messages->countTokens( messages: [['role' => 'user', 'content' => 'Hello']], model: 'claude-opus-4-6', ); echo "Tokens: " . $tokens->inputTokens; ``` -------------------------------- ### Filtering Items Across Pages Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Page.md Apply filtering logic to items as they are iterated from paginated results. This example filters out deprecated models. ```php $page = $client->models->list(limit: 20); foreach ($page->pagingEachItem() as $model) { if (!($model->deprecated ?? false)) { echo $model->id . "\n"; } } ``` -------------------------------- ### Development Configuration Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/configuration.md Configure the client for development using a local mock API. Set max retries to 0 and include debug middleware. ```php $client = new Client( baseUrl: 'http://localhost:8000', // Local mock API requestOptions: RequestOptions::with() ->withMaxRetries(0) // No retries in dev ->withTimeout(30.0) ->withMiddleware([ $debugMiddleware, ]) ); ``` -------------------------------- ### Getting Next Page Request Parameters Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Page.md Retrieve the necessary parameters to request the next page of results using cursor-based pagination. ```php if ($page->lastID) { $nextPage = $client->models->list(afterID: $page->lastID); } ``` -------------------------------- ### Configure Bedrock Client with Custom Endpoint Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/BedrockClient.md Instantiate the Bedrock Client using environment variables and specify a custom base URL for the Bedrock endpoint. ```php $client = \Anthropic\Bedrock\Client::fromEnvironment( baseUrl: 'https://bedrock-runtime.custom-endpoint.com', ); ``` -------------------------------- ### Getting Previous Page Request Parameters Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Page.md Retrieve the necessary parameters to request the previous page of results using cursor-based pagination. ```php if ($page->firstID) { $prevPage = $client->models->list(beforeID: $page->firstID); } ``` -------------------------------- ### Instantiate Anthropic Client Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Client.md Instantiate the client with an API key, using environment variables, or with custom base URL and request options. Ensure at least one authentication parameter is provided or credentials are auto-detected. ```php use Anthropic\Client; // Basic authentication with API key $client = new Client(apiKey: getenv('ANTHROPIC_API_KEY')); // Using environment variables automatically $client = new Client(); // With custom base URL and request options $client = new Client( baseUrl: 'https://custom-proxy.example.com', requestOptions: ['timeout' => 120.0, 'maxRetries' => 5] ); ``` -------------------------------- ### API Key Authentication for Client Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Client.md Instantiate the client using an API key. This sends the key in the X-Api-Key header. ```php $client = new Client(apiKey: 'sk-ant-...'); ``` -------------------------------- ### Upload File from Disk Resource Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/FileParam.md Demonstrates how to upload a file from a disk resource using `FileParam::fromResource`. Ensure the file resource is properly closed after use. ```php use Anthropic\Core\FileParam; $fd = fopen('/path/to/document.pdf', 'r'); try { $response = $client->beta->files->upload( file: FileParam::fromResource( $fd, filename: 'report.pdf', contentType: 'application/pdf' ) ); echo "Uploaded file ID: " . $response->id; } finally { fclose($fd); } ``` -------------------------------- ### Synchronous API Calls with Anthropic SDK for PHP Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/README.md Demonstrates making synchronous API calls for Messages, Models, and token counting. Ensure you have initialized the client with your API key. ```php $client = new Anthropic\Client(apiKey: 'sk-ant-...'); // Messages API $message = $client->messages->create( maxTokens: 1024, messages: [['role' => 'user', 'content' => 'Hello']], model: 'claude-opus-4-6', ); // Models API $model = $client->models->retrieve('claude-opus-4-6'); $models = $client->models->list(); // Token counting $tokens = $client->messages->countTokens( messages: [['role' => 'user', 'content' => 'Hello']], model: 'claude-opus-4-6', ); ``` -------------------------------- ### Create a Message with Claude SDK Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/README.md Initialize the client and send a basic message to Claude. The API key can be set via an environment variable or directly. ```php messages->create( maxTokens: 1024, messages: [['role' => 'user', 'content' => 'Hello, Claude']], model: 'claude-opus-4-6', ); var_dump($message->content); ``` -------------------------------- ### Implementing JsonSerializable for StructuredOutputModel Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/StructuredOutputModel.md Example of implementing the jsonSerialize() method, required by the JsonSerializable interface, to define how the object should be represented as an array for JSON encoding. ```php class Article implements StructuredOutputModel { public string $title; public string $content; public function jsonSerialize(): array { return [ 'title' => $this->title, 'content' => $this->content, ]; } } ``` -------------------------------- ### Get Model Name Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Message.md Access the name of the model that generated the message response. Useful for logging or conditional logic based on the model used. ```php echo $message->model; ``` -------------------------------- ### Page Properties Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Page.md The Page object contains properties to access the data on the current page, check for more pages, and get IDs for cursor-based pagination. ```APIDOC ## Page Properties ### `data` ```php public ?array $data; ``` Array of items on the current page. **Type:** `list|null` **Example:** ```php $page = $client->models->list(); $items = $page->data; // Array of ModelInfo objects ``` ### `hasMore` ```php public ?bool $hasMore; ``` Whether additional pages are available after the current page. **Type:** `bool|null` **Example:** ```php if ($page->hasMore) { // More pages are available } ``` ### `firstID` ```php public ?string $firstID; ``` ID of the first item in the current page. Used for cursor-based pagination going backward (to previous pages). **Type:** `string|null` **Example:** ```php if ($page->firstID) { $prevPage = $client->models->list(beforeID: $page->firstID); } ``` ### `lastID` ```php public ?string $lastID; ``` ID of the last item in the current page. Used for cursor-based pagination going forward (to next pages). **Type:** `string|null` **Example:** ```php if ($page->lastID) { $nextPage = $client->models->list(afterID: $page->lastID); } ``` ``` -------------------------------- ### Upload Multiple Files Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/FileParam.md Demonstrates how to prepare and upload multiple files in a single request by creating an array of `FileParam` objects. ```php $files = [ FileParam::fromString("data1", "file1.txt", "text/plain"), FileParam::fromString("data2", "file2.txt", "text/plain"), ]; foreach ($files as $file) { $response = $client->beta->files->upload(file: $file); // Process response } ``` -------------------------------- ### Create Message with Structured Output Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/MessagesService.md Demonstrates how to create a message and configure the output to be parsed into a specific structured object using `StructuredOutputModel`. ```APIDOC ## Create Message with Structured Output ### Description This example shows how to use the `create` method of the messages client to generate content that will be automatically parsed into a typed object. This is achieved by defining a `StructuredOutputModel` subclass and passing its class name in the `outputConfig`. ### Method `$client->messages->create()` ### Parameters - `maxTokens` (int): The maximum number of tokens to generate. - `messages` (array): An array of message objects, typically including a user message. - `model` (string): The model to use for generation (e.g., 'claude-opus-4-6'). - `outputConfig` (array): Configuration for the output format. Use `['format' => YourStructuredOutputModel::class]` to specify the desired output type. ### Request Example ```php use Anthropic\Core\Helpers\StructuredOutputModel; class Article extends StructuredOutputModel { public string $title; public string $summary; /** @var string[] */ public array $tags; } $message = $client->messages->create( maxTokens: 1024, messages: [['role' => 'user', 'content' => 'Write an article about PHP']], model: 'claude-opus-4-6', outputConfig: ['format' => Article::class], ); $article = $message->content[0]->parsed; // Article instance echo $article->title; ``` ### Response #### Success Response The response will contain a `Message` object. If `outputConfig` is used, the `content` blocks will include a `parsed` property containing an instance of the specified `StructuredOutputModel` subclass. ``` -------------------------------- ### Configuration with Custom Headers Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/configuration.md Configure the client with custom headers, such as request ID, user ID, and client version. ```php $client = new Client( requestOptions: RequestOptions::with() ->withExtraHeaders([ 'X-Request-ID' => uniqid('req_'), 'X-User-ID' => (string)$userId, 'X-Client-Version' => '1.2.3', ]) ); ``` -------------------------------- ### Bedrock Client Constructors Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/BedrockClient.md Provides methods to instantiate the Bedrock Client with different authentication strategies. ```APIDOC ## `fromEnvironment()` ### Description Create a Bedrock client using AWS credentials from the environment. Auto-detects credentials from environment variables, AWS credential files, or AWS roles and metadata services. ### Parameters - **`$region`** (`?string`) - Optional - Resolved from env/config - AWS region (e.g., `us-east-1`) - **`$baseUrl`** (`?string`) - Optional - Constructed from region - Custom Bedrock endpoint URL - **`$requestOptions`** (`RequestOptions|array|null`) - Optional - `null` - Request configuration ### Returns `Bedrock\Client` instance ### Throws `InvalidArgumentException` if region cannot be resolved ### Example ```php // Auto-detect credentials and region $client = \Anthropic\Bedrock\Client::fromEnvironment(); // Or specify region explicitly $client = \Anthropic\Bedrock\Client::fromEnvironment(region: 'us-west-2'); ``` ## `withCredentials()` ### Description Create a Bedrock client with explicit AWS credentials. ### Parameters - **`$accessKeyId`** (`string`) - Required - AWS access key ID (20-character alphanumeric) - **`$secretAccessKey`** (`string`) - Required - AWS secret access key - **`$region`** (`?string`) - Optional - `us-east-1` - AWS region - **`$securityToken`** (`?string`) - Optional - `null` - Temporary security token (for session credentials) - **`$baseUrl`** (`?string`) - Optional - Constructed from region - Custom Bedrock endpoint URL - **`$requestOptions`** (`RequestOptions|array|null`) - Optional - `null` - Request configuration ### Returns `Bedrock\Client` instance ### Example ```php $client = \Anthropic\Bedrock\Client::withCredentials( accessKeyId: 'AKIA1234567890ABCDEF', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', region: 'us-west-2', ); // With temporary credentials $client = \Anthropic\Bedrock\Client::withCredentials( accessKeyId: 'ASIA1234567890ABCDEF', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', securityToken: 'AQoDYXdzEJr...', region: 'us-east-1', ); ``` ## `withApiKey()` ### Description Create a Bedrock client using an AWS bearer token from the Bedrock API. ### Parameters - **`$apiKey`** (`string`) - Required - AWS Bedrock bearer token - **`$region`** (`?string`) - Optional - `us-east-1` - AWS region - **`$baseUrl`** (`?string`) - Optional - Constructed from region - Custom Bedrock endpoint URL - **`$requestOptions`** (`RequestOptions|array|null`) - Optional - `null` - Request configuration ### Returns `Bedrock\Client` instance ### Notes - The bearer token is sent in the `Authorization: Bearer` header - This method does not perform AWS SigV4 request signing ### Example ```php $client = \Anthropic\Bedrock\Client::withApiKey( apiKey: 'bearer_token_from_bedrock_api', region: 'us-east-1', ); ``` ``` -------------------------------- ### Get Items from Current Page Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Page.md Retrieve all items present on the current page as a standard PHP array. This is useful for iterating or processing the current batch of data. ```php $page = $client->models->list(limit: 10); $models = $page->getItems(); foreach ($models as $model) { echo $model->id . "\n"; } ``` -------------------------------- ### Client-Level Middleware Configuration Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Middleware.md Configure middleware to run for all requests made by the client. Pass an array of middleware instances to the `requestOptions` when creating the `Client`. ```php $client = new Client( requestOptions: ['middleware' => [$clientMiddleware]] ); ``` -------------------------------- ### Getting Detailed Error Information from APIStatusException Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/errors.md Illustrates how to extract specific details like status code, message, error type, and JSON error body from an APIStatusException. ```php try { $message = $client->messages->create(...); } catch (APIStatusException $e) { echo "Status: " . $e->status . "\n"; echo "Message: " . $e->getMessage() . "\n"; if (is_array($e->body)) { echo "Error type: " . ($e->body['error']['type'] ?? 'unknown') . "\n"; echo "Error details: " . json_encode($e->body['error']) . "\n"; } } ``` -------------------------------- ### Configure RequestOptions with Specific Settings Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/RequestOptions.md Use the static `with()` method to create a new RequestOptions instance with specified configurations for timeouts, retries, headers, and more. This is the recommended approach. ```php $options = new RequestOptions(); $options->withTimeout(120.0) ->withMaxRetries(5); ``` ```php $options = RequestOptions::with( timeout: 120.0, maxRetries: 5, extraHeaders: ['X-Custom-Header' => 'value'], ); ``` -------------------------------- ### Response Caching Middleware Implementation Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Middleware.md Implement a caching middleware to store and retrieve responses for GET requests. This can significantly reduce API call volume for frequently accessed, non-changing data. ```php final class CachingMiddleware implements Middleware { private array $cache = []; public function handle(RequestInterface $request, \Closure $next): ResponseInterface { $key = (string)$request->getUri(); // Return cached response for GET requests if ('GET' === $request->getMethod() && isset($this->cache[$key])) { return $this->cache[$key]; } $response = $next($request); // Cache successful GET responses if ('GET' === $request->getMethod() && 200 === $response->getStatusCode()) { $this->cache[$key] = $response; } return $response; } } ``` -------------------------------- ### RequestOptions Constructor Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/RequestOptions.md Creates a new RequestOptions instance. It's generally recommended to use the static `with()` method for creating instances. ```APIDOC ## __construct() ### Description Creates a new RequestOptions instance. Typically, use the static `with()` method instead. ### Example ```php $options = new RequestOptions(); $options->withTimeout(120.0) ->withMaxRetries(5); ``` ``` -------------------------------- ### Per-Request Option Override Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Client.md Override client-level request options for a specific API call by providing options directly to the request method. This example disables retries for a single message creation request. ```php // Per-request options $message = $client->messages->create( maxTokens: 1024, messages: [['role' => 'user', 'content' => 'Hello']], model: 'claude-opus-4-6', requestOptions: ['maxRetries' => 0], ); ``` -------------------------------- ### Production Configuration Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/configuration.md Configure the client for production with specific retry and timeout settings, and custom headers and middleware. ```php $client = new Client( requestOptions: RequestOptions::with() ->withMaxRetries(5) ->withTimeout(120.0) ->withInitialRetryDelay(1.0) ->withMaxRetryDelay(30.0) ->withExtraHeaders([ 'X-Application' => 'my-app', 'X-Version' => '1.0', ]) ->withMiddleware([ $metricsMiddleware, $loggingMiddleware, ]) ); ``` -------------------------------- ### Basic Usage of Structured Output Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/StructuredOutputModel.md Demonstrates how to use a custom class implementing StructuredOutputModel to receive structured data from the Messages API. ```APIDOC ## Basic Usage of Structured Output This example shows how to define a custom class `Article` that implements `StructuredOutputModel` and use it with the `client.messages.create` method to get structured output. ### Class Definition ```php class Article implements StructuredOutputModel { public string $title; public string $summary; public static function description(): ?string { return 'A newspaper article with title and summary'; } // ... implement required methods } ``` ### API Call ```php $message = $client->messages->create( maxTokens: 1024, messages: [['role' => 'user', 'content' => 'Summarize the latest tech news']], model: 'claude-opus-4-6', outputConfig: ['format' => Article::class], ); // Accessing the parsed structured output $article = $message->content[0]->parsed; // Article instance echo $article->title; echo $article->summary; ``` ### Response Handling The response content will have a `parsed` property containing an instance of your `Article` class, allowing direct access to its properties like `$title` and `$summary`. ``` -------------------------------- ### Generating Structured Output with Anthropic SDK for PHP Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/README.md Illustrates how to specify a structured output format for API responses using the `outputConfig` parameter. The response content will be parsed into the specified class. ```php class Article implements StructuredOutputModel { /* ... */ } $message = $client->messages->create( maxTokens: 1024, messages: [...], model: 'claude-opus-4-6', outputConfig: ['format' => Article::class], ); $article = $message->content[0]->parsed; ``` -------------------------------- ### Client Constructor Source: https://github.com/anthropics/anthropic-sdk-php/blob/main/_autodocs/api-reference/Client.md Instantiate the Anthropic API client with various configuration options including API keys, base URLs, and request options. ```APIDOC ## `__construct()` ### Description Creates a new Anthropic API client instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Parameters - **`$apiKey`** (`?string`) - Optional - API key for authentication. Reads `ANTHROPIC_API_KEY` env var if not provided. - **`$authToken`** (`?string`) - Optional - Bearer token for authentication (OAuth). Reads `ANTHROPIC_AUTH_TOKEN` env var if not provided. - **`$webhookKey`** (`?string`) - Optional - Key for verifying webhook signatures. Reads `ANTHROPIC_WEBHOOK_SIGNING_KEY` env var if not provided. - **`$baseUrl`** (`?string`) - Optional - Base URL for API requests. Defaults to `https://api.anthropic.com`. - **`$requestOptions`** (`RequestOptions|array|null`) - Optional - Request configuration options (e.g., `timeout`, `maxRetries`). - **`$credentials`** (`?CredentialResult`) - Optional - OAuth credentials for automatic token refresh. ### Notes - At least one of `$apiKey` or `$authToken` is required for API authentication. - The client automatically discovers credentials from environment variables and cloud provider metadata if not explicitly provided. - Custom headers can be provided via the `ANTHROPIC_CUSTOM_HEADERS` environment variable. ### Example ```php use Anthropic\Client; // Basic authentication with API key $client = new Client(apiKey: getenv('ANTHROPIC_API_KEY')); // Using environment variables automatically $client = new Client(); // With custom base URL and request options $client = new Client( baseUrl: 'https://custom-proxy.example.com', requestOptions: ['timeout' => 120.0, 'maxRetries' => 5] ); ``` ```