智谱 AI GLM 使用指南¶
智谱 AI 的 GLM 系列模型针对中文场景深度优化,具有出色的中文理解能力、Deep Thinking 模式和极具竞争力的价格(2025 年降价 90%)。
模型概览¶
推荐模型¶
| 模型 | 上下文 | 特色 | 适用场景 |
|---|---|---|---|
| glm-4-flash | 128K | 极低价格、快速响应 | 通用对话、简单任务 |
| glm-4-plus | 128K | 综合性能强 | 复杂推理、代码生成 |
| glm-4-air | 128K | 平衡性能和成本 | 中等复杂度任务 |
| glm-4v-plus | 128K | 多模态能力 | 图文理解、视觉问答 |
| glm-4-0520 | 128K | Deep Thinking 模式 | 需要深度推理的任务 |
快速开始¶
创建 GLM 实例:
from tfrobot.brain.chain.llms import GLM
# 使用默认配置
llm = GLM(name="glm-4-flash")
# 自定义配置
llm = GLM(
name="glm-4-flash",
context_window=128000, # 上下文窗口大小
temperature=0.7, # 温度参数
max_tokens=4096, # 最大输出 tokens
)
配置参数¶
核心参数¶
from tfrobot.brain.chain.llms import GLM
llm = GLM(
name="glm-4-flash",
temperature=0.7, # 0.0-1.0,控制随机性(默认 0.7)
top_p=0.7, # 0.0-1.0,核采样(默认 0.7,开区间)
max_tokens=4096, # 最大输出 tokens
stream=False, # 是否流式输出
context_window=128000, # 上下文窗口大小
)
参数验证示例:
from pydantic_core import ValidationError
from tfrobot.brain.chain.llms import GLM
# temperature 范围是 [0.0, 1.0]
try:
GLM(name="glm-4-flash", temperature=1.2)
except ValidationError as e:
print(f"参数验证失败: {e}")
"""
参数验证失败: 1 validation error for GLM
temperature
Input should be less than 1 [type=less_than, input_value=1.2, input_type=float]
For further information visit https://errors.pydantic.dev/2.11/v/less_than
"""
# top_p 范围是 (0.0, 1.0),开区间
try:
GLM(name="glm-4-flash", top_p=1.0)
except ValidationError as e:
print(f"参数验证失败: {e}")
"""
参数验证失败: 1 validation error for GLM
top_p
Input should be less than 1 [type=less_than, input_value=1.0, input_type=float]
For further information visit https://errors.pydantic.dev/2.11/v/less_than
"""
API 配置¶
import os
from tfrobot.brain.chain.llms import GLM
# 方式一:使用环境变量(推荐)
# export ZHIPUAI_API_KEY="your-api-key"
llm = GLM(name="glm-4-flash")
# 方式二:直接传入 API Key
llm = GLM(
name="glm-4-flash",
zhipuai_api_key=os.getenv("ZHIPUAI_API_KEY"),
timeout=60.0, # 请求超时时间(秒)
max_retries=3, # 最大重试次数
)
响应格式¶
from tfrobot.brain.chain.llms import GLM
# 纯文本格式(默认)
llm = GLM(name="glm-4-flash")
# JSON 格式(需要模型支持)
llm = GLM(name="glm-4-flash", response_format={"type": "json_object"})
# JSON Schema 格式(带结构验证)
llm = GLM(
name="glm-4-flash",
response_format={
"type": "json_schema",
"json_schema": {
"name": "Person",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
},
"required": ["name", "age"],
},
"strict": False,
},
},
)
基础用法¶
文本生成¶
from tfrobot.brain.chain.llms import GLM
from tfrobot.schema.message.conversation.message_dto import TextMessage
from tfrobot.schema.users import BaseUser
llm = GLM(name="glm-4-flash")
user = BaseUser(name="用户", uid="1")
current_input = TextMessage(content="帮我做一个100字的新疆游攻略,我从北京出发", creator=user)
result = llm.complete(current_input=current_input)
# 查看结果
print(result.generations[0].text)
#> 新疆游攻略:从北京出发,乘坐飞机抵达乌鲁木齐。第一天游览天池、天山天池;第二天参观喀纳斯湖、禾木村;第三天漫步喀什古城、艾提尕尔清真寺;第四天体验吐鲁番葡萄沟、火焰山。别忘了品尝新疆特色美食!
# 查看 Token 使用情况
print(f"输入 tokens: {result.usage['prompt_tokens']}")
#> 输入 tokens: 17
print(f"输出 tokens: {result.usage['completion_tokens']}")
#> 输出 tokens: 67
print(f"总 tokens: {result.usage['total_tokens']}")
#> 总 tokens: 84
流式输出¶
from tfrobot.brain.chain.llms import GLM
from tfrobot.schema.message.conversation.message_dto import TextMessage
from tfrobot.schema.users import BaseUser
llm = GLM(name="glm-4-flash", stream=True)
user = BaseUser(name="用户", uid="1")
current_input = TextMessage(content="帮我做一个100字的新疆游攻略", creator=user)
result = llm.complete(current_input=current_input)
# result.generations[0].text 会逐步生成
异步调用¶
import asyncio
from tfrobot.brain.chain.llms import GLM
from tfrobot.schema.message.conversation.message_dto import TextMessage
from tfrobot.schema.users import BaseUser
async def main():
llm = GLM(name="glm-4-flash")
user = BaseUser(name="用户", uid="1")
current_input = TextMessage(content="帮我做一个100字的新疆游攻略", creator=user)
result = await llm.async_complete(current_input=current_input)
print(result.generations[0].text)
#> 新疆游攻略:首先游览天山天池,领略壮丽山水;接着漫步喀纳斯湖,感受神秘的自然风光;最后品尝新疆美食,如烤羊肉、手抓饭等,感受浓郁的民族风情。
asyncio.run(main())
工具调用¶
定义工具¶
from tfrobot.drive.tool.tool import tool
@tool(name="docs_basic_calculate_sum")
def calculate_sum(a: float, b: float) -> float:
"""
计算两个数的和
Args:
a: 第一个数
b: 第二个数
Returns:
两数之和
"""
return a + b
@tool(name="docs_basic_get_weather")
def get_weather(city: str) -> str:
"""
获取指定城市的天气
Args:
city: 城市名称
Returns:
天气信息
"""
return f"{city} 今天晴天,温度 25°C"
使用 GLMWithTools¶
from tfrobot.brain.chain.llms import GLMWithTools
from tfrobot.drive.tool.tool import tool
from tfrobot.schema.message.conversation.message_dto import TextMessage
from tfrobot.schema.users import BaseUser
@tool(name="docs_glmwt_calculate_sum")
def calculate_sum(a: float, b: float) -> float:
"""
计算两个数的和
Args:
a: 第一个数
b: 第二个数
Returns:
两数之和
"""
return a + b
# GLMWithTools 预配置了 ToolPrompt
llm = GLMWithTools(name="glm-4-flash")
user = BaseUser(name="用户", uid="1")
current_input = TextMessage(content="帮我计算一下3.14加上0.98是多少", creator=user)
result = llm.complete(current_input=current_input, tools=[calculate_sum])
# 检查是否调用了工具
if result.generations[0].tool_calls:
print("模型调用了工具")
#> 模型调用了工具
for tool_call in result.generations[0].tool_calls:
print(f"工具名称: {tool_call.function.name}")
#> 工具名称: docs_glmwt_calculate_sum
print(f"参数: {tool_call.function.parameters}")
#> 参数: {"a": 3.14, "b": 0.98}
GLM vs GLMWithTools¶
from tfrobot.brain.chain.llms import GLM, GLMWithTools
from tfrobot.brain.chain.prompt.tool_prompt import ToolPrompt
# 方式一:使用 GLM(需要手动配置)
llm = GLM(name="glm-4-flash")
llm.system_msg_prompt.append(ToolPrompt())
# 方式二:使用 GLMWithTools(推荐)
llm = GLMWithTools(name="glm-4-flash")
工具过滤¶
from tfrobot.brain.chain.llms import GLMWithTools
from tfrobot.drive.tool.tool import tool
from tfrobot.schema.message.conversation.message_dto import TextMessage
from tfrobot.schema.users import BaseUser
@tool(name="docs_tool_filter_calculate_sum")
def calculate_sum(a: float, b: float) -> float:
"""
计算两个数的和
Args:
a: 第一个数
b: 第二个数
Returns:
两数之和
"""
return a + b
@tool(name="docs_tool_filter_get_weather")
def get_weather(city: str) -> str:
"""
获取指定城市的天气
Args:
city: 城市名称
Returns:
天气信息
"""
return f"{city} 今天晴天,温度 25°C"
# 只允许特定的工具可用
llm = GLMWithTools(name="glm-4-flash", available_tools=["docs_tool_filter_calculate_sum"]) # 只允许 calculate_sum
user = BaseUser(name="用户", uid="1")
user_input = TextMessage(content="帮我计算3.14 + 0.98", creator=user)
# 即使传入多个工具,只有 calculate_sum 会被使用
result = llm.complete(current_input=user_input, tools=[calculate_sum, get_weather])
多模态支持¶
图片理解¶
from pydantic_core import Url
from tfrobot.brain.chain.llms import GLM
from tfrobot.schema.message.conversation.message_dto import ImageMessage, TextMessage
from tfrobot.schema.users import BaseUser
# 使用 glm-4v-plus 进行图片理解
llm = GLM(name="glm-4.6v")
user = BaseUser(name="用户", uid="1")
# 使用公开可访问的图片 URL(示例使用百度百科的图片)
# 注意:实际使用时请替换为您自己的图片 URL
img_message = ImageMessage(
content=Url("https://bkimg.cdn.bcebos.com/pic/c75c10385343fbf285d0b172ba7eca8064388fe6"),
alt_text="一张图片",
creator=user,
)
# 添加文本消息
txt_message = TextMessage(content="帮我看一下,图中是什么动物?", creator=user)
result = llm.complete(current_input=img_message, conversation=[txt_message])
print(result.generations[0].text)
#>
# >
多模态消息¶
from tfrobot.brain.chain.llms import GLM
from tfrobot.schema.message.conversation.message_dto import MultiPartMessage
from tfrobot.schema.message.msg_part import ImagePart, ImgUrl, TextPart
from tfrobot.schema.users import BaseUser
# 使用 glm-4v-plus
llm = GLM(name="glm-4.6v")
user = BaseUser(name="用户", uid="1")
msg = MultiPartMessage(
content=[
TextPart(text="这张图片里有什么?"),
ImagePart(
image_url=ImgUrl(
url="https://bkimg.cdn.bcebos.com/pic/c75c10385343fbf285d0b172ba7eca8064388fe6", mime_type="image/jpeg"
)
),
],
creator=user,
)
result = llm.complete(current_input=msg)
高级功能¶
上下文管理¶
from tfrobot.brain.chain.llms import GLM
# 设置上下文窗口
llm = GLM(name="glm-4-flash", context_window=128000) # 128K tokens
# 查看上下文窗口大小
print(llm.context_window)
#> 128000
Prompt 自定义¶
from tfrobot.brain.chain.llms import GLM
from tfrobot.brain.chain.prompt.memo_prompt import MemoPrompt
from tfrobot.brain.chain.prompt.template.jinja2_template import Jinja2PromptTemplate
from tfrobot.schema.types import Locale
llm = GLM(name="glm-4-flash")
# 系统消息
system_prompt = MemoPrompt(
template=Jinja2PromptTemplate(templates={Locale.DEFAULT: "你是一个专业的 Python 开发者,擅长代码审查和优化。"})
)
llm.system_msg_prompt = [system_prompt]
# 输入后提示
after_input_prompt = MemoPrompt(
template=Jinja2PromptTemplate(templates={Locale.DEFAULT: "请使用 Markdown 格式回复,代码块标明语言。"})
)
llm.after_input_msg_prompt = [after_input_prompt]
# 使用 Jinja2 模板
jinja_prompt = MemoPrompt(
template=Jinja2PromptTemplate(templates={Locale.DEFAULT: "回答:{{ additional_info.question }}"})
)
JSON 响应与示例¶
from tfrobot.brain.chain.llms import GLM
from tfrobot.brain.chain.prompt.additional_info_prompt import AdditionalInfoPrompt
from tfrobot.brain.chain.prompt.template.f_string_template import FStrPromptTemplate
from tfrobot.schema.message.conversation.message_dto import TextMessage
from tfrobot.schema.users import BaseUser
llm = GLM(name="glm-4-flash")
# 添加 JSON 示例到系统提示
json_res_example_prompt = AdditionalInfoPrompt(
template=FStrPromptTemplate(templates={"zh": "JSON 示例: {additional_info[__tf_llm_json_result_examples__]}"}),
always_render=False,
)
llm.system_msg_prompt = [json_res_example_prompt]
user = BaseUser(name="用户", uid="1")
current_input = TextMessage(content="提取以下信息为JSON:张三,邮箱zhangsan@example.com", creator=user)
# 使用 JSON 格式并带示例
result = llm.complete(
current_input=current_input,
response_format={"type": "json_object", "examples": {"name": "示例", "email": "example@gmail.com"}},
)
# 结果会被解析为字典
print(result.generations[0].text) # {"name": "张三", "email": "zhangsan@example.com"}
#> {'name': '张三', 'email': 'zhangsan@example.com'}
错误处理¶
常见错误¶
| 错误码 | 原因 | 解决方案 |
|---|---|---|
| 1261 | 上下文超长 | 使用 Chain 的 compact 功能 |
| 1301 | API 密钥错误 | 检查环境变量 ZHIPUAI_API_KEY |
| 1302 | 配额不足 | 检查账户余额 |
| 1303 | 参数错误 | 检查请求参数 |
| 1304 | 内容审核失败 | 检查输入内容 |
上下文超长处理¶
from tfrobot.brain.chain.chain import Chain
from tfrobot.brain.chain.llms import GLM
from tfrobot.schema.exceptions import ContextTooLargeError
from tfrobot.schema.message.conversation.message_dto import TextMessage
from tfrobot.schema.users import BaseUser
llm = GLM(name="glm-4-flash")
user = BaseUser(name="用户", uid="1")
# 模拟一个很长的对话历史
long_conversation = [TextMessage(content=f"历史消息 {i}", creator=user) for i in range(1000)]
user_input = TextMessage(content="很长的问题...", creator=user)
try:
result = llm.complete(current_input=user_input, conversation=long_conversation)
except ContextTooLargeError as e:
print(f"上下文超长: {e.message}")
print(f"模型: {e.model_name}")
# 使用 Chain 自动压缩
chain = Chain(llm=llm)
result = chain.run(input_message=user_input)
最佳实践¶
1. Temperature 设置¶
from tfrobot.brain.chain.llms import GLM
# 需要创造性(如写作)
llm_creative = GLM(name="glm-4-flash", temperature=0.9)
# 需要稳定性(如代码生成)
llm_stable = GLM(name="glm-4-flash", temperature=0.1)
# 平衡模式
llm_balanced = GLM(name="glm-4-flash", temperature=0.7)
2. 中文场景优化¶
from tfrobot.brain.chain.llms import GLM
from tfrobot.schema.message.conversation.message_dto import TextMessage
from tfrobot.schema.users import BaseUser
# GLM 对中文有天然优势
llm = GLM(name="glm-4-flash")
user = BaseUser(name="用户", uid="1")
result = llm.complete(current_input=TextMessage(content="解释什么是量子纠缠,用通俗易懂的语言", creator=user))
3. 工具设计原则¶
from tfrobot.drive.tool.tool import tool
@tool
def search_database(query: str, limit: int = 10) -> str:
"""
在数据库中搜索信息
Args:
query: 搜索关键词
limit: 返回结果数量限制(默认 10)
Returns:
搜索结果摘要
"""
# 实现数据库搜索逻辑
# results = perform_search(query, limit)
# return format_results(results)
return f"搜索结果: {query} (前{limit}条)"