python-expert
Complete Python stack for cloud-native projects: async backend with FastAPI and Pydantic v2, agent flow orchestration with LangGraph/LangChain on AWS Bedrock, data science (pandas, scikit-learn, numpy), Jupyter notebooks, testing with pytest, and code quality with ruff/black/mypy/bandit. Use when building AI services (api, context-layer), writing FastAPI route handlers, implementing LangGraph StateGraph nodes/edges, doing data science/ML work, working with Jupyter notebooks, or running Python linting/type checks. Trigger: Python, FastAPI, Pydantic, LangGraph, pytest, ruff. Do NOT trigger for: frontend development, mobile development, DevOps/CI scripting in Bash. For AI architecture questions (RAG, model selection, evaluation), use agent-architecture-expert or evaluation-expert instead.
- License 许可
- MIT
- 最近更新
- 2026-08-27
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- python-expert
- license
- MIT
- metadata
- { "author": "Community", "status": "stable", "version": "1.0", "category": "backend" }
- description
- Complete Python stack for cloud-native projects: async backend with FastAPI and Pydantic v2, agent flow orchestration with LangGraph/LangChain on AWS Bedrock, data science (pandas, scikit-learn, numpy), Jupyter notebooks, testing with pytest, and code quality with ruff/black/mypy/bandit. Use when building AI services (api, context-layer), writing FastAPI route handlers, implementing LangGraph StateGraph nodes/edges, doing data science/ML work, working with Jupyter notebooks, or running Python linting/type checks. Trigger: Python, FastAPI, Pydantic, LangGraph, pytest, ruff. Do NOT trigger for: frontend development, mobile development, DevOps/CI scripting in Bash. For AI architecture questions (RAG, model selection, evaluation), use agent-architecture-expert or evaluation-expert instead.
02 资源文件 5
- 参考文档evals/evals.json2.5 KB
- 参考文档references/async-patterns.md1.3 KB
- 参考文档references/datascience.md1.2 KB
- 参考文档references/langgraph-patterns.md1.6 KB
- 参考文档references/testing-patterns.md1.4 KB
03 SKILL.md 正文
Python Expert
Python Stack: FastAPI, LangGraph/LangChain, data science, testing and linting.
Core Stack
- API: FastAPI 0.110+ (routers, Depends, lifespan, middleware)
- Validation: Pydantic v2 (
model_config = ConfigDict(from_attributes=True)) - Async:
asyncio, httpx, SQLAlchemy 2.0 async, asyncpg - AI: LangGraph (StateGraph, nodes, conditional edges) + LangChain (chains, tools)
- AI Runtime: AWS Bedrock (
ChatBedrockConverse) - Data Science: pandas, scikit-learn, numpy, joblib
- Notebooks: Jupyter (jupytext, nbconvert, papermill, kernels)
- Testing: pytest + fixtures + parametrize + httpx
AsyncClient - Linting:
ruff format->ruff check->mypy->bandit - Packaging: pyproject.toml / uv / poetry
Project Structure
src/
api/routers/ # route handlers (thin)
core/ # config, dependencies, lifespan
models/ # Pydantic schemas (request/response)
services/ # business logic
repositories/ # data access
multi_agents/
orchestrator/
branches/<stimulus>/<version>/
graph.py # StateGraph definition
nodes.py # node functions
edges.py # conditional routing
stimuli_registry.py
state.py # shared TypedDict state
tests/
Architecture
Router -> Service -> Repository (NEVER skip layers)
- Routers: parse -> call service -> return Pydantic model
- Service: business logic only (no HTTP concerns)
- Repository: async data access
- NEVER business logic in routers | NEVER sync blocking in
async def
Rules
source .venv/bin/activatebeforepytest/python— ALWAYS- Docstrings: Google style (Args/Returns/Raises)
ensure_ascii=Falseonly injson.dumps, never in LLM system prompts- ASCII-only in LLM system prompts (no em-dash, smart quotes)
- NEVER log PII (tokens, government IDs)
LangGraph / AI Patterns
from langgraph.graph import StateGraph, END
from typing import TypedDict
class State(TypedDict):
messages: list
next: str
graph = StateGraph(State)
graph.add_node("analyze", analyze_node)
graph.add_conditional_edges("analyze", route_fn, {"a": "nodeA", "b": END})
app = graph.compile()
- NEVER mutate state directly -> return patches only
- NEVER hardcode model IDs -> use config/env
- ALWAYS version branches (
v1/,v2/) — never overwrite - ALWAYS register new stimuli in
stimuli_registry.py - ALWAYS use
astream/ainvokefor async execution - Wire to Bedrock via
ChatBedrockConverse
Data Science
- pandas: vectorized ops over loops (100x perf)
- scikit-learn: pipelines, ColumnTransformer, cross-validation
- numpy: broadcasting, masking, avoid Python-level loops
- joblib: model persistence (
dump/load), parallel processing - Notebooks: jupytext for .py sync, nbconvert for automation, NEVER secrets in notebooks
Testing
import pytest
from httpx import AsyncClient, ASGITransport
from myapp.main import app
@pytest.mark.anyio
async def test_create_item():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
response = await client.post("/items", json={"value": 1000})
assert response.status_code == 201
- Fixtures over setup/teardown. Parametrize over loops.
httpx.AsyncClientwithASGITransportfor FastAPI testing- NEVER global client — always
async with
Linting (Golden Chain)
ruff format -> ruff check -> mypy -> bandit
Stop on first failure. Never || true in CI.
Constraints
- NEVER business logic in routers -> service layer only
- NEVER sync blocking in
async def->run_in_executoror async libs - NEVER
import *— explicit imports only - NEVER mutate LangGraph state directly — return patches
- NEVER hardcode model IDs or secrets in notebooks
- ALWAYS type-annotate all function signatures
- ALWAYS
raise HTTPExceptionwith explicitstatus_code - ALWAYS propagate
request_idviacontextvars - NEVER
from langchain_community import *— pin exact imports
Security
- ALWAYS run
banditin CI andpip-auditfor dependency CVEs (OWASP A03) - NEVER use
pickleoryaml.loadon untrusted input (CWE-502) — useyaml.safe_loador JSON - NEVER pass user input into URLs fetched by httpx/requests without validation (SSRF)
- ALWAYS use parameterized queries — never string-concatenate SQL (SQLi)
Overview
Python services in this project use FastAPI for async APIs, LangGraph on AWS Bedrock for agent orchestration, and pandas/scikit-learn for data science. This skill covers the full stack from route handlers to LangGraph state machines to linting.
Quick Reference
| Layer | Library | Responsibility |
|---|---|---|
| API | FastAPI + Pydantic v2 | Route handlers, request/response validation |
| AI Workflows | LangGraph + Bedrock | Agent state machines, LLM invocation |
| Data | pandas, scikit-learn, numpy | Analytics, ML pipelines |
| Testing | pytest + httpx AsyncClient | Unit + integration tests |
| Linting | ruff → mypy → bandit | Format, type-check, security scan |
Workflow
- Define Pydantic v2 models with
ConfigDict(from_attributes=True)for request/response schemas - Implement FastAPI router with thin handlers: parse → call service → return model
- Write async service layer with business logic and
contextvarsforrequest_id - For AI workflows: define LangGraph
StateGraphwith typedState, nodes, and conditional edges - Register new agent branches in
stimuli_registry.pywith versioned directories - Write pytest fixtures + parametrized tests using
httpx.AsyncClientwithASGITransport - Run golden chain:
ruff format→ruff check→mypy→bandit
Anti-patterns
FAIL: Business logic in FastAPI route handlers PASS: Route handlers only parse input and delegate to service layer
# FAIL:
@app.post("/items")
async def create_item(req: ItemRequest):
if req.value <= 0:
raise HTTPException(400)
result = await db.execute("INSERT ...")
return {"status": "ok"}
# PASS:
@app.post("/items")
async def create_item(req: ItemRequest):
return await item_service.create(req)
FAIL: Synchronous blocking calls inside async def
PASS: Use async libraries or run_in_executor for CPU-bound work
# FAIL:
async def process():
time.sleep(2) # blocks event loop
result = pd.DataFrame(...).apply(slow_fn) # CPU-bound blocks event loop
# PASS:
async def process():
await asyncio.sleep(2)
result = await asyncio.to_thread(lambda: pd.DataFrame(...).apply(slow_fn))
FAIL: Mutating LangGraph state directly inside nodes PASS: Always return patches from node functions
# FAIL:
def analyze_node(state: State) -> dict:
state["messages"].append({"role": "assistant", "content": "done"})
return state
# PASS:
def analyze_node(state: State) -> dict:
return {"messages": [{"role": "assistant", "content": "done"}]}
References
-
FastAPI Documentation (last_verified: 2025-02)
-
LangGraph Tutorial (last_verified: 2025-01)
-
AWS Bedrock Converse API (last_verified: 2024-12)
Verification Checklist
- [ ] Business logic separated into service layer (never in routers)
- [ ] All
async deffunctions use async libraries only (no sync blocking calls) - [ ] LangGraph nodes return state patches (never mutate state directly)
- [ ] Pydantic v2 models use
ConfigDict(from_attributes=True)for ORM mode - [ ] Golden chain passed:
ruff format→ruff check→mypy→bandit - [ ]
request_idpropagated viacontextvarsthroughout request lifecycle - [ ] No PII logged (tokens, government IDs)
- [ ]
banditandpip-auditrun clean; nopickle/yaml.loadon untrusted input
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Event loop blocked during request | Sync time.sleep() or CPU-bound operation in async def |
Replace with asyncio.sleep() or await asyncio.to_thread() for CPU work |
| FastAPI returns 422 on valid input | Pydantic v2 model uses v1-style config or ConfigDict missing |
Verify model_config = ConfigDict(from_attributes=True) on model |
| LangGraph node state not updating | Node mutates state directly instead of returning patch | Change node to return dict of only changed keys (never mutate state arg) |
| Pydantic v2 JSON serialization fails for custom types (edge case: non-serializable types) | Custom type lacks __get_pydantic_core_schema__ or serializer |
Add model_serializer or use field_serializer decorator on the field; register type adapter |
| [WARN] FastAPI Depends() evaluates DB session outside request context on error path | Exception handler may try to access request-scoped dependency after request cleaned up | Create DB session in middleware/lifespan, not Depends(); use try/finally for cleanup |
| pytest --cov shows 100% coverage but critical exception path was never tested | Coverage tracks line execution, not logic branches; uncovered except blocks hidden from metric | Use --cov-branch to measure branch coverage; enforce if/except path coverage in CI gate |
| Limitation: LangGraph checkpoint created during node execution is rolled back if node later fails | Checkpointing at node start commits state that node may not fully validate until end | Checkpoint only at end of node execution; use conditional edge to skip checkpoint on partial failure |
04 同仓库更多 Skills
web-browsing-agent-expert
Web browsing for AI agents: driving a headless browser (Playwright, Puppeteer) from agent tooling, navigation and page-state grounding, DOM extraction and structured data capture, form interaction, session and cookie management, anti-bot mitigation awareness, and safe browsing rules (no PII exfiltration, respect robots and terms). Use when building a browsing tool or MCP server for an agent, teaching an agent to navigate and read web pages, extracting structured content from dynamic sites, or handling login walls and pagination in agent workflows. Trigger: web browsing agent, headless browser, Playwright MCP, Puppeteer, browser automation for agents, DOM extraction, page navigation, session management. Do NOT trigger for: end-to-end UI testing of an application (use playwright-expert); writing standalone scraping scripts for data pipelines (use python-expert); fetching a single public URL (use the fetch tool).
vector-databases
Design and operate vector databases for cloud-native AI features. Use when selecting between pgvector, Pinecone, or Weaviate for AI context layer or integration-hub; designing embedding schemas and index parameters; implementing ANN search with metadata filtering; managing embedding model versions; optimizing query latency; or debugging low retrieval quality. Pairs with rag-architecture for pipeline design and postgres-database-expert for pgvector specifics. Trigger: vector database, pgvector, Pinecone, Weaviate, embedding, ANN search, HNSW, cosine similarity. Do NOT trigger for: relational SQL optimization, standard PostgreSQL schema design, Redis caching.
typescript-expert
Full-stack TypeScript stack for modern projects: frontend SSR/CSR with Next.js 14 App Router and React, backend APIs with Node.js (Express/Fastify), state management with Zustand/Redux Toolkit, unit and integration testing with Vitest/Jest + React Testing Library + MSW, and static analysis with ESLint/Prettier/tsc. Use when building React components or hooks, implementing Next.js App Router or Server Components, writing Node.js REST API handlers, implementing middleware (auth, rate-limit, logging), managing client state (Zustand/RTK), writing frontend/backend tests, or running TypeScript linting/type checks. Trigger: TypeScript, Next.js, React, Zustand, Node.js, Express, Fastify, MSW, Vitest. Do NOT trigger for: Python backend development, Go microservices, iOS/mobile development.
tool-usage
Guide correct tool selection, design, and orchestration for AI agents. Use when choosing between dedicated vs Bash tools, designing MCP tool interfaces, naming tool parameters, handling tool response limits, orchestrating parallel vs sequential calls, evaluating tool accuracy, applying ACI design principles, selecting workflow patterns, or reading/filtering/transforming/generating structured data (JSON, YAML, CSV, TOML, XML). Trigger: tool selection, MCP tool design, orchestration, ACI, parallel execution, composite tool, structured data, jq, yq, dasel, mlr, csvkit. Do NOT trigger for: writing application business logic, domain-specific development (route to domain skill), database migrations.
token-efficiency
Enforce token-efficient output, compression, caching, and model routing. Use when calibrating response verbosity, applying compression strategies to logs or RAG chunks, routing tasks to the right model tier, setting thinking budgets, enforcing word limits, compressing context before reinitiation, applying KV-cache ordering, masking tool output observations, or applying clarification-first protocol before irreversible actions. Trigger: token efficiency, compression, model routing, thinking budget, KV-cache, clarification protocol. Do NOT trigger for: non-agent tooling, CI/CD pipeline scripting, infrastructure provisioning.
time-series-db
Time-series database patterns for cloud-native metrics and analytics: TimescaleDB, InfluxDB, and Amazon Timestream selection; continuous aggregates, retention policies, downsampling, and integration with Prometheus/Grafana. Use when storing business metrics over time, building custom business dashboards, designing high-frequency event storage, or querying time-bucketed aggregations. Trigger: time-series, TimescaleDB, InfluxDB, Prometheus, Grafana, hypertable, continuous aggregate, retention policy. Do NOT trigger for: relational PostgreSQL schema design, NoSQL document stores, Kafka event streaming.