首页 > 最新动态 > 专家视窗

php开发聊天 接入deepseek

更新时间:2025-06-12 作者:中栖梧桐

第一个问题:php开发聊天 接入deepseek(摘抄一些核心代码)

1、安装

composer require deepseek-php/deepseek-php-client  # 示例命令‌:ml-citation{ref="4" data="citationList"}

2、创建DeepSeek客户端实例

use DeepSeek\DeepSeekClient;  # 若使用官方库‌:ml-citation{ref="4" data="citationList"}
$apiKey = 'YOUR_API_KEY';     # 从环境变量或安全存储读取‌:ml-citation{ref="2,3" data="citationList"}
$client = DeepSeekClient::build($apiKey);  # 官方客户端初始化‌:ml-citation{ref="4" data="citationList"}

3、发送对话请求


$postData = [
    'model' => 'deepseek-chat',  
    'messages' => [
        ['role' => 'system', 'content' => '你是一个助手'],  
        ['role' => 'user', 'content' => '你好']  
    ],
    'temperature' => 1,
    'max_tokens' => 2048,
    'stream' => false  # 非流式模式‌:ml-citation{ref="1,5" data="citationList"}
];
$response = $client->chatCompletions($postData);  # 调用方法‌:ml-citation{ref="5" data="citationList"}

 4、处理响应

if ($response) {
    $result = json_decode($response, true);
    $reply = $result['choices']['message']['content'];
    echo $reply;  # 输出回复内容‌:ml-citation{ref="5,6" data="citationList"}
}

5、启用流输出:

$postData['stream'] = true;
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) {
    echo $data;  # 实时输出流数据
    return strlen($data);
});  # 需自行实现 cURL 流处理‌:ml-citation{ref="1,7" data="citationList"}

6、保存对话记录

file_put_contents('conversation.txt', json_encode($postData) . PHP_EOL, FILE_APPEND);  # 结构化存储‌:ml-citation{ref="1" data="citationList"}

8、错误处理

if (curl_errno($ch)) {
    error_log('cURL Error: ' . curl_error($ch));  # 记录错误日志‌:ml-citation{ref="3" data="citationList"}
}

第一个问题,给出来的都不是具体的代码,都是一些代码片段。

然后问第二个问题:提供一个完整的PHP接入DeepSeek聊天示例

1、基础代码结构


<?php
class DeepSeekChat {
    private $apiUrl = 'https://api.siliconflow.cn/v1/chat/completions';
    private $apiKey;  // 从环境变量获取‌:ml-citation{ref="1,3" data="citationList"}
    private $logFile = 'conversation.log';

    public function __construct() {
        $this->apiKey = getenv('DEEPSEEK_API_KEY');  // 安全读取密钥‌:ml-citation{ref="1,5" data="citationList"}
        if (!file_exists($this->logFile)) {
            touch($this->logFile);
        }
    }

    public function sendMessage($message, $history = []) {
        $messages = array_merge(
            [['role' => 'system', 'content' => '你是有道AI助手']],
            $history,
            [['role' => 'user', 'content' => $message]]
        );

        $postData = [
            'model' => 'deepseek-chat',
            'messages' => $messages,
            'temperature' => 1,
            'max_tokens' => 2048,
            'stream' => false
        ];

        return $this->executeRequest($postData);
    }

    private function executeRequest($data) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->apiUrl,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $this->apiKey
            ],
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true  // 生产环境强制验证‌:ml-citation{ref="3,5" data="citationList"}
        ]);

        $response = curl_exec($ch);
        $this->logConversation($data, $response);

        if (curl_errno($ch)) {
            throw new Exception('API请求失败: ' . curl_error($ch));
        }

        return $this->parseResponse($response);
    }

    private function parseResponse($response) {
        $result = json_decode($response, true);
        if (isset($result['choices']['message']['content'])) {
            return $result['choices']['message']['content'];
        }
        throw new Exception('API响应解析失败');
    }

    private function logConversation($request, $response) {
        $logEntry = json_encode([
            'timestamp' => date('Y-m-d H:i:s'),
            'request' => $request,
            'response' => json_decode($response, true)
        ]) . PHP_EOL;
        file_put_contents($this->logFile, $logEntry, FILE_APPEND);
    }
}

// 使用示例
$chat = new DeepSeekChat();
try {
    $reply = $chat->sendMessage("PHP如何接入DeepSeek?");
    echo "AI回复: " . $reply;
} catch (Exception $e) {
    echo "错误: " . $e->getMessage();
}
?>

这个代码,直接可以用,就很厉害!

2、流式响应拓展方案

在executeRequest 方法中增加流式处理:


