GLM-4-9B-Chat-1M开发者实操手册:REST API调用、stream流式响应、错误码处理

发布时间:2026/7/11 5:09:13

GLM-4-9B-Chat-1M开发者实操手册:REST API调用、stream流式响应、错误码处理 GLM-4-9B-Chat-1M开发者实操手册REST API调用、stream流式响应、错误码处理1. 开篇为什么你需要这份实操手册如果你正在寻找一个能处理超长文本、支持多轮对话、还能调用工具的开源大模型那么GLM-4-9B-Chat-1M很可能就是你的答案。这个模型最吸引人的地方就是它支持长达1M约200万中文字符的上下文窗口这意味着你可以把整本书、长篇报告或者复杂的代码库扔给它分析。但问题来了模型能力再强如果不知道怎么用那也是白搭。很多开发者拿到模型镜像后只会用网页界面点点按钮不知道怎么通过代码来调用更别提处理流式响应和错误了。这份手册就是来解决这个问题的。我会手把手带你从零开始学会如何通过REST API调用GLM-4-9B-Chat-1M怎么处理流式响应让对话更流畅以及遇到错误时该怎么排查和解决。看完之后你就能把这个强大的模型集成到自己的应用里了。2. 环境准备确认你的模型服务已经就绪在开始写代码之前我们得先确认模型服务已经正常启动了。如果你用的是CSDN星图镜像广场提供的预置镜像这一步通常很简单。2.1 检查服务状态打开终端运行下面这个命令看看模型加载的日志cat /root/workspace/llm.log如果看到类似下面的输出就说明模型已经加载成功服务正在运行INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRLC to quit) INFO: Started server process [1] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Model loaded successfully: glm-4-9b-chat-1m关键信息在这里服务运行在http://0.0.0.0:8000这是我们后面调用API的地址。2.2 了解API端点vLLM部署的模型通常会提供几个标准的API端点/v1/completions- 用于文本补全/v1/chat/completions- 用于对话我们主要用这个/v1/models- 获取模型信息/health- 健康检查记下这些端点我们马上就会用到。3. 基础调用你的第一个API请求让我们从一个最简单的例子开始。假设你想让模型帮你写一段Python代码计算斐波那契数列。3.1 使用Python的requests库首先确保你安装了requests库pip install requests然后创建一个简单的Python脚本import requests import json # API的基础地址 BASE_URL http://localhost:8000/v1 def simple_chat(): 最简单的对话示例 # 构造请求数据 payload { model: glm-4-9b-chat-1m, messages: [ { role: user, content: 用Python写一个计算斐波那契数列的函数要求能处理前20项 } ], max_tokens: 500, # 最大生成token数 temperature: 0.7, # 温度参数控制随机性 stream: False # 非流式响应 } try: # 发送POST请求 response requests.post( f{BASE_URL}/chat/completions, jsonpayload, headers{Content-Type: application/json} ) # 检查响应状态 if response.status_code 200: result response.json() # 提取模型回复 reply result[choices][0][message][content] print(模型回复) print(reply) print(f\n本次消耗token数{result.get(usage, {}).get(total_tokens, 未知)}) else: print(f请求失败状态码{response.status_code}) print(f错误信息{response.text}) except requests.exceptions.ConnectionError: print(连接失败请检查服务是否启动) except Exception as e: print(f发生错误{str(e)}) if __name__ __main__: simple_chat()运行这个脚本你应该能看到模型生成的Python代码。如果一切正常恭喜你你已经成功调用了GLM-4-9B-Chat-1M3.2 理解请求参数让我解释一下上面用到的几个关键参数model指定要使用的模型名称这里固定为glm-4-9b-chat-1mmessages对话历史是一个列表每个元素包含role角色和content内容role可以是system系统提示、user用户、assistant助手max_tokens限制模型生成的最大token数防止生成过长内容temperature控制生成随机性的参数值越高接近1.0输出越随机、有创意值越低接近0输出越确定、保守一般设置在0.6-0.9之间stream是否使用流式响应False表示一次性返回完整结果4. 流式响应让对话更流畅如果你用过ChatGPT的网页版会发现它的回复是一个字一个字慢慢出现的这就是流式响应。这种体验比等完整回复生成完再一次性显示要好得多。4.1 什么是流式响应简单说流式响应就是服务器一边生成内容一边把生成的内容分块发送给客户端。这样客户端可以实时显示部分结果用户不用干等着。4.2 实现流式调用修改我们之前的代码启用流式响应import requests import json def stream_chat(): 流式对话示例 payload { model: glm-4-9b-chat-1m, messages: [ { role: user, content: 给我讲一个关于人工智能的短故事大约200字 } ], max_tokens: 300, temperature: 0.8, stream: True # 启用流式响应 } print(开始生成故事...\n) try: # 发送流式请求 with requests.post( f{BASE_URL}/chat/completions, jsonpayload, headers{Content-Type: application/json}, streamTrue # 重要启用流式接收 ) as response: if response.status_code 200: full_response # 逐行读取流式响应 for line in response.iter_lines(): if line: line line.decode(utf-8) # 跳过SSE格式的前缀 if line.startswith(data: ): data_str line[6:] # 去掉data: 前缀 if data_str [DONE]: print(\n\n故事生成完成) break try: data json.loads(data_str) # 提取增量内容 delta data.get(choices, [{}])[0].get(delta, {}) content delta.get(content, ) if content: print(content, end, flushTrue) full_response content except json.JSONDecodeError: # 忽略非JSON数据 pass else: print(f请求失败{response.status_code}) print(response.text) except Exception as e: print(f流式请求出错{str(e)}) if __name__ __main__: stream_chat()运行这个脚本你会看到故事一个字一个字地出现就像有人在实时打字一样。4.3 流式响应的优势更好的用户体验用户不用等待完整响应可以边生成边阅读实时反馈如果生成的内容不符合预期可以提前中断内存友好客户端可以边接收边处理不需要缓存完整响应适合长文本对于GLM-4-9B-Chat-1M支持的1M长文本流式响应几乎是必须的5. 处理长文本发挥1M上下文的威力GLM-4-9B-Chat-1M最大的特点就是支持1M上下文。这意味着什么意味着你可以上传整篇论文让它总结给一个完整的代码库让它分析进行超长的多轮对话处理复杂的文档分析任务5.1 长文本处理示例让我们试试让模型分析一篇长文档def long_context_chat(): 长上下文对话示例 # 模拟一个长文档这里用重复文本模拟实际使用时可以读取文件 long_document 人工智能AI是计算机科学的一个分支它企图了解智能的实质并生产出一种新的能以人类智能相似的方式做出反应的智能机器。 该领域的研究包括机器人、语言识别、图像识别、自然语言处理和专家系统等。人工智能从诞生以来理论和技术日益成熟应用领域也不断扩大。 人工智能的发展经历了几个阶段 1. 1950年代人工智能的诞生图灵测试提出 2. 1960-1970年代符号主义AI的发展 3. 1980年代专家系统的兴起 4. 1990年代机器学习开始受到关注 5. 2000年代至今深度学习革命 当前AI的主要应用领域包括 - 自然语言处理机器翻译、情感分析、智能客服 - 计算机视觉人脸识别、自动驾驶、医疗影像分析 - 语音识别智能助手、语音转文字 - 推荐系统电商推荐、内容推荐 AI面临的挑战 - 数据隐私和安全问题 - 算法偏见和公平性 - 可解释性问题 - 就业影响和社会伦理 * 50 # 重复50次模拟长文档 print(f文档长度约{len(long_document)}字符) payload { model: glm-4-9b-chat-1m, messages: [ { role: system, content: 你是一个AI技术专家擅长总结和分析长文档。 }, { role: user, content: f请分析以下关于人工智能的长文档并回答\n\n{long_document}\n\n问题根据文档内容总结AI发展的主要阶段和当前面临的主要挑战。 } ], max_tokens: 800, temperature: 0.3, # 对于分析任务温度可以设低一些 stream: False } try: response requests.post( f{BASE_URL}/chat/completions, jsonpayload, headers{Content-Type: application/json}, timeout60 # 长文本处理需要更长时间 ) if response.status_code 200: result response.json() reply result[choices][0][message][content] print(\n *50) print(模型分析结果) print(*50) print(reply) usage result.get(usage, {}) print(f\nToken使用情况) print(f 输入token{usage.get(prompt_tokens, N/A)}) print(f 输出token{usage.get(completion_tokens, N/A)}) print(f 总token{usage.get(total_tokens, N/A)}) else: print(f请求失败{response.status_code}) print(response.text) except requests.exceptions.Timeout: print(请求超时长文本处理可能需要更多时间) except Exception as e: print(f错误{str(e)}) if __name__ __main__: long_context_chat()5.2 长文本处理的最佳实践分批处理如果文档实在太长可以考虑分批发送使用system提示明确告诉模型你的需求调整temperature分析类任务建议用较低的temperature0.3-0.5设置合理超时长文本处理需要时间设置足够的超时时间监控token使用关注usage字段了解资源消耗6. 错误处理遇到问题怎么办在实际使用中你肯定会遇到各种错误。好的错误处理能让你的应用更健壮。6.1 常见的错误类型让我带你看看可能会遇到哪些错误以及怎么处理def handle_errors(): 错误处理示例 test_cases [ { name: 正常请求, payload: { model: glm-4-9b-chat-1m, messages: [{role: user, content: 你好}], max_tokens: 50 } }, { name: 模型名称错误, payload: { model: wrong-model-name, # 错误的模型名 messages: [{role: user, content: 你好}], max_tokens: 50 } }, { name: 消息格式错误, payload: { model: glm-4-9b-chat-1m, messages: 不是列表格式, # 错误的格式 max_tokens: 50 } }, { name: token数超限, payload: { model: glm-4-9b-chat-1m, messages: [{role: user, content: 你好}], max_tokens: 100000 # 设置过大 } } ] for test in test_cases: print(f\n测试{test[name]}) print(- * 30) try: response requests.post( f{BASE_URL}/chat/completions, jsontest[payload], headers{Content-Type: application/json}, timeout10 ) print(f状态码{response.status_code}) if response.status_code 200: print(✓ 请求成功) result response.json() if error in result: print(f错误信息{result[error]}) else: print(f✗ 请求失败) try: error_data response.json() print(f错误详情{error_data}) except: print(f响应内容{response.text}) except requests.exceptions.ConnectionError: print(✗ 连接失败 - 服务可能未启动) except requests.exceptions.Timeout: print(✗ 请求超时) except Exception as e: print(f✗ 其他错误{str(e)}) time.sleep(1) # 避免请求过快 if __name__ __main__: handle_errors()6.2 错误码和含义vLLM API通常返回标准的HTTP状态码和错误信息400 Bad Request请求参数错误模型名称不对消息格式错误参数类型错误404 Not FoundAPI端点不存在422 Unprocessable Entity参数验证失败429 Too Many Requests请求频率过高500 Internal Server Error服务器内部错误503 Service Unavailable服务不可用模型可能正在加载6.3 健壮的错误处理策略在实际应用中我建议你这样处理错误class GLMClient: 一个更健壮的GLM客户端示例 def __init__(self, base_urlhttp://localhost:8000/v1): self.base_url base_url self.session requests.Session() self.max_retries 3 self.retry_delay 1 # 秒 def chat(self, messages, max_tokens500, temperature0.7, streamFalse): 发送聊天请求包含重试机制 payload { model: glm-4-9b-chat-1m, messages: messages, max_tokens: max_tokens, temperature: temperature, stream: stream } for attempt in range(self.max_retries): try: if stream: return self._stream_chat(payload) else: return self._normal_chat(payload) except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e: if attempt self.max_retries - 1: print(f请求失败{self.retry_delay}秒后重试... ({attempt 1}/{self.max_retries})) time.sleep(self.retry_delay) self.retry_delay * 2 # 指数退避 else: raise Exception(f请求失败已重试{self.max_retries}次: {str(e)}) except Exception as e: # 其他错误不重试 raise e def _normal_chat(self, payload): 普通聊天请求 response self.session.post( f{self.base_url}/chat/completions, jsonpayload, headers{Content-Type: application/json}, timeout30 ) response.raise_for_status() # 如果状态码不是200抛出异常 result response.json() # 检查API返回的错误 if error in result: error_msg result[error].get(message, 未知错误) error_type result[error].get(type, api_error) raise Exception(fAPI错误 [{error_type}]: {error_msg}) return result def _stream_chat(self, payload): 流式聊天请求 # 流式处理逻辑这里省略具体实现 pass def health_check(self): 健康检查 try: response self.session.get(f{self.base_url}/models, timeout5) return response.status_code 200 except: return False # 使用示例 if __name__ __main__: client GLMClient() # 先检查服务状态 if client.health_check(): print(服务正常) # 发送请求 messages [ {role: user, content: 你好请介绍一下你自己} ] try: result client.chat(messages, max_tokens200) print(result[choices][0][message][content]) except Exception as e: print(f请求失败: {str(e)}) else: print(服务不可用请检查模型是否已启动)7. 高级功能工具调用和函数调用GLM-4-9B-Chat-1M支持工具调用Function Call这让它能够执行更复杂的任务。比如你可以定义一些工具函数让模型在需要的时候调用它们。7.1 工具调用示例def function_call_example(): 工具调用示例 # 定义可用的工具函数 tools [ { type: function, function: { name: get_weather, description: 获取指定城市的天气信息, parameters: { type: object, properties: { city: { type: string, description: 城市名称如北京、上海 }, date: { type: string, description: 日期格式为YYYY-MM-DD默认为今天, default: today } }, required: [city] } } }, { type: function, function: { name: calculate, description: 执行数学计算, parameters: { type: object, properties: { expression: { type: string, description: 数学表达式如2 3 * 4 } }, required: [expression] } } } ] # 模拟的工具函数实现 def execute_tool_call(tool_call): 执行工具调用 function_name tool_call[function][name] arguments json.loads(tool_call[function][arguments]) if function_name get_weather: city arguments.get(city, 未知城市) date arguments.get(date, 今天) return f{city}在{date}的天气是晴朗温度25°C elif function_name calculate: expression arguments.get(expression, ) try: # 注意实际应用中不要用eval这里只是示例 result eval(expression) return f{expression} {result} except: return f无法计算表达式: {expression} return 未知工具调用 # 对话历史 messages [ { role: user, content: 今天北京天气怎么样然后帮我计算一下(15 27) * 3等于多少 } ] payload { model: glm-4-9b-chat-1m, messages: messages, tools: tools, tool_choice: auto, # 让模型自动决定是否调用工具 max_tokens: 500 } try: # 第一轮模型决定调用工具 response requests.post( f{BASE_URL}/chat/completions, jsonpayload, headers{Content-Type: application/json} ) if response.status_code 200: result response.json() message result[choices][0][message] print(第一轮响应) print(json.dumps(message, ensure_asciiFalse, indent2)) # 检查是否有工具调用 if tool_calls in message and message[tool_calls]: print(\n检测到工具调用执行工具...) # 将模型的响应添加到对话历史 messages.append(message) # 执行所有工具调用 for tool_call in message[tool_calls]: tool_result execute_tool_call(tool_call) # 将工具执行结果添加到对话历史 messages.append({ role: tool, tool_call_id: tool_call[id], content: tool_result }) # 第二轮将工具结果发送给模型 payload[messages] messages response2 requests.post( f{BASE_URL}/chat/completions, jsonpayload, headers{Content-Type: application/json} ) if response2.status_code 200: result2 response2.json() final_reply result2[choices][0][message][content] print(\n最终回复) print(final_reply) else: print(f请求失败{response.status_code}) print(response.text) except Exception as e: print(f错误{str(e)}) if __name__ __main__: function_call_example()7.2 工具调用的使用场景工具调用功能非常强大适合这些场景数据查询查询数据库、API数据计算任务执行复杂计算文件操作读写文件、处理文档系统操作执行系统命令需谨慎外部服务集成调用其他服务的API8. 实战项目构建一个简单的AI对话应用现在让我们把前面学到的所有知识结合起来构建一个完整的AI对话应用。8.1 完整的客户端实现import requests import json import time from typing import List, Dict, Optional, Iterator import threading class GLMChatClient: GLM-4-9B-Chat-1M聊天客户端 def __init__(self, base_url: str http://localhost:8000/v1): 初始化客户端 Args: base_url: API基础地址 self.base_url base_url self.session requests.Session() self.conversation_history: List[Dict] [] def add_message(self, role: str, content: str): 添加消息到对话历史 self.conversation_history.append({ role: role, content: content }) def clear_history(self): 清空对话历史 self.conversation_history.clear() def chat(self, user_input: str, system_prompt: Optional[str] None, max_tokens: int 500, temperature: float 0.7, stream: bool False) - str: 发送聊天请求 Args: user_input: 用户输入 system_prompt: 系统提示词 max_tokens: 最大生成token数 temperature: 温度参数 stream: 是否使用流式响应 Returns: 模型回复内容 # 添加用户消息到历史 self.add_message(user, user_input) # 构建消息列表 messages [] # 添加系统提示如果有 if system_prompt: messages.append({role: system, content: system_prompt}) # 添加上下文历史最后10轮对话避免过长 context_messages self.conversation_history[-20:] # 最多保留10轮对话 messages.extend(context_messages) # 构建请求数据 payload { model: glm-4-9b-chat-1m, messages: messages, max_tokens: max_tokens, temperature: temperature, stream: stream } try: if stream: return self._stream_chat(payload) else: return self._normal_chat(payload) except Exception as e: # 从历史中移除失败的用户输入 if self.conversation_history and self.conversation_history[-1][role] user: self.conversation_history.pop() raise e def _normal_chat(self, payload: Dict) - str: 普通聊天请求 response self.session.post( f{self.base_url}/chat/completions, jsonpayload, headers{Content-Type: application/json}, timeout60 ) if response.status_code ! 200: error_msg f请求失败: {response.status_code} try: error_data response.json() if error in error_data: error_msg f - {error_data[error].get(message, 未知错误)} except: error_msg f\n{response.text} raise Exception(error_msg) result response.json() # 提取回复内容 if choices in result and len(result[choices]) 0: reply result[choices][0][message][content] # 添加助手回复到历史 self.add_message(assistant, reply) # 打印token使用情况可选 if usage in result: usage result[usage] print(f[Token使用: 输入{usage.get(prompt_tokens, 0)} | f输出{usage.get(completion_tokens, 0)} | f总计{usage.get(total_tokens, 0)}]) return reply else: raise Exception(响应格式错误) def _stream_chat(self, payload: Dict) - str: 流式聊天请求 full_reply try: with self.session.post( f{self.base_url}/chat/completions, jsonpayload, headers{Content-Type: application/json}, streamTrue, timeout60 ) as response: if response.status_code ! 200: error_text response.text raise Exception(f流式请求失败: {response.status_code}\n{error_text}) print(AI: , end, flushTrue) for line in response.iter_lines(): if line: line line.decode(utf-8) if line.startswith(data: ): data_str line[6:] if data_str [DONE]: break try: data json.loads(data_str) delta data.get(choices, [{}])[0].get(delta, {}) content delta.get(content, ) if content: print(content, end, flushTrue) full_reply content except json.JSONDecodeError: continue print() # 换行 # 添加助手回复到历史 self.add_message(assistant, full_reply) return full_reply except Exception as e: # 从历史中移除失败的用户输入 if self.conversation_history and self.conversation_history[-1][role] user: self.conversation_history.pop() raise e def get_history(self) - List[Dict]: 获取对话历史 return self.conversation_history.copy() def export_history(self, filepath: str): 导出对话历史到文件 with open(filepath, w, encodingutf-8) as f: json.dump(self.conversation_history, f, ensure_asciiFalse, indent2) def load_history(self, filepath: str): 从文件加载对话历史 with open(filepath, r, encodingutf-8) as f: self.conversation_history json.load(f) # 使用示例 def interactive_chat(): 交互式聊天示例 client GLMChatClient() print( * 50) print(GLM-4-9B-Chat-1M 交互式聊天) print(输入 quit 退出clear 清空历史history 查看历史) print( * 50) # 设置系统提示可选 system_prompt 你是一个有帮助的AI助手回答要简洁明了。 while True: try: user_input input(\n你: ).strip() if not user_input: continue if user_input.lower() quit: print(再见) break elif user_input.lower() clear: client.clear_history() print(对话历史已清空) continue elif user_input.lower() history: history client.get_history() if not history: print(对话历史为空) else: print(\n对话历史:) for msg in history[-10:]: # 显示最近10条 role 用户 if msg[role] user else AI print(f{role}: {msg[content][:50]}...) continue # 选择响应模式 use_stream input(使用流式响应(y/n, 默认n): ).strip().lower() y print() try: reply client.chat( user_inputuser_input, system_promptsystem_prompt, max_tokens500, temperature0.7, streamuse_stream ) if not use_stream: print(fAI: {reply}) except Exception as e: print(f错误: {str(e)}) except KeyboardInterrupt: print(\n\n对话结束) break except Exception as e: print(f系统错误: {str(e)}) if __name__ __main__: interactive_chat()8.2 应用功能说明这个完整的客户端提供了以下功能对话历史管理自动维护对话上下文流式/非流式切换根据需要选择响应模式错误处理完善的异常处理机制历史导出/导入保存和加载对话记录交互式界面方便测试和演示Token统计监控资源使用情况你可以基于这个客户端进一步开发Web界面使用Flask/FastAPI桌面应用使用PyQt/Tkinter集成到现有系统中添加更多高级功能工具调用、文件上传等9. 总结从入门到实战通过这份手册我们从最基础的API调用开始一步步深入最后构建了一个完整的AI对话应用。让我们回顾一下关键要点9.1 核心要点回顾环境确认是关键在开始编码前一定要确认模型服务已经正常启动理解API参数掌握messages、max_tokens、temperature、stream等核心参数的含义和用法流式响应提升体验对于长文本或需要实时反馈的场景流式响应是更好的选择充分利用长上下文GLM-4-9B-Chat-1M的1M上下文是它的核心优势适合处理超长文档健壮的错误处理网络错误、参数错误、服务错误都需要妥善处理工具调用扩展能力通过函数调用让模型能够执行更复杂的任务完整的客户端设计考虑对话历史管理、配置管理、错误重试等实际需求9.2 性能优化建议在实际使用中你可能会遇到性能问题。这里有一些优化建议合理设置max_tokens根据实际需要设置不要盲目设大批量处理请求如果需要处理大量相似请求考虑批量发送缓存重复内容对于相同的查询可以考虑缓存结果监控资源使用关注token使用情况和响应时间考虑异步处理对于高并发场景使用异步客户端9.3 下一步学习方向如果你已经掌握了这些基础可以考虑深入学习模型微调在自己的数据上微调模型获得更好的领域表现多模型集成结合多个模型的优势构建更强大的系统生产环境部署考虑负载均衡、自动扩缩容、监控告警等成本优化探索量化、蒸馏等技术降低推理成本安全加固添加内容过滤、频率限制、审计日志等安全措施GLM-4-9B-Chat-1M是一个功能强大的开源模型通过合理的API调用和工程实践你可以在各种场景中发挥它的价值。记住最好的学习方式就是动手实践现在就去尝试构建你自己的AI应用吧获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

相关新闻