<?php
namespace app\controller;
use support\Request;
use Webman\Openai\Chat;
use Workerman\Protocols\Http\Chunk;
class ChatController
{
public function completions(Request $request)
{
$connection = $request->connection;
// https://api.openai.com 國內(nèi)訪問不到的話可以用地址 https://api.openai-proxy.com 替代
$chat = new Chat(['apikey' => 'sk-xx', 'api' => 'https://api.openai.com']);
$chat->completions(
[
'model' => 'gpt-3.5-turbo',
'stream' => true,
'messages' => [['role' => 'user', 'content' => 'hello']],
], [
'stream' => function($data) use ($connection) {
// 當(dāng)openai接口返回數(shù)據(jù)時轉(zhuǎn)發(fā)給瀏覽器
$connection->send(new Chunk(json_encode($data, JSON_UNESCAPED_UNICODE) . "\n"));
},
'complete' => function($result, $response) use ($connection) {
// 響應(yīng)結(jié)束時檢查是否有錯誤
if (isset($result['error'])) {
$connection->send(new Chunk(json_encode($result, JSON_UNESCAPED_UNICODE) . "\n"));
}
// 返回空的chunk代表響應(yīng)結(jié)束
$connection->send(new Chunk(''));
},
]);
// 先返回一個http頭,后面數(shù)據(jù)異步返回
return response()->withHeaders([
"Transfer-Encoding" => "chunked",
]);
}
}
命令行里怎么獲取 $connection 對象
use Workerman\Connection\TcpConnection;
大神,怎么 new 這個對象呢
public function __construct(EventInterface $eventLoop, $socket, string $remoteAddress = '')
這三個參數(shù)不知道傳什么
protected function execute(InputInterface $input, OutputInterface $output): int
{
$chat = new Chat(['apikey' => 'sk-xxxx', 'api' => 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions']);
$chat->completions(
[
'model' => 'qwen-max',
'stream' => true,
'messages' => [['role' => 'user', 'content' => 'hello']],
], [
'stream' => function($data) {
echo " ---------- data start ----------";
print($data);
echo " ---------- data end ----------";
},
'complete' => function($result, $response) {
echo " ---------- result start ----------";
print_r($result);
echo " ---------- result end ----------";
},
]);
return self::SUCCESS;
}
哦我理解了,不在控制器里用的時候,用不到 $connection 對象
我在 command 里的代碼類似這樣,但是報錯:
[RuntimeException]
Timer can only be used in workerman running environment