OpenAI APIとは?2026年最新モデル一覧
OpenAI APIを使うことで、ChatGPTの能力をあなたのアプリに組み込めます。2026年現在、GPT-4o・GPT-4o-mini・o3・o3-miniなど用途に合わせた多様なモデルが利用可能です。
| モデル | 特徴 | 用途 | コスト目安 |
|---|---|---|---|
| GPT-4o | 最高精度・マルチモーダル | 複雑なタスク | 高 |
| GPT-4o-mini | 高速・低コスト | 日常タスク | 低 |
| o3 | 推論特化・高精度 | 数学・コード | 最高 |
| o3-mini | 推論・コスト効率 | STEM問題 | 中 |
セットアップとAPIキーの取得
pip install openai python-dotenv
# .envファイル
OPENAI_API_KEY=sk-...
基本的なAPIコール
from openai import OpenAI
from dotenv import load_dotenv
import os
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# シンプルなチャット
def chat(user_message: str, system_prompt: str = "You are a helpful assistant.") -> str:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_message}
],
temperature=0.7,
max_tokens=2000
)
return response.choices[0].message.content
# 使用例
result = chat("Pythonで機械学習を始める方法を教えて")
print(result)
ストリーミング対応:リアルタイム出力
def chat_stream(user_message: str):
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": user_message}],
stream=True
)
full_response = ""
for chunk in stream:
if chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
print(content, end="", flush=True)
full_response += content
return full_response
# FastAPIとの組み合わせ(SSE)
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
@app.post("/chat/stream")
async def chat_endpoint(query: str):
async def generate():
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": query}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
yield f"data: {chunk.choices[0].delta.content}\n\n"
return StreamingResponse(generate(), media_type="text/event-stream")
プロンプトエンジニアリングの実践テクニック
Chain-of-Thought(COT)プロンプティング
cot_prompt = """
以下の問題を解いてください。ステップバイステップで考えてください。
問題: {problem}
考え方:
1. まず何が求められているかを整理する
2. 使える情報・公式を列挙する
3. 段階的に計算する
4. 答えを確認する
解答:
"""
Few-Shot プロンプティング
few_shot_prompt = """
テキストを3段階(ポジティブ/ニュートラル/ネガティブ)で感情分析してください。
例1:
テキスト: 「このサービスは本当に素晴らしい!また使いたいです」
感情: ポジティブ
理由: 肯定的な評価と再利用意向が明示されている
例2:
テキスト: 「普通の商品でした。可もなく不可もなく」
感情: ニュートラル
理由: 特に強い感情表現がない中立的な評価
分析対象:
テキスト: {text}
感情:
理由:
"""
Function Calling(ツール呼び出し)
import json
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "指定した都市の天気情報を取得する",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "都市名(例:東京、大阪)"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度単位"
}
},
"required": ["city"]
}
}
}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "東京の今日の天気は?"}],
tools=tools,
tool_choice="auto"
)
# Function Callが発生した場合
if response.choices[0].message.tool_calls:
tool_call = response.choices[0].message.tool_calls[0]
function_args = json.loads(tool_call.function.arguments)
print(f"関数: {tool_call.function.name}")
print(f"引数: {function_args}")
RAG(Retrieval Augmented Generation)の実装
from openai import OpenAI
import numpy as np
client = OpenAI()
# 文書をembeddingベクトルに変換
def get_embedding(text: str) -> list[float]:
response = client.embeddings.create(
model="text-embedding-3-small",
input=text
)
return response.data[0].embedding
# コサイン類似度で関連文書を検索
def cosine_similarity(a: list, b: list) -> float:
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
def rag_chat(query: str, documents: list[dict]) -> str:
query_embedding = get_embedding(query)
# 関連度でソート
scored_docs = [
(doc, cosine_similarity(query_embedding, doc['embedding']))
for doc in documents
]
top_docs = sorted(scored_docs, key=lambda x: x[1], reverse=True)[:3]
# コンテキストを構築
context = "
---
".join([doc['content'] for doc, _ in top_docs])
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": f"以下のコンテキストを参考に質問に答えてください:
{context}"
},
{"role": "user", "content": query}
]
)
return response.choices[0].message.content
コスト最適化のベストプラクティス
- モデル選択:複雑でないタスクはgpt-4o-miniを使う(コスト1/10以下)
- プロンプト圧縮:システムプロンプトは簡潔に、不要な説明を省く
- キャッシュ活用:同一プロンプトの結果をRedisでキャッシュ
- バッチ処理:Batch APIで非リアルタイムタスクを50%引きで処理
- トークン監視:使用量をDashboardで毎日確認、アラート設定
まとめ
OpenAI APIは使い方次第で劇的な生産性向上をもたらします。まずは基本的なチャット実装から始め、Function CallingやRAGへと段階的にスキルアップしましょう。コスト管理を徹底しながら、実用的なAIアプリを構築してください。