Chatgpt Apiは、人工知能・機械学習分野における重要な概念・技術です。
ChatGPT API は、OpenAI が提供する GPT シリーズの大規模言語モデルにアクセスするための REST API です。2023 年 3 月に公開されて以来、多くの Web サービス、アプリケーション、ツールが ChatGPT API を統合し、自然言語処理の民主化を推進してきました。開発者は数行のコードで GPT-3.5、GPT-4、GPT-4o、GPT-4o mini などの強力なモデルを利用できます。
| モデル | 用途 | 価格(Input / Output / 1M トークン) |
|---|---|---|
| GPT-4o | 最新・汎用 | $2.50 / $10.00 |
| GPT-4o mini | 低コスト | $0.15 / $0.60 |
| GPT-4 Turbo | 長文対応 | $10.00 / $30.00 |
| GPT-4 | 標準 | $30.00 / $60.00 |
| GPT-3.5 Turbo | 高速・安価 | $0.50 / $1.50 |
| o1(推論特化) | 複雑な推論 | $15.00 / $60.00 |
| o3-mini |
| 推論・低コスト |
| $1.10 / $4.40 |
pip install openai
export OPENAI_API_KEY='your-api-key-here'
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "自作 PC の CPU は何を選ぶべき?"}
]
)
print(response.choices[0].message.content)
使用するモデルを指定
出力のランダム性:
生成する最大トークン数
Nucleus sampling:
繰り返しペナルティ:
新しいトピックの促進
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Pythonでフィボナッチ数列を書いて"}],
stream=True
)
for chunk in response:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end='')
モデルに外部関数を呼び出させる機能:
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "指定した都市の天気を取得",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "東京の天気は?"}],
tools=tools
)
# tool_calls の処理
if response.choices[0].message.tool_calls:
for call in response.choices[0].message.tool_calls:
# 関数を実行
result = get_weather(**json.loads(call.function.arguments))
GPT-4o、GPT-4 Turbo 等は画像を入力できる:
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"}
}
]
}
]
)
JSON スキーマに従った構造化出力:
from pydantic import BaseModel
class Product(BaseModel):
name: str
price: float
category: str
response = client.beta.chat.completions.parse(
model="gpt-4o-2024-08-06",
messages=[{"role": "user", "content": "iPhone 15 Pro の商品情報"}],
response_format=Product
)
product = response.choices[0].message.parsed
print(product.name, product.price)
長期コンテキスト、ファイル検索、コードインタプリタを備えた高度な API:
GPT-3.5 Turbo、GPT-4o mini で可能:
# ファインチューニング開始
client.fine_tuning.jobs.create(
training_file="file-abc123",
model="gpt-4o-mini-2024-07-18"
)
テキストをベクトル化:
response = client.embeddings.create(
model="text-embedding-3-small",
input="自作 PC の選び方"
)
embedding = response.data[0].embedding # 1536 次元
| サービス | 特徴 |
|---|---|
| OpenAI | 最大規模、GPT-4o |
| Anthropic Claude | 長文、安全性 |
| Google Gemini | マルチモーダル |
| Meta Llama API | オープンモデル |
| Mistral AI | ヨーロッパ系 |
| Together AI | オープンモデルホスティング |
| Ollama(ローカル) | 無料、プライバシー |