智谱 AI 免费 API 调用
智谱 AI 提供免费的模型 API 服务,支持 HTTP、Python、Java、JavaScript 等多种调用方式。以下是基于 Python SDK 的调用示例。
1. 获取 API Key
- 访问官网注册登录。
- 点击右上角控制台。
- 选择 API-Key,添加新的 API-Key 并命名确认。
- 在开发文档中查看免费模型列表。
2. 安装 Python SDK
首先安装 Python SDK:
pip install zai-sdk
验证安装是否成功:
import zai
print(zai.__version__)
3. 循环对话示例
以下是一个使用 glm-4.5-flash 免费模型的循环对话 Python 样例,请替换为你的 API Key 进行测试。
from zai import ZhipuAiClient
def main():
# 初始化客户端
client = ZhipuAiClient(api_key='你的 api-key')
print("欢迎使用 Z.ai 聊天机器人!输入 'quit' 退出。")
# 对话历史
conversation = [{"role": "system", "content": "你是一个友好的 AI 助手"}]
while True:
# 获取用户输入
user_input = input("您:")
if user_input.lower() == 'quit':
break
try:
# 添加用户消息
conversation.append({"role": "user", "content": user_input})
# 创建聊天请求
response = client.chat.completions.create(
model="glm-4.5-flash",
messages=conversation,
temperature=0.7,
max_tokens=,
thinking={: }
)
ai_response = response.choices[].message.content
()
conversation.append({: , : ai_response})
Exception e:
()
()
__name__ == :
main()


