python-ai-backend

Use when writing, modifying, or reviewing Python 3.11+ backend code, FastAPI routers, Pydantic v2 schemas, async database repositories, data pipelines, or LLM/RAG integrations.

O que é python-ai-backend?

python-ai-backend is a Claude Code agent skill that use when writing, modifying, or reviewing Python 3.11+ backend code, FastAPI routers, Pydantic v2 schemas, async database repositories, data pipelines, or LLM/RAG integrations.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/kadir465/agent-vault/tree/HEAD/skills/python-ai-backend

Installed? Explore more Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

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 in AGENTS.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 legacy typing.List or typing.Optional.
  • Zero Untyped Dict Payloads: Never pass raw untyped dict objects across layer boundaries (Router <-> Service <-> Repository). Model every payload with Pydantic v2 or dataclasses.

2. FastAPI Layering & Dependency Injection

Enforce the inward dependency rule from ARCHITECTURE.md:

  1. 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).
  2. 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 inside services/ or domain/. Raise typed domain exceptions instead.
  3. 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_validator hooks to enforce domain invariants before data enters services.
  • Configuration Management: Load environment variables strictly through a singleton pydantic_settings.BaseSettings class; never scatter os.getenv() calls across application modules.

4. Non-Blocking Async I/O & Database Hygiene

  • Protect the Event Loop: Inside async def functions, never invoke blocking calls (requests, urllib, time.sleep, synchronous file I/O, or synchronous DB drivers).
    • Use httpx.AsyncClient with explicit httpx.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.
  • 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:

  1. 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.
  2. Resilience & Cost Bounds: Every external or local LLM call must specify:
    • Explicit request timeout and max_tokens ceiling.
    • Bounded retries (max 2–3 attempts) with exponential backoff and jitter only for transient errors (429, 502, 503, 504, connection timeouts)—never retry 400 or authentication errors.
  3. 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.
  4. 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 structlog or standard logging configured for JSON output with request_id context. Never use print(), 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)

Individual skills in this repo

This repo contains 1 individual skill — each has its own dedicated page.

Habilidades Relacionadas