如何调用智谱清言GLM系API实现智能问答

本文介绍了如何通过注册智谱AI获取APIkey,然后使用Python实现GLM-4API进行智能问答,包括使用SDK和直接请求的方式。

诸神缄默不语-个人CSDN博文目录

GLM系列大模型是智谱AI提供的系列语言模型。本文介绍如何用Python语言调用GLM的API实现智能问答。

智谱大模型开放平台:https://www.bigmodel.cn/claude-code?ic=UDLTAAXDGI
官方文档:https://docs.bigmodel.cn/cn/guide/start/introduction

模型报价:https://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

https://docs.bigmodel.cn/cn/guide/develop/python/introduction

需要使用的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"])

  1. python使用库cryptography报错如何解决_cryptography 版本过高-CSDN博客 ↩︎

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诸神缄默不语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值