0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ChatGPT を Python で使ってみる

0
Posted at

普通に ChatGPT の API を使うまでのメモ。

準備

以下の URL から API Key を取得
https://platform.openai.com/api-keys
image.png

発行されたキーをコピー。(画面外にも長く続きます)
image.png


#!/usr/bin/env python3
import json
import requests
import os

os.environ["OPENAI_API_KEY"]="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"

url = "https://api.openai.com/v1/chat/completions"

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"],
}

data = {
    "model": "gpt-3.5-turbo",
    "messages": [
        {
            "role": "user",
            "content": "こんにちは",
        }
    ]
}


response = requests.post(url=url, headers=headers, json=data)
response.encoding = "utf-8"
print(json.dumps(response.json(), indent=2, ensure_ascii=False))

お金払ってくださいと出ました。

{
  "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"
  }
}

https://platform.openai.com/settings/organization/billing/overview
こちらから支払いを登録します。

image.png

以下のように返事が来ました。

{
  "id": "chatcmpl-DESv79SOAs6l8k0YWYxDptPN3bpjp",
  "object": "chat.completion",
  "created": 1772340133,
  "model": "gpt-3.5-turbo-0125",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "こんにちは!お元気ですか?何かお手伝いできることがあればお知らせくださいね。",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 8,
    "completion_tokens": 32,
    "total_tokens": 40,
    "prompt_tokens_details": {
      "cached_tokens": 0,
      "audio_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 0,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  },
  "service_tier": "default",
  "system_fingerprint": null
}

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?