php开发聊天 接入deepseek

用魔法打败魔法,通过Deepseek生成代码,最终功能实现了:

第一个问题: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"}
}
复制代码

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

打完收工!

 

posted @   帅到要去报警  阅读(92)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示