最近好像大家都在講OpenAI,如果您也想玩,可以在Laravel的API寫個簡易的API測試哦。
因為可以用curl呼叫,所以透過guzzle就能呼叫了。
如果您登入了openai的網站,可在此處看到官方的教學說明
https://beta.openai.com/docs/quickstart/build-your-application
API的KEY的申請,就在這頁的下方就有按鈕了
+ Create new secret key
再把key加到Laravel的.env中,這裡我取名叫
OPENAI_KEY=
在routes/api.php中新增/openai功能
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
Route::get('/openai', function (Request $r) {
if(empty($r->text)){
return sprintf("呼叫API:<br/>%s/api/openapi?text=問的問題",env("APP_URL"));
}
$client = new Client;
$api_url = "https://api.openai.com/v1/completions";
$json = <<<JSON
{
"model": "text-davinci-003",
"prompt": "用正體中文回應我:$r->text",
"temperature": 0.9,
"max_tokens": 150,
"top_p": 1,
"frequency_penalty": 0.0,
"presence_penalty": 0.6,
"stop": [" Human:", " AI:"]
}
JSON;
$json = json_decode(preg_replace('/[\x00-\x1F]/', '', $json), true);
try {
$r = $client->request('POST', $api_url, [
'headers' => [
'Authorization' => 'Bearer ' . env("OPENAI_KEY")
],
'json' => $json
]);
} catch (ClientException $e) {
return json_decode($e->getResponse()->getBody()->getContents(), true);
}
return $r;
});
然後打開自己Laravel專案的/api/openai?text=就能輸入測試囉
在官方網站有大量的範例可以參考,中間的Json如何設定的
https://beta.openai.com/examples/
No Comment
Post your comment