A Complete Guide to GLM Function Calling with Copy-Paste Templates

2026-11-09 · Prompt Tutorials

Function Calling is the key switch that turns GLM from a chatbot into something that can actually do work. This article, based on the tool-calling mechanism of the BigModel API platform, gives you copy-paste definition templates and a complete call flow so you can skip the usual pitfalls.

1. How GLM Tool Calling Works

GLM models (including the reasoning-oriented GLM-5 series) accept tools via the tools parameter in the Chat Completions API. When the model returns tool_calls, your code executes the real function and passes the result back as a role="tool" message. Keep these in mind:

  • The model never executes functions itself; it only decides whether to call, which one, and with what arguments;
  • tool_choice="auto" lets the model decide, while setting it to a specific function name forces a call;
  • Tool results must include the matching tool_call_id, or the next turn will fail.

Use strict JSON Schema for parameter definitions — how well GLM follows your fields depends directly on how clearly you describe them.

2. Tool Definition Template (Copy-Paste Ready)

json
{
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Query current weather for a city. Call when the user asks about weather, temperature, precipitation, or clothing advice.",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string",
              "description": "City name in Chinese, e.g.: 北京"
            },
            "date": {
              "type": "string",
              "description": "Query date in YYYY-MM-DD format; defaults to today if omitted"
            }
          },
          "required": ["city"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}

The description field is where most people cut corners, and it hurts the most. Spell out "when to call this" and GLM's trigger accuracy improves noticeably.

3. Full Call Flow and System Prompt

Pair the tools above with a system prompt like this:

You are a weather assistant with access to the get_weather tool.
Rules:
1. Always call the tool for weather-related questions; never fabricate data from memory;
2. If the user doesn't specify a city, ask first instead of guessing;
3. If the tool fails, say so honestly; never invent results;
4. Reply in Simplified Chinese, reporting only the fields the tool returns.

And the Python skeleton:

python
from zhipuai import ZhipuAI

client = ZhipuAI(api_key="YOUR_KEY")

messages = [
    {"role": "system", "content": SYSTEM_PROMPT},
    {"role": "user", "content": "Is today good for running in Beijing?"}
]

resp = client.chat.completions.create(
    model="glm-4-plus",  # check the BigModel official page for available models
    messages=messages,
    tools=tools,
    tool_choice="auto",
)

msg = resp.choices[0].message
if msg.tool_calls:
    for tc in msg.tool_calls:
        result = execute(tc.function.name, tc.function.arguments)
        messages.append(msg)
        messages.append({
            "role": "tool",
            "tool_call_id": tc.id,
            "content": result
        })
    final = client.chat.completions.create(
        model="glm-4-plus", messages=messages, tools=tools)
    print(final.choices[0].message.content)

4. Multiple Tools and Parallel Calls

For complex scenarios, declare several tools and GLM will route semantically. With both get_weather and search_poems attached, a question like "what poems suit a rainy day" may trigger a weather lookup followed by recommendations — a single response can carry multiple tool_calls. Your executor should loop over every tool_call and return each result individually.

5. Common Pitfalls

1. arguments is a JSON string: run json.loads before executing; don't treat it as an object; 2. With thinking mode enabled, note how the response separates reasoning content from the final answer — field names depend on the official docs; 3. Conflicting tool descriptions: overlapping semantics cause random tool selection — keep responsibilities mutually exclusive; 4. Parameter hallucination: always list required fields and specify value formats in descriptions; 5. Streaming output: tool_calls arrive in chunks; you need to assemble the delta fragments.

Compared with function calling in GPT, Claude, or DeepSeek, GLM's protocol largely follows the OpenAI style, so migrating existing OpenAI SDK code is low-cost — and its handling of Chinese parameter descriptions is a comfortable fit. Treat tool definitions and system prompts like code: maintain them, write test cases to verify trigger accuracy, and this kind of feature ships stably.

本文为使用方法整理,内容选自网上公开资料,供参考;本站为非官方资讯站,产品能力以官方页面为准。