159人参与 • 2025-02-13 • Php
本文将介绍如何使用 php 调用 deepseek api,实现流式对话并保存对话记录。php 版本使用面向对象的方式实现,代码结构清晰,易于维护。
deepseek-project/ ├── main.php # 主程序 └── conversation.txt # 对话记录文件
<?php
class deepseekchat {
private $url = 'https://api.siliconflow.cn/v1/chat/completions';
private $apikey = 'your_api_key'; // 替换为你的 api key
private $logfile = 'conversation.txt';
public function __construct() {
// 确保日志文件存在且可写
if (!file_exists($this->logfile)) {
touch($this->logfile);
}
}
private function savetofile($content, $isquestion = false) {
$timestamp = date('y-m-d h:i:s');
$text = $isquestion
? "\n[$timestamp] question:\n$content\n\n[$timestamp] answer:\n"
: $content;
file_put_contents($this->logfile, $text, file_append);
}
private function processstreamingresponse($handle) {
$buffer = '';
while (!feof($handle)) {
$chunk = fread($handle, 1024);
$buffer .= $chunk;
// 处理缓冲区中的每一行
while (($pos = strpos($buffer, "\n")) !== false) {
$line = substr($buffer, 0, $pos);
$buffer = substr($buffer, $pos + 1);
if (strlen(trim($line)) > 0) {
if (strpos($line, 'data: ') === 0) {
$data = substr($line, 6); // 移除 "data: " 前缀
if ($data === '[done]') {
continue;
}
$json = json_decode($data, true);
if ($json && isset($json['choices'][0]['delta']['content'])) {
$content = $json['choices'][0]['delta']['content'];
echo $content;
flush();
$this->savetofile($content);
}
}
}
}
}
}
public function chat() {
while (true) {
echo "\n请输入您的问题 (输入 q 退出): ";
$question = trim(fgets(stdin));
if ($question === 'q') {
echo "程序已退出\n";
break;
}
// 保存问题
$this->savetofile($question, true);
// 准备请求数据
$data = [
'model' => 'deepseek-ai/deepseek-v3',
'messages' => [
[
'role' => 'user',
'content' => $question
]
],
'stream' => true,
'max_tokens' => 2048,
'temperature' => 0.7,
'top_p' => 0.7,
'top_k' => 50,
'frequency_penalty' => 0.5,
'n' => 1,
'response_format' => [
'type' => 'text'
]
];
// 准备 curl 请求
$ch = curl_init($this->url);
curl_setopt_array($ch, [
curlopt_post => true,
curlopt_postfields => json_encode($data),
curlopt_returntransfer => true,
curlopt_httpheader => [
'content-type: application/json',
'authorization: bearer ' . $this->apikey
],
curlopt_writefunction => function($ch, $data) {
echo $data;
return strlen($data);
}
]);
try {
// 发送请求并处理响应
$handle = curl_exec($ch);
if (curl_errno($ch)) {
throw new exception(curl_error($ch));
}
// 添加分隔符
echo "\n----------------------------------------\n";
$this->savetofile("\n----------------------------------------\n");
} catch (exception $e) {
$error_msg = "请求错误: " . $e->getmessage() . "\n";
echo $error_msg;
$this->savetofile($error_msg);
} finally {
curl_close($ch);
}
}
}
}
// 运行程序
$chatbot = new deepseekchat();
$chatbot->chat();
deepseekchat: 主类,封装所有功能__construct: 构造函数,初始化日志文件savetofile: 保存对话记录processstreamingresponse: 处理流式响应chat: 主对话循环private function savetofile($content, $isquestion = false) {
$timestamp = date('y-m-d h:i:s');
$text = $isquestion
? "\n[$timestamp] question:\n$content\n\n[$timestamp] answer:\n"
: $content;
file_put_contents($this->logfile, $text, file_append);
}
curl_setopt_array($ch, [
curlopt_post => true,
curlopt_postfields => json_encode($data),
curlopt_returntransfer => true,
curlopt_httpheader => [
'content-type: application/json',
'authorization: bearer ' . $this->apikey
]
]);
model: 使用的模型名称stream: 启用流式输出max_tokens: 最大输出长度 (2048)temperature: 控制随机性 (0.7)top_p, top_k: 采样参数frequency_penalty: 重复惩罚系数代码包含完整的错误处理机制:
在代码中替换 your_api_key 为你的实际 api key。
php main.php
内存管理
文件操作
网络请求
php 版本的 deepseek api 实现采用面向对象方式,代码结构清晰,易于维护和扩展。通过 curl 实现流式处理,提供了良好的交互体验。
到此这篇关于php调用deepseek api的完整指南的文章就介绍到这了,更多相关php调用deepseek api内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论