0% read

Gemma 4 Function CallingでAIエージェントを構築する方法

4月 7, 2026

Gemma 4はネイティブなFunction Callingサポートを搭載しており、単にテキストを生成するだけでなく、アクションを実行するAIエージェントを構築できます。API呼び出し、データベースクエリ、Web検索、計算の実行など。このガイドでは、Gemma 4とPythonを使ってゼロから動作するエージェントを構築する方法を紹介します。

Function Callingとは?

Function Callingは、モデルが答えを推測する代わりに、いつ外部ツールを使うか決定できるようにします。Gemma 4に「東京の天気は?」と聞いて幻覚の回答を得る代わりに、モデルは天気APIを呼び出す構造化リクエストを出力し、あなたがそれを実行し、結果をフィードバックし、モデルは実データに基づいて自然言語の回答を生成します。

フローはこのようになります:

ユーザー:「東京の天気は?」
  → モデル:{"function": "get_weather", "args": {"city": "Tokyo"}}
  → あなたのコードが天気APIを呼ぶ → {"temp": 22, "condition": "sunny"}を返す
  → モデル:「東京は今22°Cで晴れています。」

JSON Schemaによるツール定義

まず、Gemma 4にどのツールが利用可能か伝える必要があります。各ツールは名前、目的、パラメータを記述するJSON Schemaで定義されます:

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a city. Use this when the user asks about weather conditions.",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "City name, e.g. 'Tokyo', 'New York'"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["city"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "calculate",
            "description": "Perform mathematical calculations. Use for any math the user asks about.",
            "parameters": {
                "type": "object",
                "properties": {
                    "expression": {
                        "type": "string",
                        "description": "Math expression to evaluate, e.g. '2 + 2', 'sqrt(144)'"
                    }
                },
                "required": ["expression"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "web_search",
            "description": "Search the web for current information. Use when the user asks about recent events or facts you're unsure about.",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Search query"
                    },
                    "num_results": {
                        "type": "integer",
                        "description": "Number of results to return (default: 3)"
                    }
                },
                "required": ["query"]
            }
        }
    }
]

良いツール説明は重要です。モデルはそれらを使用して、どのツールをいつ呼ぶか決定します。各ツールがいつ使われるべきかを具体的に説明してください。

エージェントループの構築

Ollama API経由でGemma 4を使用する完全なPythonエージェント:

import json
import requests
import math

OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "gemma4:12b"

# ツール実装を定義
def get_weather(city: str, unit: str = "celsius") -> dict:
    """Simulated weather API — replace with a real API call"""
    # In production, call OpenWeatherMap, WeatherAPI, etc.
    return {
        "city": city,
        "temperature": 22,
        "unit": unit,
        "condition": "sunny",
        "humidity": 45
    }

def calculate(expression: str) -> dict:
    """Safe math evaluation"""
    allowed_names = {
        "sqrt": math.sqrt,
        "sin": math.sin,
        "cos": math.cos,
        "pi": math.pi,
        "e": math.e,
        "abs": abs,
        "round": round
    }
    try:
        result = eval(expression, {"__builtins__": {}}, allowed_names)
        return {"expression": expression, "result": result}
    except Exception as e:
        return {"expression": expression, "error": str(e)}

def web_search(query: str, num_results: int = 3) -> dict:
    """Simulated web search — replace with real search API"""
    return {
        "query": query,
        "results": [
            {"title": f"Result about {query}", "snippet": "Relevant information..."}
        ]
    }

# 関数名を実装にマッピング
TOOL_MAP = {
    "get_weather": get_weather,
    "calculate": calculate,
    "web_search": web_search,
}

def call_gemma(messages: list, tools: list) -> dict:
    """Send a chat request to Gemma 4 via Ollama"""
    response = requests.post(OLLAMA_URL, json={
        "model": MODEL,
        "messages": messages,
        "tools": tools,
        "stream": False
    })
    return response.json()

