PHP code example of ahmadrosid / anthropic-php
1. Go to this page and download the library: Download ahmadrosid/anthropic-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/ */
ahmadrosid / anthropic-php example snippets
use Anthropic\Anthropic;
$client = Anthropic::factory()
->withHeaders([
'anthropic-version' => '2023-06-01', // Required!
'content-type' => 'application/json',
'x-api-key' => env('ANTHROPIC_API_KEY', '')
])
->make();
use Anthropic\Model;
$response = $client->chat()->create([
'model' => Model::CLAUDE_OPUS_4_7,
'max_tokens' => 4096,
'messages' => [
['role' => 'user', 'content' => 'Hello!']
]
]);
$response = $client->chat()->create([
'model' => 'claude-opus-4-7',
'max_tokens' => 4096,
'system' => 'You are a helpful assistant.',
'messages' => [
[
'role' => 'user',
'content' => 'Hello, how are you?'
]
]
]);
$content = $response->choices[0]->message->content;
echo $content;
$model = 'claude-sonnet-4-6';
$max_tokens = 4096;
$temperature = 0;
$systemMessage = 'Always reply with "Hello!"';
$messages = [
[
'role' => 'user',
'content' => 'Hi there...'
]
];
$stream = $client->chat()->createStreamed([
'model' => $model,
'temperature' => $temperature,
'max_tokens' => $max_tokens,
'system' => $systemMessage,
'messages' => $messages,
]);
foreach ($stream as $response) {
$text = $response->choices[0]->delta->content;
echo $text;
}
bash
composer