php 流式请求
原生curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->chatService->api);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->chatService->token,
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'model' => $this->chatService->model,
'temperature' => $this->chatService->temperature,
'stream' => $this->chatService->stream,
'messages' => $prompt,
]));
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $message) use (&$answer, $uid) {
$answer .= $message;
return strlen($message);
});
curl_exec($ch);
guzzle
$client = new \GuzzleHttp\Client([
'verify' => false,
'stream' => true,
]);
$response = $client->post($this->api, [
'body' => json_encode([
'model' => $this->model,
'temperature' => $this->temperature,
'stream' => $this->stream,
'messages' => $messages,
]),
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->token,
],
]);
$body = $response->getBody();
if ($onMessage) {
while (!$body->eof()) {
$res = \GuzzleHttp\Psr7\Utils::readLine($body);
$this->handleMessage($res, $onMessage);
}
}
最后更新于 2024-05-14 03:49:38 并被添加「」标签,已有 601 位童鞋阅读过。
此处评论已关闭