GLM系列大模型是智谱AI提供的系列语言模型。本文介绍如何用Python语言调用GLM的API实现智能问答。
我的GLM Coding邀请链接:
🚀 速来拼好模,智谱 GLM Coding 超值订阅,邀你一起薅羊毛!Claude Code、Cline 等 10+ 大编程工具无缝支持,“码力”全开,越拼越爽!立即开拼,享限时惊喜价!
链接:www.bigmodel.cn/claude-code…
智谱大模型开放平台:bigmodel.cn/
官方文档:docs.bigmodel.cn/cn/guide/st…
模型报价:open.bigmodel.cn/pricing
文本模型GLM-4.5-Flash、视觉理解模型GLM-4.6V-Flash是免费的,我在下面一般会以这两个模型为例写代码,如果不是这两个模型说明这两个模型到使用限制了,我被迫换成别的模型了……
1. 获得API key
注册并登录智谱AI开放平台
点击“查看API key”:
复制的API key用于调用API
2. 撰写代码并实现提问和回答
2.1 使用智谱SDK
需要使用的Python环境>3.8
首先下载包:pip install zai-sdk
2025.12.10 注意还需要安装sniffio这个包,否则会报ModuleNotFoundError: No module named 'sniffio':pip install sniffio
2025.12.24(Python 3.9)现在不需要手动安装sniffio了,但是需要手动降低cryptography包的版本:pip install cryptography==41.0.21
否则会报这个bug:
Traceback (most recent call last):
File "D:\codes\kpcode\tryai\try2.py", line 3, in <module>
from zai import ZhipuAiClient
File "env_path\lib\site-packages\zai\__init__.py", line 1, in <module>
from ._client import ZaiClient, ZhipuAiClient
File "env_path\lib\site-packages\zai\_client.py", line 29, in <module>
from .core import (
File "env_path\lib\site-packages\zai\core\_jwt_token.py", line 5, in <module>
import jwt
File "env_path\lib\site-packages\jwt\__init__.py", line 1, in <module>
from .api_jwk import PyJWK, PyJWKSet
File "env_path\lib\site-packages\jwt\api_jwk.py", line 7, in <module>
from .algorithms import get_default_algorithms, has_crypto, requires_cryptography
File "env_path\lib\site-packages\jwt\algorithms.py", line 11, in <module>
from .utils import (
File "env_path\lib\site-packages\jwt\utils.py", line 7, in <module>
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve
File "env_path\lib\site-packages\cryptography\hazmat\primitives\asymmetric\ec.py", line 11, in <module>
from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
File "env_path\lib\site-packages\cryptography\exceptions.py", line 9, in <module>
from cryptography.hazmat.bindings._rust import exceptions as rust_exceptions
ImportError: DLL load failed while importing _rust: 找不到指定的程序。
文本→文本
from zai import ZhipuAiClient
client = ZhipuAiClient(api_key=api_key)
# Create chat completion
response = client.chat.completions.create(
model="GLM-4.5-Flash",
messages=[{"role": "user", "content": "你好,请介绍一下自己, Z.ai!"}],
)
print(response.choices[0].message.content)
(如果设置环境变量设置ZAI_API_KEY为api_key,就不用再传入api_key参数)
2.2 使用HTTP API
headers的Authorization的两种写法
以下代码中Authorization都以Bearer key的形式来写。这个key可以直接填ChatGLM的API KEY,也可以填JWT token。
JWT token会更安全一些
文本→文本
import requests
def call_zhipu_api(messages, model="glm-4.7"):
url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
headers = {
"Authorization": f"Bearer {chatglm_api_key}",
"Content-Type": "application/json",
}
data = {"model": model, "messages": messages, "temperature": 1.0}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"API调用失败: {response.status_code}, {response.text}")
# 使用示例
messages = [{"role": "user", "content": "你好,请介绍一下自己"}]
result = call_zhipu_api(messages)
print(result["choices"][0]["message"]["content"])