原生curl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$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);
}
}