| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 | <?phpnamespace app\api\controller;use app\common\controller\Api;/** * AI */class Deepseek extends Api{    protected $noNeedLogin = ['*'];    protected $noNeedRight = ['*'];    public function test()    {        // 这是模拟的文本片段 - 实际应替换为真实的API调用        $textChunks = [            "你好!这是 DeepSeek 的流式文本响应。\n\n",            "我正在逐块返回文本内容。\n",            "这种方式可以实现实时输出效果。\n",            "这种方式可以实现实时输出效果。\n",            "这种方式可以实现实时输出效果。\n",            "这种方式可以实现实时输出效果。\n",            "最后一块内容。\n"        ];        // 逐块输出文本        foreach ($textChunks as $chunk) {            echo $chunk;            ob_flush(); // 刷新PHP输出缓冲区            flush();    // 刷新系统缓冲区            sleep(1); // 暂停0.3秒模拟网络延迟        }    }    public function deepseek(){        $config = config('deepseek');        $apiKey = $config['key']; //        $url = 'https://api.deepseek.com/chat/completions';        $params = input();        $data = [            'model' => $params['model'],            'messages' => $params['messages'],//            "frequency_penalty" => 0,            "max_tokens"        => 2048,            /*"presence_penalty"  => 0,            "response_format"   => [                "type" => $params['type']            ],            "stop"              => null,*/            "stream"            => true,            /*"stream_options"    => null,            "temperature"       => 1,            "top_p"             => 1,            "tools"             => null,            "tool_choice"       => "none",            "logprobs"          => false,            "top_logprobs"      => null*/        ];        // 初始化cURL会话        $ch = curl_init($url);// 设置cURL选项        curl_setopt_array($ch, [            CURLOPT_RETURNTRANSFER => true,            CURLOPT_SSL_VERIFYHOST => false,            CURLOPT_SSL_VERIFYPEER => false,            CURLOPT_POST => true,            CURLOPT_POSTFIELDS => json_encode($data),            CURLOPT_HTTPHEADER => [                'Content-Type: application/json',                'Authorization: Bearer ' . $apiKey,                'Accept: text/event-stream' // 重要:声明接受事件流            ],            CURLOPT_WRITEFUNCTION => function($ch, $data) {                echo $data;                ob_flush();                flush();                return strlen($data); // 返回已处理数据长度            }        ]);        // 执行请求        $response = curl_exec($ch);        // 错误处理        if (curl_errno($ch)) {            echo 'Error: ' . curl_error($ch);        }        // 关闭连接        curl_close($ch);    }}
 |