当前位置:   article > 正文

开源模型应用落地-FastAPI-助力模型交互-进阶篇-生命周期事件(一)_modelscope fastapi

modelscope fastapi

一、前言

   FastAPI 的高级用法可以为开发人员带来许多好处。它能帮助实现更复杂的路由逻辑和参数处理,使应用程序能够处理各种不同的请求场景,提高应用程序的灵活性和可扩展性。

    在数据验证和转换方面,高级用法提供了更精细和准确的控制,确保输入数据的质量和安全性。它还能更高效地处理异步操作,提升应用程序的性能和响应速度,特别是在处理大量并发请求时优势明显。

    此外,高级用法还有助于更好地整合数据库操作、实现数据的持久化和查询优化,以及实现更严格的认证和授权机制,保护应用程序的敏感数据和功能。总之,掌握 FastAPI 的高级用法可以帮助开发人员构建出功能更强大、性能更卓越、安全可靠的 Web 应用程序。

    本篇学习FastAPI的生命周期事件,示例均在开源模型应用落地-FastAPI-助力模型交互-WebSocket篇(二)基础上进行扩展,建议有需要的老铁们,先去学习。


二、术语

2.1. Lifespan Events(生命周期事件)

    通过生命周期事件,可以更好地管理应用的整个生命周期中的资源和操作,确保资源的正确初始化和释放,提高应用的性能、可靠性和可维护性。

    Lifespan Events主要有以下作用:

  1. 资源初始化与释放:可以在应用启动时执行一些初始化操作,例如创建数据库连接池、加载共享的机器学习模型等需要在整个应用中使用且可在请求间共享的资源。在应用关闭时,执行清理和释放资源的操作,例如关闭数据库连接、释放内存或其他相关资源。
  2. 避免不必要的操作:如果某些资源的初始化成本较高(如加载大型模型),使用 Lifespan Events 可以避免在每次请求时都进行初始化,仅在应用启动后且接收请求之前执行一次。同时,也可以防止在一些不需要处理实际请求的情况下(如运行简单的自动化测试)进行不必要的资源加载,从而提高性能和效率。
  3. 分离启动和关闭逻辑:将与应用启动和关闭相关的逻辑集中在一个地方进行管理,使代码更加清晰和可维护。
     

三、前置条件

3.1. 创建虚拟环境&安装依赖

  1. conda create -n fastapi_test python=3.10
  2. conda activate fastapi_test
  3. pip install fastapi websockets uvicorn transformers==4.32.0 accelerate tiktoken einops transformers_stream_generator==0.0.4 scipy

3.2. 下载Qwen-1_8B-Chat模型

huggingface:

https://huggingface.co/Qwen/Qwen-1_8B-Chaticon-default.png?t=N7T8https://huggingface.co/Qwen/Qwen-1_8B-Chat

​魔搭:

魔搭社区汇聚各领域最先进的机器学习模型,提供模型探索体验、推理、训练、部署和应用的一站式服务。icon-default.png?t=N7T8https://modelscope.cn/models/qwen/Qwen-1_8B-Chat


四、技术实现

