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

相关推荐
2301_76444133几秒前
2025年YOLO算法案例应用领域应用趋势
python·yolo
汗流浃背了吧,老弟!10 分钟前
构建RAG系统时,如何选择合适的嵌入模型(Embedding Model)?
人工智能·python·embedding
盐真卿20 分钟前
python第四部分:模块(每日更新)
开发语言·python
喵手42 分钟前
Python爬虫零基础入门【第九章:实战项目教学·第2节】“接口优先“项目:从 Network 还原 JSON 接口分页!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·接口优先·json接口分页
将心ONE44 分钟前
QwenTTS 预设音色
python
冷雨夜中漫步1 小时前
Python入门——字符串
开发语言·python
Yvonne爱编码1 小时前
Java 接口学习核心难点深度解析
java·开发语言·python
June bug1 小时前
(#数组/链表操作)合并两个有重复元素的无序数组,返回无重复的有序结果
数据结构·python·算法·leetcode·面试·跳槽
人工智能AI技术1 小时前
【Agent从入门到实践】33 集成多工具,实现Agent的工具选择与执行
人工智能·python
AIFQuant2 小时前
如何通过股票数据 API 计算 RSI、MACD 与移动平均线MA
大数据·后端·python·金融·restful