Intelligent Chargeback Agent · CIRI

The API is the toolbox, not the agent

There are 32 endpoints and none of them decides the order the others are called in. n8n does that, on a canvas where every step is a named node. There is no “AI Agent” node here picking tools on its own: 14 of these endpoints are the walkthrough that can be replayed without an analyst, and the canvas fixes the order in advance, not a model.

The circuit

Every endpoint is a pin on the board. Tap one to see what it answers and which store it goes to — that is where the pattern the brief asks for shows up: the exact value comes from SQLite, what is alike from Qdrant, and the model receives both already chewed over.

Tap a pin on the circuit, or replay the whole walkthrough.

The latencies are measured against the Render deployment, not estimated. Reproducible without starting n8n: python scripts/seguir_el_flujo.py TXN-00042, which reads the workflow as a specification and makes the same calls in the same order.

How the RAG works

Two collections in Qdrant and one rule that separates them: what gets indexed is what you look up by similarity, not what you look up by identity. A transaction is asked for by its id — searching for it by similarity would be absurd. A precedent, on the other hand, cannot be asked for by id: what you want is “cases like this one”.

Code builds the query. No LLM. Voyage AI 1024 dims policies 17 · editable via the API historical_cases 60+ · grows on its own verdicts one per policy precedents top 5 · cut-off 0.40 The prompt context already chewed over resolved well → back into the corpus DETERMINISTIC QDRANT
Code builds the query, not the model. It is a template with the case's fields: contracargo {motivo}, {canal}, {método}, score {n}/100, {país}, plus per-rule enrichments — if the method is crypto it appends “no reversible blocker”, if the country is outside LATAM it appends “plazo extendido”. Two investigations of the same case produce exactly the same text, which is what makes the embeddings cache worth having.
INDEXED Policies · Historical cases Looked up by similarity: “which rules apply here?”, “what was done in cases like this?” NOT INDEXED Transactions · Logs Asked for by identity. A transaction is found by its id; its logs, whole, by that same id.
Putting everything into the vector store is the easy temptation and the expensive mistake: searching for TXN-00042 by similarity can return TXN-00043, which is a different transaction belonging to somebody else. An id does not admit “alike”.

Which patterns it uses, and which it does not

What follows is not a catalogue: it is what was applied, where it hurts if it is missing, and what was deliberately decided against.

The core domain/decision.py domain/precedentes.py zero dependencies · zero mocks to test it LLMClient Tracer PORTS FuenteDeCasos Completador PORTS n8n · the orchestrator The adapters, interchangeable AnthropicClient · OpenAICompatibleClient LangfuseTracer · TrazadorLocal · NoOpTracer
Ports and adapters. The core declares what it needs and does not know who supplies it. This is not a brochure claim: LLMClient has two implementations that do not share a line —one uses the Anthropic SDK, the other speaks raw HTTP to any OpenAI-compatible endpoint— and switching between them touches not one caller. That is what lets demo mode run on a genuinely free model instead of serving a recording.
evaluate policies synthesize judge they say WHICH STEP they are, never which client to use LLMManager the only door anthropic gemini · groq + 8 more one registry, not three tables
Facade, and why it is not decoration. Nobody outside LLMManager touches a client: callers say which step they are and get the answer back. As long as the caller could pick the client, it could pick the wrong one — and it did: the judge resolved demo mode's service and then invoked the production one, so half the pipeline went out through Anthropic with no credit while the other half ran on Gemini.
✳ Strategy as data, and a registry The differences between models are a table, not a chain of ifs.

A model that reasons needs more token budget than one that does not; one free tier takes five requests per minute and another thirty. That could be a ladder of conditionals; it is a table of frozen Perfil records, with the measured fact that justifies each number written beside it: one of the fields exists because a call spent ~3,900 reasoning tokens and reported 159 of answer.

The model wins over the provider when the two disagree, and rightly so: OpenRouter serves both Llama and Gemini, and you do not talk to them the same way.

adding a provider: 3 edits → 1 entry in proveedores.py
⇄ Adapter Only one, and it is the one that translates somebody else's protocol into ours.

