1
0

Laravel(PHP)でOpenAI APIを使用する

Last updated at Posted at 2024-03-17

ハッカソンで、Laravel(PHP)からOpenAIのAPIをたたく機会がありました。
OpenAI APIのドキュメントにはPython、node.js、curlの呼び出し形式がありますが、PHPからの呼び出し形式はなかったので、備忘録として書き残します。

目次

テキストからテキスト

https://platform.openai.com/docs/guides/text-generation
エンドポイント:https://api.openai.com/v1/chat/completions

[
    'model' => 'gpt-4',
        'messages' => [
            [
                "role" => "user",
                "content" => [
                    [
                        "type" => "text",
                        "text" => {プロンプト}
                    ],
                ],
            ]
        ],
    "max_tokens" => 1000,
]

テキストから画像

https://platform.openai.com/docs/guides/images
エンドポイント:https://api.openai.com/v1/images/generations

[
    'model' => 'dall-e-3',
    'prompt' => {プロンプト},
    'size' => "1024x1024",
    'quality' => "standard",
    'n' => 1,
]

画像からテキスト

https://platform.openai.com/docs/guides/vision
エンドポイント:https://api.openai.com/v1/chat/completions

[
    [
        'model' => 'gpt-4-vision-preview',
        'messages' => [
            [
                "role" => "user",
                "content" => [
                    [
                        "type" => "text",
                        "text" => {プロンプト}
                    ],
                    [
                        "type" => "image_url",
                        "image_url" => [
                            "url" => {画像へのURL}
                        ]
                    ],
                ],
            ]
        ],
        "max_tokens" => 1000,
    ]
]

APIリクエストの実装方法

リクエストにはHttpファサードを使用しました。
また、リクエストのヘッダにOpenAIのサイトで生成したトークンを含める必要があるので、AuthorizationヘッダのBearer認証でトークンを送りました。

$responseの中身はモデルによって違うので注意が必要です。
都度返ってきたJSONをデコードして中身を確認し、欲しいデータを取ってきてください。

$apiKey = {OpenAIのAPIキー};
$headers = [
    "Content-Type" => "application/json",
    "Authorization" => "Bearer $apiKey"
]
$response = Http::withHeaders($headers)
    ->timeout(60)
    ->post({エンドポイント}, {呼び出し形式通りのデータ});
1
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
1
0