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