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

相关推荐
天诰1 小时前
SA-T-06 轨迹数据工程 脏数据检测
人工智能·python·算法·语言模型·ai编程
Java后端的Ai之路2 小时前
Anthropic 官方文章《Building always-on agents》构建指南
开发语言·网络·python
badhope3 小时前
Agent 说发布成功,文章却 404:我补了 4 张回读收据
后端·python·ai编程
xurileidian3 小时前
第 30 篇 · 边玩边学Python · 猜数字小游戏 把判断循环异常串起来
前端·python·算法
leeshuqing4 小时前
剪刀石头布-Python练习
python·游戏·优化·列表·字典·控制语句
ZhuoAIStage4 小时前
图上有设备,机房条件0命中:剧院舞台音视频提资缺项,AI智能体为何判「需补充」不判「设计错漏」
python·正则表达式·舞台工艺·智能体审图·提资核查
汤姆宝库4 小时前
HNSW:分层图上的贪心检索
开发语言·python
呆呆虫124 小时前
Google Custom Search API 2027 停服替代:SerpBase 等 5 种全网搜索方案对比
python·serp api·serpbase·custom search·接口迁移
絲唸4 小时前
可信机器学习与对抗鲁棒性:温度读数有误差,温室的高温判定还能信吗?
人工智能·python·深度学习·神经网络·算法·机器学习·机器人
维爱智VR认知学能4 小时前
VR抗干扰训练调度器:视听干扰等级分层注入与安全上限熔断实现
python·软件工程·架构设计