openai-api-development について
PythonでOpenAI APIアプリケーションを開発するためのスキルです。チャット、Assistants、関数呼び出し、埋め込み、マルチモーダル要求を扱い、信頼性やコスト、安全性の実践方法も示します。
主な機能
- 01Chat Completionsとストリーミング
- 02Assistants APIのスレッドとツール
- 03関数呼び出しのパターン
- 04埋め込み生成の指針
- 05マルチモーダル画像要求
- 06エラー処理とコスト対策
活用シーン
- 01Pythonチャットアプリの実装
- 02モデル応答への関数呼び出し追加
- 03テキストの埋め込み生成
- 04画像分析要求の構築
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ mindrally/ skills --skill openai-api-developmentインストール後、Claude Code で/openai-api-developmentを入力して読み込まれたか確認します。
詳細
OpenAI API 開発
GPT モデル、Assistants API、関数呼び出し、埋め込み、そして本番環境に対応した AI アプリケーションの構築を含む、OpenAI API 開発のエキスパートです。
主な原則
- 正確な Python の例を用いて、簡潔で技術的な回答を作成します
- すべての関数シグネチャに型ヒントを使用します
- 適切なエラー処理と再試行ロジックを実装します
- API キーをハードコードせず、環境変数を使用します
- OpenAI の利用ポリシーとレート制限のガイドラインに従います
セットアップと設定
環境のセットアップ
import os
from openai import OpenAI
# Always use environment variables for API keys
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
ベストプラクティス
- API キーは
.envファイルに保存し、絶対にコミットしないでください - ローカル開発では
python-dotenvを使用します - 適切なキーのローテーション戦略を実装します
- 開発環境と本番環境には個別のキーを設定します
Chat Completions API
基本的な使い方
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
temperature=0.7,
max_tokens=1000
)
message = response.choices[0].message.content
ストリーミング応答
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Tell me a story"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
モデルの選択
- 複雑な推論やマルチモーダルタスクには
gpt-4oを使用します - 高速で費用対効果の高い応答には
gpt-4o-miniを使用します - 高度な推論タスクには
o1モデルを使用します - 速度が求められる単純なタスクには
gpt-3.5-turboの使用を検討します
関数呼び出し
関数の定義
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and state, e.g., San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["location"]
}
}
}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"
)
ツール呼び出しの処理
import json
def process_tool_calls(response, messages):
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
messages.append(response.choices[0].message)
for tool_call in tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
# Execute the function
result = execute_function(function_name, function_args)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result)
})
# Get final response
return client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools
)
return response
Assistants API
アシスタントの作成
assistant = client.beta.assistants.create(
name="Data Analyst",
instructions="You are a data analyst. Analyze data and provide insights.",
tools=[
{"type": "code_interpreter"},
{"type": "file_search"}
],
model="gpt-4o"
)
スレッドの管理
# Create a thread
thread = client.beta.threads.create()
# Add a message
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="Analyze this data..."
)
# Run the assistant
run = client.beta.threads.runs.create_and_poll(
thread_id=thread.id,
assistant_id=assistant.id
)
# Get messages
if run.status == "completed":
messages = client.beta.threads.messages.list(thread_id=thread.id)
埋め込み
埋め込みの生成
response = client.embeddings.create(
model="text-embedding-3-small",
input="Your text to embed",
encoding_format="float"
)
embedding = response.data[0].embedding
埋め込みに関するベストプラクティス
- 費用対効果を重視する場合は
text-embedding-3-smallを使用します - 最高の精度が必要な場合は
text-embedding-3-largeを使用します - 効率化のため、リクエストをまとめて送信します(入力は最大 2048 件)
- API の重複呼び出しを避けるため、埋め込みをキャッシュします
- ストレージを最適化するため、適切な dimensions パラメーターを使用します
ビジョンとマルチモーダル
画像分析
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.jpg",
"detail": "high"
}
}
]
}
]
)
エラー処理
再試行ロジック
from openai import RateLimitError, APIError
import time
def call_with_retry(func, max_retries=3, base_delay=1):
for attempt in range(max_retries):
try:
return func()
except RateLimitError:
delay = base_delay * (2 ** attempt)
time.sleep(delay)
except APIError as e:
if attempt == max_retries - 1:
raise
time.sleep(base_delay)
raise Exception("Max retries exceeded")
一般的なエラーの種類
RateLimitError:指数バックオフを実装しますAPIError:API のステータスを確認し、バックオフを使って再試行しますAuthenticationError:API キーを確認しますInvalidRequestError:入力パラメーターを検証します
コストの最適化
- タスクの複雑さに応じて適切なモデルを使用します
- リクエストの前にトークン数をカウントします
- 長い応答にはストリーミングを使用します
- 適切な場合は応答をキャッシュします
- 妥当な
max_tokensの上限を設定します - 時間に制約のないリクエストには Batch API を使用します
セキュリティのベストプラクティス
- クライアント側のコードで API キーを公開しないでください
- エンドポイントにレート制限を実装します
- ユーザー入力を検証し、サニタイズします
- ユーザー生成コンテンツにはコンテンツモデレーションを使用します
- 監視と監査のため、API の使用状況を記録します
依存関係
- openai
- python-dotenv
- tiktoken(トークン数のカウント用)
- pydantic(入力の検証用)
- tenacity(再試行ロジック用)
コメント
Markdown 対応