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?

OpenAI APIからレスポンスを取得する手順(Python)

Posted at

OpenAI APIキーを取得するまで

1. OpenAIの公式サイトへアクセス

OpenAIのAPIページ にアクセスします。

2. アカウントを作成/ログイン

まだアカウントを持っていない場合は、アカウントを作成してください。すでにアカウントがある場合はログインします。

3. APIキーの発行ページへ移動

Dashboard → API keys → Create new secret key

スクリーンショット 2025-02-19 11.39.13.png

keyのNameとProjectを指定してcreate sceret key ボタンをクリックするとキーが作成されます
※一度しか表示されないので、安全な場所に保存してください

4. クレジット情報を登録

設定(⚙️) → Builling

スクリーンショット 2025-02-19 12.05.27.png

クレジット情報を登録しないと以下のエラーになる

openai.RateLimitError: Error code: 429

APIキーを環境変数に保存

🖥️ Windows(PowerShell)

# powershell

$env:OPENAI_API_KEY="your-api-key"

または、~/.bashrc や ~/.bash_profile に以下を追加:

# powershell

[System.Environment]::SetEnvironmentVariable("OPENAI_API_KEY", "your-api-key", "User")

🐧 macOS/Linux(Bash)

# bash

export OPENAI_API_KEY="your-api-key"

プロンプトを送り、結果をターミナルに表示する

# ターミナル

pip install openai
# test.py

import os
from openai import OpenAI

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "user", "content": "これはテストですと言ってください"}
    ]
)

print(response.choices[0].message.content)
# ターミナル
python test.py

# 出力結果
これはテストです
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?