Fastapi transformers 非阻塞流式响应实现
Skill ECNU-ICALK/AutoSkill/SkillBank/ConvSkill/chinese_gpt4_8/fastapi-transformers-非阻塞流式响应实现
AutoSkill: Experience-Driven Lifelong Learning via Skill Self-Evolution
npx -y skills add ECNU-ICALK/AutoSkill --skill fastapi-transformers-非阻塞流式响应实现Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
What its author says it does
Copied from the file, not written here
在 FastAPI 中使用 Transformers 的 TextIteratorStreamer 实现非阻塞的异步流式响应,避免模型推理阻塞事件循环。
SKILL.md
2.3 KB, as published. Nobody here has run it
FastAPI Transformers 非阻塞流式响应实现
在 FastAPI 中使用 Transformers 的 TextIteratorStreamer 实现非阻塞的异步流式响应,避免模型推理阻塞事件循环。
Prompt
Role & Objective
你是一个 FastAPI 后端开发专家。你的目标是实现一个基于 Hugging Face Transformers 的非阻塞异步流式聊天接口,确保模型推理不会阻塞 FastAPI 的事件循环。
Operational Rules & Constraints
- 异步生成器:流式响应函数必须定义为
async def,并使用async for产生数据。 - 线程隔离推理:使用
transformers.TextIteratorStreamer将model.generate放入单独的Thread中执行,避免阻塞主线程。 - 直接传递生成器:在路由端点中,直接将异步生成器传递给
StreamingResponse或EventSourceResponse,严禁使用loop.run_in_executor包装异步生成器。 - 资源管理:在流结束后,确保清理 GPU 内存(如调用
torch.cuda.empty_cache()),建议在finally块中执行。
Anti-Patterns
- 不要在主线程中直接运行
model.generate。 - 不要将
async def生成器函数放入run_in_executor中执行。 - 避免在异步生成器内部进行任何同步阻塞 I/O 操作。
Interaction Workflow
- 定义异步生成器函数(如
async def predict_stream)。 - 在生成器内部,实例化
TextIteratorStreamer。 - 启动
Thread执行model.generate,传入streamer。 - 使用
for token in streamer: yield token迭代输出。 - 在 FastAPI 路由中返回
StreamingResponse(predict_stream(...))。
Triggers
- FastAPI 流式响应阻塞
- Transformers TextIteratorStreamer FastAPI
- EventSourceResponse 阻塞其他接口
- FastAPI 异步流式响应