モデルの機能

ツール呼び出し

ツール呼び出し(関数呼び出し)を使うと、モデルが定義した関数への構造化された呼び出しを返します。みなさんのコードでそれらを実行し、結果をモデルに渡して回答を得ます。Tool calling 機能を持つモデルで利用できます。

全体の流れ

  1. 1JSON Schema で tools に関数を記述します。
  2. 2モデルが tool_calls を返します(finish_reason は tool_calls になります)。
  3. 3みなさんのコードで各関数を実行し、結果を対応する tool_call_id を付けた role: "tool" メッセージとして追加します。
  4. 4再度 API を呼び出すと、モデルがツールの結果を使って回答します。
import json

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string", "description": "City name, e.g. Tokyo"}},
            "required": ["city"],
        },
    },
}]
messages = [{"role": "user", "content": "What's the weather in Tokyo?"}]

resp = client.chat.completions.create(model="gpt-4.1-mini", messages=messages, tools=tools)
msg = resp.choices[0].message
if msg.tool_calls:
    messages.append(msg)                              # 1. keep the assistant's tool_calls
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)    # 2. run the tool in your code
        result = {"city": args["city"], "temp_c": 22, "sky": "clear"}
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
    final = client.chat.completions.create(model="gpt-4.1-mini", messages=messages, tools=tools)
    print(final.choices[0].message.content)           # 3. the model answers using the result

ツール利用の制御

tool_choice動作
"auto"(デフォルト)モデルが判断します
"none"ツールを呼び出しません
"required"少なくとも 1 つのツールを呼び出します
{"type": "function", "function": {"name": "..."}}特定の関数を強制します
一部の新しいモデルは強制的なツール利用(required や関数名の指定)に対応しておらず、400 を返します。auto を使用し、各ツールをいつ使うべきかをプロンプトで指示してください。

並行呼び出し

モデルは複数の tool_calls を一度に返す場合があります。すべてを実行し、結果ごとに 1 件の tool メッセージ(tool_call_id で対応付け)を同じリクエストで送信してください。

Anthropic 形式

ネイティブ形式では、ツールは input_schema で記述し、呼び出しは tool_use / tool_result のコンテンツブロックとして往復します。

resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=[{
        "name": "get_weather",
        "description": "Get the current weather for a city",
        "input_schema": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    }],
    messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
)
# When stop_reason == "tool_use", content holds tool_use blocks; run them and reply with:
# {"role": "user", "content": [{"type": "tool_result", "tool_use_id": block.id, "content": "..."}]}

ヒント

  • ツールが何をするもので、いつ使うべきかを、名前と説明に明確に記述してください。モデルはそれをもとに選択します。
  • スキーマは厳格に保ってください。enum と required を活用し、曖昧な自由入力フィールドは避けてください。
  • ツールを実行する前に引数を検証してください。必ず JSON としてパースし、文字列の一致で処理しないでください。
  • ツールの結果は、モデルが必要とするフィールドだけを含めた簡潔なものにしてください。入力トークンの節約になります。