Loading... # 智谱AI HTTP API 调用教程 # 一、概述 ## 1. 简介 ### A. 是什么 智谱AI 提供基于 RESTful 架构的应用程序接口,通过标准的 HTTP 协议与智谱AI 的模型服务进行交互。开发者可以使用任何支持 HTTP 协议的编程语言或开发框架调用智谱AI 的各种 AI 模型。 ### B. 为什么学 - 跨平台兼容:支持所有支持 HTTP 协议的编程语言和平台 - 标准协议:基于 RESTful 设计,遵循 HTTP 标准,易于理解和使用 - 灵活集成:可以集成到任何现有的应用程序和系统中 - 实时调用:支持同步和异步调用,满足不同场景需求 ### C. 学完能做什么 - 使用任何编程语言调用智谱AI 的 GLM 系列模型 - 实现简单对话、流式响应和多轮对话功能 - 正确处理 API 鉴权和错误响应 - 在生产环境中安全、高效地集成智谱AI 服务 # 二、环境准备 ## 1. 前置条件 - 有效的智谱AI 账户 - 已获取 API Key - 基本的 HTTP 请求知识 - 至少熟悉一种编程语言(Python、JavaScript、Java 等) ## 2. 获取 API Key ### 步骤流程 1. 访问智谱AI 开放平台:https://bigmodel.cn 2. 注册并登录账户 3. 进入 API Keys 管理页面创建 API Key 4. 复制生成的 API Key 以供使用 ### 安全建议 建议将 API Key 设置为环境变量,避免硬编码到代码中,以提高安全性。 # 三、API 基础信息 ## 1. 请求端点 ### 通用 API 端点 ``` https://open.bigmodel.cn/api/paas/v4/ ``` ### Coding 专用端点 使用 GLM 编码套餐时,需要使用专属端点: ``` https://open.bigmodel.cn/api/coding/paas/v4 ``` 注意:Coding API 端点仅限 Coding 场景使用,不适用于通用 API 场景。 ## 2. 请求头要求 所有请求必须包含以下 HTTP 头: | 请求头 | 值 | 说明 | |-------|---|------| | Content-Type | application/json | 指定请求体格式为 JSON | | Authorization | Bearer YOUR_API_KEY | API 密钥鉴权 | ## 3. 支持的鉴权方式 ### A. API Key 鉴权 最简单的鉴权方式,直接使用 API Key: ```bash curl --location 'https://open.bigmodel.cn/api/paas/v4/chat/completions' \ --header 'Authorization: Bearer YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "model": "glm-4.7", "messages": [ { "role": "user", "content": "你好" } ] }' ``` ### B. JWT Token 鉴权 适用于需要更复杂权限控制的场景(具体实现请参考官方文档)。 # 四、基础调用示例 ## 1. 简单对话 ### 请求示例 ```bash curl --location 'https://open.bigmodel.cn/api/paas/v4/chat/completions' \ --header 'Authorization: Bearer YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "model": "glm-4.7", "messages": [ { "role": "user", "content": "请介绍一下人工智能的发展历程" } ], "temperature": 1.0, "max_tokens": 1024 }' ``` ### 参数说明 - model:使用的模型名称,如 glm-4.7 - messages:对话消息列表 - temperature:控制输出随机性,范围 0-2,默认 1.0 - max_tokens:限制响应最大 token 数 ## 2. 流式响应 ### 请求示例 ```bash curl --location 'https://open.bigmodel.cn/api/paas/v4/chat/completions' \ --header 'Authorization: Bearer YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "model": "glm-4.7", "messages": [ { "role": "user", "content": "写一首关于春天的诗" } ], "stream": true }' ``` ### 流式响应特点 - 设置 stream 参数为 true 启用流式响应 - 响应以 Server-Sent Events(SSE)格式返回 - 可以实时获取模型生成的内容 ## 3. 多轮对话 ### 请求示例 ```bash curl --location 'https://open.bigmodel.cn/api/paas/v4/chat/completions' \ --header 'Authorization: Bearer YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "model": "glm-4.7", "messages": [ { "role": "system", "content": "你是一个专业的编程助手" }, { "role": "user", "content": "什么是递归?" }, { "role": "assistant", "content": "递归是一种编程技术,函数调用自身来解决问题..." }, { "role": "user", "content": "能给我一个 Python 递归的例子吗?" } ] }' ``` ### 消息角色说明 - system:设置系统角色和行为 - user:用户消息 - assistant:模型回复的历史消息 # 五、常用编程语言示例 ## 1. Python 实现 ### 完整代码示例 ```python import requests import json def call_zhipu_api(messages, model="glm-4.7"): url = "https://open.bigmodel.cn/api/paas/v4/chat/completions" headers = { "Authorization": "Bearer YOUR_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']) ``` ### 环境变量配置 ```python import os from dotenv import load_dotenv load_dotenv() api_key = os.getenv("ZHIPU_API_KEY") ``` ## 2. JavaScript 实现 ### 使用 Fetch API ```javascript async function callZhipuAPI(messages) { const url = 'https://open.bigmodel.cn/api/paas/v4/chat/completions'; const headers = { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }; const data = { model: 'glm-4.7', messages: messages, temperature: 1.0 }; const response = await fetch(url, { method: 'POST', headers: headers, body: JSON.stringify(data) }); if (!response.ok) { throw new Error(`API调用失败: ${response.status}`); } return await response.json(); } // 使用示例 const messages = [ {role: 'user', content: '你好'} ]; callZhipuAPI(messages).then(result => { console.log(result.choices[0].message.content); }); ``` ## 3. Java 实现 ### 使用 OkHttp ```java import okhttp3.*; import com.google.gson.Gson; import java.io.IOException; public class ZhipuAPIClient { private static final String API_URL = "https://open.bigmodel.cn/api/paas/v4/chat/completions"; private static final String API_KEY = "YOUR_API_KEY"; private final OkHttpClient client; private final Gson gson; public ZhipuAPIClient() { this.client = new OkHttpClient(); this.gson = new Gson(); } public String callAPI(Message[] messages) throws IOException { RequestBody body = RequestBody.create( MediaType.parse("application/json"), gson.toJson(new ChatRequest("glm-4.7", messages)) ); Request request = new Request.Builder() .url(API_URL) .post(body) .addHeader("Authorization", "Bearer " + API_KEY) .addHeader("Content-Type", "application/json") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException("API调用失败: " + response); } ChatResponse chatResponse = gson.fromJson( response.body().string(), ChatResponse.class ); return chatResponse.choices[0].message.content; } } } ``` # 六、错误处理 ## 1. 常见错误码 | 错误码 | 说明 | 解决方案 | |-------|------|---------| | 401 | 未授权 | 检查 API Key 是否正确 | | 429 | 请求过于频繁 | 降低请求频率,实施重试机制 | | 500 | 服务器内部错误 | 稍后重试,如持续出现请联系支持 | 更多错误码和解决方案请参考官方 API 错误码文档。 ## 2. 错误处理最佳实践 ### 实施指数退避重试机制 ```python import time import random def call_with_retry(func, max_retries=3): for attempt in range(max_retries): try: return func() except Exception as e: if attempt == max_retries - 1: raise wait_time = (2 ** attempt) + random.random() time.sleep(wait_time) ``` ### 记录详细错误日志 ```python import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) try: result = call_zhipu_api(messages) except Exception as e: logger.error(f"API调用失败: {str(e)}", exc_info=True) ``` # 七、实践建议 ## 1. 安全性 ### A. API Key 管理 - 妥善保管 API Key,不要在代码中硬编码 - 使用环境变量或配置文件存储敏感信息 - 定期轮换 API Key ### B. 数据传输 - 始终使用 HTTPS 协议 - 实施适当的加密措施保护数据传输 ## 2. 性能优化 ### A. 连接管理 - 实施连接池和会话复用 - 合理设置超时时间 ### B. 并发处理 - 使用异步请求处理高并发场景 - 考虑使用消息队列削峰填谷 ## 3. 监控与告警 ### A. 关键指标 - 监控 API 调用频率和成功率 - 跟踪响应时间和错误率 ### B. 告警机制 - 设置合理的告警阈值 - 建立快速响应流程 # 八、架构图 ```mermaid sequenceDiagram participant Client as 客户端应用 participant API as 智谱AI API participant Auth as 鉴权服务 participant Model as GLM 模型 Client->>Auth: 1. 携带 API Key Auth->>API: 2. 验证通过 Client->>API: 3. 发送 HTTP 请求 API->>Model: 4. 调用模型推理 Model->>API: 5. 返回生成结果 API->>Client: 6. 返回 JSON 响应 ```  # 九、更多资源 ## 1. 官方文档 - API 文档:查看完整的 API 接口文档和参数说明 - 技术支持:获取技术支持和帮助 ## 2. 相关资源 - 核心参数文档 - 官方 Python SDK *** ## 参考资料 1. [智谱AI HTTP API 调用文档](https://docs.bigmodel.cn/cn/guide/develop/http/introduction) 最后修改:2026 年 01 月 20 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请随意赞赏