解读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,我们能够处理并行任务,有效利用服务器资源。这样的设计模式对于需要处理大量并发请求的应用程序非常有用。

相关推荐
try2find21 分钟前
agent环境安装spacy
python·智能体
ellenwan202625 分钟前
期货程序化开平标志错了总拒单:天勤 last_msg 排查思路
python
装不满的克莱因瓶31 分钟前
自动微分的原理:计算图与前向传播
人工智能·pytorch·python·数学·ai·微积分·计算图
console.log('npc')1 小时前
将 Figma 接入 Codex MCP:从 `/plugins` 到本地插件配置的完整教程
前端·人工智能·python·figma·code·codex·mcp
资深流水灯工程师1 小时前
PySide6 QMainWindow与QWidget秒解
开发语言·python
popcorn_min1 小时前
California Housing 可复现回归实验:随机森林预测加州房价
python
吴佳浩 Alben1 小时前
pytorch 你不学?_EP01_环境准备与安装验证
人工智能·pytorch·python
XiaoZhangGOGOGO1 小时前
新的文本编辑方式
python
留白_1 小时前
pandas练习题
python·数据分析·pandas
放下华子我只抽RuiKe51 小时前
FastAPI 全栈后端(六):中间件与依赖注入
ai·中间件·fastapi·ai编程·qwen·ai大模型·openclaw