简介
本文将介绍如何使用 php 调用 deepseek api,实现流式对话并保存对话记录。php 版本使用面向对象的方式实现,代码结构清晰,易于维护。
1. 环境准备
1.1 系统要求
- php 7.0 或更高版本
- php curl 扩展
- 文件写入权限
1.2 项目结构
deepseek-project/ ├── main.php # 主程序 └── conversation.txt # 对话记录文件
2. 完整代码实现
<?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();
3. 代码详解
3.1 类结构
deepseekchat
: 主类,封装所有功能__construct
: 构造函数,初始化日志文件savetofile
: 保存对话记录processstreamingresponse
: 处理流式响应chat
: 主对话循环
3.2 关键功能
文件操作
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 配置
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 ] ]);
3.3 参数说明
model
: 使用的模型名称stream
: 启用流式输出max_tokens
: 最大输出长度 (2048)temperature
: 控制随机性 (0.7)top_p
,top_k
: 采样参数frequency_penalty
: 重复惩罚系数
4. 错误处理
代码包含完整的错误处理机制:
- curl 错误检查
- json 解析错误处理
- 文件操作错误处理
- 异常捕获和日志记录
5. 使用方法
5.1 修改配置
在代码中替换 your_api_key
为你的实际 api key。
5.2 运行程序
php main.php
5.3 交互方式
- 输入问题进行对话
- 输入 ‘q’ 退出程序
- 查看 conversation.txt 获取对话记录
6. 性能优化建议
内存管理
- 使用适当的缓冲区大小
- 及时清理变量
- 避免大量数据积累
文件操作
- 使用文件锁防止并发写入
- 定期清理日志文件
- 考虑使用数据库存储
网络请求
- 设置合理的超时时间
- 使用持久连接
- 处理网络异常
总结
php 版本的 deepseek api 实现采用面向对象方式,代码结构清晰,易于维护和扩展。通过 curl 实现流式处理,提供了良好的交互体验。
到此这篇关于php调用deepseek api的完整指南的文章就介绍到这了,更多相关php调用deepseek api内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论