1. Go to this page and download the library: Download claude-php/claude-3-api 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/ */
claude-php / claude-3-api example snippets
use Claude\Claude3Api\Client;
use Claude\Claude3Api\Config;
// Create a configuration object with your API key
$config = new Config('your-api-key-here');
// Create a client
$client = new Client($config);
// Send a single string message
$response = $client->chat("Hello, Claude");
echo "Claude's response: " . $response->getContent()[0]['text'];
$response = $client->chat([
['role' => 'user', "content" => "Hello, Claude"],
['role' => 'assistant', "content" => "Hello! It's nice to meet you. How can I assist you today?"],
['role' => 'user', "content" => "What is the population of Sydney?"],
]);
echo "Claude's response: " . $response->getContent()[0]['text'];
$client->streamMessage('Hello, how are you?', function ($chunk) {
echo $chunk;
});
$client->streamMessage([
['role' => 'user', "content" => "Hello, Claude"],
['role' => 'assistant', "content" => "Hello! It's nice to meet you. How can I assist you today?"],
['role' => 'user', "content" => "What is the population of Sydney?"],
], function ($chunk) {
echo $chunk;
});
use Claude\Claude3Api\Config;
use Claude\Claude3Api\Client;
$apiKey = 'sk-#############################'; // OpenAI API Key
$config = new Config($apiKey);
$config->useOpenAI();
$client = new Client($config);
$response = $client->chat("Hello, OpenAI");
echo "OpenAI's response: " . $response->getChoices()[0]['message']['content'];
use Claude\Claude3Api\Config;
use Claude\Claude3Api\Client;
$apiKey = 'sk-#############################'; // DeepSeek API Key
$config = new Config($apiKey);
$config->useDeepSeek();
$client = new Client($config);
$response = $client->chat("Hello, DeepSeek");
echo "DeepSeek's response: " . $response->getChoices()[0]['message']['content'];
use Claude\Claude3Api\Config;
use Claude\Claude3Api\Client;
$apiKey = 'sk-#############################'; // Other API Key
$baseUrl = 'https://api.deepseek.com';
$apiVersion = '2023-06-01';
$model = 'deepseek-chat';
$authType = Config::AUTH_TYPE_BEARER; // or Config::AUTH_TYPE_API_KEY
$messagePath = '/chat/completions';
$maxTokens = 8192;
$config = new Config($apiKey, $apiVersion, $baseUrl, $model, $maxTokens, $authType, $messagePath);
$client = new Client($config);
$response = $client->chat("Hello, Other Provider");
echo "Other Provider's response: " . $response->getChoices()[0]['message']['content'];
use Claude\Claude3Api\Models\Message;
use Claude\Claude3Api\Models\Content\TextContent;
use Claude\Claude3Api\Requests\MessageRequest;
// Create a message request
$messageRequest = new MessageRequest();
// Add a user message
$userMessage = new Message('user', [
new TextContent('What is the capital of France?')
]);
$messageRequest->addMessage($userMessage);
// Send the message and get the response
$response = $client->sendMessage($messageRequest);
// Process the response
echo "Claude's response: " . $response->getContent()[0]['text'];
use Claude\Claude3Api\Models\Content\ImageContent;
// Send a message with both image and text
$response = $client->sendMessageWithImage('path/to/image.jpg', 'What is in this image?');
echo "Claude's description: " . $response->getContent()[0]['text'];
use Claude\Claude3Api\Models\Tool;
$weatherTool = new Tool(
'get_weather',
'Get the current weather in a given location',
[
'type' => 'object',
'properties' => [
'location' => [
'type' => 'string',
'description' => 'The city and state, e.g. San Francisco, CA'
],
'unit' => [
'type' => 'string',
'enum' => ['celsius', 'fahrenheit'],
'description' => 'The unit of temperature'
]
],
'e'] === 'text') {
echo "Claude's response: " . $content['text'] . "\n";
} elseif ($content['type'] === 'tool_use') {
echo "Tool used: " . $content['name'] . "\n";
echo "Tool input: " . json_encode($content['input']) . "\n";
// Here you would typically execute the actual tool
// and send the result back to Claude in a new message
}
}
use Claude\Claude3Api\Models\Message;
use Claude\Claude3Api\Models\Content\TextContent;
use Claude\Claude3Api\Models\Content\CacheControl;
use Claude\Claude3Api\Requests\MessageRequest;
// Create a message request
$messageRequest = new MessageRequest();
// Set system message with cacheable content
$systemMessage = new Message('system', [
// Regular system instruction
new TextContent("You are an AI assistant tasked with analyzing literary works."),
// Large text to be cached (e.g., an entire book)
TextContent::withEphemeralCache("<the entire contents of Pride and Prejudice>")
]);
// Add the system message properly
$messageRequest->addSystemMessage($systemMessage);
// Add a user message
$userMessage = new Message('user', [
new TextContent('Analyze the major themes in Pride and Prejudice.')
]);
$messageRequest->addMessage($userMessage);
// Send the message
$response = $client->sendMessage($messageRequest);
// Check if the cache was created
if ($response->createdCache()) {
echo "Created a new cache entry with " . $response->getCacheCreationInputTokens() . " tokens\n";
}
// Process the response
echo "Claude's response: " . $response->getContent()[0]['text'] . "\n";
// --- Send a second request using the same cached content ---
// Create a new message request (the cache will be used automatically)
$messageRequest2 = new MessageRequest();
// Set the exact same system message with the same cache control
$systemMessage2 = new Message('system', [
new TextContent("You are an AI assistant tasked with analyzing literary works."),
TextContent::withEphemeralCache("<the entire contents of Pride and Prejudice>")
]);
// Add the system message properly
$messageRequest2->addSystemMessage($systemMessage2);
// Add a different user message
$userMessage2 = new Message('user', [
new TextContent('Who is the protagonist in Pride and Prejudice and what are their key characteristics?')
]);
$messageRequest2->addMessage($userMessage2);
// Send the second message
$response2 = $client->sendMessage($messageRequest2);
// Check if the cache was used
if ($response2->usedCache()) {
echo "Used cache for " . $response2->getCacheReadInputTokens() . " tokens\n";
echo "Only processed " . $response2->getInputTokens() . " new input tokens\n";
}
// Process the response
echo "Claude's response: " . $response2->getContent()[0]['text'] . "\n";
// Create text content with cache control
$textWithCache = TextContent::withEphemeralCache("Large text to be cached");
// Check cache stats in the response
$response->getCacheCreationInputTokens(); // Tokens written to cache
$response->getCacheReadInputTokens(); // Tokens read from cache
$response->getInputTokens(); // Non-cached tokens
$response->getOutputTokens(); // Output tokens
$response->usedCache(); // Whether the request used cache
$response->createdCache(); // Whether the request created a cache
use Claude\Claude3Api\Config;
use Claude\Claude3Api\Client;
// Method 1: Enable 128k token output with default token setting (131072)
$config = new Config('your-api-key');
$config->enable128kOutputWithTokens();
$client = new Client($config);
// Method 2: Enable 128k token output with custom token limit
$config = new Config('your-api-key');
$config->enable128kOutputWithTokens(100000); // Set to 100k tokens
$client = new Client($config);
// Method 3: Manual configuration
$config = new Config('your-api-key');
$config->enableBetaFeature('output-128k-2025-02-19');
$config->setMaxTokens(131072);
$client = new Client($config);
// Use the client with extended output capacity
$response = $client->chat("Generate a comprehensive report on...");
bash
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.