Skip to content

参考数据:Claude API 参考 — PHP ​

Data: Claude API reference — PHP

v2.1.63

PHP SDK reference

Claude API — PHP ​

注意: PHP SDK 是 Anthropic 官方的 PHP SDK。暂不支持 tool runner 和 Agent SDK。支持 Bedrock、Vertex AI 和 Foundry 客户端。

安装 ​

bash
composer require "anthropic-ai/sdk"

客户端初始化 ​

php
use Anthropic\Client;

// 使用环境变量中的 API key
$client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));

Amazon Bedrock ​

php
use Anthropic\BedrockClient;

$client = new BedrockClient(
    region: 'us-east-1',
);

Google Vertex AI ​

php
use Anthropic\VertexClient;

$client = new VertexClient(
    region: 'us-east5',
    projectId: 'my-project-id',
);

Anthropic Foundry ​

php
use Anthropic\FoundryClient;

$client = new FoundryClient(
    authToken: getenv("ANTHROPIC_AUTH_TOKEN"),
);

基础消息请求 ​

php
$message = $client->messages->create(
    model: '{\{OPUS_ID}\}',
    maxTokens: 1024,
    messages: [
        ['role' => 'user', 'content' => 'What is the capital of France?'],
    ],
);
echo $message->content[0]->text;

流式传输 ​

php
$stream = $client->messages->createStream(
    model: '{\{OPUS_ID}\}',
    maxTokens: 1024,
    messages: [
        ['role' => 'user', 'content' => 'Write a haiku'],
    ],
);

foreach ($stream as $event) {
    echo $event;
}

工具使用(手动循环) ​

PHP SDK 通过 JSON schema 支持原始工具定义。有关工具定义格式和 agentic loop 模式,请参阅共享的工具使用概念。


英文原文 / English Original

Claude API — PHP ​

Note: The PHP SDK is the official Anthropic SDK for PHP. Tool runner and Agent SDK are not available. Bedrock, Vertex AI, and Foundry clients are supported.

Installation ​

bash
composer require "anthropic-ai/sdk"

Client Initialization ​

php
use Anthropic\\Client;

// Using API key from environment variable
$client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));

Amazon Bedrock ​

php
use Anthropic\\BedrockClient;

$client = new BedrockClient(
    region: 'us-east-1',
);

Google Vertex AI ​

php
use Anthropic\\VertexClient;

$client = new VertexClient(
    region: 'us-east5',
    projectId: 'my-project-id',
);

Anthropic Foundry ​

php
use Anthropic\\FoundryClient;

$client = new FoundryClient(
    authToken: getenv("ANTHROPIC_AUTH_TOKEN"),
);

Basic Message Request ​

php
$message = $client->messages->create(
    model: '{\{OPUS_ID}\}',
    maxTokens: 1024,
    messages: [
        ['role' => 'user', 'content' => 'What is the capital of France?'],
    ],
);
echo $message->content[0]->text;

Streaming ​

php
$stream = $client->messages->createStream(
    model: '{\{OPUS_ID}\}',
    maxTokens: 1024,
    messages: [
        ['role' => 'user', 'content' => 'Write a haiku'],
    ],
);

foreach ($stream as $event) {
    echo $event;
}

Tool Use (Manual Loop) ​

The PHP SDK supports raw tool definitions via JSON schema. See the shared tool use concepts for the tool definition format and agentic loop pattern.