利用套件來串接chatGpt api
composer require orhanerday/open-ai
到OpenAi官方網站進行註冊以及創造api token
先設定env
OPENAI_API_KEY={OPENAI_API_KEY}
use Orhanerday\OpenAi\OpenAi;
// 建議使用config
$openAi = new OpenAi(env('OPENAI_API_KEY'));
// 跟基本串接API一樣
$chat = $open_ai->chat([
'model' => 'gpt-3.5-turbo',
'messages' => [
[
"role" => "user",
"content" => "今天天氣如何"
],
],
'max_tokens' => 1000,
]);
// message
dd(Arr::get(json_decode($chat,1)),'choices.0.message.content');
會發現回應時間隨著傳送過去的文字複雜度以及長度而增加
查了網路資料後來終於發現一個東西
串流
使用串流套件的範例如下
php
use Orhanerday\OpenAi\OpenAi;
$openAi = new OpenAi(env('OPEN_AI_API_KEY'));
$opts = [
'prompt' => "Hello",
'temperature' => 0.9,
"max_tokens" => 150,
"frequency_penalty" => 0,
"presence_penalty" => 0.6,
"stream" => true,
];
// set header
header('Content-type: text/event-stream');
header('Cache-Control: no-cache');
header('Access-Control-Allow-Origin: *');
$openAi->chat($opts, function ($curl_info, $data) {
echo $data . "<br><br>";
echo PHP_EOL;
ob_flush();
flush();
return strlen($data);
});
html
html>
<html>
<head>
<title>SSE Example</title>
</head>
<body>
<div id="divID">Hello</div>
<script>
var eventSource = new EventSource("{endPoint}");
var div = document.getElementById('divID');
eventSource.onmessage = function (e) {
if (e.data == "[DONE]") {
eventSource.close();
console.log('done');
return false;
} else {
const content = JSON.parse(e.data).choices[0].delta.content;
if (content != undefined) {
div.innerHTML += JSON.parse(e.data).choices[0].delta.content;
}
}
};
eventSource.onerror = function (e) {
console.log(e);
};
</script>
</body>
</html>
demo
No Comment!
Join Us Discuss