ChatGLM3-6B与Flask快速构建API服务

📅 发布时间:2026/7/11 11:33:11 👁️ 浏览次数:
ChatGLM3-6B与Flask快速构建API服务
ChatGLM3-6B与Flask快速构建API服务1. 引言想把自己部署的ChatGLM3-6B大模型变成一个可以随时调用的API服务吗用Flask框架就能轻松搞定不需要复杂的架构不需要专业的后端知识跟着这篇教程一步步来你就能搭建一个属于自己的AI对话API。不管你是想给小程序加个智能对话功能还是想让其他系统能调用你的模型这个方案都能帮到你。Flask作为Python最轻量的Web框架之一学习成本低部署简单特别适合快速原型开发。接下来我会手把手教你如何从零开始用Flask把ChatGLM3-6B包装成一个完整的API服务包括怎么处理请求、怎么优化性能还有怎么避免常见的坑。2. 环境准备与依赖安装开始之前确保你的机器已经准备好这些基础环境系统要求Python 3.8或更高版本至少16GB内存运行ChatGLM3-6B需要支持CUDA的GPU推荐能大幅加速推理安装必要的包# 创建虚拟环境可选但推荐 python -m venv chatglm-api source chatglm-api/bin/activate # Linux/Mac # 或者 chatglm-api\Scripts\activate # Windows # 安装核心依赖 pip install flask transformers torch如果你打算处理并发请求还可以安装这些额外的包pip install gunicorn gevent # 生产环境部署用验证安装import flask import transformers print(Flask版本:, flask.__version__) print(Transformers版本:, transformers.__version__)如果上面的代码能正常运行说明基础环境已经准备好了。3. 最简单的Flask API示例在连接ChatGLM3-6B之前我们先来个最简单的Flask应用热热身from flask import Flask, request, jsonify app Flask(__name__) app.route(/chat, methods[POST]) def chat(): data request.get_json() message data.get(message, ) # 这里先模拟回复后面会换成真实的模型调用 response f收到了你的消息: {message} return jsonify({ response: response, status: success }) if __name__ __main__: app.run(host0.0.0.0, port5000, debugTrue)保存为app.py然后运行python app.py用curl测试一下curl -X POST http://127.0.0.1:5000/chat \ -H Content-Type: application/json \ -d {message: 你好}你应该能看到返回的JSON响应。这就是Flask最基本的用法是不是很简单4. 集成ChatGLM3-6B模型现在我们来接入真正的ChatGLM3-6B模型。首先确保你已经下载了模型权重可以从Hugging Face或ModelScope获取。模型加载代码from transformers import AutoTokenizer, AutoModel import torch class ChatGLMService: def __init__(self, model_pathTHUDM/chatglm3-6b): self.tokenizer AutoTokenizer.from_pretrained( model_path, trust_remote_codeTrue ) self.model AutoModel.from_pretrained( model_path, trust_remote_codeTrue, devicecuda if torch.cuda.is_available() else cpu ).eval() def generate_response(self, message, historyNone): if history is None: history [] response, updated_history self.model.chat( self.tokenizer, message, historyhistory ) return response, updated_history # 初始化服务 chat_service ChatGLMService()整合到Flask中from flask import Flask, request, jsonify from datetime import datetime app Flask(__name__) service ChatGLMService() app.route(/api/chat, methods[POST]) def api_chat(): try: data request.get_json() message data.get(message, ) history data.get(history, []) if not message: return jsonify({error: 消息不能为空}), 400 # 调用模型生成回复 start_time datetime.now() response, new_history service.generate_response(message, history) processing_time (datetime.now() - start_time).total_seconds() return jsonify({ response: response, history: new_history, processing_time: processing_time, status: success }) except Exception as e: return jsonify({error: str(e)}), 500 app.route(/health, methods[GET]) def health_check(): return jsonify({status: healthy, timestamp: datetime.now().isoformat()})现在你的API已经能真正调用ChatGLM3-6B了试试发送一些消息看看模型的回复。5. 性能优化技巧直接这样部署可能会遇到性能问题特别是同时有多个请求的时候。这里有几个实用的优化方法1. 启用批处理# 修改generate_response方法支持批处理 def generate_batch_responses(self, messages_list): responses [] for message, history in messages_list: response, new_history self.model.chat( self.tokenizer, message, historyhistory ) responses.append((response, new_history)) return responses2. 使用GPU加速 确保你的torch安装了CUDA版本pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu1183. 模型量化减少内存占用# 加载时使用8bit量化 model AutoModel.from_pretrained( model_path, trust_remote_codeTrue, devicecuda, load_in_8bitTrue # 需要bitsandbytes包 ).eval()4. 添加缓存机制from functools import lru_cache lru_cache(maxsize1000) def get_cached_response(message, history_hash): # 历史记录的哈希值作为缓存键 return service.generate_response(message, history)6. 生产环境部署建议开发环境用app.run()没问题但生产环境需要更稳定的方案使用Gunicorn部署pip install gunicorn gevent gunicorn -w 4 -k gevent -b 0.0.0.0:5000 app:app添加超时控制from flask import abort import signal class TimeoutException(Exception): pass def timeout_handler(signum, frame): raise TimeoutException(处理超时) app.route(/api/chat, methods[POST]) def api_chat(): signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(30) # 30秒超时 try: # ...处理逻辑 signal.alarm(0) # 取消定时器 return response except TimeoutException: return jsonify({error: 处理超时}), 408添加速率限制from flask_limiter import Limiter from flask_limiter.util import get_remote_address limiter Limiter( appapp, key_funcget_remote_address, default_limits[100 per day, 10 per hour] ) app.route(/api/chat, methods[POST]) limiter.limit(5 per minute) def api_chat(): # ...原有逻辑7. 完整代码示例这里提供一个完整可用的版本from flask import Flask, request, jsonify from transformers import AutoTokenizer, AutoModel import torch from datetime import datetime from functools import lru_cache import signal class TimeoutException(Exception): pass def timeout_handler(signum, frame): raise TimeoutException(处理超时) class ChatGLMService: def __init__(self, model_pathTHUDM/chatglm3-6b): self.tokenizer AutoTokenizer.from_pretrained( model_path, trust_remote_codeTrue ) self.model AutoModel.from_pretrained( model_path, trust_remote_codeTrue, devicecuda if torch.cuda.is_available() else cpu ).eval() lru_cache(maxsize1000) def generate_response(self, message, history_hash): history [] if not history_hash else eval(history_hash) response, new_history self.model.chat( self.tokenizer, message, historyhistory ) return response, str(new_history) app Flask(__name__) service ChatGLMService() app.route(/api/chat, methods[POST]) def api_chat(): signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(30) try: data request.get_json() message data.get(message, ) history_hash data.get(history_hash, ) if not message: return jsonify({error: 消息不能为空}), 400 start_time datetime.now() response, new_history_hash service.generate_response(message, history_hash) processing_time (datetime.now() - start_time).total_seconds() signal.alarm(0) return jsonify({ response: response, history_hash: new_history_hash, processing_time: processing_time, status: success }) except TimeoutException: return jsonify({error: 处理超时}), 408 except Exception as e: return jsonify({error: str(e)}), 500 finally: signal.alarm(0) app.route(/health, methods[GET]) def health_check(): return jsonify({status: healthy, timestamp: datetime.now().isoformat()}) if __name__ __main__: app.run(host0.0.0.0, port5000, debugTrue)8. 总结这样一套下来你应该已经能用Flask把ChatGLM3-6B包装成可用的API服务了。从最简单的示例开始逐步加入模型调用、性能优化、生产环境部署的建议整个过程其实并不复杂。实际使用中可能会遇到一些具体问题比如内存不够、响应速度慢等这时候可以根据实际情况调整优化策略。比如如果用户不多可能不需要做那么复杂的缓存如果并发量很大可能要考虑分布式部署。最重要的是先跑起来再慢慢优化。这个方案虽然简单但已经能解决很多实际场景的需求了。你可以基于这个基础继续添加用户认证、日志记录、监控告警等功能让它更加强大和稳定。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。