一、准备工作
- 注册 DeepSeek 账号并获取 API Key
- 查看 DeepSeek API 文档(假设接口地址为 https://api.deepseek.com/v1/chat/completions)
- 确保已安装 ThinkPHP 6.x
- 安装 HTTP 客户端(系统自带):
二、项目配置
1. 配置 API 密钥
在 .env 文件中添加:
2. 创建配置文件
config/deepseek.php:
三、创建服务类
app/service/DeepSeekService.php:
apiKey = $config['api_key'];
$this->apiUrl = $config['api_url'];
}
/**
* 发送请求到 DeepSeek
* @param string $prompt 用户输入
* @param array $params 额外参数
* @return array
*/
public function chatCompletion(string $prompt, array $params = [])
{
try {
$headers = [
'Authorization' => 'Bearer ' . $this->apiKey,
'Content-Type' => 'application/json'
];
$defaultData = [
'model' => 'deepseek-chat', // 根据实际模型修改
'messages' => [
['role' => 'user', 'content' => $prompt]
],
'temperature' => 0.7
];
$data = array_merge($defaultData, $params);
$response = Http::withHeaders($headers)
->timeout(30)
->post($this->apiUrl, json_encode($data));
if ($response->statusCode() !== 200) {
throw new \Exception('API 请求失败:' . $response->getReasonPhrase());
}
return json_decode($response->getBody(), true);
} catch (\Throwable $e) {
throw new HttpResponseException(
json(['code' => 500, 'msg' => '服务异常:' . $e->getMessage()])
);
}
}
}
四、创建控制器
app/controller/DeepSeek.php:
400, 'msg' => '请输入有效内容']);
}
try {
$service = new DeepSeekService();
$response = $service->chatCompletion($prompt, [
'max_tokens' => 1000 // 自定义参数
]);
// 解析响应(根据实际 API 返回结构调整)
$result = $response['choices'][0]['message']['content'] ?? '';
return json([
'code' => 200,
'data' => $result
]);
} catch (\Exception $e) {
return json(['code' => 500, 'msg' => $e->getMessage()]);
}
}
}
五、路由配置
route/app.php:
六、前端示例
public/index.html(简单示例):
DeepSeek 测试
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
function sendRequest() {
const prompt = $('#input').val();
$('#result').html('请求中...');
$.post('/deepseek/chat', {prompt: prompt}, function(res) {
if(res.code === 200) {
$('#result').text(res.data);
} else {
$('#result').text('错误:' + res.msg);
}
}).fail(() => {
$('#result').text('请求失败');
});
}
</script>
七、测试流程
- 启动服务:php think run
- 访问 http://localhost:8000/index.html
- 输入文本并点击发送
- 查看返回结果
八、高级配置
1. 请求超时设置
修改服务类中的 timeout(30) 参数
2. 流式响应处理(需根据 API 支持情况)
3. 频率限制处理
在控制器中添加中间件:
九、注意事项
- API密钥必须保密,不要提交到版本库
- 生产环境需要添加身份验证中间件
- 建议添加请求日志记录
- 根据实际 API 返回结构调整响应解析逻辑
- 处理可能的 API 响应格式:
以上为完整的对接流程,实际开发中请根据 DeepSeek 官方 API 文档调整参数和响应处理逻辑。