使用 PHP 的 curl 扩展来发送 API 请求。以下是一个简单的 PHP 脚本,它向 Claude AI 发送一个消息并接收一个响应:
<?php
$apiKey = 'YOUR_CLAUDE_AI_API_KEY';
$modelId = 'claude-3-5-sonnet-20240620'; // 替换为你想要使用的模型
// 创建一个cURL资源
$ch = curl_init();
// 设置URL和相应的头文件
curl_setopt($ch, CURLOPT_URL, "https://api.anthropic.com/v1/messages");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/json',
'Content-Type: application/json',
'anthropic-version: 2023-06-01',
'x-api-key: ' . $apiKey
]);
// 要发送的数据
$data = [
"max_tokens" => 1024,
"messages" => [[ "role"=> "user", "content"=> "Hello, Claude" ]],
"stream" => false,
"model" => $modelId
];
$data_string = json_encode($data);
// 发送数据
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
// 接收返回的json response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 执行cURL请求
$response = curl_exec($ch);
// 关闭cURL资源,并释放系统资源
curl_close($ch);
// 处理返回的数据
$result = json_decode($response, true);
// 输出结果
print_r($result);
?>
将 'YOUR_CLAUDE_AI_API_KEY' 替换为你的实际 API 密钥,并根据需要调整 $messages 中的 'content' 部分。


0 个评论