There is a large gap between an impressive AI demonstration and a system that enters production at a bank and survives its first audit. Most of that gap is engineering.
This document describes the multiagent architecture standard we apply. It reflects delivery experience in environments where decisions must be explained to people who need more than an interpretation of model behavior.
We publish the full approach, including the pitfalls that were expensive to discover. The implementation details below describe this architecture; validate library behavior and failure policies against the versions and requirements of your own system.
The organizing principle
The LLM is used only for natural language generation. Business decisions, including authentication, authorization, calculations and rule-based routing, are deterministic and executed by ordinary code.
A language model is useful for interpreting ambiguous requests and writing clear responses. It does not provide a reproducible, line-by-line testable decision record.
When an auditor asks why application 84,213 was denied in March, the answer needs to be a commit and a record, rather than a hypothesis about model behavior that day.
In practice, the boundary looks like this. Identifiers from the original implementation are retained in the examples:
# business/credito.py
# Pure function. Same input, same decision.
# Covered by unit tests and traceable through Git history.
def avaliar_elegibilidade(proposta: Proposta) -> Decisao:
if proposta.idade < IDADE_MINIMA:
return Decisao.negar(motivo="IDADE_MINIMA", politica="POL-CRED-014")
if proposta.score < faixa_minima(proposta.produto):
return Decisao.negar(motivo="SCORE_ABAIXO_DA_FAIXA", politica="POL-CRED-021")
return Decisao.aprovar(
limite=calcular_limite(proposta),
politica="POL-CRED-030",
)
The agent receives a completed Decisao, including the reason and policy identifier,
and writes the customer message. It cannot approve or deny the application.
Everything below supports that boundary under deadline pressure, scope changes and team turnover.
Structure
Folder boundaries prevent specific classes of error:
<project>/
├── <gateway> FastAPI, webhook, CLI — replaceable, outside the core
├── agents/ one file per agent, all inheriting from AgenteBase
├── core/ domain-independent infrastructure
│ ├── state.py state TypedDict and helpers
│ ├── graph_builder.py
│ ├── router.py
│ ├── registry.py
│ ├── llm.py
│ ├── observability.py
│ └── prompt_loader.py
├── business/ deterministic rules — no LLM
├── guardrails/ input, output and flow
├── tools/ tools exposed to agents
├── prompts/ <agent>_v<N>.yaml
├── evals/ datasets and evaluation runners
├── docs/adr/ architecture decision records
└── tests/ unit and integration tests
The most valuable rule: business/ imports nothing from core/ or agents/.
If a rule needs conversational interpretation to decide, separate that interpretation
from the business rule.
This constraint takes effort initially and pays off as the project grows.
State
A single TypedDict travels through the graph. More important than the fields
is who may write each one.
| Field | Type | Writer |
|---|---|---|
messages |
list |
agents, through a helper |
session_id |
str |
gateway |
turno |
int |
core |
autenticado |
bool |
business/auth.py only, never the LLM |
agente_atual |
str |
core |
proximo_agente |
str | None |
the agent initiating a handoff |
handoff_context |
dict | source agent |
encerrado |
bool |
agents |
autenticado illustrates the principle. If the LLM could write this field,
a crafted user message could attempt to declare the session authenticated.
Only business/auth.py writes it, and that function is extensively tested.
Avoid underscore-prefixed state fields in this pattern. We encountered
checkpoint/schema handling that silently discarded them. Verify persistence with
your chosen implementation; store partial conversational data in messages.
Dynamic agent registry
No core component knows an agent by name. The graph is built from a registry:
class AgenteBase(ABC):
nome: str
descricao: str
requer_autenticacao: bool
@abstractmethod
def run(self, state: State) -> State: ...
Adding an agent means inheriting from AgenteBase and calling registrar().
The router, graph builder and guardrails remain unchanged.
This allows a new production specialist to be added without modifying already audited core code paths.
AgenteBase also provides shared behavior: a sliding context window containing
the first two messages and the latest six, LLM calls with observability callbacks,
and consumption of handoff_context.
Guardrails as a mandatory envelope
Every agent runs inside the same wrapper:
FlowGuard → InputGuard → Agent → OutputGuard
The graph builder wraps every registered node. No agent bypasses the wrapper because registration has no unguarded path.
FlowGuard reads requer_autenticacao from the registry and redirects to
triage when required. Authorization occurs before any tokens are spent.
InputGuard applies checks in this order, which matters for cost and security:
- Closed-session blocking, except at the entry agent
- Rate limiting
- Maximum message size
- Empty or excessively short messages
- Prompt injection attempts
- Domain scope
Step 6 uses a lightweight classifier for ambiguous cases. In this implementation, replies up to five words bypass that classifier, preserving responses such as “yes,” “that works” and “the second one.” This heuristic needs domain-specific testing.
OutputGuard removes leaked tracebacks and technical details, redacts third-party PII and checks for card numbers, passwords and tokens before output is sent.
Routing and invisible handoffs
The router has three steps, in this order:
state.encerrado→END- If
state.proximo_agenteis set → route there - Otherwise →
END
The third step is a common source of failures. Returning agente_atual as the
default can create an infinite loop: the agent finishes and is immediately called again.
A handoff is silent. The source agent sets proximo_agente without adding a message.
The graph executes the next node before returning control to the user. From outside,
the transition between specialists looks like one conversation.
Versioned prompts
Prompts live in YAML with explicit versions, such as triagem_v3.yaml.
The change process is consistent:
- Create
<agent>_v<N+1>.yaml - Run the evaluation suite
- Update
PROMPT_VERSION - Commit that change separately
During an incident, reverting behavior means pointing to the previous prompt version, without a code deployment or application rollback, while retaining a record of the change.
Evaluation with a regression gate
Each agent has an evaluation set built from real cases in the client domain. Prompt, model or rule changes trigger the suite.
A decline beyond the agreed threshold blocks promotion. This makes changes in nondeterministic behavior measurable against a known baseline.
We separate three levels:
- Agent level: the isolated agent responds correctly within its scope
- Behavioral: the system refuses prohibited requests, avoids leaks and respects scope
- End to end: complete journeys with a real LLM
The first two run in CI. Real-LLM journeys sit behind a pytest marker and run on demand because each execution incurs cost.
Three-layer observability
Three layers degrade gracefully:
- Structured JSON logs: always active, without an external dependency
- In-memory buffer: feeds the operations dashboard
- External tracing: optional, with isolated failures
The third layer must not take down the first. When tracing fails, the system loses external visibility while continuing to serve requests. Availability incidents can also carry reporting obligations in regulated environments.
We instrument session cost, step latency, active prompt version, guardrail events and each handoff.
Persisted state
A checkpointer persists state at each turn. SQLite supports development; Redis or Postgres can support production. This pattern includes an in-memory fallback, which sacrifices durability to preserve availability. Whether that tradeoff is acceptable must be defined for the particular operation.
Persisted state enables a session to be reconstructed months later, turn by turn.
For active-session listing, this implementation uses a separate pluggable session
index, updated by a gateway upsert on every turn, rather than depending on a
checkpointer-specific listing interface.
A replaceable model layer
The provider sits behind a cached factory configured through environment variables. We use two instances with different purposes:
- Primary:
temperature=0.2, for writing - Classifier:
temperature=0.0,max_tokens=10, for binary classification
Switching suppliers or moving to an open model on client infrastructure does not change business logic. Model prices and quality change frequently; the architecture should accommodate that.
Recorded decisions
Every structural choice becomes a short ADR: context, alternatives, decision and consequences. Stable numbering, one decision per file.
When someone later asks why the router does not retry, the reasoning is available alongside the conclusion.
Expensive pitfalls
These are lessons worth checking before implementation.
proximo_agente not cleared after a handoff. The destination agent finishes
without setting a new handoff, but the old field remains and the graph loops.
The wrapper should clear proximo_agente at the start of each execution.
Returning agente_atual as the router default. Another route to an infinite
loop, and expensive enough to mention twice.
Underscore-prefixed state fields. In the checkpoint configuration we used, these were discarded without useful errors or logs. Test your state round trip.
Premature handoff. Transferring before the user sees the current step can lose a message. A local flag prevents the immediate transition when needed.
Consuming handoff_context more than once. The destination agent repeats its
greeting every turn. Consume the context when building the system prompt, then clear it.
Accents in Python regex matching. \bmedic does not match “médico.” Normalize
with unicodedata.NFKD before comparison, using one shared core helper.
Patching the wrong import location. monkeypatch.setattr("modulo.funcao", ...)
does not replace a name already bound by from modulo import funcao elsewhere.
Patch the name where it is looked up. A passing test that exercises nothing is misleading.
AsyncIOScheduler needs an active event loop. Test construction without starting
it, or use an asynchronous test with shutdown during teardown.
What stays outside the standard
The user interface, domain, concrete LLM provider, external APIs and tracing infrastructure vary between projects and remain outside the core standard.
The core should not need to know whether it serves a bank or a healthcare insurer.
Where to start
When building from scratch, this order reduces rework:
state.pyand the router, with the correct default caseAgenteBaseand the registry- The guardrail wrapper, before adding a second agent
- One real agent working end to end
- The first evaluation set with real cases
- Persistent checkpointing
- Observability
Items 3 and 5 are often delayed. They also have a major influence on whether the system reaches production.
