1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OllamaのTool CallingをPythonで試す:qwen3:8bが関数呼び出しを返すまで

1
Posted at

はじめに

OllamaはOpenAI互換のTool Calling(関数呼び出し)をサポートしています。モデルにツール定義を渡すと、通常の文章ではなく構造化された呼び出しを返します。

この記事では、/api/chat にツールを渡し、実際に返ってくる tool_calls を確認します。

環境

  • Windows 11(ビルド 10.0.26200)
  • Ollama 0.40.13
  • モデル: qwen3:8b

やったこと

1. ツールを定義する

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "指定した都市の現在の天気を返す",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "都市名(例: 東京)",
                    }
                },
                "required": ["city"],
            },
        },
    }
]

2. ツール付きでチャットする

import json
import urllib.request

payload = {
    "model": "qwen3:8b",
    "messages": [{"role": "user", "content": "東京の天気を教えて"}],
    "tools": tools,
    "stream": False,
    "think": False,
    "options": {"num_ctx": 4096, "temperature": 0},
}

req = urllib.request.Request(
    "http://127.0.0.1:11434/api/chat",
    data=json.dumps(payload).encode(),
    headers={"Content-Type": "application/json"},
    method="POST",
)
with urllib.request.urlopen(req, timeout=300) as r:
    data = json.loads(r.read().decode())

msg = data["message"]
print(msg.get("content"))
print(json.dumps(msg.get("tool_calls"), ensure_ascii=False))

結果:

tool_calls: [{"function": {"name": "get_weather", "arguments": {"city": "東京"}}}]

モデルは文章ではなく、get_weather(city="東京") に対応する構造を返しました。

3. ツールを実行して結果を返す

実際の関数を呼び出し、結果を role: "tool" のメッセージとして会話に追加します。

def get_weather(city: str) -> dict:
    # 実運用ではAPIを呼ぶ。ここでは固定値
    return {"city": city, "weather": "晴れ", "temp_c": 18}

call = msg["tool_calls"][0]["function"]
result = get_weather(**call["arguments"])

messages = [
    {"role": "user", "content": "東京の天気を教えて"},
    msg,
    {
        "role": "tool",
        "tool_name": call["name"],
        "content": json.dumps(result, ensure_ascii=False),
    },
]

4. 結果を含めて最終回答を得る

payload2 = {
    "model": "qwen3:8b",
    "messages": messages,
    "tools": tools,
    "stream": False,
    "think": False,
    "options": {"num_ctx": 4096, "temperature": 0},
}
# 同じ /api/chat へPOSTし、message.content を表示

結果の例:

東京は晴れ、気温は18度です。

5. 呼び出しを検証する

モデルの出力は信用せず、ツール名と引数を検証します。

ALLOWED = {"get_weather"}

def validate_call(call: dict) -> dict:
    fn = call.get("function", {})
    name = fn.get("name")
    args = fn.get("arguments", {})
    if name not in ALLOWED:
        raise ValueError(f"unknown tool: {name}")
    if not isinstance(args, dict):
        raise ValueError("arguments must be an object")
    city = args.get("city")
    if not isinstance(city, str) or not city.strip():
        raise ValueError("city is required")
    return {"name": name, "arguments": {"city": city.strip()}}

ハマった点

argumentsはJSON文字列のことがある

実装やバージョンによって、arguments がdictではなくJSON文字列で返ることがあります。isinstance(args, str) なら json.loads() してから扱います。

ツールを実行するのはアプリ側

モデルは「呼びたい」という構造を返すだけで、実際の関数は実行しません。副作用のある操作(削除・送金・外部API)は、必ずアプリ側で権限と引数を検証してから実行します。

モデルがツールを呼ばないことがある

質問が曖昧だったり、ツールの説明が不足していると、通常の文章で回答します。description と引数の説明を具体的に書き、必要ならシステムプロンプトで「ツールを使ってください」と指示します。

ループを止める

ツール結果を返して再度呼ぶと、モデルがまたツールを呼ぶことがあります。最大呼び出し回数を決め、超えたら打ち切ります。

まとめ

  • /api/chat に tools を渡すと、tool_calls に構造化された呼び出しが返る。
  • qwen3:8bは「東京の天気」から get_weather(city="東京") を返した。
  • 実行はアプリ側。ツール名・引数・権限を検証する。
  • arguments はJSON文字列の場合があるため、型を確認する。
  • 呼び出し回数の上限を決めてループを止める。
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?