by Devin Yang

建立於: 2年前 ( 更新: 2年前 )

最近好像大家都在講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/

 

Tags: openapi ai laravel

Devin Yang

文章內容無法一一說明,如果您有什麼不了解處,歡迎提問哦:)

No Comment

Post your comment

需要登入才可留言!

類似的文章


nginx,dlaravel

如何設定nginx上的HTTPS,取得Qualys的SSL A+評分

本文介紹如何調整nginx的ssl設定,讓網站取得SSL報告,取得A+的評比。 這裡我使用的為 letsencrypt 免費憑證。 只要您使用D-Laravel預設的Docker官方nginx新版image,應該都可以達到跟我一樣的效果。 可透過下方檢測您的主機SSL設定。 https://www.ssllabs.com/ssltest/index.html

laravel,blade

Laravel 5.5 make:model的-a參數及Blade套版chunk功能介紹

不了解什麼是make:model -a參數嗎,這個影片將簡單介紹,實際操作過程, 並使用Blade套版中的chunk功能結尾。

laravel

@dump介紹,Laravel 5.6.8新功能

在Laravel 5.6的directive多了一個新功能叫@dump了 讓我們來看看他有多cool。