見出し画像

OpenAI の API を使ってみた

 ChatGPT を提供する OpenAI 社の API を使った時の備忘録です。


前提

AlmaLinux release 8.9

curl 7.61.1

ログイン

 ブラウザで OpenAI のサイトをアクセスします。URL https://openai.com/

動画生成 Sora がニュースになった後のトップページでは、右上の Menu から login へ進みます
私は 簡単な既存グーグルアカウントでログインしました
マイクロソフトの傘下なので そのロゴが? 初回に許可するだけです
API へ進みます
Setting へ進みます

 最大3ヵ月 18ドルまで無料で使えます。私はニュースになった2022年末12月28日にチャットGPTを試してみたため無料枠は2023年4月1日期限切れとなっていました(>_<)。その為 クレジットカードを登録し最小額分を購入しました。新規の方は「動作確認」まで読み飛ばしてください。

Billing へ進みます
Add payment details へ進みます
私は個人なので Individual へ進みます
クレジットカード情報を入力します
チャージする購入単位のようです
Confirm Payment で 初回の決済が確定します
「Add to credit balance」はワンクリックで決済されるので要注意です

動作確認

Documentation / Quickstart

 公式ドキュメントに動作確認手順が説明されています。このうち 指定のサーバーへ質問を送信し 回答を受信する curl コマンドを試します。

https://platform.openai.com/docs/quickstart?context=curl

curl コマンド準備

 linux にログインし、もし curl がなければ次のようにインストールします。

$ sudo dnf install curl

 次のような応答があれば curl を利用できます。

$ curl -V

curl 7.61.1 (x86_64-redhat-linux-gnu) libcurl/7.61.1 OpenSSL/1.1.1k zlib/1.2.11 brotli/1.0.6 libidn2/2.2.0 libpsl/0.20.2 (+libidn2/2.2.0) libssh/0.9.6/openssl/zlib nghttp2/1.33.0
Release-Date: 2018-09-05
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp scp sftp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IDN IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz brotli TLS-SRP HTTP2 UnixSockets HTTPS-proxy PSL

API key 取得

https://platform.openai.com/api-keys
Create secret key
Copy で キーを控えておきます

 キーを忘れたり 他人に知られた場合は、削除して作り直します。

実行

 シェルの環境変数「OPENAI_API_KEY」に取得したキーを設定するコマンドです。キーは「sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX」だとします。

$ export OPENAI_API_KEY="sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
$ echo $OPENAI_API_KEY

sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

と応答があれば、正しく設定されています。公式ドキュメント通り下記コマンドを実行します。json 形式テキストを https で送信・受信する基本中の基本ですね。

$ curl https://api.openai.com/v1/chat/completions   -H "Content-Type: application/json"   -H "Authorization: Bearer $OPENAI_API_KEY"   -d '{
    "model": "gpt-3.5-turbo",
    "messages": [
      {
        "role": "system",
        "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."
      },
      {
        "role": "user",
        "content": "Compose a poem that explains the concept of recursion in programming."
      }
    ]
  }'

すると

{
  "id": "chatcmpl-yyyyyyyyyyyyyyyyyyyyyyyy",
  "object": "chat.completion",
  "created": 1712132080,
  "model": "gpt-3.5-turbo-0125",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "In the realm of code, a magic dwells,\nWhere recursion weaves its wondrous spells.\nA function that calls itself with glee,\nUnraveling the depths of a problem to see.\n\nLike a mirrored hall that endlessly reflects,\nRecursion dives deep, never vexed.\nThrough layers of calls, it charts a course,\nSolving mysteries with elegant force.\n\nThink of a Russian doll, nested inside,\nEach one smaller, a recursive guide.\nBreaking down a task into pieces small,\nUntil the solution triumphantly calls.\n\nIt's a dance of functions, intertwined,\nA symphony of loops, the mind will find.\nIn the web of recursion, beauty gleams,\nA poetic melody in programming dreams.\n\nSo embrace the power of recursive art,\nIn the world of code, it plays a vital part.\nUnraveling complexity with graceful spin,\nRecursion weaves a tale that draws us in."
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 39,
    "completion_tokens": 184,
    "total_tokens": 223
  },
  "system_fingerprint": "fp_zzzzzzzzzzzz"
}

このような応答があれば成功です。無料枠が終わり支払不足だと次のような応答になりました。

{
    "error": {
        "message": "You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.",
        "type": "insufficient_quota",
        "param": null,
        "code": "insufficient_quota"
    }
}

 キーが空だと次のようなエラーが応答されました。

{
    "error": {
        "message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.",
        "type": "invalid_request_error",
        "param": null,
        "code": null
    }
}

 日本語だとこんな感じです。

$ curl https://api.openai.com/v1/chat/completions   -H "Content-Type: application/json"   -H "Authorization: Bearer $OPENAI_API_KEY"   -d '{
    "model": "gpt-3.5-turbo",
    "messages": [
      {
        "role": "system",
        "content": "あなたはウクライナの大統領です。"
      },
      {
        "role": "user",
        "content": "戦争を終わらせる方法はありますか?"
      }
    ]
  }'
{
  "id": "chatcmpl-yyyyyyyyyyyyyyyyyyyyyyyy",
  "object": "chat.completion",
  "created": 1713574191,
  "model": "gpt-3.5-turbo-0125",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "はい、戦争を終わらせる方法はあります。まず第一に、交渉と外交手段を活用して対話を促進し、平和的な解決策を模索することが重要です。また、第三国や国際機関との協力を通じて仲介や支援を受けることも効果的です。さらに、国内外の支持を得るために、情報発信や説得力のあるコミュニケーション戦略を展開することも大切です。\n\n戦争は多くの犠牲をもたらすだけでなく、長期的な悪影響も及ぼすため、その早期の終結が重要です。私たちは平和を築くために全力を尽くし、紛争を解決するために努力を惜しまないことが必要です。"
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 45,
    "completion_tokens": 275,
    "total_tokens": 320
  },
  "system_fingerprint": "fp_zzzzzzzzzzzz"
}

終わり

 大げさなソフトウェアを構築することなく確認出来るので、オリジナルプログラム開発時の問題の切り分けに役立ちます。

この記事が気に入ったらサポートをしてみませんか?