PHP code example of alle-ai / anthropic-api-php

1. Go to this page and download the library: Download alle-ai/anthropic-api-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alle-ai / anthropic-api-php example snippets




lleAI\Anthropic\Client;
use AlleAI\Anthropic\Models\Model;

$client = Client::fromApiKey(getenv('ANTHROPIC_API_KEY'));

$response = $client->messages()->create(
    model: Model::CLAUDE_SONNET_4_7,
    maxTokens: 1024,
    messages: [
        ['role' => 'user', 'content' => 'Write a haiku about PHP.'],
    ],
);

echo $response->text();
echo "\n\nUsed {$response->usage->inputTokens} input + {$response->usage->outputTokens} output tokens.\n";

$client = Client::fromEnvironment(); // reads ANTHROPIC_API_KEY

use AlleAI\Anthropic\Http\RetryPolicy;

$client = Client::builder()
    ->withApiKey(getenv('ANTHROPIC_API_KEY'))
    ->withAnthropicVersion('2023-06-01')
    ->withAnthropicBeta('prompt-caching-2024-07-31')
    ->withRetryPolicy(new RetryPolicy(maxAttempts: 5, baseDelay: 1.0))
    ->withTimeout(120.0)
    ->build();

use AlleAI\Anthropic\Streaming\Events\ContentBlockDeltaEvent;
use AlleAI\Anthropic\Streaming\Events\Deltas\TextDelta;

$stream = $client->messages()->stream(
    model: Model::CLAUDE_SONNET_4_7,
    maxTokens: 1024,
    messages: [['role' => 'user', 'content' => 'Tell me a story.']],
);

foreach ($stream as $event) {
    if ($event instanceof ContentBlockDeltaEvent && $event->delta instanceof TextDelta) {
        echo $event->delta->text;
    }
}

$final = $stream->toMessage();   // aggregated MessageResponse
echo "\nDone in {$final->usage->outputTokens} tokens.\n";

use AlleAI\Anthropic\Tools\ClassTool;
use AlleAI\Anthropic\Tools\Schema\Attributes\Enum;
use AlleAI\Anthropic\Tools\Schema\Attributes\Param;
use AlleAI\Anthropic\Tools\ToolSet;

final class GetWeather extends ClassTool
{
    public function name(): string        { return 'get_weather'; }
    public function description(): string { return 'Get current weather'; }

    /** @return array<string, mixed> */
    protected function runTool(
        #[Param('City name')] string $city,
        #[Param('Units')] #[Enum('c', 'f')] string $units = 'c',
    ): array {
        return ['city' => $city, 'temp' => 24, 'units' => $units];
    }
}

$loop = $client->messages()->toolLoop(
    model: Model::CLAUDE_SONNET_4_7,
    maxTokens: 4096,
    messages: [['role' => 'user', 'content' => 'Weather in Accra and Tokyo?']],
    tools: new ToolSet(new GetWeather()),
);

$final = $loop->run();   // automatic tool-call round-trips until end_turn
echo $final->text();

use AlleAI\Anthropic\Messages\Content\ImageBlock;
use AlleAI\Anthropic\Messages\Content\TextBlock;

$response = $client->messages()->create(
    model: Model::CLAUDE_SONNET_4_7,
    maxTokens: 1024,
    messages: [[
        'role' => 'user',
        'content' => [
            ImageBlock::fromFile(__DIR__ . '/diagram.png'),
            TextBlock::of('Describe this diagram.'),
        ],
    ]],
);

use AlleAI\Anthropic\Messages\Content\CacheControl;
use AlleAI\Anthropic\Messages\Content\TextBlock;

$response = $client->messages()->create(
    model: Model::CLAUDE_SONNET_4_7,
    maxTokens: 1024,
    system: [
        TextBlock::of('You are a helpful assistant.'),
        TextBlock::of($longCorpus)->withCacheControl(CacheControl::ephemeral('1h')),
    ],
    messages: [['role' => 'user', 'content' => 'Summarize.']],
);

echo "Cache read: {$response->usage->cacheReadInputTokens}\n";

use AlleAI\Anthropic\Messages\ThinkingConfig;
use AlleAI\Anthropic\Messages\Content\ThinkingBlock;
use AlleAI\Anthropic\Messages\Content\TextBlock;

$response = $client->messages()->create(
    model: Model::CLAUDE_OPUS_4_7,
    maxTokens: 16_000,
    thinking: ThinkingConfig::enabled(budgetTokens: 10_000),
    messages: [['role' => 'user', 'content' => 'Prove there are infinitely many primes.']],
);

foreach ($response->content as $block) {
    if ($block instanceof ThinkingBlock) {
        // internal reasoning — typically logged or hidden from end users
    }
    if ($block instanceof TextBlock) {
        echo $block->text;
    }
}

use AlleAI\Anthropic\Exceptions\AnthropicException;
use AlleAI\Anthropic\Exceptions\AuthenticationException;
use AlleAI\Anthropic\Exceptions\RateLimitException;
use AlleAI\Anthropic\Exceptions\OverloadedException;

try {
    $response = $client->messages()->create(/* ... */);
} catch (AuthenticationException $e) {
    // 401 — bad API key
} catch (RateLimitException $e) {
    // 429 — back off
    sleep($e->retryAfter() ?? 30);
} catch (OverloadedException $e) {
    // 529 — Anthropic capacity issue
} catch (AnthropicException $e) {
    // anything else from this SDK
    error_log('Anthropic API call failed: ' . $e->getMessage());
}

use AlleAI\Anthropic\Auth\BedrockAuth;

$client = Client::builder()
    ->withAuth(BedrockAuth::fromEnvironment(region: 'us-east-1'))
    ->build();

// Use Bedrock model id format:
$response = $client->messages()->create(
    model: 'anthropic.claude-sonnet-4-7-v1:0',
    maxTokens: 1024,
    messages: [['role' => 'user', 'content' => 'Hello']],
);

use AlleAI\Anthropic\Auth\VertexAuth;

$client = Client::builder()
    ->withAuth(VertexAuth::fromEnvironment(
        projectId: 'my-gcp-project',
        region: 'us-east5',
    ))
    ->build();

$response = $client->messages()->create(
    model: 'claude-sonnet-4-7@20260101',  // Vertex publisher format
    maxTokens: 1024,
    messages: [['role' => 'user', 'content' => 'Hello']],
);

use GuzzleHttp\Client as GuzzleClient;

$guzzle = new GuzzleClient([
    'timeout' => 60,
    'proxy' => 'http://corporate-proxy:3128',
]);

$client = Client::builder()
    ->withApiKey(getenv('ANTHROPIC_API_KEY'))
    ->withHttpClient($guzzle)
    ->build();
bash
composer