OpenAICompatibleClient adapts OpenAI's protocol to the LLMClient Protocol. It is what lets ten different providers come in through the same door without any caller finding out.

What holds the differences between model families is not an adapter, and that is why it is not called one: it is perfiles.py, because what it holds is the profile each family is spoken to with — token floor, what to retry, how many requests per minute. Parameterising behaviour is not translating an interface.

⏱ Rate limiter, on the client side Not reaching the ceiling, instead of reacting to the 429.

The free tiers that make this system evaluable have tight ceilings, and the tightest is the embeddings one: Voyage allows 3 requests per minute. Since each investigation does two semantic searches, two analyses back to back already brush against it.

rate_limiter.py hands out turns before calling, with a sliding window per key: while you are below the ceiling nothing waits, and only when the window fills does it sleep until the oldest call turns a minute old. A fixed interval would add latency to the first investigation, which is exactly the one somebody is watching.

It is a component and not a private method because two paths need it. While it lived inside LLMManager, the model's path had preventive control and the embeddings one did not — which is precisely the one with the lowest ceiling. A capability that exists once and is needed twice is a component.

And the client asks for the turn, not whoever calls it. LLMManager.completar presented itself as “the door to the model” and it was not: the panel's ephemeral pipeline —demo mode and BYOK— receives ready-made clients and invokes them directly. Which meant the one path that runs on a free tier was precisely the one that never asked for a turn. With the quota inside the client, both doors go through it.

Waiting has to be visible. From outside, a limiter doing its job and a hung process are indistinguishable — and waiting is the normal case in demo mode: Gemini free is 5 requests per minute and one investigation makes 3 calls. The limiter announces itself before sleeping and the panel shows the provider, a countdown and the reason.

private to LLMManager → used by the model and by the RAG, and the wait is visible
☰ One table translates the failures, and only one The same cause said three different things depending on the way out.

There are three paths that surface a failure: the HTTP handlers, the panel's streaming and the HTML error page. If each classifies on its own, the same cause says three different things depending on the way out. And classifying by substring over the exception's message is fragile: that message can carry the response body inside it, so searching for “404” there matches against a file name and attributes to a 503 a cause it does not have.

domain/fallos.py classifies in order of confidence: exception type, then status code, and only at the end substring — and only where the SDK gives nothing else. Returning “I do not know” is a legitimate answer: an honest 500 comes out with its request_id, and that is worth more than an invented cause.

The panel still classifies on its own, and that is fine: once the SSE has started emitting, the response went out with a 200 and no @app.exception_handler can change it. It shares the classification even though it cannot share the transport.

∅ Null object With no observability configured, nobody asks whether there is observability.

NoOpTracer implements the same contract and does nothing. No caller writes if tracer is not None, which is exactly the point: the “switched off” case stops being a branch and becomes one more implementation.

It is cheap because the interface is small — three methods. A ten-method Protocol would have made the null object a burden instead of a solution.

▣ Parameter object One type, instead of nine loose arguments that get passed wrong.

CaseContext replaced three modellings of the same concept, each with its own names for the same fields. It is frozen: a case's context is not mutated while it is being analysed.

Revision does the same for the guardrails, and there it wins something concrete: adding a rule that needs a new piece of data does not change the signature of the other five or of the runner.

⌥ What was decided AGAINST A pattern you do not need is a layer somebody has to read.

Repository over db.py: no. What there is is an honest Table Data Gateway —it returns dict, not entities— and with a single backend and no ORM, one repository per aggregate would be ceremony. What did come out of there is the DDL: creating tables and migrating columns is not data access, and it lives in data/esquema.py.

Event bus for the alerts: no. There is one subscriber. An observer with N subscribers for a single one is noise; the injected callable says more.

Dependency injection container: no. The composition root in FastAPI's lifespan is the right place, and it already supports the case that mattered: the tests build the graph without fighting startup.

State machine for the pipeline: no. The steps are linear and read top to bottom.

How it meets SOLID

