本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了怎么在laravel10项目中使用chatgpt?感兴趣的朋友,下面一起来看一下,希望对大家有帮助。
在 Laravel 10 项目中使用 ChatGPT!
你会得到什么


我假设你已经使用官方文档安装了 Laravel 10 框架
第一步:创建控制器
input('prompt');
$response = $this->askToChatGPT($prompt);
return view('chatgpt.response', ['response' => $response]);
}
private function askToChatGPT($prompt)
{
$response = Http::withoutVerifying()
->withHeaders([
'Authorization' => 'Bearer ' . env('CHATGPT_API_KEY'),
'Content-Type' => 'application/json',
])->post('https://api.openai.com/v1/engines/text-davinci-003/completions', [
"prompt" => $prompt,
"max_tokens" => 1000,
"temperature" => 0.5
]);
return $response->json()['choices'][0]['text'];
}
}第二步:创建路由
name('chatgpt.index');
Route::post('/chatgpt/ask', [ChatG²PTController::class, 'ask'])
->name('chatgpt.ask');第三步:创建布局
// layouts/app.blade.php
My ChatGPT App
@yield('content')
第四步:创建 index 页面
// chatgpt/index.blade.php
@extends('layouts.app')
@section('content')
Ask something to ChatGPT
@endsection第五步:创建 response 页面
// chatgpt/response.blade.php
@extends('layouts.app')
@section('content')
ChatGPT answer
{{ $response }}
@endsection最后第六步:创建一个 .env 变量
CHATGPT_API_KEY=YOUR_API_KEY
获取 ChatGPT API 密钥
要获取 API 密钥,您可以转到您的 openai 平台帐户中的 api-keys 部分并生成您的密钥

如果你想要更多的例子,你可以去官方的例子部分:platform.openai.com/examples
推荐学习:《laravel视频教程》










