内容更新日: 2026-06-09
概要
関数呼び出しは、モデルがあなたが定義した関数を呼び出すことを可能にし、外部システムとの連携を実現します。モデルは関数を直接実行するのではなく、関数名と引数を返し、あなたのコードがそれらを実行して結果をモデルに返します。完全な例
import json
from openai import OpenAI
client = OpenAI(api_key="sk-xxx", base_url="https://api.crazyrouter.com/v1")
# 1. Define tools
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather information for a specified city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g.: New York"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["city"]
}
}
},
{
"type": "function",
"function": {
"name": "search_products",
"description": "Search for products",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search keyword"},
"max_price": {"type": "number", "description": "Maximum price"}
},
"required": ["query"]
}
}
}
]
# 2. Mock function implementations
def get_weather(city, unit="celsius"):
return {"city": city, "temperature": 22, "unit": unit, "condition": "Sunny"}
def search_products(query, max_price=None):
return [{"name": f"{query} Product A", "price": 99}, {"name": f"{query} Product B", "price": 199}]
# 3. Conversation loop
messages = [{"role": "user", "content": "What's the weather like in New York today? Also search for umbrellas"}]
response = client.chat.completions.create(
model="gpt-5.5",
messages=messages,
tools=tools,
tool_choice="auto"
)
message = response.choices[0].message
# 4. Handle tool calls
if message.tool_calls:
messages.append(message)
for tool_call in message.tool_calls:
func_name = tool_call.function.name
args = json.loads(tool_call.function.arguments)
if func_name == "get_weather":
result = get_weather(**args)
elif func_name == "search_products":
result = search_products(**args)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result, ensure_ascii=False)
})
# 5. Get final response
final = client.chat.completions.create(
model="gpt-5.5",
messages=messages,
tools=tools
)
print(final.choices[0].message.content)
特定の関数呼び出しを強制する
response = client.chat.completions.create(
model="gpt-5.5",
messages=messages,
tools=tools,
tool_choice={"type": "function", "function": {"name": "get_weather"}}
)
対応モデル
このページの OpenAI 互換関数呼び出しの例については、まず以下の検証済みベースラインを使用してください:gpt-5.5
gpt-5.5 によるツール呼び出しは、2026年3月23日に Crazyrouter 本番環境で検証されました。他のベンダー製については、リクエスト形式やサポート内容が異なる場合があるため、事前にそれぞれの専用ページで確認してください。