Not as a declaration: each letter below says what moved and what it enables. The numbers come from an audit that was run over the code and whose record survives in docs/decisions.md.

S One reason to change, and only one The central service did six things. Now it does one.

ResolutionService had 15 of its 22 methods declared static: fifteen pure functions living inside a class whose state seven methods used. When two thirds of a class does not need its state, the boundary is somewhere else — and the code itself was pointing at it.

It was split in four: the orchestration stayed where it was, the deterministic decision went to domain/decision.py, the precedent summary to domain/precedentes.py and the guardrails to services/guardrails.py. The same with Analyzer, which mixed a merchant's risk with an SLA's clock — and the SLA decides compensation, which is money.

resolution.py · 819 lines → 331 lines + 3 modules
O Open to extension without editing what already works Adding a guardrail meant editing a function. Now it means writing one.

The project presents “six guardrails” as one of its differentiators, and that number was frozen: the seventh forced another if inside a function that built a list by hand. Now a guardrail is a function that looks at a resolution and returns a warning or None, and the list is a tuple.

The two moments stay separate, and that is substantive: the divergence rules can only run before the deterministic override, which is the only window in which the model's proposal still exists. Afterwards, the delivered resolution carries the code's decision, and comparing it with itself says nothing.

editing guardrails.despues_del_override → one function and one line in a tuple
L Swapping one implementation for another cannot change what the system decides And for that, what an implementation declares has to be true.

There are three implementations of Tracer and the system has to be able to use any of them without changing behaviour. That demands that what they declare be true: enabled does not mean “I was configured”, it means “I am observing”, and whether the panel's metrics come from the remote service or from the local log depends on that answer.

A tracer that leaves enabled at True while its calls fail would leave the panel with fewer metrics switched on than switched off. That is why it shuts down on the first failure and does not retry: a wrong host or an invalid credential do not fix themselves.

The Protocol was split in two as well. Writing observations and reading what was observed are different capabilities: some implementations write and cannot read. While they were one, the consumer had to dodge the contract with getattr to find out which one it was talking to — and a Protocol the consumer has to work around stopped being the contract.

1 Protocol + 2 getattr → Tracer + FuenteDeMetricas
I Ask for little, and say what you are asking for The pipeline received 29 operations and used 5.

The contracts existed in fact —they were honoured— but they were not written down, so they were discovered by reading the code. PipelineService received the whole database and uses five methods; ResolutionService received its most important seam as a parameter with no type annotation.

The criterion for writing a Protocol was that the consumer uses considerably less than it receives. Where it uses nearly all of it, the concrete class stayed — and that is argued too: there is a single backend, there is no ORM, and five Protocols with one implementation each is ceremony, not inversion.

db: Database (29 methods) → db: FuenteDeCasos (5)
D Depend on the contract, not on the implementation The decision core no longer depends on anything.

domain/decision.py and domain/precedentes.py are pure functions over dict: they know nothing of the model client, the tracer or the database. They are tested without a single mock. While they lived inside the service, that logic dragged Tracer, LLMClient and ModelosService into its dependency graph for no reason other than sharing a file.

The provider registry is the other case: with three parallel tables under the same key, forgetting one fails silently — with no base URL, the Groq model would go out with the Groq credential towards Anthropic's API, and the error would talk about authentication. It is one entry, and an id that is missing raises saying which one it is.

3 tables synchronised by hand → 1 registry · the rest derives from it

Why this is not a CRUD with an LLM on top. The nine context steps are deterministic and cheap; the two that call the model receive everything already chewed over. The recommendation does not come from the model “thinking”: it comes from the policy verdicts, and the model writes the justification.

That is why the order matters and is in plain sight. An agent that picks its own tools resolves the same case differently twice. These fourteen calls are written in advance —which of them run depends on the case: with a cached report the walkthrough ends at the second, and a BLOCKER does not go through the form— and when the result is unconvincing you can point at which one of them answered badly.

32 endpoints · 14 in a case's walkthrough · 18 to operate the system
Full, executable contract at /docs (OpenAPI). Panel at /panel.