Python & AI Backend Engineering Standard
Objective
Enforce production-grade Python 3.11+ architecture, strict Pydantic v2 boundary contracts, non-blocking async execution, and resilient LLM/RAG pipeline integration aligned with ARCHITECTURE.md, CONVENTIONS.md, and SECURITY.md.
1. Toolchain & Typing Baseline
- Runtime & Environment: Target Python 3.11+. Execute all commands through the project's locked runner (
uv run,poetry run) specified inAGENTS.md. - Complete Type Annotations: Every function, method, fixture, and dependency must declare explicit parameter and return types. Use modern built-in generics (
list[str],dict[str, Any],X | None) instead of legacytyping.Listortyping.Optional. - Zero Untyped Dict Payloads: Never pass raw untyped
dictobjects across layer boundaries (Router <-> Service <-> Repository). Model every payload with Pydantic v2 ordataclasses.
2. FastAPI Layering & Dependency Injection
Enforce the inward dependency rule from ARCHITECTURE.md:
- Thin Routers (
api/routes/):- Route handlers must contain zero business logic, zero direct ORM/SQL queries, and zero direct LLM/HTTP client calls.
- Responsibilities are strictly limited to: parsing validated Pydantic inputs, resolving dependencies via
Annotated[..., Depends(...)], calling a single Application Service method, and returning the standard API response envelope (CONVENTIONS.md).
- Application Services (
services/):- Encapsulate all business workflows, orchestration, and authorization checks.
- Must remain framework-agnostic: never import
fastapi.Request,fastapi.HTTPException, or HTTP status codes insideservices/ordomain/. Raise typed domain exceptions instead.
- Repositories & Adapters (
repositories/,adapters/):- Isolate all SQLAlchemy/Supabase queries, vector store operations, and external API/LLM SDK calls behind explicit repository or client interfaces.
3. Pydantic v2 Data Contracts
- Strict Boundary Models: Configure all external request, webhook, and LLM output schemas with
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)so unexpected fields fail fast at the boundary. - Explicit Constraints: Use
Field(..., min_length=1, max_length=...)and custom@field_validator/@model_validatorhooks to enforce domain invariants before data enters services. - Configuration Management: Load environment variables strictly through a singleton
pydantic_settings.BaseSettingsclass; never scatteros.getenv()calls across application modules.
4. Non-Blocking Async I/O & Database Hygiene
- Protect the Event Loop: Inside
async deffunctions, never invoke blocking calls (requests,urllib,time.sleep, synchronous file I/O, or synchronous DB drivers).- Use
httpx.AsyncClientwith explicithttpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0)for outbound HTTP calls. - Offload CPU-bound operations (embedding generation, tokenization, dataframe transforms, local model inference) via
await asyncio.to_thread(...)or dedicated background workers.
- Use
- Database & Query Discipline:
- Use parameterized queries or ORM expressions exclusively; never format user input into SQL strings.
- Prevent N+1 query loops by using explicit eager loading (
selectinload/joinedload) when fetching relational collections. - Keep database transactions scoped to the unit of work in the Application layer; never commit inside low-level repository helper methods.
5. LLM, RAG & AI Pipeline Guardrails
When building LLM clients, agents, or retrieval pipelines:
- Structured Outputs Over Raw Text: Whenever downstream code parses an LLM response, enforce structured JSON output validated against a Pydantic v2 schema. If validation fails, trigger at most one schema-guided repair retry before raising a typed
LLMOutputValidationError. - Resilience & Cost Bounds: Every external or local LLM call must specify:
- Explicit request
timeoutandmax_tokensceiling. - Bounded retries (max 2–3 attempts) with exponential backoff and jitter only for transient errors (
429,502,503,504, connection timeouts)—never retry400or authentication errors.
- Explicit request
- Prompt Injection Isolation: Never concatenate untrusted user text, retrieved RAG chunks, or web content directly into system prompts. Wrap untrusted context inside explicit structural delimiters (e.g.,
<retrieved_context>...</retrieved_context>) and instruct the model to treat enclosed content strictly as passive data. - Deterministic Evaluation Hooks: Keep prompt templates, chunking parameters, and model identifiers externalized as constants or configuration fields rather than hardcoded inside control flow.
6. Error Handling & Structured Observability
- Typed Domain Exceptions: Define a base
AppDomainError(code: str, message: str, details: list[dict[str, Any]] | None = None)hierarchy mapped centrally in FastAPI exception handlers to HTTP status codes (400,401,403,404,409,422,502,504). - Structured Logging: Use
structlogor standardloggingconfigured for JSON output withrequest_idcontext. Never useprint(), and never log raw API keys, auth headers, or unmasked user PII.
Anti-Patterns: Rejected vs. Accepted Implementation
Rejected (Fat Router + Blocking I/O + Raw Dict)
@router.post("/analyze")
async def analyze(payload: dict, db: Session = Depends(get_db)):
res = requests.post("https://api.example.com/llm", json=payload) # Blocks event loop, no timeout
db.execute(text(f"INSERT INTO logs VALUES ('{payload['id']}')")) # SQL injection risk
return res.json() # Bypasses standard response envelope
Accepted (Thin Router + Pydantic v2 + Async Service)
class AnalyzeRequest(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
document_id: UUID
query: str = Field(..., min_length=3, max_length=2000)
@router.post("/analyze", response_model=ApiResponse[AnalyzeResult])
async def analyze_document(
payload: AnalyzeRequest,
service: Annotated[AnalysisService, Depends(get_analysis_service)],
request_id: Annotated[str, Depends(get_request_id)],
) -> ApiResponse[AnalyzeResult]:
result = await service.run_analysis(document_id=payload.document_id, query=payload.query)
return ApiResponse.ok(data=result, request_id=request_id)
### Accepted (Thin Router + Pydantic v2 + Async Service)
```python
class AnalyzeRequest(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
document_id: UUID
query: str = Field(..., min_length=3, max_length=2000)
@router.post("/analyze", response_model=ApiResponse[AnalyzeResult])
async def analyze_document(
payload: AnalyzeRequest,
service: Annotated[AnalysisService, Depends(get_analysis_service)],
request_id: Annotated[str, Depends(get_request_id)],
) -> ApiResponse[AnalyzeResult]:
result = await service.run_analysis(document_id=payload.document_id, query=payload.query)
return ApiResponse.ok(data=result, request_id=request_id)