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;

$headers = [
    'anthropic-version' => '2023-06-01',
    'anthropic-beta' => 'messages-2023-12-15',
    'content-type' => 'application/json',
    'x-api-key' => env('ANTHROPIC_API_KEY', '')
];

$client = Anthropic::factory()
    ->withHeaders($headers)
    ->make();

$model = 'claude-3-opus-20240229';
$max_tokens = 4096;
$temperature = 0;
$systemMessage = 'Always reply with "Hello!"';
$messages = [
    [
        'role' => 'user',
        'content' => 'Hi there...'
    ]
];

$response = $client->chat()->create([
    'model' => $model,
    'temperature' => $temperature,
    'max_tokens' => $max_tokens,
    'system' => $systemMessage,
    'messages' => $messages,
]);

$content = $response->choices[0]->message->content;

echo $content;

$model = 'claude-3-opus-20240229';
$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