智谱AI: ChatGLM API的使用

一、获取API

1、打开网址:智谱AI开放平台 注册账号登录

2、登录,查看API key (注册后赠送100万token,实名认证后多赠送400万, 有效期一个)

二、安装及调用

安装质谱SDK

shell 复制代码
pip install zhipuai

调用方式

  1. 流式调用

    python 复制代码
    from zhipuai import ZhipuAI
    client = ZhipuAI(api_key="") # 请填写您自己的APIKey
    response = client.chat.completions.create(
      model="glm-4",  # 填写需要调用的模型名称
        messages=[
            {"role": "user", "content": "你好!你叫什么名字"},
        ],
        stream=True,
        )
    for chunk in response:
        print(chunk.choices[0].delta)
  2. 非流式调用

    python 复制代码
    from zhipuai import ZhipuAI
    client = ZhipuAI(api_key="") # 填写您自己的APIKey
    response = client.chat.completions.create(
        model="glm-4",  # 填写需要调用的模型名称
        messages=[
            {"role": "user", "content": "作为一名营销专家,请为我的产品创作一个吸引人的slogan"},
            {"role": "assistant", "content": "当然,为了创作一个吸引人的slogan,请告诉我一些关于您产品的信息"},
            {"role": "user", "content": "智谱AI开放平台"},
            {"role": "assistant", "content": "智启未来,谱绘无限一智谱AI,让创新触手可及!"},
            {"role": "user", "content": "创造一个更精准、吸引人的slogan"}
        ],
    )
    print(response.choices[0].message)

具体调用参数可参考官方文档: 智谱AI接口文档

相关推荐
花酒锄作田13 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪16 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽17 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战17 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama