LoginSignup
3
0

PHPからchatGPTを呼び出してみた

Last updated at Posted at 2023-05-25

はじめに

最近話題のchatGPTですが、PHPから呼び出せないかなとなったので調査しました。

色々と呼び出す方法はあるみたいですが、
それぞれ出来たり出来なかったりな感じなようなので取り敢えず自分の作業ログを残すという感じで記事化します。

取り敢えずやりながら書いてるので最終的にうまく行くか現時点では謎なのが怖い。

前提条件

  • PHPを動かせる環境がある事
  • composerが導入されている事
  • chatGPTを使用するopenaiのアカウントがある事

ライブラリの導入

調査したところライブラリがあるみたいなので早速導入してみます。
ライブラリはこちら。

composerにパスを通す権限がない

composer_error.jpg

% php composer.phar require openai-php/client
Warning from https://repo.packagist.org: Support for Composer 1 is deprecated and some packages will not be available. You should upgrade to Composer 2. See https://blog.packagist.com/deprecating-composer-1-support/
Info from https://repo.packagist.org: #StandWithUkraine


  [InvalidArgumentException]
  Package openai-php/client at version  has a PHP requirement incompatible with your PHP version (7.4.33)


require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--update-with-all-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...
%

PHPのバージョンが足りないって怒られました。悲しい。
chatGPTを使う為にはPHP7.4.33では駄目なようです。

お疲れさまでした。また次回の記事でお会いしましょう。

。。。

で、終わったら流石に怒られそうなのでPHPのバージョンを上げてみます。

image.png

会社のプロダクトもこんな感じでコードも含めて勝手に更新されれば良いのに。
※ちなみにさくらのレンタルサーバで作業しています。

という感じでPHPのバージョン上げて再実行。
ここに置いてある他のPHPファイルが動かなくなりそうだけどまあ無視で…。

image.png

何か長文のエラーが…。今回の記事もここまで…。

と思いましたが、PHPのバージョンを上げたらcomposerのバージョンも上げないといけないのでは?という霊感が働いたので取り敢えず更新してみる。

composer_selfupdate.jpg

何だか長文でNoticeエラーが大量に表示れましたが

composer_selfupdate2.jpg

更新されていたのでヨシ!!

…というわけで再実行。

composer.jpg

何かうまくいった感じがします。


{
    "require": {
        "openai-php/client": "^0.4.2",
        "symfony/http-client": "^6.2",
        "nyholm/psr7": "^1.8"
    },
    "config": {
        "allow-plugins": {
            "php-http/discovery": true
        }
    }
}

導入後のcomposer.jsonはこんな感じになりました。

・PHPのバージョンが古いとライブラリの導入はできない。
・PHPのバージョン上げたらcomposerのバージョンも上げないといけない。

という学びでした。

API KEYの取得

こちらのページから取得できる模様

メニューからAPI keysを選択

api1.jpg

Create new secret keyを押下する事でsecret keyを発行できました。

image.png

いざ実装

取り敢えず見様見真似で実装。
class構成とかそういうのは今回は度外視。

<?php
require_once 'vendor/autoload.php';

// 取得してきたAPIを設定
$api_key = 'API KEY設定してね!!';

$client = OpenAI::client($api_key);

$result = $client->completions()->create([
    'model' => 'text-davinci-003',
    'prompt' => 'steamでオススメのゲームを教えてください',
]);

var_dump($result->toArray());

何か文章途切れてない…????

% php chat.php
array(6) {
  ["id"]=>
  string(34) "cmpl-7JcmEA6rIlpGLCsfHRlPoRp0WlyEc"
  ["object"]=>
  string(15) "text_completion"
  ["created"]=>
  int(1684911646)
  ["model"]=>
  string(16) "text-davinci-003"
  ["choices"]=>
  array(1) {
    [0]=>
    array(4) {
      ["text"]=>
      string(46) "

・Cities: Skylines
・Kerbal Space Program
"
      ["index"]=>
      int(0)
      ["logprobs"]=>
      NULL
      ["finish_reason"]=>
      string(6) "length"
    }
  }
  ["usage"]=>
  array(3) {
    ["prompt_tokens"]=>
    int(21)
    ["completion_tokens"]=>
    int(16)
    ["total_tokens"]=>
    int(37)
  }
}

無料版だから途切れているのか、実装の方法が間違えているのか解らん
…となってましたが、別の文章の構成がtokenの値で管理されていて引数で指定しないといけないらしい。

料金もtokenで計算されるので、無駄に増えないように指定可能になっているのではないかなーと想定。

max_tokensを指定する事でtokenを大量に消費する文章も返してくれるようになるとの事なので早速設定。

<?php
require_once 'vendor/autoload.php';

// 取得してきたAPIを設定
$api_key = 'API KEY設定してね!!';

$client = OpenAI::client($api_key);

$result = $client->completions()->create([
    'model' => 'text-davinci-003',
    'prompt' => 'steamでオススメのゲームを教えてください',
    "max_tokens" => 500,
]);

var_dump($result->toArray());

早速実行

% php -e chat.php
array(6) {
  ["id"]=>
  string(34) "cmpl-7Jd0inkq3s3PLG1w98pgaltKcsLNY"
  ["object"]=>
  string(15) "text_completion"
  ["created"]=>
  int(1684912544)
  ["model"]=>
  string(16) "text-davinci-003"
  ["choices"]=>
  array(1) {
    [0]=>
    array(4) {
      ["text"]=>
      string(209) "

・A Hat in Time
・Cuphead
・Frostpunk
・Kerbal Space Program
・Killing Floor 2
・Mount &Blade II: Bannerlord
・Portal 2
・Rocket League
・Subnautica
・Team Fortress 2
・The Elder Scrolls V: Skyrim"
      ["index"]=>
      int(0)
      ["logprobs"]=>
      NULL
      ["finish_reason"]=>
      string(4) "stop"
    }
  }
  ["usage"]=>
  array(3) {
    ["prompt_tokens"]=>
    int(21)
    ["completion_tokens"]=>
    int(67)
    ["total_tokens"]=>
    int(88)
  }
}
%

おわり

普段のchatGPTと比べると結論しか言わない感じで印象が変わりますが、
望んだ回答を得られるようになりました。
パラメータに関しては調べればもっと面白い事が出来そうな感じはしますね!
混み入った機能は有料版だけになりそうな感じがしなくもないですが。
弊社のプロダクトにも何らかの形で組み込む事ができるかもしれません。

ここまで読んでいただきありがとうございました!

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0