公開日

Function CallingとツールUse:LLMを業務システムにつなぐ

型付きツールを通じて、LLMにERPの照会、チケットの作成、CRMレコードの更新を任せる方法。スキーマ、実行ループ、構造化出力、検証、エラー処理を解説します。

執筆者
Ali ÖzdurmuşVeni AI 創業者
更新日
読了時間
読了時間 約5分

Function Calling(ツール利用とも呼ばれます)は、言語モデルが、特定の関数を特定の引数で実行するよう、自社のコードに依頼できる仕組みです。モデルと業務システムをつなぐ橋渡し役です。モデルが商品4471の在庫数が必要だと判断し、コードがERPを呼び出し、モデルが実際のデータに基づいて回答を書きます。モデルがシステムに直接触れることはなく、主導権は常にコード側にあります。

コードサンプルは説明用のPythonです。clientは初期化済みのSDKクライアント、MODELは選択したモデルIDのプレースホルダーです。

Function Callingとは

Traditional:
User: "How is the weather in Istanbul?"
LLM: "I don't know the weather" (hallucination risk)

Function Calling:
User: "How is the weather in Istanbul?"
LLM: {"function": "get_weather", "args": {"city": "Istanbul"}}
System: get_weather("Istanbul") → 15°C
LLM: "The weather in Istanbul is 15°C"

OpenAI方式のFunction Calling

基本的な使い方

python
from openai import OpenAI

client = OpenAI()
MODEL = "your-model-id"

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the weather for a specific city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "City name, e.g. Istanbul"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["city"]
            }
        }
    }
]

response = client.chat.completions.create(
    model=MODEL,
    messages=[{"role": "user", "content": "How is the weather in Istanbul?"}],
    tools=tools,
    tool_choice="auto"
)

並列Function Calling

複数の関数を同時に呼び出します。

python
tools = [
    {"type": "function", "function": weather_function},
    {"type": "function", "function": stock_function},
    {"type": "function", "function": news_function}
]

response = client.chat.completions.create(
    model=MODEL,
    messages=[{
        "role": "user", 
        "content": "Istanbul weather, TSLA stock and current news?"
    }],
    tools=tools,
    tool_choice="auto"
)

# Response can contain multiple tool calls
for tool_call in response.choices[0].message.tool_calls:
    print(f"Function: {tool_call.function.name}")
    print(f"Args: {tool_call.function.arguments}")

関数の実行ループ

python
def execute_function_call(tool_call):
    name = tool_call.function.name
    args = json.loads(tool_call.function.arguments)
    
    if name == "get_weather":
        return get_weather(**args)
    elif name == "get_stock_price":
        return get_stock_price(**args)
    else:
        return f"Unknown function: {name}"

def chat_with_functions(user_message, tools):
    messages = [{"role": "user", "content": user_message}]
    
    while True:
        response = client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=tools
        )
        
        assistant_message = response.choices[0].message
        messages.append(assistant_message)
        
        if not assistant_message.tool_calls:
            # No tool call, exit loop
            return assistant_message.content
        
        # Execute functions
        for tool_call in assistant_message.tool_calls:
            result = execute_function_call(tool_call)
            messages.append({
                "role": "tool",
                "tool_call_id": tool_call.id,
                "content": str(result)
            })

ClaudeのツールUse

Anthropic APIでのツール利用

python
from anthropic import Anthropic

client = Anthropic()
MODEL = "your-model-id"

tools = [
    {
        "name": "get_weather",
        "description": "Get weather for a city",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "City name"
                }
            },
            "required": ["city"]
        }
    }
]

response = client.messages.create(
    model=MODEL,
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "How is the weather in Ankara?"}]
)

# Tool use response handling
if response.stop_reason == "tool_use":
    tool_use = next(
        block for block in response.content 
        if block.type == "tool_use"
    )
    
    # Execute tool
    result = execute_tool(tool_use.name, tool_use.input)
    
    # Continue conversation
    response = client.messages.create(
        model=MODEL,
        max_tokens=1024,
        messages=[
            {"role": "user", "content": "How is the weather in Ankara?"},
            {"role": "assistant", "content": response.content},
            {
                "role": "user",
                "content": [
                    {
                        "type": "tool_result",
                        "tool_use_id": tool_use.id,
                        "content": result
                    }
                ]
            }
        ]
    )

構造化出力(JSONモード)

JSONモード

現在では多くのプロバイダーが、指定したJSONスキーマへの適合を保証する、スキーマ強制型の構造化出力も提供しています。利用できる場合はそちらを優先してください。通常のJSONモードが保証するのは有効なJSONであることだけで、自社の構造までは保証しません。

