ThinkPHP 对接 DeepSeek 的教程(以 ThinkPHP 6.x 版本为例)

boyanx1周前技术教程3

一、准备工作

  1. 注册 DeepSeek 账号并获取 API Key
  2. 查看 DeepSeek API 文档(假设接口地址为 https://api.deepseek.com/v1/chat/completions)
  3. 确保已安装 ThinkPHP 6.x
  4. 安装 HTTP 客户端(系统自带):

二、项目配置

1. 配置 API 密钥

在 .env 文件中添加:

2. 创建配置文件

config/deepseek.php:

三、创建服务类

app/service/DeepSeekService.php:

<?php
namespace app\service;

use think\facade\Config;
use think\facade\Http;
use think\exception\HttpResponseException;

class DeepSeekService
{
    protected $apiKey;
    protected $apiUrl;

    public function __construct()
    {
        $config = Config::get('deepseek');
        $this->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:

<?php
namespace app\controller;

use app\BaseController;
use app\service\DeepSeekService;
use think\facade\Request;

class DeepSeek extends BaseController
{
    /**
     * 聊天接口
     * @return \think\Response
     */
    public function chat()
    {
        $prompt = Request::param('prompt', '');
        if (empty($prompt)) {
            return json(['code' => 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(简单示例):

<!DOCTYPE html>
<html>
<head>
    <title>DeepSeek 测试</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
    <textarea id="input" rows="4" cols="50"></textarea>
    <button onclick="sendRequest()">发送</button>
    <div id="result"></div>

    <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>
</body>
</html>

七、测试流程

  1. 启动服务:php think run
  2. 访问 http://localhost:8000/index.html
  3. 输入文本并点击发送
  4. 查看返回结果

八、高级配置

1. 请求超时设置

修改服务类中的 timeout(30) 参数

2. 流式响应处理(需根据 API 支持情况)

3. 频率限制处理

在控制器中添加中间件:

九、注意事项

  1. API密钥必须保密,不要提交到版本库
  2. 生产环境需要添加身份验证中间件
  3. 建议添加请求日志记录
  4. 根据实际 API 返回结构调整响应解析逻辑
  5. 处理可能的 API 响应格式:

以上为完整的对接流程,实际开发中请根据 DeepSeek 官方 API 文档调整参数和响应处理逻辑。

相关文章

Flask 数据可视化

数据可视化是数据处理中的重要部分,前面我们了解了 Flask 的开发和部署,如何用 Flask 做数据可视化呢?今天我们来了解一下。Python 语言极富表达力,并且拥有众多的数据分析库和框架,是数据...

Flask+Pandas+CSV报表实现示例

以下是一个基于 Flask + Pandas + CSV 的简单报表实现示例,包含数据加载、处理和可视化展示:1. 项目结构bashflask-report/├── app.py├── data/│...

57challenges-56个挑战-客户端设计(part4)

上题目:接昨天:https://www.toutiao.com/article/7125986007236936226/昨天解决了前端界面格式化的问题,今天完成把json格式转化为excel表格,并供...

前端架构师成长之路:避免将 JWT 存储在 localStorage 中

看到很多文章介绍将 JWT 存储在 localStorage 中,事实上,个人觉得建议最好不要。这就是将敏感信息存储在 localStorage 中,对于安全问题来说是个挑战,对于客户端的行为在安全问...

57.后端必备的前端技巧

文章目录前言1.jquery的两种按钮点击和发送请求:2.vue中的按钮定义和axios请求:总结前言现在都是前后端分离的开发,很多时候可能后端不会再写html,jquery了,但是一些场景之下后端还...

Spring Boot之集成WebSocket实现前后端通信,这你必须得会!

1. 前言这将又会是干货满满的一期,全程无尿点不废话只抓重点教,具有非常好的学习效果,拿好小板凳准备就坐!希望学习的过程中大家认真听好好学,学习的途中有任何不清楚或疑问的地方皆可评论区留言或私信,bu...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。