普通に ChatGPT の API を使うまでのメモ。
準備
以下の URL から API Key を取得
https://platform.openai.com/api-keys

#!/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
こちらから支払いを登録します。
以下のように返事が来ました。
{
"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
}

