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実装サンプルまとめ(チャット、画像生成、音声、ファイル管理など)

0
Posted at

【完全保存版】OpenAI API 全エンドポイントのPython実装サンプルまとめ(チャット、画像生成、音声、ファイル管理など)

こんにちは、都内でフルスタックやってるエンジニアです。
今回は、OpenAI APIの全エンドポイントをPythonで完全網羅します。快速にOpenAIの全貌を理解するために約なればと思います

対象API一覧

  • モデル管理
  • チャット生成
  • テキスト完結
  • テキスト編集
  • 埋め込み生成
  • 画像生成
  • 音声文字起こし
  • 音声翻訳
  • コンテンツモデレーション
  • ファイル管理
  • 微調整モデル
  • 利用量取得

🔧 前提準備

pip install openai

環境変数にAPIキーを設定:

export OPENAI_API_KEY=sk-xxxxx

またはコード内で直接指定:

import openai
openai.api_key = "sk-xxxxx"

📌 1. モデル一覧取得 /v1/models

models = openai.Model.list()
for m in models['data']:
    print(m['id'])

利用可能なモデル一覧を取得できます。非推奨モデルも含まれるので注意。


💬 2. チャット生成 /v1/chat/completions

response = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "あなたは優秀なエンジニアです。"},
        {"role": "user", "content": "PythonでOpenAI APIを使う方法は?"}
    ]
)
print(response['choices'][0]['message']['content'])

ChatGPT系モデル(gpt-3.5, gpt-4)専用。messagesをやり取りの履歴として送る。


📝 3. テキスト完結 /v1/completions

response = openai.Completion.create(
    model="text-davinci-003",
    prompt="日本の都道府県をすべて列挙してください。",
    max_tokens=100
)
print(response.choices[0].text.strip())

古いモデル用。新規プロジェクトでは/chat/completions推奨。


✏️ 4. テキスト編集 /v1/edits

response = openai.Edit.create(
    model="text-davinci-edit-001",
    input="私は明日 学校 行く",
    instruction="正しい日本語に修正してください。"
)
print(response.choices[0].text.strip())

指定した指示に従ってテキストを修正。翻訳やリライトにも使える。


📌 5. 埋め込み生成 /v1/embeddings

response = openai.Embedding.create(
    model="text-embedding-ada-002",
    input="自然言語処理とは何か?"
)
embedding = response['data'][0]['embedding']
print(len(embedding), embedding[:5])

文章の意味を数値ベクトルに変換。類似検索、クラスタリングに使える。


🖼️ 6. 画像生成 /v1/images/generations

response = openai.Image.create(
    prompt="a futuristic cityscape at night",
    n=1,
    size="512x512"
)
print(response['data'][0]['url'])

DALL·Eを使って画像を生成。プロンプトエンジニアリングの工夫が肝。


🎙️ 7. 音声文字起こし /v1/audio/transcriptions

audio_file = open("audio_sample.mp3", "rb")
response = openai.Audio.transcribe("whisper-1", audio_file)
print(response["text"])

Whisperによる音声→文字起こし。多言語対応。


🌐 8. 音声翻訳 /v1/audio/translations

audio_file = open("japanese_audio.mp3", "rb")
response = openai.Audio.translate("whisper-1", audio_file)
print(response["text"])

日本語など他言語→英語への翻訳。transcribeと同様の使い方。


🚨 9. コンテンツモデレーション /v1/moderations

response = openai.Moderation.create(input="I want to hurt someone.")
print(response["results"][0]["flagged"])

有害コンテンツの自動判定に。特にチャットボットに組み込む際は必須。


📁 10. ファイル管理 /v1/files

アップロード:

file = open("data.jsonl", "rb")
response = openai.File.create(file=file, purpose='fine-tune')
print(response["id"])

一覧取得:

files = openai.File.list()
for f in files["data"]:
    print(f["filename"])

削除:

openai.File.delete("file-abc123")

微調整用やバッチ処理用ファイルの管理に。


🔧 11. 微調整モデル /v1/fine-tunes

response = openai.FineTuningJob.create(training_file="file-abc123", model="gpt-3.5-turbo")
print(response)

ステータス確認:

jobs = openai.FineTuningJob.list()

fine-tunes は旧API、FineTuningJob が新API。CLIベースの運用が多いが、Pythonからも操作可能。


📊 12. 利用量取得 /v1/usage

import datetime

start = datetime.date.today().replace(day=1).isoformat()
end = datetime.date.today().isoformat()

response = openai.api_requestor.APIRequestor().request(
    method="GET",
    url=f"/v1/usage?start_date={start}&end_date={end}"
)
print(response)

利用量ダッシュボードの自動化などに。ベータAPIのため変更に注意。


🧠 まとめ

機能 エンドポイント 推奨モデル例
チャット /v1/chat/completions gpt-4, gpt-3.5-turbo
テキスト補完 /v1/completions text-davinci-003
画像生成 /v1/images/generations DALL·E
音声文字起こし /v1/audio/transcriptions whisper-1
埋め込み /v1/embeddings text-embedding-ada-002
編集 /v1/edits text-davinci-edit-001
モデレーション /v1/moderations N/A
微調整モデル /v1/fine-tunes gpt-3.5-turbo (FT済)

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?