Anthropic PHP SDK

repository·main·Indexed 41 days ago

https://github.com/anthropics/anthropic-sdk-php

A type-safe, feature-rich PHP interface for interacting with the Anthropic Claude API. Supports Claude Messages, streaming responses via SSE, structured output using PHP classes, and file uploads. Includes specialized clients for the Anthropic AWS gateway and Amazon Bedrock, as well as built-in support for PSR-18 HTTP clients, automatic retries with exponential backoff, and pagination iterators. Requires PHP 8.1.0+.

Tokens
8.8K
Snippets
28
Records
33
Agent score
51%

What's inside Anthropic PHP SDK

  1. Initialize Value Objects

    main

    When working with Value Objects, it is recommended to use the static with constructor and named parameters. Alternatively, you can use builders.

    Example using with: Base64ImageSource::with(data: '...', ...)

    Example using builders: (new Base64ImageSource)->withData('...')

  2. Implement Middleware

    main

    You can intercept every HTTP request by passing middleware to the requestOptions. Middleware can be a callable with the signature callable(RequestInterface $request, callable $next): ResponseInterface or a class implementing Anthropic\Middleware with a handle() method.

    Middleware runs once per HTTP attempt, inside the SDK's retry loop. If a middleware reads a response body, it must rewind it or return a replacement so the SDK can decode it. Middleware can be applied at the client level (all requests) or the request level (single call).

    <?php
    
    use Anthropic\Client;
    use Anthropic\Middleware;
    use Psr\Http\Message\RequestInterface;
    use Psr\Http\Message\ResponseInterface;
    
    // Example: A callable middleware
    $logger = function (RequestInterface $request, callable $next): ResponseInterface {
        error_log("-> {$request->getMethod()} {$request->getUri()}");
        $response = $next($request);
        error_log("<- {$response->getStatusCode()}");
        return $response;
    };
    
    // Example: A class-based middleware
    final class TracingMiddleware implements Middleware
    {
        public function handle(RequestInterface $request, \Closure $next): ResponseInterface
        {
            return $next($request->withHeader('x-trace-id', bin2hex(random_bytes(8))));
        }
    }
    
    // Apply to client-level (all requests)
    $client = new Client(requestOptions: ['middleware' => [$logger, new TracingMiddleware]]);
    
    // Apply to request-level (this call only)
    $client->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      model: 'claude-sonnet-5',
      requestOptions: ['middleware' => [$logger]],
    );
  3. Use Structured Output with PHP classes

    main

    Define a schema by extending Anthropic\Core\Helpers\StructuredOutputModel. Pass the class name in the outputConfig array under the format key. The SDK will automatically convert the class to a JSON schema and parse the response into a typed instance of your class.

    <?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-sonnet-5',
      outputConfig: ['format' => Article::class],
    );
    
    $article = $message->content[0]->parsed; // Returns an Article instance
    echo $article->title;
  4. Install the Claude SDK for PHP

    main

    Install the SDK via Composer. The SDK requires a PSR-18 compliant HTTP client. If you do not have one, install Guzzle.

    composer require "anthropic-ai/sdk:^0.50.0"
    # If you don't have a PSR-18 client, install Guzzle:
    composer require guzzlehttp/guzzle
  5. Stream responses using Server-Sent Events (SSE)

    main

    Use createStream to receive streamed responses. You can iterate over the stream directly, or use a MessageAccumulator to collect the streamed events into a single complete Message object (handling text concatenation, tool input assembly, and usage totals).

    Note: Streaming requests use a streamingTransporter PSR-18 client. If unset, it defaults to the standard transporter. You may need a streaming-capable HTTP client implementation.

    <?php
    
    use Anthropic\Client;
    use Anthropic\Messages\Model;
    use Anthropic\Lib\Streaming\MessageAccumulator;
    
    $client = new Client(
      apiKey: getenv('ANTHROPIC_API_KEY') ?: 'my-anthropic-api-key'
    );
    
    // 1. Basic streaming iteration
    $stream = $client->messages->createStream(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      model: Model::CLAUDE_SONNET_5,
    );
    
    foreach ($stream as $message) {
      var_dump($message);
    }
    
    // 2. Accumulating stream into a single Message object
    $accumulator = MessageAccumulator::forMessages();
    foreach ($stream as $event) {
      $accumulator->accumulate($event);
    }
    
    $message = $accumulator->message(); // Returns Anthropic\Messages\Message
    echo $message->content[0]->text;
  6. Make custom or undocumented requests

    main

    To interact with undocumented endpoints or send extra parameters, you can use the following methods:

    1. Undocumented Parameters: Use extraQueryParams, extraBodyParams, and extraHeaders within the requestOptions array of a standard method call. These override documented parameters of the same name.
    2. Undocumented Endpoints: Use $client->request() to make arbitrary HTTP requests (e.g., POST, GET) to any path while retaining authentication, retries, and other SDK benefits.
    <?php
    
    use Anthropic\Messages\Model;
    
    // 1. Sending extra parameters to a documented endpoint
    $message = $client->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      model: Model::CLAUDE_SONNET_5,
      requestOptions: [
        'extraQueryParams' => ['my_query_parameter' => 'value'],
        'extraBodyParams' => ['my_body_parameter' => 'value'],
        'extraHeaders' => ['my-header' => 'value'],
      ],
    );
    
    // 2. Making a request to an undocumented endpoint
    $response = $client->request(
      method: "post",
      path: '/undocumented/endpoint',
      query: ['dog' => 'woof'],
      headers: ['useful-header' => 'interesting-value'],
      body: ['hello' => 'world']
    );
  7. Upload files using FileParam

    main

    File uploads can be handled by passing a resource from fopen(), a string of file contents, or a Anthropic\Core\FileParam instance. Use FileParam::fromString() or FileParam::fromResource() to wrap your data with necessary metadata like filename and content type.

    <?php
    
    use Anthropic\Core\FileParam;
    
    // Using FileParam::fromString:
    $contents = file_get_contents('/path/to/file');
    $fileMetadata = $client->files->upload(
      file: FileParam::fromString($contents, filename: '/path/to/file', contentType: 'text/plain'),
    );
    
    // Using FileParam::fromResource:
    $fd = fopen('/path/to/file', 'r');
    try {
      $fileMetadata = $client->files->upload(
        file: FileParam::fromResource($fd, filename: '/path/to/file', contentType: 'text/plain'),
      );
    } finally {
      fclose($fd);
    }
  8. Requirements and Versioning for the Anthropic PHP SDK

    main

    The Anthropic PHP SDK requires PHP 8.1.0+.

    The package follows Semantic Versioning (SemVer). Because the library is currently in initial development (major version 0), APIs are subject to change without notice. Improvements to non-runtime PHPDoc type definitions are treated as non-breaking changes.

  9. Get started with Claude Messages

    main

    Initialize the Anthropic\Client with your API key and use the messages->create method to interact with Claude. Note that the SDK uses named parameters for optional arguments; you must set arguments by name to ensure forward compatibility.

    <?php
    
    use Anthropic\Client;
    
    $client = new Client(
      apiKey: getenv('ANTHROPIC_API_KEY') ?: 'my-anthropic-api-key'
    );
    
    $message = $client->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      model: 'claude-opus-4-6',
    );
    
    var_dump($message->content);
  10. Paginate through list results

    main

    List methods in the Anthropic API are paginated. The SDK provides auto-paginating iterators. Use getItems() to iterate over the current page, or pagingEachItem() to automatically fetch all items across all pages via additional network requests.

    <?php
    
    use Anthropic\Client;
    
    $client = new Client(
      apiKey: getenv('ANTHROPIC_API_KEY') ?: 'my-anthropic-api-key'
    );
    
    $page = $client->beta->messages->batches->list(limit: 20);
    
    // Fetch items from the current page only
    foreach ($page->getItems() as $item) {
      var_dump($item->id);
    }
    
    // Fetch items from all pages automatically
    foreach ($page->pagingEachItem() as $item) {
      var_dump($item->id);
    }
  11. Configure request retries

    main

    The SDK automatically retries certain errors (Connection errors, 408, 409, 429, >=500, and timeouts) up to 2 times by default using exponential backoff. You can configure or disable this using the maxRetries option in requestOptions at either the client level or the individual request level.

    <?php
    
    use Anthropic\Client;
    use Anthropic\Messages\Model;
    
    // Configure the default for all requests (e.g., disable retries):
    $client = new Client(requestOptions: ['maxRetries' => 0]);
    
    // Or, configure per-request:
    $result = $client->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      model: Model::CLAUDE_SONNET_5,
      requestOptions: ['maxRetries' => 5],
    );
  12. Configure Foundry Client Base URL and Resource

    main

    The Foundry client determines its baseUrl using one of two methods:

    1. Explicit Base URL: Provide a baseUrl directly via withCredentials() or fromEnvironment().
    2. Resource Name: Provide a resource name. The client will construct the URL using the pattern: https://{resource}.services.ai.azure.com/anthropic/.

    Note: baseUrl and resource are mutually exclusive. If you provide a baseUrl, the resource argument must be null (or not provided).