vague memory

うろ覚えを無くしていこうともがき苦しむ人の備忘録

OpenAI Usage を取得する

2023/07/21 追記 現在この手法は利用できません。
APIキーでの認証は不可となったようです。 StatusCode:403、session key が必要というメッセージが返却されます。

Your request to GET /dashboard/billing/usage must be made with a session key (that is, it can only be made from the browser). You made it with the following key type: secret.


前置き

OpenAI の使用量を取得したくなりました。 日次と当月の使用量は Usage dashboard で確認できます。

How will I know how many tokens I’ve used each month?

Log in to your account to view your usage tracking dashboard. This page will show you how many tokens you’ve used during the current and past billing cycles.

ドキュメント上の URL リンクは beta.openai.com となっていますが、現在は platform.openai.com にリダイレクトされます。

この値を定期的に取得して通知してダッシュボードに行かずとも日々確認できるようにしたいと思いました。 詳細はダッシュボードを見れば良いので、今週使いすぎたな位のざっくりとした物で十分です。

取得方法

Usage の API は用意されていないようなので、以下を参考に Usage dashboard から値を取得します。

curl で total_usage を取得する例です。

  • total_usage は 各 cost の合計
  • total_usage, cost は /100 で $ (ドル)
_ORGANIZATION="Your Organization"
_OPENAI_APIKEY="Your API Key"

_START_DATE="$(date -u +'%Y-%m')-01"
_END_DATE="$(date -u -v+1m +'%Y-%m')-01"
# for GNU
#_START_DATE="$(date -u +'%Y-%m')-01"
#_END_DATE="$(date -u -d '1 month' +'%Y-%m')-01"

curl -sSf "https://api.openai.com/dashboard/billing/usage?end_date=${_END_DATE}&start_date=${_START_DATE}" \
-H "openai-organization: ${_ORGANIZATION}" \
-H "authorization: Bearer ${_OPENAI_APIKEY}" \
| jq -r '"$" + (.total_usage | round / 100 | tostring)'

利用例

取得した値を日次で Slack に流してます。

余談

公式ドキュメントに記載が無いので使えなくなる or 方法が変わる可能性はありますが、当面は大丈夫なようです。 何も指定せず実行すると API key を指定せよと怒られます。

$ curl "https://api.openai.com/dashboard/billing/usage"
{
  "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 accesing 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
  }
}

返却されるJSON例です。model毎のcost算出も行えます。

{
  "object": "list",
  "daily_costs": [
    {
      "timestamp": 0.0,
      "line_items": [
        {
          "name": "Instruct models",
          "cost": 0.0
        },
        {
          "name": "Chat models",
          "cost": 0.0
        },
        {
          "name": "GPT-4",
          "cost": 0.0
        },
        {
          "name": "Fine-tuned models",
          "cost": 0.0
        },
        {
          "name": "Embedding models",
          "cost": 0.0
        },
        {
          "name": "Image models",
          "cost": 0.0
        },
        {
          "name": "Audio models",
          "cost": 0.0
        }
      ]
    },
    ...
  ],
  "total_usage": 0.0
}