post($url, [ 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $apiKey ], 'json' => [ 'model' => 'gpt-3.5-turbo', 'messages' => [['role' => 'user', 'content' => 'Say this is a test!']], 'temperature' => 0.7 ] ]); $res = object_to_array(json_decode($response->getBody()->getContents())); return jsonSuccess($res); } public function myTestGpt1(){ $openaiClient = Manager::build( new \GuzzleHttp\Client(), new Authentication(Env::get("gpt.api_key1")) ); $response = $openaiClient->chatCompletions()->create( new \Tectalic\OpenAi\Models\ChatCompletions\CreateRequest([ 'model' => 'gpt-4', 'messages' => [ [ 'role' => 'user', 'content' => 'Will using a well designed and supported third party package save time?用中文回答' ], ], ]) )->toModel(); echo $response->choices[0]->message->content; } public function myTestGpt2(){ header('Access-Control-Allow-Origin: *'); // 允许任何来源 header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type'); header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); header('Connection: keep-alive'); // $request = Request::instance(); $data = $this->request->post(); $input = $data['message']; // $input = $this->request->post('message'); // 获取前端传递的用户输入 $client = new Client(); $response = $client->post('https://api.openai.com/v1/chat/completions', [ 'headers' => [ 'Authorization' => 'Bearer '.Env::get("gpt.api_key1"), 'Content-Type' => 'application/json', ], 'json' => [ 'model' => 'gpt-4', 'messages' => [['role' => 'user', 'content' => $input]], 'stream' => true, ], 'stream' => true ]); $body = $response->getBody(); while (!$body->eof()) { $chunk = $body->read(1024); // 读取流数据 echo "data: " . json_encode($chunk, JSON_UNESCAPED_UNICODE) . "\n\n"; ob_flush(); flush(); } exit; } }