ツール利用パターン:関数呼び出し、構造化ツール、多段推論

Dev.to / 2026/5/12

💬 オピニオンDeveloper Stack & InfrastructureIdeas & Deep AnalysisTools & Practical UsageModels & Research

要点

  • この記事では、ツール利用(関数呼び出し)によってLLMがデータベースやAPI、コード実行などの外部システムと連携できるようになり、自律エージェントに近い振る舞いが可能になることを解説しています。
  • 各ツールは、機械が実行可能な明確なスキーマで定義する必要があり、パラメータ名のわかりやすさ、型制約、任意パラメータのデフォルト設定が重要だと述べています。
  • 標準的な「ツール利用ループ」パターンとして、モデルがツール呼び出しを提案し、アプリケーションが実行し、その結果をモデルへ戻して推論を継続する流れを示しています。
  • 本番システムでのマルチステップ推論を支えるために、ツールの連鎖や構造化ツールの考え方を扱い、エージェントのワークフローの信頼性と制御性を高めることを狙っています。

この記事はもともと AI Study Room に掲載されました。動作するコード例や関連記事を含む完全版は、元の投稿をご覧ください。

ツール利用パターン:関数呼び出し、構造化ツール、多段階推論

はじめに

ツール利用、または関数呼び出しは、LLM が外部システムと相互作用できるようにします。データベースの問い合わせ、API の呼び出し、コードの実行、情報の取得などです。この機能により、LLM はテキスト生成器から自律エージェントへと変わります。本記事では、生産環境においてツール呼び出しを定義し、呼び出し、連鎖させるための主要なパターンを扱います。

ツールの定義

すべてのツールには、LLM が理解でき、アプリケーションが実行できる明確なスキーマが必要です。

from openai import OpenAI

from pydantic import BaseModel

client = OpenAI()

tools = [

    {

        "type": "function",

        "function": {

            "name": "search_documents",

            "description": "キーワードで社内ドキュメントを検索します。メタデータ付きの関連する抜粋を返します。",

            "parameters": {

                "type": "object",

                "properties": {

                    "query": {

                        "type": "string",

                        "description": "検索クエリです。より良い結果のために具体的な用語を使用してください",

                    },

                    "max_results": {

                        "type": "integer",

                        "description": "返す結果の数(1-20)",

                        "minimum": 1,

                        "maximum": 20,

                    },

                    "filters": {

                        "type": "object",

                        "properties": {

                            "date_from": {"type": "string", "format": "date"},

                            "department": {"type": "string"},

                        },

                    },

                },

                "required": ["query"],

            },

        },

    }

]

重要な原則:説明的なパラメータ名を使い、明確な説明を付けること、適切な型の制約を設定すること、任意パラメータにはデフォルトを用意することです。LLM はこれらの説明を使って、どのツールを呼び出すか、そしてどの引数で呼び出すかを判断します。

関数呼び出しループ

標準的なパターンはループです。生成し、ツール呼び出しがないか確認し、実行し、その結果を再びフィードバックします。

def tool_use_loop(messages: list, tools: list, max_turns=10):

    for turn in range(max_turns):

        response = client.chat.completions.create(

            model="gpt-4o",

            messages=messages,

            tools=tools,

            tool_choice="auto",

        )

        message = response.choices[0].message

        messages.append(message)

        if not message.tool_calls:

            return message.content

        for tool_call in message.tool_calls:

            result = execute_tool(tool_call.function.name, tool_call.function.arguments)

            messages.append({

                "tool_call_id": tool_call.id,

                "role": "tool",

                "content": str(result),

            })

    return "Max turns reached"

def execute_tool(name: str, args_json: str):

    args = json.loads(args_json)

    if name == "search_documents":

        return search_documents(**args)

    elif name == "calculate":

        return calculate(**args)

    raise ValueError(f"Unknown tool: {name}")

LLM はツール結果を新しいコンテキストとして受け取り、さらに別のツールを呼び出すべきか、最終回答を生成すべきかを判断します。

ツールによる多段階推論

複雑なタスクでは、後続の呼び出しがそれ以前の結果に依存する複数回のツール呼び出しが必要になります。

def research_workflow(topic: str):

    messages = [{"role": "user", "content": f"{topic} を調査し、包括的な要約を書いてください。"}]

    # Step 1: Search for information

    response = client.chat.completions.create(

        model="gpt-4o", messages=messages, tools=research_tools, tool_choice="auto"

    )

    # Execute search, get results

    # Step 2: Verify facts using a different source

    # Step 3: Structure the findings

    # Step 4: Generate the summary

    return final_summary

バリデーション付き構造化ツール

Anthropic のツール利用 API は、JSON Schema と strict モードによる構造化ツール定義をサポートしています。

import anthropic

client = anthropic.Anthropic()

response = client.messages.create(

    model="claude-sonnet-4-20260512",

    max_tokens=1024,

    tools=[

        {

            "name": "get_weather",

            "description": "指定した場所の現在の天気を取得します",

            "input_schema": {

                "type": "object",

                "properties": {

                    "location": {"type": "string", "description": "都市名"},

                    "units": {"type": "string", "enum": ["celsius", "fahrenheit"]},

                },

完全なコード例、比較テーブル、関連リソースについては AI Study Room の全文記事をご覧ください。

役に立ちましたか? AI Study Room の 開発者ガイドおよびツール比較 をもっとチェックしてみてください。

返却形式: {"translated": "翻訳されたHTML"}