首页 / 开源项目 / 正文
开源项目

FastAPI AI项目实战:快速搭建高性能异步推理服务与接口

chuanbook chuanbook
发布于 2026 年 12 月 06 日
阅读 约5分钟
浏览 1
评论 0

fastapi-ai-project/ ├── app/ │ ├── main.py │ ├── api/ │ │ ├── routes/ │ │ │ ├── chat.py │ │ │ ├── completion.py │ │ │ └── vision.py │ │ └── dependencies.py │ ├── core/ │ │ ├── config.py │ │ ├── logging.py │ │ └── exceptions.py │ ├── schemas/ │ │ ├── request.py │ │ └── response.py │ ├── services/ │ │ ├── inference_service.py │ │ └── model_manager.py │ ├── models/ │ │ ├── loader.py │ │ └── predictor.py │ └── data/ │ ├── cache.py │ └── repository.py ├── tests/ ├── requirements.txt └── README.md

python3.11 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip pip install fastapi uvicorn[standard] pydantic-settings

from contextlib import asynccontextmanager from fastapi import FastAPI

@asynccontextmanager async def lifespan(app: FastAPI):

app.state.model = load_model(settings.model_path, device=settings.device)
app.state.model_ready = True
yield
app.state.model_ready = False

app = FastAPI(lifespan=lifespan)

from enum import Enum from pydantic import BaseModel, Field

class Role(str, Enum):

system = "system"
user = "user"
assistant = "assistant"
tool = "tool"

class Message(BaseModel):

role: Role
content: str

class ChatRequest(BaseModel):

model: str
messages: list[Message] = Field(min_length=1)
temperature: float = Field(default=0.7, ge=0, le=2)
max_tokens: int = Field(default=512, ge=1, le=4096)
stream: bool = False

from concurrent.futures import ThreadPoolExecutor from starlette.concurrency import run_in_threadpool

class InferenceService:

def __init__(self, model, pool_size: int = 4):
    self.model = model
    self.executor = ThreadPoolExecutor(max_workers=pool_size)

async def infer(self, inputs):
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(
        self.executor, self._sync_infer, inputs
    )

def _sync_infer(self, inputs):
    return self.model.generate(inputs)

import pytest from unittest.mock import AsyncMock from fastapi.testclient import TestClient from app.main import app

@pytest.fixture def client():

with TestClient(app) as c:
    yield c

def test_health(client):

resp = client.get("/health")
assert resp.status_code == 200

def test_infer_bad_input(client):

resp = client.post("/v1/infer", json={"text": ""})
assert resp.status_code == 422

@pytest.mark.asyncio async def test_infer_service_uses_preprocess():

service = InferenceService(model=AsyncMock(return_value="ok"))
result = await service.infer("  hello  ")
service.model.assert_awaited_once_with("hello")
赞0
踩0
☆收藏0
版权声明
文章版权声明:除非注明,否则均为chuanbook原创文章,转载或复制请以超链接形式并注明出处。
分享到
chuanbook

链接已复制到剪贴板