4.1. startup & shutdown event

  1. # -*- coding: utf-8 -*-
  2. import traceback
  3. from transformers import AutoTokenizer, AutoModelForCausalLM
  4. from transformers import GenerationConfig
  5. import torch
  6. import uvicorn
  7. from typing import Annotated
  8. from fastapi import (
  9. Depends,
  10. FastAPI,
  11. WebSocket,
  12. WebSocketException,
  13. WebSocketDisconnect,
  14. status,
  15. )
  16. model_path = "E:/model/qwen-1_8b-chat"
  17. class ConnectionManager:
  18. def __init__(self):
  19. self.active_connections: list[WebSocket] = []
  20. async def connect(self, websocket: WebSocket):
  21. await websocket.accept()
  22. self.active_connections.append(websocket)
  23. def disconnect(self, websocket: WebSocket):
  24. self.active_connections.remove(websocket)
  25. async def send_personal_message(self, message: str, websocket: WebSocket):
  26. await websocket.send_text(message)
  27. async def broadcast(self, message: str):
  28. for connection in self.active_connections:
  29. await connection.send_text(message)
  30. manager = ConnectionManager()
  31. app = FastAPI()
  32. async def authenticate(
  33. websocket: WebSocket,
  34. userid: str,
  35. secret: str,
  36. ):
  37. if userid is None or secret is None:
  38. raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
  39. print(f'userid: {userid},secret: {secret}')
  40. if '12345' == userid and 'xxxxxxxxxxxxxxxxxxxxxxxxxx' == secret:
  41. return 'pass'
  42. else:
  43. return 'fail'
  44. async def chat(query):
  45. position = 0
  46. try:
  47. for response in model.chat_stream(tokenizer, query, history = None):
  48. result = response[position:]
  49. position = len(response)
  50. yield result
  51. except Exception:
  52. traceback.print_exc()
  53. @app.websocket("/ws")
  54. async def websocket_endpoint(*,websocket: WebSocket,userid: str,permission: Annotated[str, Depends(authenticate)],):
  55. await manager.connect(websocket)
  56. try:
  57. while True:
  58. text = await websocket.receive_text()
  59. if 'fail' == permission:
  60. await manager.send_personal_message(
  61. f"authentication failed", websocket
  62. )
  63. else:
  64. if text is not None and len(text) > 0:
  65. async for msg in chat(text):
  66. await manager.send_personal_message(msg, websocket)
  67. except WebSocketDisconnect:
  68. manager.disconnect(websocket)
  69. print(f"Client #{userid} left the chat")
  70. await manager.broadcast(f"Client #{userid} left the chat")
  71. def loadTokenizer():
  72. tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
  73. return tokenizer
  74. def loadModel(config):
  75. model = AutoModelForCausalLM.from_pretrained(model_path, device_map="cpu", trust_remote_code=True).eval()
  76. model.generation_config = config
  77. return model
  78. @app.on_event("startup")
  79. async def startup_event():
  80. global model,tokenizer
  81. config = GenerationConfig.from_pretrained(model_path, trust_remote_code=True, top_p=0.9, temperature=0.45,repetition_penalty=1.1, do_sample=True, max_new_tokens=8192)
  82. tokenizer = loadTokenizer()
  83. model = loadModel(config)
  84. @app.on_event("shutdown")
  85. def shutdown_event():
  86. torch.cuda.empty_cache()
  87. if __name__ == '__main__':
  88. uvicorn.run(app, host='0.0.0.0',port=7777)

调用结果:

用户输入:你好

模型输出:你好!有什么我能帮助你的吗?

说明:

  1. 在startup事件函数中加载模型资源
  2. 在shutdown时间函数中释放资源
  3. startup & shutdown event已过期,后面可能会被移除,建议使用lifespan event代替

