ChatGpt Stream 数据调用【PHP示例】

		$res = $openaiClient->chatCompletions()->create(
			new \Tectalic\OpenAi\Models\ChatCompletions\CreateRequest([
				                                                          'model'    => 'gpt-3.5-turbo',
				                                                          'stream' =>true,
				                                                          'stop'=>'[done]',
				                                                        //   'model'    => 'gpt-4',
				                                                          'messages' => [
					                                                          [
						                                                          'role'    => 'user',
						                                                          'content' => "你是谁啊",
					                                                          ],
				                                                          ],
			                                                          ]),
		)->getResponse();

		if ($res->getStatusCode() == 200) {
            $body = $res->getBody();
            header('Content-Type: text/event-stream');
			header('Cache-Control: no-cache');
			header('Connection: keep-alive');
			header('X-Accel-Buffering: no');
            while (!$body->eof()) {
                $line = $this->readLine($body);
    
                if (! str_starts_with($line, 'data:')) {
                    continue;
                }
    
                $data = trim(substr($line, strlen('data:')));
    
                if ($data === '[DONE]') {
                    break;
                }
    
                $response = json_decode($data, true, 512, JSON_THROW_ON_ERROR);

                echo $response['choices'][0]['delta']['content'] ?? '';
                flush();
                ob_flush();
                sleep(3);
            }
            $body->close();
        }

    }
    
        private function readLine( $stream)
    {
        $buffer = '';

        while (! $stream->eof()) {
            if ('' === ($byte = $stream->read(1))) {
                return $buffer;
            }
            $buffer .= $byte;
            if ($byte === "\n") {
                break;
            }
        }

        return $buffer;
    }

大概就是这么个思路吧,请求的client可以随意替换

你可能感兴趣的:(chatgpt,php,javascript)