下面通过智谱的 HTTP 接口完成一次非流式对话。先跑通请求,再接入 SDK;旧示例里的自行签 JWT、手工拼接 JSON 和历史模型枚举不作为入门步骤。
准备 API Key 与模型
在自己的平台账号创建 API Key,并选一个账号有权使用的模型 ID。是否收费、额度和速率限制以控制台为准。
PowerShell 中设置当前进程的环境变量:
$env:GLM_API_KEY = '填写自己的API Key'$env:GLM_MODEL = '填写可用的模型ID'密钥不写进文章、Git 仓库或前端网页。当前官方接口支持 Authorization: Bearer API_KEY,这里直接使用密钥认证。
完整 Python 请求
需要 Python 3,不需要额外依赖。保存为 chat.py:
import jsonimport osfrom urllib.error import HTTPErrorfrom urllib.request import Request, urlopen
api_key = os.environ['GLM_API_KEY']model = os.environ['GLM_MODEL']payload = { 'model': model, 'messages': [{'role': 'user', 'content': '用一句话解释视频转码'}], 'stream': False,}request = Request( 'https://open.bigmodel.cn/api/paas/v4/chat/completions', data=json.dumps(payload, ensure_ascii=False).encode('utf-8'), headers={'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json'}, method='POST',)try: with urlopen(request, timeout=60) as response: result = json.load(response)except HTTPError as error: with error: detail = error.read().decode('utf-8', errors='replace') raise RuntimeError(f'HTTP {error.code}: {detail}') from error
choices = result.get('choices') or []if not choices: raise RuntimeError('响应中没有 choices,请检查错误响应与所选模型类型')print(choices[0]['message'].get('content', ''))python .\chat.pymessages 保存本次发送的对话,stream=False 是 JSON 布尔值。json.dumps 负责转义引号和换行,不能把任意用户内容直接拼到 JSON 字符串里。下一轮想保留上下文,需要由应用把相关历史消息一起发送。
401 先查密钥,429 查额度或速率,超时查网络和模型响应时间。接口返回成功也不能保证生成内容正确;代码和事实仍需验证。
参考:智谱 API 快速开始。
评论