以下是一个使用PHP调用DeepSeek API进行对话的简单示例。假设DeepSeek API的端点是https://api.deepseek.com/v1/chat,并且你需要一个API密钥来进行身份验证。
$message,
'model' => 'deepseek-chat', // 假设使用的模型名称
'max_tokens' => 50, // 最大生成的token数量
];
// 初始化cURL会话
$ch = curl_init($apiUrl);
// 设置cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
]);
// 执行cURL请求并获取响应
$response = curl_exec($ch);
// 检查是否有错误发生
if (curl_errno($ch)) {
echo 'cURL错误: ' . curl_error($ch);
} else {
// 解析JSON响应
$responseData = json_decode($response, true);
// 检查API响应是否成功
if (isset($responseData['choices'][0]['message']['content'])) {
echo 'DeepSeek回复: ' . $responseData['choices'][0]['message']['content'];
} else {
echo 'API请求失败: ' . print_r($responseData, true);
}
}
// 关闭cURL会话
curl_close($ch);
?>
API端点:$apiUrl是DeepSeek API的URL。
API密钥:$apiKey是你的API密钥,用于身份验证。
请求数据:$data包含要发送的消息、模型名称和生成的最大token数量。
cURL设置:使用cURL发送POST请求,并设置必要的HTTP头。
响应处理:解析API的JSON响应,并输出DeepSeek的回复。
你需要替换your_api_key_here为你的实际API密钥。
确保API端点和请求参数与DeepSeek API文档一致。
你可能需要根据API的响应结构调整代码中的解析逻辑。
将代码保存为一个PHP文件(例如deepseek_chat.php),然后在支持PHP的环境中运行它。