Qwen2.5-72B-Instruct-GPTQ-Int4实战教程:vLLM API封装为REST服务
Qwen2.5-72B-Instruct-GPTQ-Int4实战教程vLLM API封装为REST服务1. 引言从模型部署到服务化如果你已经成功部署了Qwen2.5-72B-Instruct-GPTQ-Int4这样的大模型可能会发现一个问题虽然模型跑起来了但怎么让其他应用方便地调用它呢总不能每次都去敲命令行或者打开一个特定的前端界面吧。这就是我们今天要解决的问题。vLLM虽然提供了强大的推理引擎但它本身更像一个“发动机”我们需要给它装上一个“方向盘”和“仪表盘”让其他程序能够像调用普通Web服务一样使用这个大模型。简单来说我们要做两件事把vLLM的API封装成标准的REST服务提供一个简单易用的前端界面进行验证这样无论是你的Python脚本、Java应用还是其他任何支持HTTP请求的程序都能轻松调用这个720亿参数的大模型了。2. 环境准备与快速检查在开始封装之前我们先确认一下环境是否正常。按照你提供的部署步骤模型应该已经在运行了。2.1 检查模型服务状态打开终端运行以下命令查看模型是否部署成功cat /root/workspace/llm.log如果看到类似下面的输出说明模型已经成功加载并运行INFO 07-10 14:30:15 llm_engine.py:73] Initializing an LLM engine with config: model/root/workspace/models/Qwen2.5-72B-Instruct-GPTQ-Int4, tokenizer/root/workspace/models/Qwen2.5-72B-Instruct-GPTQ-Int4, tokenizer_modeauto, trust_remote_codeTrue, dtypeauto, max_seq_len32768, download_dirNone, load_formatauto, tensor_parallel_size1, seed0) INFO 07-10 14:30:15 model_runner.py:63] Loading model weights took 285.12 GB INFO 07-10 14:30:15 model_runner.py:65] Model weights loaded successfully INFO 07-10 14:30:15 llm_engine.py:153] LLM engine initialized successfully这个日志告诉我们几个重要信息模型路径正确模型权重加载成功285.12GB确实是个大家伙引擎初始化成功2.2 理解当前的服务架构在封装之前我们先了解一下vLLM默认提供了什么OpenAI兼容的APIvLLM默认在端口8000提供了一个OpenAI格式的API基本的HTTP接口支持/v1/completions、/v1/chat/completions等端点但是这些接口可能不够“友好”或者不符合你的项目标准。比如你可能需要统一的错误处理请求限流更详细的日志特定的响应格式身份验证这就是我们需要自己封装一层的原因。3. 使用FastAPI封装vLLM为REST服务FastAPI是一个现代、快速的Python Web框架特别适合构建API服务。我们将用它来封装vLLM。3.1 安装必要的依赖首先确保你已经安装了必要的包。如果没有可以运行pip install fastapi uvicorn httpx pydantic3.2 创建REST服务封装代码创建一个名为vllm_rest_server.py的文件内容如下from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import List, Optional, Dict, Any import httpx import json import time from datetime import datetime app FastAPI( titleQwen2.5-72B-Instruct API服务, description基于vLLM封装的Qwen2.5-72B-Instruct-GPTQ-Int4模型REST API, version1.0.0 ) # vLLM服务的地址默认是localhost:8000 VLLM_BASE_URL http://localhost:8000 # 定义请求模型 class ChatMessage(BaseModel): role: str # system, user, assistant content: str class ChatRequest(BaseModel): messages: List[ChatMessage] max_tokens: Optional[int] 1024 temperature: Optional[float] 0.7 top_p: Optional[float] 0.9 stream: Optional[bool] False class CompletionRequest(BaseModel): prompt: str max_tokens: Optional[int] 1024 temperature: Optional[float] 0.7 top_p: Optional[float] 0.9 stream: Optional[bool] False # 健康检查端点 app.get(/health) async def health_check(): 检查服务是否健康 try: async with httpx.AsyncClient(timeout10.0) as client: response await client.get(f{VLLM_BASE_URL}/health) if response.status_code 200: return { status: healthy, timestamp: datetime.now().isoformat(), vllm_status: running } else: return { status: degraded, timestamp: datetime.now().isoformat(), vllm_status: unavailable, details: fvLLM returned status {response.status_code} } except Exception as e: return { status: unhealthy, timestamp: datetime.now().isoformat(), vllm_status: error, details: str(e) } # 聊天补全端点 app.post(/v1/chat/completions) async def chat_completion(request: ChatRequest): 聊天式补全接口 start_time time.time() try: # 构建vLLM请求 vllm_request { model: Qwen2.5-72B-Instruct-GPTQ-Int4, messages: [msg.dict() for msg in request.messages], max_tokens: request.max_tokens, temperature: request.temperature, top_p: request.top_p, stream: request.stream } # 调用vLLM服务 async with httpx.AsyncClient(timeout60.0) as client: response await client.post( f{VLLM_BASE_URL}/v1/chat/completions, jsonvllm_request, headers{Content-Type: application/json} ) if response.status_code ! 200: raise HTTPException( status_coderesponse.status_code, detailfvLLM服务返回错误: {response.text} ) result response.json() # 添加性能指标 processing_time time.time() - start_time result[processing_time] processing_time result[model] Qwen2.5-72B-Instruct-GPTQ-Int4 return result except httpx.TimeoutException: raise HTTPException( status_code504, detail请求vLLM服务超时请稍后重试 ) except Exception as e: raise HTTPException( status_code500, detailf处理请求时发生错误: {str(e)} ) # 文本补全端点 app.post(/v1/completions) async def text_completion(request: CompletionRequest): 文本补全接口 start_time time.time() try: # 构建vLLM请求 vllm_request { model: Qwen2.5-72B-Instruct-GPTQ-Int4, prompt: request.prompt, max_tokens: request.max_tokens, temperature: request.temperature, top_p: request.top_p, stream: request.stream } # 调用vLLM服务 async with httpx.AsyncClient(timeout60.0) as client: response await client.post( f{VLLM_BASE_URL}/v1/completions, jsonvllm_request, headers{Content-Type: application/json} ) if response.status_code ! 200: raise HTTPException( status_coderesponse.status_code, detailfvLLM服务返回错误: {response.text} ) result response.json() # 添加性能指标 processing_time time.time() - start_time result[processing_time] processing_time result[model] Qwen2.5-72B-Instruct-GPTQ-Int4 return result except httpx.TimeoutException: raise HTTPException( status_code504, detail请求vLLM服务超时请稍后重试 ) except Exception as e: raise HTTPException( status_code500, detailf处理请求时发生错误: {str(e)} ) # 模型信息端点 app.get(/v1/models) async def list_models(): 获取可用模型列表 return { data: [ { id: Qwen2.5-72B-Instruct-GPTQ-Int4, object: model, created: 1730000000, owned_by: Qwen, permission: [], root: Qwen2.5-72B-Instruct-GPTQ-Int4, parent: None } ], object: list } # 批量处理端点可选用于提高效率 app.post(/v1/batch/chat) async def batch_chat_completion(requests: List[ChatRequest]): 批量聊天补全接口 results [] for request in requests: try: result await chat_completion(request) results.append(result) except Exception as e: results.append({ error: str(e), success: False }) return { results: results, total: len(results), successful: sum(1 for r in results if error not in r) } if __name__ __main__: import uvicorn uvicorn.run(app, host0.0.0.0, port8080)3.3 启动REST服务保存文件后运行以下命令启动服务python vllm_rest_server.py服务将在http://localhost:8080启动。你可以通过浏览器访问http://localhost:8080/docs查看自动生成的API文档。4. 使用Chainlit前端进行调用验证现在我们已经有了REST服务接下来用Chainlit创建一个简单的前端来验证服务是否正常工作。4.1 创建Chainlit应用创建一个名为app.py的文件内容如下import chainlit as cl import httpx import json from typing import List, Dict, Any # REST服务的地址 API_BASE_URL http://localhost:8080 async def call_chat_api(messages: List[Dict[str, str]], max_tokens: int 1024, temperature: float 0.7) - str: 调用封装的REST API进行聊天 try: async with httpx.AsyncClient(timeout120.0) as client: response await client.post( f{API_BASE_URL}/v1/chat/completions, json{ messages: messages, max_tokens: max_tokens, temperature: temperature, stream: False } ) if response.status_code 200: result response.json() return result[choices][0][message][content] else: return fAPI调用失败: {response.status_code} - {response.text} except httpx.TimeoutException: return 请求超时请稍后重试 except Exception as e: return f发生错误: {str(e)} cl.on_chat_start async def start_chat(): 聊天开始时的初始化 # 检查服务健康状态 try: async with httpx.AsyncClient(timeout10.0) as client: response await client.get(f{API_BASE_URL}/health) if response.status_code 200: health_status response.json() if health_status[status] healthy: await cl.Message( contentf✅ Qwen2.5-72B-Instruct服务已就绪\n f模型: Qwen2.5-72B-Instruct-GPTQ-Int4\n f状态: {health_status[vllm_status]}\n f时间: {health_status[timestamp]}\n\n f你可以开始提问了 ).send() else: await cl.Message( contentf⚠️ 服务状态异常: {health_status}\n f部分功能可能不可用。 ).send() else: await cl.Message( contentf❌ 无法连接到API服务请检查服务是否运行。 ).send() except Exception as e: await cl.Message( contentf❌ 连接服务失败: {str(e)} ).send() # 发送欢迎消息 welcome_msg ## Qwen2.5-72B-Instruct聊天助手 我已经准备好为你服务了我是基于Qwen2.5-72B-Instruct-GPTQ-Int4模型构建的智能助手。 **我可以帮你** - 回答各种问题 - 协助写作和创作 - 分析和解释复杂概念 - 编程和技术咨询 - 语言翻译 - 以及其他你能想到的任务 **模型特点** - 720亿参数大模型 - 支持128K上下文长度 - GPTQ 4-bit量化 - 支持29种语言 直接输入你的问题让我们开始对话吧 await cl.Message(contentwelcome_msg).send() cl.on_message async def handle_message(message: cl.Message): 处理用户消息 # 显示思考状态 msg cl.Message(content) await msg.send() # 构建消息历史 messages [ { role: system, content: 你是一个有帮助的AI助手。请用中文回答用户的问题回答要详细、准确、有帮助。 }, { role: user, content: message.content } ] # 调用API response_text await call_chat_api(messages) # 更新消息内容 msg.content response_text await msg.update() cl.on_settings_update async def handle_settings_update(settings: Dict[str, Any]): 处理设置更新 cl.user_session.set(settings, settings) await cl.Message(contentf设置已更新: {settings}).send() # Chainlit配置 cl.instrument_openai() # 添加侧边栏设置 cl.password_auth_callback def auth_callback(username: str, password: str): # 简单的认证生产环境请使用更安全的方式 if username admin and password admin123: return cl.User(identifieradmin) else: return None # 运行应用 if __name__ __main__: cl.run()4.2 创建Chainlit配置文件创建一个名为chainlit.md的文件作为应用说明# Qwen2.5-72B-Instruct聊天助手 这是一个基于Qwen2.5-72B-Instruct-GPTQ-Int4模型的聊天应用。 ## 功能特点 - 支持长对话128K上下文 - 多语言支持29种语言 - 实时响应 - 简洁易用的界面 ## 使用说明 1. 在下方输入框输入你的问题 2. 按Enter或点击发送按钮 3. 等待模型生成回答 ## 技术栈 - 后端FastAPI vLLM - 前端Chainlit - 模型Qwen2.5-72B-Instruct-GPTQ-Int4 ## 注意事项 - 复杂问题可能需要较长的响应时间 - 请确保API服务正在运行 - 对于编程问题模型可以生成代码但需要人工验证4.3 启动Chainlit应用首先确保REST服务正在运行在另一个终端中然后启动Chainlitchainlit run app.pyChainlit会在http://localhost:8000启动注意不要和vLLM的8000端口冲突如果冲突可以修改端口。打开浏览器访问Chainlit界面你应该能看到一个漂亮的聊天界面。5. 完整验证流程现在让我们通过一个完整的流程来验证整个系统是否正常工作。5.1 第一步检查所有服务状态打开三个终端窗口分别运行终端1 - 检查vLLM服务# 检查vLLM是否运行 curl http://localhost:8000/health终端2 - 检查REST服务# 检查FastAPI服务是否运行 curl http://localhost:8080/health终端3 - 检查Chainlit服务# 访问Chainlit界面 echo 打开浏览器访问: http://localhost:80005.2 第二步通过API直接测试在测试Chainlit之前我们先直接用API测试一下REST服务# 测试聊天接口 curl -X POST http://localhost:8080/v1/chat/completions \ -H Content-Type: application/json \ -d { messages: [ {role: system, content: 你是一个有帮助的AI助手}, {role: user, content: 请用中文介绍一下你自己} ], max_tokens: 500, temperature: 0.7 }如果一切正常你会看到类似这样的响应{ id: chatcmpl-123, object: chat.completion, created: 1677652288, model: Qwen2.5-72B-Instruct-GPTQ-Int4, choices: [ { index: 0, message: { role: assistant, content: 你好我是基于Qwen2.5-72B-Instruct模型构建的AI助手... }, finish_reason: stop } ], usage: { prompt_tokens: 25, completion_tokens: 150, total_tokens: 175 }, processing_time: 2.345 }5.3 第三步通过Chainlit界面测试现在打开Chainlit界面通常是http://localhost:8000尝试问几个问题简单测试你好请介绍一下你自己知识测试Python中的装饰器是什么请举例说明创作测试写一首关于春天的短诗代码测试用Python写一个快速排序算法观察响应速度和质量。由于是720亿参数的大模型响应可能需要几秒钟时间。6. 高级功能与优化建议6.1 添加请求限流为了防止服务被滥用我们可以添加限流功能。修改vllm_rest_server.pyfrom slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address from slowapi.errors import RateLimitExceeded # 初始化限流器 limiter Limiter(key_funcget_remote_address) app.state.limiter limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) # 在需要限流的端点添加装饰器 app.post(/v1/chat/completions) limiter.limit(10/minute) # 每分钟10次 async def chat_completion(request: ChatRequest): # ... 原有代码 ...6.2 添加请求日志为了更好地监控服务添加请求日志import logging from fastapi import Request # 配置日志 logging.basicConfig( levellogging.INFO, format%(asctime)s - %(name)s - %(levelname)s - %(message)s ) logger logging.getLogger(__name__) app.middleware(http) async def log_requests(request: Request, call_next): 记录所有请求的中间件 start_time time.time() response await call_next(request) process_time time.time() - start_time logger.info( fMethod: {request.method} fPath: {request.url.path} fStatus: {response.status_code} fDuration: {process_time:.2f}s ) return response6.3 添加缓存机制对于重复的请求可以添加缓存提高响应速度from functools import lru_cache import hashlib def get_request_hash(request_data: dict) - str: 生成请求的哈希值用于缓存键 request_str json.dumps(request_data, sort_keysTrue) return hashlib.md5(request_str.encode()).hexdigest() lru_cache(maxsize100) async def cached_chat_completion(request_hash: str, request_data: dict): 带缓存的聊天补全 # 这里调用实际的vLLM服务 # ... 原有调用代码 ...6.4 支持流式响应如果需要支持流式响应逐字输出可以这样修改app.post(/v1/chat/completions/stream) async def chat_completion_stream(request: ChatRequest): 流式聊天补全接口 async def generate(): # 构建流式请求 vllm_request { model: Qwen2.5-72B-Instruct-GPTQ-Int4, messages: [msg.dict() for msg in request.messages], max_tokens: request.max_tokens, temperature: request.temperature, top_p: request.top_p, stream: True # 启用流式 } async with httpx.AsyncClient(timeout120.0) as client: async with client.stream( POST, f{VLLM_BASE_URL}/v1/chat/completions, jsonvllm_request, headers{Content-Type: application/json} ) as response: async for chunk in response.aiter_bytes(): yield chunk return StreamingResponse(generate(), media_typetext/event-stream)7. 常见问题与解决方案7.1 服务启动失败问题启动FastAPI服务时提示端口被占用解决修改端口号比如从8080改为8081if __name__ __main__: import uvicorn uvicorn.run(app, host0.0.0.0, port8081) # 修改端口7.2 连接vLLM服务超时问题REST服务无法连接到vLLM解决检查vLLM是否在运行ps aux | grep vllm检查vLLM端口默认是8000确认没有冲突修改连接地址# 如果vLLM运行在其他机器或端口 VLLM_BASE_URL http://其他IP:8000 # 或 http://localhost:其他端口7.3 内存不足问题运行大模型时内存不足解决检查可用内存free -h考虑使用更小的模型或进一步量化调整vLLM参数减少内存使用7.4 响应速度慢问题模型响应时间过长解决调整生成参数减少max_tokens启用批处理同时处理多个请求使用缓存对相似请求使用缓存结果7.5 Chainlit无法连接API问题Chainlit显示无法连接到API服务解决检查API服务地址是否正确检查防火墙设置确保所有服务都在运行8. 总结通过这个教程我们成功地将vLLM部署的Qwen2.5-72B-Instruct-GPTQ-Int4模型封装成了一个完整的REST服务并提供了一个友好的前端界面。整个过程可以分为几个关键步骤8.1 核心成果回顾服务化封装使用FastAPI将vLLM的API封装成标准的REST服务提供了统一的接口和错误处理前端交互通过Chainlit创建了直观的聊天界面让非技术用户也能轻松使用大模型完整验证从底层服务检查到API测试再到前端验证确保整个系统正常工作扩展功能添加了健康检查、请求日志、限流等生产级功能8.2 关键优势标准化接口提供符合RESTful标准的API方便其他系统集成易于使用Chainlit前端让交互变得简单直观可扩展性架构设计允许轻松添加新功能生产就绪包含错误处理、日志、监控等生产环境需要的功能8.3 下一步建议如果你想让这个系统更加完善可以考虑添加身份验证为API添加API密钥验证实现负载均衡部署多个实例并使用负载均衡器添加监控集成Prometheus和Grafana进行性能监控优化性能实现请求批处理、响应缓存等优化容器化部署使用Docker和Kubernetes进行容器化部署8.4 实际应用场景这个封装好的服务可以用于企业内部助手为员工提供智能问答服务客服系统集成到客服平台提供智能回复内容创作辅助写作、翻译、摘要生成教育工具作为学习助手回答学生问题研发辅助帮助程序员解决技术问题最重要的是你现在有了一个可以随时调用720亿参数大模型的标准化服务无论是通过API还是通过友好的界面都能轻松利用这个强大的AI能力。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2438851.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!