def run_agent(user_input: str, tools: list, max_steps: int = 5):
    """Run the agent loop with multi-step tool use"""
    messages = [
        {
            "role": "system",
            "content": "You are a helpful assistant. Use the provided tools when needed. Always use tools for weather, calculations, and current information instead of guessing."
        },
        {"role": "user", "content": user_input}
    ]

    for step in range(max_steps):
        response = call_gemma(messages, tools)
        message = response["message"]

        # モデルがツールを呼びたいか確認
        if "tool_calls" in message and message["tool_calls"]:
            # 各ツール呼び出しを処理
            for tool_call in message["tool_calls"]:
                func_name = tool_call["function"]["name"]
                func_args = tool_call["function"]["arguments"]

                print(f"  → Calling {func_name}({func_args})")

                # ツールを実行
                if func_name in TOOL_MAP:
                    result = TOOL_MAP[func_name](**func_args)
                else:
                    result = {"error": f"Unknown tool: {func_name}"}

                # ツール呼び出しと結果をメッセージに追加
                messages.append(message)
                messages.append({
                    "role": "tool",
                    "content": json.dumps(result)
                })
        else:
            # モデルが最終テキストレスポンスを返した
            print(f"Agent: {message['content']}")
            return message["content"]

    return "Agent reached maximum steps without completing."

# エージェントを実行
if __name__ == "__main__":
    run_agent("What's the weather in Tokyo and what's 15% of 8500?", tools)

このエージェントは複数のステップを持つクエリを処理できます。「東京の天気と8500の15%は?」と聞くと、Gemma 4はget_weathercalculateを別々に呼び出し、両方の結果を組み合わせて1つの自然な応答を作成します。

マルチステップエージェントパターン

実際のエージェントは、後の呼び出しが以前の結果に依存する、複数のツール呼び出しをチェーンする必要がよくあります:

# 例:「近くのレストランを探してそこの天気を確認」
# ステップ1:モデルがweb_search("restaurants near me")を呼ぶ
# ステップ2:モデルが結果を見て、get_weather(結果の都市)を呼ぶ
# ステップ3:モデルが両方を組み合わせて推薦に
#
# エージェントループは自然にこれを処理 — 各ツールの結果が
# 会話に追加され、モデルは完全な履歴に基づいて次に何をするか決定

信頼できるツール使用のための構造化出力

Gemma 4は構造化出力をサポートしており、モデルを特定のJSON形式で応答するように強制できます。エージェントの最終回答を機械可読な構造で必要とする場合に便利:

response = requests.post(OLLAMA_URL, json={
    "model": MODEL,
    "messages": messages,
    "format": {
        "type": "object",
        "properties": {
            "answer": {"type": "string"},
            "confidence": {"type": "number"},
            "sources": {
                "type": "array",
                "items": {"type": "string"}
            }
        },
        "required": ["answer", "confidence"]
    },
    "stream": False
})

これによりスキーマに合致する有効なJSONが保証されます — もう自由形式テキストを解析して最善を祈る必要はありません。

より良いFunction Callingのためのヒント

ヒント理由
詳細なツール説明を書くモデルは説明に基づいて正しいツールを選択
スキーマでrequiredフィールドを使用モデルが重要パラメータを省略するのを防ぐ
ツール数を5-10に制限ツールが多すぎるとモデルが混乱
説明に例を含める"e.g., 'New York', 'London'"でモデルは引数を正しくフォーマット
エラーを優雅に処理エラー情報を返してモデルが再試行またはユーザーに通知できるように
max_steps制限を設定モデルがツールを呼び続けた場合の無限ループを防ぐ

よくある落とし穴

モデルがツールを無視して直接答える: システムプロンプトでモデルに明示的にツールを使うよう指示してください。「NEVER guess weather/math/facts — always use the provided tools」を追加。

引数の型が間違っている: モデルが整数パラメータに3ではなく"3"を送る場合、ツール実装に型強制を追加してください。

モデルが不必要にツールを呼ぶ: ツール説明でいつ使うかを具体的に。「Use ONLY when the user explicitly asks about weather」の方が「Get weather information」より良いです。

次のステップ

Function CallingはGemma 4をチャットボットから実際のツールに変えます。実際のAPI — 天気、検索、データベース、メール — を接続すれば、すべて自分のハードウェアでローカルに動作する、現実世界で意味のあるアクションを実行できるAIエージェントが手に入ります。

gemma4 — interact

Stop reading. Start building.

~/gemma4 $ Get hands-on with the models discussed in this guide. No deployment, no friction, 100% free playground.

Launch Playground />
Gemma 4 AI

Gemma 4 AI

Related Guides

Gemma 4 Function CallingでAIエージェントを構築する方法 | ブログ