webman框架实现类chatgpt问答流式对话
使用php框架webman的SSE技术实现类chatgpt问答流式对话(可根据业务需求调整对接不同的第三方:文心一言,Kimi等)
代码实例
需要用到 guzzlehttp/guzzle 库,使用composer安装
composer require guzzlehttp/guzzle
1、路由
// 对话助手(流式响应)-路由
Route::get('/aigc/chat', [StreamController::class, 'dataAnalysisStream']);
2、Controller层(StreamController)
use support\Request;
use support\Response;
use Workerman\Connection\TcpConnection;
use app\interfaces\impl\InfiniteInquiryImpl;
class StreamController extends BaseController
{
//发起请求类
private InfiniteInquiryImpl $infiniteInquiryImpl;
public function __construct()
{
$this->infiniteInquiryImpl = new InfiniteInquiryImpl();
}
//请求处理方法
public function dataAnalysisStream(Request $request): Response
{
//获取问题参数
$question = $request->get('message', '');
/**
* 第三方接口(流式响应)
* 可修改为其他第三方接口
**/
$response_body = $this->infiniteInquiryImpl->dataAnalysisStream($question);
$connection = $request->connection;
//每秒检查连接状态,可修改此值
$id = Timer::add(1, function () use ($connection, &$id, $response_body) {
if ($connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
Timer::del($id);
}
//对返回的响应进行循环输出给客户端
while (!$response_body->eof()) {
$chunk = $response_body->read(1024);
$connection->send($chunk, true);
}
});
$headers = [
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
'Connection' => 'keep-alive',
];
return response('', 200, $headers);
}
}
3、Service请求层(InfiniteInquiryImpl)
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\StreamInterface;
use support\Log;
use WebmanTech\LaravelHttpClient\Facades\Http;
class InfiniteInquiryImpl
{
private Client $client;
public function __construct()
{
$this->client = new Client([
// 超时时间
'timeout' => 60,
// 关闭ssl校验
'verify' => false,
// 开启流式响应
'stream' => true
]);
}
//第三方对话接口
public function dataAnalysisStream($question)
{
$data = [
'query' => $question,
];
$response_url = '请求第三方接口地址';
try {
$response = $this->client->request('POST', $response_url, [
'json' => $data
]);
// 获取HTTP响应状态码
if (200 == $response->getStatusCode()){
return $response->getBody();
}
return false;
} catch (GuzzleException $e) {
Log::error('错误信息: ' . $e->getMessage());
return false;
}
}
}
最后效果
点击查看更多内容
1人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