python
response = client.chat.completions.create(
    model=MODEL,
    response_format={"type": "json_object"},
    messages=[
        {
            "role": "system",
            "content": "Respond in JSON format."
        },
        {
            "role": "user",
            "content": "Suggest me 3 programming languages."
        }
    ]
)

data = json.loads(response.choices[0].message.content)
# {"languages": ["Python", "JavaScript", "Go"]}

Pydanticによる検証

python
from pydantic import BaseModel
from typing import List

class ProgrammingLanguage(BaseModel):
    name: str
    use_case: str
    difficulty: str

class LanguageRecommendation(BaseModel):
    languages: List[ProgrammingLanguage]
    reasoning: str

def get_structured_response(prompt: str, model: BaseModel):
    schema = model.model_json_schema()
    
    response = client.chat.completions.create(
        model=MODEL,
        response_format={"type": "json_object"},
        messages=[
            {
                "role": "system",
                "content": f"JSON schema: {json.dumps(schema)}"
            },
            {"role": "user", "content": prompt}
        ]
    )
    
    return model.model_validate_json(
        response.choices[0].message.content
    )

Instructorライブラリ

Pydantic + OpenAIと簡単に連携できます。

python
import instructor
from pydantic import BaseModel
from openai import OpenAI

client = instructor.from_openai(OpenAI())

class UserInfo(BaseModel):
    name: str
    age: int
    email: str

user = client.chat.completions.create(
    model=MODEL,
    response_model=UserInfo,
    messages=[
        {"role": "user", "content": "John Doe, 25 years old, john@email.com"}
    ]
)

print(user.name)  # John Doe
print(user.age)   # 25

複雑なツール定義

ネストしたパラメーター

python
{
    "name": "create_calendar_event",
    "description": "Create a calendar event",
    "parameters": {
        "type": "object",
        "properties": {
            "title": {"type": "string"},
            "datetime": {
                "type": "object",
                "properties": {
                    "date": {"type": "string", "format": "date"},
                    "time": {"type": "string", "format": "time"},
                    "timezone": {"type": "string"}
                },
                "required": ["date", "time"]
            },
            "attendees": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "email": {"type": "string"},
                        "role": {"type": "string", "enum": ["required", "optional"]}
                    }
                }
            },
            "reminder": {
                "type": "object",
                "properties": {
                    "minutes_before": {"type": "integer"},
                    "method": {"type": "string", "enum": ["email", "popup"]}
                }
            }
        },
        "required": ["title", "datetime"]
    }
}

エラー処理

python
class FunctionCallError(Exception):
    pass

def safe_execute_function(tool_call, available_functions):
    try:
        name = tool_call.function.name
        args = json.loads(tool_call.function.arguments)
        
        if name not in available_functions:
            raise FunctionCallError(f"Unknown function: {name}")
        
        # Parameter validation
        func = available_functions[name]
        sig = inspect.signature(func)
        
        for param in sig.parameters.values():
            if param.default is inspect.Parameter.empty:
                if param.name not in args:
                    raise FunctionCallError(
                        f"Missing required parameter: {param.name}"
                    )
        
        # Execute with timeout
        with timeout(30):
            result = func(**args)
        
        return {"success": True, "result": result}
        
    except json.JSONDecodeError as e:
        return {"success": False, "error": f"Invalid JSON: {e}"}
    except FunctionCallError as e:
        return {"success": False, "error": str(e)}
    except TimeoutError:
        return {"success": False, "error": "Function timeout"}
    except Exception as e:
        return {"success": False, "error": f"Execution error: {e}"}

ベストプラクティス

1. 明確な説明文

python
# Bad
{"name": "search", "description": "Searches"}

# Good
{
    "name": "search_products",
    "description": "Searches in e-commerce product database. "
                   "Can search by product name, category or brand. "
                   "Returns maximum 20 results."
}

2. Enumの活用

python
"payment_method": {
    "type": "string",
    "enum": ["credit_card", "bank_transfer", "crypto"],
    "description": "Payment method"
}

3. デフォルト値

python
"limit": {
    "type": "integer",
    "default": 10,
    "description": "Result limit (default: 10)"
}

まとめ

Function Callingは、言語モデルを、実際のシステムと連携して動けるコンポーネントに変えます。正確なツールの説明、厳密なスキーマ、検証、タイムアウトによって、信頼性が高まります。安全のために、まずは読み取り専用のツールから始め、書き込みや送信を伴う操作には承認を必須にし、すべての呼び出しをログに残してください。

Veni AIは、アクセス制御と監査ログを備えた、明確に定義されたツールを通じて、AIアプリケーションをERP、CRM、メール、文書システムにつなぎます。サービスを見る、またはお使いのシステムについてご相談ください。

続けて読む

AIで動かしたい業務はありますか?

現在の動き方のまま、1つの業務プロセスをご説明ください。AIアプリケーションやエージェントが担える繰り返しのステップをお示しします。