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")