解读FastAPI异步化为transformers模型打造高性能接口解析

bash 复制代码
from fastapi import FastAPI
from transformers import AutoModel, AutoTokenizer
import numpy as np
from starlette.responses import JSONResponse
 
 app = FastAPI()

加载模型和分词器

bash 复制代码
model = AutoModel.from_pretrained("distilbert-base-uncased")
  tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")

异步函数用于将输入文本转换为模型需要的格式

bash 复制代码
  async def prepare_input_for_model(text: str):
       inputs = tokenizer.encode(text, return_tensors='pt')
           return inputs

异步函数用于模型预测

bash 复制代码
 async def get_prediction(inputs):
        outputs = model(inputs)
        return outputs.logits

异步接口用于处理HTTP请求并返回预测结果

bash 复制代码
   @app.post("/predict")
   async def predict(text: str):
             inputs = await prepare_input_for_model(text)
             outputs = await get_prediction(inputs)
             predictions = np.argmax(outputs.numpy(), axis=-1)
             return JSONResponse(content={"prediction": predictions[0]})

这段代码展示了如何使用FastAPI框架的异步功能来提高性能。通过异步函数prepare_input_for_model和get_prediction,我们能够处理并行任务,有效利用服务器资源。这样的设计模式对于需要处理大量并发请求的应用程序非常有用。

相关推荐
Super Scraper6 分钟前
如何使用 cURL 发送 JSON:-d、--json 及常见错误的完整指南
人工智能·爬虫·python·自动化·json·mcp
半壶清水10 分钟前
用python脚本加html自建的书法字典
开发语言·python·html
The moon forgets11 分钟前
DreamVLA:世界知识驱动的视觉-语言-动作新范式
人工智能·pytorch·python·深度学习·具身智能·vla
myenjoy_115 分钟前
Python + Snap7 实现西门子 S7-1200/1500 数据采集
开发语言·python
大学竞赛君24 分钟前
第十六届蓝桥杯大赛软件赛决赛 Python 大学 A 组
python·职场和发展·蓝桥杯
-FxYaM-35 分钟前
图吧工具箱与自动化运维
python
aqi0035 分钟前
15天学会AI应用开发(四)根据Token长度截断历史对话
人工智能·python·大模型·ai编程·ai应用
*neverGiveUp*35 分钟前
初步了解Django框架
开发语言·python·django
狐言乱雨1 小时前
深入理解KV Cache:大模型推理加速的核心技术
python