OpenAI API 使い方ガイド|GPT-4o・o3・DALL-E対応

🟢

OpenAI API 使い方ガイド

GPT-4o、o3、DALL-E 3 など OpenAI の API を使いこなすための実践ガイド。Python / TypeScript 対応。随時更新。

最終更新: 2026年3月

1. アカウントとAPIキー

  1. platform.openai.com でアカウント作成
  2. API Keys → Create new secret key
  3. export OPENAI_API_KEY=”sk-…” で環境変数に設定

2. SDK インストール

Python

pip install openai

TypeScript / Node.js

npm install openai

3. Chat Completions API

from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "あなたは親切なアシスタントです。"},
        {"role": "user", "content": "量子コンピュータを小学生にわかるように説明して"}
    ]
)

print(response.choices[0].message.content)

4. モデル一覧

モデル 特徴 用途
o3 最高性能の推論モデル 数学、コーディング、複雑な分析
o4-mini 高速推論モデル コスパ重視の推論タスク
GPT-4o マルチモーダル対応 汎用、Vision、音声
GPT-4o mini 高速・低コスト チャットボット、大量処理

5. Structured Outputs

JSONスキーマを指定すると、確実にその形式で出力を受け取れます。

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "東京と大阪の人口を教えて"}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "cities",
            "schema": {
                "type": "object",
                "properties": {
                    "cities": {"type": "array",
                        "items": {"type": "object",
                            "properties": {
                                "name": {"type": "string"},
                                "population": {"type": "integer"}
                    }}}
                }
            }
        }
    }
)

6. 画像入力(Vision)

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "この画像を説明してください"},
            {"type": "image_url", "image_url": {
                "url": "https://example.com/image.jpg"
            }}
        ]
    }]
)

7. 画像生成(gpt-image)

response = client.images.generate(
    model="gpt-image-1",
    prompt="夕暮れの京都の金閣寺、水面に反射する金色",
    n=1,
    size="1024x1024"
)

image_url = response.data[0].url

8. Function Calling

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "指定された都市の天気を取得",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "都市名"}
            },
            "required": ["city"]
        }
    }
}]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "東京の天気は?"}],
    tools=tools
)

9. 料金体系

モデル 入力 / 1M tokens 出力 / 1M tokens
o3 $2 (cached: $0.50) $8
GPT-4o $2.50 $10
GPT-4o mini $0.15 $0.60
上部へスクロール