4.2. lifespan event

  1. import traceback
  2. from contextlib import asynccontextmanager
  3. from transformers import AutoTokenizer, AutoModelForCausalLM
  4. from transformers import GenerationConfig
  5. import torch
  6. import uvicorn
  7. from typing import Annotated
  8. from fastapi import (
  9. Depends,
  10. FastAPI,
  11. WebSocket,
  12. WebSocketException,
  13. WebSocketDisconnect,
  14. status,
  15. )
  16. model_path = "E:/model/qwen-1_8b-chat"
  17. class ConnectionManager:
  18. def __init__(self):
  19. self.active_connections: list[WebSocket] = []
  20. async def connect(self, websocket: WebSocket):
  21. await websocket.accept()
  22. self.active_connections.append(websocket)
  23. def disconnect(self, websocket: WebSocket):
  24. self.active_connections.remove(websocket)
  25. async def send_personal_message(self, message: str, websocket: WebSocket):
  26. await websocket.send_text(message)
  27. async def broadcast(self, message: str):
  28. for connection in self.active_connections:
  29. await connection.send_text(message)
  30. manager = ConnectionManager()
  31. def loadTokenizer():
  32. tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
  33. return tokenizer
  34. def loadModel(config):
  35. model = AutoModelForCausalLM.from_pretrained(model_path, device_map="cpu", trust_remote_code=True).eval()
  36. model.generation_config = config
  37. return model
  38. @asynccontextmanager
  39. async def lifespan(app: FastAPI):
  40. # 加载模型
  41. global model, tokenizer
  42. config = GenerationConfig.from_pretrained(model_path, trust_remote_code=True, top_p=0.9, temperature=0.45,
  43. repetition_penalty=1.1, do_sample=True, max_new_tokens=8192)
  44. tokenizer = loadTokenizer()
  45. model = loadModel(config)
  46. yield
  47. # 释放资源
  48. torch.cuda.empty_cache()
  49. app = FastAPI(lifespan=lifespan)
  50. async def authenticate(
  51. websocket: WebSocket,
  52. userid: str,
  53. secret: str,
  54. ):
  55. if userid is None or secret is None:
  56. raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
  57. print(f'userid: {userid},secret: {secret}')
  58. if '12345' == userid and 'xxxxxxxxxxxxxxxxxxxxxxxxxx' == secret:
  59. return 'pass'
  60. else:
  61. return 'fail'
  62. async def chat(query):
  63. position = 0
  64. try:
  65. for response in model.chat_stream(tokenizer, query, history = None):
  66. result = response[position:]
  67. position = len(response)
  68. yield result
  69. except Exception:
  70. traceback.print_exc()
  71. @app.websocket("/ws")
  72. async def websocket_endpoint(*,websocket: WebSocket,userid: str,permission: Annotated[str, Depends(authenticate)],):
  73. await manager.connect(websocket)
  74. try:
  75. while True:
  76. text = await websocket.receive_text()
  77. if 'fail' == permission:
  78. await manager.send_personal_message(
  79. f"authentication failed", websocket
  80. )
  81. else:
  82. if text is not None and len(text) > 0:
  83. async for msg in chat(text):
  84. await manager.send_personal_message(msg, websocket)
  85. except WebSocketDisconnect:
  86. manager.disconnect(websocket)
  87. print(f"Client #{userid} left the chat")
  88. await manager.broadcast(f"Client #{userid} left the chat")
  89. if __name__ == '__main__':
  90. uvicorn.run(app, host='0.0.0.0',port=7777)

调用结果:

没有输出警告信息

用户输入:你好,广州有什么好玩的地方推荐?

模型输出:广州有很多值得一去的景点,比如白云山、长隆野生动物园、陈家祠、珠江夜游等。此外,你还可以去逛逛上下九步行街,品尝当地的美食,或者参观广州塔等高楼大厦。


五、附带说明

5.1. 测试界面

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Chat</title>
  5. </head>
  6. <body>
  7. <h1>WebSocket Chat</h1>
  8. <form action="" onsubmit="sendMessage(event)">
  9. <label>USERID: <input type="text" id="userid" autocomplete="off" value="12345"/></label>
  10. <label>SECRET: <input type="text" id="secret" autocomplete="off" value="xxxxxxxxxxxxxxxxxxxxxxxxxx"/></label>
  11. <br/>
  12. <button onclick="connect(event)">Connect</button>
  13. <hr>
  14. <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
  15. <button>Send</button>
  16. </form>
  17. <ul id='messages'>
  18. </ul>
  19. <script>
  20. var ws = null;
  21. function connect(event) {
  22. var userid = document.getElementById("userid")
  23. var secret = document.getElementById("secret")
  24. ws = new WebSocket("ws://localhost:7777/ws?userid="+userid.value+"&secret=" + secret.value);
  25. ws.onmessage = function(event) {
  26. var messages = document.getElementById('messages')
  27. var message = document.createElement('li')
  28. var content = document.createTextNode(event.data)
  29. message.appendChild(content)
  30. messages.appendChild(message)
  31. };
  32. event.preventDefault()
  33. }
  34. function sendMessage(event) {
  35. var input = document.getElementById("messageText")
  36. ws.send(input.value)
  37. input.value = ''
  38. event.preventDefault()
  39. }
  40. </script>
  41. </body>
  42. </html>

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/868513
推荐阅读
相关标签
  

闽ICP备14008679号