コンテンツにスキップ
メインサイト ニュース コンソール

FC 関数呼び出し

関数呼び出し(Function Calling)により、モデルは必要に応じてあなたが定義した関数の実行を要求し、その関数の結果に基づいて回答を続けます。 4ALL API では GPT、Claude、Gemini シリーズがいずれも標準の OpenAI tools プロトコルをサポートしており、1 つのコードを記述するだけで複数モデルにまたがって利用できます。

基本フロー

  1. リクエスト内で tools を使って関数シグネチャを宣言する;
  2. モデルが finish_reason: "tool_calls" と関数名、JSON パラメータを返す;
  3. あなたが関数を実行し、その結果を role: "tool" メッセージとして返す;
  4. モデルが結果に基づいて最終回答を返す。

tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "指定した都市の現在の天気を照会する",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
resp = client.chat.completions.create(
model="gpt-5.5", messages=messages, tools=tools
)
call = resp.choices[0].message.tool_calls[0]
# 関数実行後に返却:
messages.append(resp.choices[0].message)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": '{"temp": 31, "condition": "sunny"}',
})
final = client.chat.completions.create(model="gpt-5.5", messages=messages, tools=tools)

注意事項

  • パラメータはモデルが生成した JSON 文字列であるため、必ず検証してから実行し、コマンドや SQL に直接連結しないこと;
  • モデルは一度に複数の tool_calls を返す場合があるため、1 つずつ実行し、tool_call_id に対応させて返却する;
  • tool_choice: "required" で呼び出しを強制でき、"none" で無効化できる;
  • ストリーミングモードでは関数パラメータが増分で送られてくるため、完全に結合してから解析する必要がある。詳しくはストリーミング出力を参照。