<?php
class DeepSeekClient {
private $apiKey;
private $apiUrl = 'https://api.deepseek.com/chat/completions';
private $model = 'deepseek-chat';
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
/**
* 发送普通请求
*/
public function chat($messages, $options = []) {
$defaultOptions = [
'max_tokens' => 1000,
'temperature' => 0.7,
'stream' => false
];
$options = array_merge($defaultOptions, $options);
$data = [
'model' => $this->model,
'messages' => $messages
] + $options;
$ch = curl_init($this->apiUrl);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->apiKey,
'Accept: application/json'
],
CURLOPT_TIMEOUT => 60,
CURLOPT_SSL_VERIFYPEER => false, // 禁用 SSL 验证
CURLOPT_SSL_VERIFYHOST => 0, // 禁用主机名验证
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
throw new Exception('cURL 错误: ' . curl_error($ch));
}
curl_close($ch);
if ($httpCode != 200) {
throw new Exception('API 请求失败,HTTP 代码: ' . $httpCode . ' 响应: ' . $response);
}
return json_decode($response, true);
}
/**
* 流式聊天
*/
public function streamChat($messages, $callback, $options = []) {
$defaultOptions = [
'max_tokens' => 1000,
'temperature' => 0.7,
'stream' => true
];
$options = array_merge($defaultOptions, $options);
$data = [
'model' => $this->model,
'messages' => $messages
] + $options;
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $this->apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->apiKey,
'Accept: text/event-stream'
],
CURLOPT_WRITEFUNCTION => function($ch, $data) use ($callback) {
$lines = explode("\n", $data);
foreach ($lines as $line) {
if (strpos($line, 'data: ') === 0) {
$jsonStr = substr($line, 6);
if ($jsonStr === '[DONE]') {
$callback('', true); // 传输完成
} else if (!empty(trim($jsonStr))) {
$json = json_decode($jsonStr, true);
if (isset($json['choices'][0]['delta']['content'])) {
$callback($json['choices'][0]['delta']['content'], false);
}
}
}
}
return strlen($data);
}
]);
curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception('cURL 错误: ' . curl_error($ch));
}
curl_close($ch);
}
}
// 使用示例
try {
$apiKey = 'sk-********';
$client = new DeepSeekClient($apiKey);
// 普通聊天
$messages = [
['role' => 'system', 'content' => '你是一个中文助手'],
['role' => 'user', 'content' => '请用中文介绍一下你自己']
];
$response = $client->chat($messages);
echo "回答: " . $response['choices'][0]['message']['content'] . PHP_EOL;
// 流式聊天
echo "流式响应: ";
$client->streamChat($messages, function($content, $done) {
if (!$done) {
echo $content;
flush();
} else {
echo PHP_EOL . "--- 结束 ---" . PHP_EOL;
}
});
} catch (Exception $e) {
echo "错误: " . $e->getMessage() . PHP_EOL;
}
?>