public function streamMessage($message) {
    $postData = $this->buildRequestData($message);
    $postData['stream'] = true;  // 启用流式传输‌:ml-citation{ref="1,3" data="citationList"}

    $ch = curl_init();
    // ... 初始化配置同上
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) {
        $lines = explode("\n", $data);
        foreach ($lines as $line) {
            if (strpos($line, 'data: ') === 0) {
                $json = substr($line, 6);
                $response = json_decode($json, true);
                if (isset($response['choices']['delta']['content'])) {
                    echo $response['choices']['delta']['content'];
                    flush();
                }
            }
        }
        return strlen($data);
    });
    curl_exec($ch);
}

3、错误监控

// 在构造函数中增加监控
set_error_handler(function($errno, $errstr) {
    error_log("DeepSeek Error: $errstr");
});

两个问题其实已经给出了答案了。

第三个问题:给我 流式响应扩展方案 的详细代码示例


class DeepSeekChat {
    // ... 保留原有属性和构造函数

    /**
     * 流式对话处理(支持上下文延续)
     * @param string $message 用户输入
     * @param array $history 对话历史(格式:[['role'=>'user', 'content'=>'内容'],...])
     */
    public function streamMessage(string $message, array $history = []) {
        $messages = array_merge(
            [['role' => 'system', 'content' => '你是有道AI助手']],
            $history,
            [['role' => 'user', 'content' => $message]]
        );

        $postData = [
            'model' => 'deepseek-chat',
            'messages' => $messages,
            'temperature' => 1,
            'max_tokens' => 2048,
            'stream' => true  // 启用流式模式‌:ml-citation{ref="1,3" data="citationList"}
        ];

        $this->executeStreamRequest($postData);
    }

    private function executeStreamRequest(array $data) {
        $ch = curl_init();
        try {
            curl_setopt_array($ch, [
                CURLOPT_URL => $this->apiUrl,
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'Authorization: Bearer ' . $this->apiKey
                ],
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($data),
                CURLOPT_WRITEFUNCTION => function($ch, $data) {
                    $this->processStreamChunk($data);  // 处理数据块
                    return strlen($data);
                },
                CURLOPT_SSL_VERIFYPEER => true,  // 强制SSL验证‌:ml-citation{ref="5" data="citationList"}
                CURLOPT_TIMEOUT => 120  // 超时设置‌:ml-citation{ref="3" data="citationList"}
            ]);
            
            if (!curl_exec($ch) && curl_errno($ch)) {
                throw new Exception('流式请求失败: ' . curl_error($ch));
            }
        } finally {
            curl_close($ch);  // 确保释放资源‌:ml-citation{ref="3" data="citationList"}
        }
    }

    private function processStreamChunk(string $chunk) {
        $lines = explode("\n", trim($chunk));
        foreach ($lines as $line) {
            if (strpos($line, 'data: ') === 0) {  // 识别有效数据行‌:ml-citation{ref="6" data="citationList"}
                $jsonStr = substr($line, 6);
                if ($jsonStr === '[DONE]') return;  // 流结束标记‌:ml-citation{ref="3" data="citationList"}
                
                $response = json_decode($jsonStr, true);
                if (isset($response['choices']['delta']['content'])) {
                    echo $response['choices']['delta']['content'];
                    flush();  // 实时输出缓冲区‌:ml-citation{ref="1" data="citationList"}
                }
            }
        }
    }
}

使用示例:


// 初始化对话
$chat = new DeepSeekChat();

// 执行流式请求
try {
    header('Content-Type: text/plain; charset=utf-8');  // 设置HTTP流头‌:ml-citation{ref="3" data="citationList"}
    $chat->streamMessage("用PHP实现快速排序算法");
} catch (Exception $e) {
    error_log("流式错误: " . $e->getMessage());  // 错误日志记录‌:ml-citation{ref="5" data="citationList"}
}

到此,功能基本就全部实现了。

转载请以链接形式注明出处:

本篇文章来源于 "中栖梧桐云" :https://www.womtech.cn

中栖梧桐云 版权与免责声明:

① 凡本网注明“来源:中栖梧桐云”的所有作品,版权均属于中栖梧桐云,版权归中栖梧桐云所有,未经本网授权不得转载、摘编或利用其它方式使用上述作品。已经本网授权使用作品的,应在授权范围内使用,并注明“来源:中栖梧桐云”。违反上述声明者,本网将追究其相关法律责任。

② 凡本网注明“来源:XXX(非中栖梧桐云)”的作品,均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。

③ 本网部分内容来自互联网,如因作品内容、版权和其它问题需要同本网联系的,请在30日内进行。

※ 联系方式:中栖梧桐云 Email:jinostart@126.com

最新活动

分类

立即注册,开启您的0门槛上融媒体云之旅!

免费试用

关注联系我们

微信公众号 微博

联系我们

热门推荐

快速入口

支持与服务

全部行业解决方案

    友情链接

    数字报刊软件 电子报刊软件 中栖梧桐网站地图 北京金启程科技

©2021-2025 中栖梧桐 京ICP备15002495号-2 京公网安备11011402013126

    联系我们

售前电话咨询 13910566257 售后电话咨询 13910426449 更多