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);
    }
}

此处评论已关闭