Laravel
ChatGptを使ってみた
ヤス
公開日:2023/02/22
はじめに
最近話題になっている「ChatGPT」というAIチャットが気になったので使ってみました。
PHPでの記事はいくつかありましたがLaravelを使った記事はなかったので、Laravel + Livewire で使ってみました。
ChatGPT とは
ChatGPTとは、OpenAIという企業が開発したAIチャットサービスです。
色々な質問に回答してくれて、プログラムの簡単なソースも回答してくれます。
質問例:PHP で素数を求める関数を教えて

Laravel + Livewire で実装
・app/Http/Livewire/ChatGpt.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Illuminate\Support\Facades\Http;
class ChatGpt extends Component
{
private $api_url = 'https://api.openai.com/v1/completions';
private $api_key = '取得したAPIキー';
//APIリクエストのパラメータ
private $api_param = [
//OpenAI 文章生成モデル(2023年2月時点で最新)
'model' => 'text-davinci-003',
//生成する文章の最大単語数
'max_tokens' => 4000,
//単語のランダム性(0~2)0に近いほどランダム性が低い
//0:毎回同じ文章を生成
//2.0:完全にランダムに次の単語を選ぶ
'temperature' => 0.5,
//次の単語を選ぶ(0~1)
//0.1にすると、予測する次の単語は確率の高い上位10%の候補から選択
'top_p' => 1.0,
//既に出てきた単語をもう一度使うかどうか(-2~2)
//-2.0:同じ単語を繰り返し使う
//2.0:同じ単語は繰り返し使いづらい
'presence_penalty' => 0.0,
//既に出てきた単語をもう一度使うかどうか(-2~2)
//presence_penaltyと違い使った回数に応じてペナルティを加える
'frequency_penalty' => 1.0,
];
public $text = null;
public $answer = null;
public function render()
{
$this->answer = null;
//ChatGptのAPIにリクエスト
if(!is_null($this->text)){
//入力された文字を入力
$api_add_param['prompt'] = $this->text;
$json_response = Http::withHeaders([
'Authorization' => 'Bearer '.$this->api_key,
])->post($this->api_url,$api_add_param + $this->api_param);
$responses = json_decode($json_response,true);
}
//レスポンスがあれば、回答を入力
if(isset($responses['choices'])){
foreach ($responses['choices'] as $choices) {
if(isset($choices['text'])){
$this->answer .= $choices['text'];
}
}
}
return view('components.chatgpt')->extends("layouts.display");
}
}
・resources/views/layouts/display.blade.php
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="ROBOTS" content="NOINDEX, NOFOLLOW" />
<title>ChatGPT テスト</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
@livewireStyles
</head>
<body>
<div class="container-fluid">
<div class="row">
@yield("content")
</div>
</div>
@livewireScripts
</body>
</html>
・resources/views/components/chatgpt.blade.php
@if(!is_null($answer))ChatGptに質問してみよう。Loading...@endif<pre> {{$answer}} </pre>
使ってみる
Laravelで動作するようになったので、実際に使って確認してみました。
「卓球で勝つ方法を教えてください」と入力して、送信してみると無事返信が取得できました。

使ってみた感想
かなり正確にこちらの入力内容を理解して、回答がされていると思いました。
ただ、嘘の回答などがされる時もあるので、利用者がある程度気をつけた方が良いかなと感じました。
最後に
リリースしてから3ヶ月ほどしか経過していませんが、色々なところで目にする機会があり話題性はかなり高いと感じています。
Microsoft は2023年2月7日に OpenAI と協力して、自社の検索サービスの「Bing」にChatGPTような対話式の検索を発表しました。
Googleも同じ時期に新たな会話型のAIサービス「Bard」を発表しています。
今後は会話形式での検索が主流になるかもしれないです。