Install any skill in seconds. Free to start, no credit card required.
Get Started Free →A reference layered architecture for production LangChain 1.0 and LangGraph 1.0 Python services: LLM factories, DI, config, tenant scoping.
Use this skill ↓23% 86%+64 ptsof test cases passed
Passed 19 of 22 test cases with the skill, and 5 of 22 without it.
In a multi-tenant FastAPI service using LangChain, module-level retriever initialization causes multi-tenant data cross-contamination. Show how to implement a factory function that produces retrievers dynamically without rebuilding vector store connections on every HTTP call.
The retriever factory is placed in adapters/retriever_factory.py
3 of 3 safety checks passed
Eight months into a LangChain service, a code review surfaces the mess.
Twelve chain definitions live inlined inside FastAPI route handlers. Three
retrievers are constructed at module-global scope, one bound to
tenant_id="acme" because that was the first tenant in the pilot —
that retriever now returns Acme's documents to every other tenant, a P33
leak that has been live in production for six weeks.
max_retries=6 is hardcoded at four separate call sites. A
RunnableWithMessageHistory backed by the default
InMemoryChatMessageHistory loses every conversation on pod restart
(P22) — which is most days, because Cloud Run scales to zero.
Config is read from os.environ in three modules with three different
fallback strategies. There is no place to put a new provider without
touching seven files, and nobody remembers why the retriever is built
at import time.
The fix is not "rename a variable." The fix is an architecture that made every one of those mistakes hard to write. This skill is the target layered architecture:
app/ — FastAPI routes. Thin. Parses HTTP, calls into services,
serializes response. No chain logic, no vendor clients, no env vars.services/ — chain and graph definitions. Take dependencies through
constructor args, not module-level imports.adapters/ — vendor clients, LLM factory, retriever factory, tool
factory. This is where langchain-anthropic is imported. Nowhere else.config/ — one Pydantic Settings class. SecretStr for keys,
Literal["dev","staging","prod"] for env names, .env file loader.domain/ — Pydantic models, typed LangGraph state, enums. No I/O.Five layers, five imports deep at most. Dependency direction is
strictly downward. app imports services; services imports
adapters; adapters imports config and domain. Never the reverse.
Import-linter enforces this in CI. Pain-catalog anchors: P22 (in-memory
history loses messages — architectural fix is persistent history
injected via DI) and P33 (per-tenant vector stores leak if retriever
bound at import — architectural fix is per-request factory). Adjacent:
Next to this one in the catalogue, plus more from the same author.