CIRI · Chargeback agent

RAG
from a transaction to the context the model reads

RAG in this system is not a call: it is a chain of transformations over text, and a model decides none of them. Code builds the query, code picks how many results to bring back and code ranks them. The model receives the context already assembled and its work starts there. This page follows that whole chain with a real case.

Qdrant · vector store SQLite · exact value Code, no model Model call What goes back into the index

The case this whole page follows: TXN-00051 — Airbnb, USD 2,095.90, Crypto, COL, POS channel, antifraud score 8. Stated reason: “No reconoce la compra” (does not recognise the purchase). The texts in the boxes below are what the system produces, not illustrative examples — they stay in Spanish because that is the language of the corpus, the policies and the logs.

01What goes into the index Two collections · 1024 dimensions · voyage-multilingual-2

Every document is turned into text before being embedded, and the shape of that text is a design decision: a policy is one whole document, never split. They run 60 to 90 tokens, and their unit of meaning is indivisible — condition, threshold and exception only mean something together. Splitting them into chunks would have multiplied the points without adding a single useful distinction.

policies 17 in the dataset · grows through the API

One policy, one point. Its full Markdown is embedded:

# POL-EXC-003 **Categoria:** EXCEPCIÓN **Politica:** Transacciones en cripto ## Descripcion Las transacciones realizadas con criptomonedas no son elegibles para chargeback bajo ninguna circunstancia. Se aplica política de 'no reversibilidad' inherente al protocolo. **Referencia:** Manual de Excepciones v1.0, Sec. 4
point id
uuid5(code) — deterministic, allows rewriting
payload
code, name, category, description, reference, markdown, puede_bloquear and sla_dias

historical_cases 60 · grows with every endorsed case

A case is not embedded alone: its transaction is glued to it, because a precedent without its context resembles nothing.

Caso CB-0038: contracargo por Monto incorrecto Resolucion: Caso cerrado sin resolución en Rappi, Cuenta Virtual, CHL, USD 1187.58, score antifraude 74 Observaciones: Error en sistema de pagos detectado — cargo doble por timeout.
payload
the whole case + merchant, amount, payment method, country and fraud_score from its transaction, plus the text that was embedded
filterable
transaction_id has its own index in Qdrant: it is what holds up the exclusion of a transaction's own cases

What is deliberately not indexed

Transactions and logs. A transaction is reached by its exact identifier, and the logs are fetched whole by transaction_id. Searching for “the transaction most similar to TXN-00051” answers no question anybody actually has: embedding them would have been spending on an index nobody queries. RAG is reserved for what does have semantic neighbours — a policy written in prose, a case somebody else resolved.

02Code builds the query rag/retriever.py · QueryBuilder

There is no model writing the query. There is a template with the transaction's fields and four enrichment rules that add vocabulary when the transaction falls into a known case. The consequence is that the same transaction always produces the same search: zero cost, zero latency, and an auditor can reconstruct what was searched for.

Base templatefor_policies()
contracargo {motivo}, {canal}, {método}, score {n}/100, {país}
The four rulesand which fired on TXN-00051
✓ method = Crypto → “criptomonedas no reversible blocker” ✓ score < 30 → “transaccion de alto riesgo fraude score bajo” ✗ country outside LATAM → “internacional fuera LATAM plazo extendido” ✗ channel = IVR → “limite monto IVR”

COL is LATAM and the channel is POS, so those two add nothing. The other two do: without them, the query says nowhere that this payment is irreversible, and POL-EXC-003 —the only policy that can issue a blocking verdict— competes on similarity with the other sixteen with no advantage at all.

What comes outpolicy query
contracargo No reconoce la compra, POS, Cripto, score 8/100, COL criptomonedas no reversible blocker transaccion de alto riesgo fraude score bajo

That string travels back in the response as query_used. Returning the query and not only the results is what makes the search auditable: it can be repeated by hand.

And in parallelfor_similar_cases()
Contracargo en Airbnb por USD 2095.90, Cripto, COL, score 8, motivo: No reconoce la compra

A different template, because it is looking for a different thing. The policy one describes a situation against a body of rules; the case one describes a transaction against other transactions. Sharing one template would have been shorter and worse.

03A single trip to Voyage rag/retriever.py · search_policies_and_cases()

Through the direct pipeline —the panel's, which is the default mode— both queries are embedded in a single call to the embeddings API: search_policies_and_cases() puts the two texts together and sends them with _embed_batch. It is not a micro-optimization: on Voyage's free tier every trip counts, and the two searches always happen together. Through n8n the saving does not apply: GET /api/policies/search and GET /api/cases/similar are two separate HTTP nodes and each embeds its own query, so that is two trips. The result is identical either way —the same code builds the query— and the only thing that changes is how many times it goes out to the network.

2 texts → 2 vectors1024 dimensions each
["contracargo No reconoce la compra, POS, Cripto…", "Contracargo en Airbnb por USD 2095.90, Cripto…"] ↓ one request [[0.021, -0.118, …], [-0.004, 0.267, …]]

voyage-multilingual-2 was chosen for its performance in Spanish: the dataset, the policies and the logs are in Spanish, and translating in order to embed would have introduced a loss at the one point in the chain where meaning is all there is.

04Two searches, two opposite rules Different corpora call for different strategies

Here is the least obvious decision in the RAG: the two collections are queried by opposite criteria. On the policies, everything is retrieved and the model filters; on the precedents, the filtering is aggressive and the model receives few. The reason is the cost of being wrong on each side — missing a policy means breaking a rule; bringing in a weak precedent means pushing the model to reason about something that is not alike.

policieshistorical_cases
how many all the indexed ones — the collection is counted on every search the top 5
threshold 0.0 — no floor 0.40 cosine
filter none must_not on transaction_id: a transaction is not its own precedent. The preference for payment method is applied by the re-ranking, not by a filter
re-ranking not needed: they all get in +0.05 same method · +0.03 same country · capped at 1.0
who filters the model, reading each policy and emitting NOT_APPLICABLE the code, before the model sees anything
why a small, normative corpus. A cosine threshold can leave out a relevant policy written in different words, and that omission is invisible: there is no error, there is a rule that was never evaluated an open, growing corpus. A precedent with low similarity is not a precedent: it is noise the model will cite anyway
A transaction is not its own precedentmust_not on transaction_id

47 of the dataset's 100 transactions have a case of their own, and those cases came out first — not by chance. A case's indexed document carries the merchant, the method, the country and the amount of its transaction formatted exactly like the query, so the similarity is maximal by construction; and the re-ranking adds its two bonuses on top, which cannot miss because those fields were copied from that very transaction.

On TXN-00006 that put CB-0025 and CB-0047 in positions 1 and 2, and the justification cited “CB-0025 fue aprobado en 10d” as if it were somebody else's trend. That is answer leakage: the agent was reading the ending before forming an opinion. It is excluded at retrieval and not in the prompt, and it leaves no gaps: fifteen candidates are requested for five slots, so the slots fill up with other transactions' precedents, which are the only ones that tell you anything.

The limit is counted, not assumed_total_politicas()

The retrieval cap was the constant 17 —the dataset's policies—. Loading number 18 through POST /api/policies/ indexed it correctly and listed it correctly, but the worst-ranked of the 18 disappeared from the model's context with no log and no warning: the system kept working and evaluated one policy fewer. Now the limit comes from counting the collection on every search, which on a corpus this size is cheap and is correct for any number.

05The context the model sees rag/formatter.py + domain/precedentes.py · one single criterion for order and labelling

The results do not go into the prompt raw. What is unified is not the format —each use builds its own text, and the single summary line shown below is written by domain/precedentes.py— but the criterion: annotate_by_motivo decides once, in a module of its own, which precedent shares a pattern, where that resemblance came from and what order they go in. Both uses come out of there: the prompt and the report's deterministic summary. They used to be duplicated and they did drift apart — the same precedent was described differently depending on who was looking at it.

Policies → v1_policy_eval · Haiku

Numbered Markdown sections, one field per bullet. The model issues a verdict for each one: PASS, FAIL, WARNING, BLOCKER or NOT_APPLICABLE, always citing the code. The [PUEDE BLOQUEAR] mark comes from the policy's puede_bloquear field, not from a list of codes in the prompt: that is why the prompt can say “only the marked ones can block” without naming POL-EXC-003 by hand.

### Politica 1 [PUEDE BLOQUEAR] (relevancia: …%) - Codigo: POL-EXC-003 - Categoria: EXCEPCIÓN - Nombre: Transacciones en cripto - Descripcion: Las transacciones realizadas con criptomonedas… - Referencia: Manual de Excepciones v1.0, Sec. 4

The percentage is elided on purpose: it is the cosine against the index as it stands and changes with every run. Everything else is the literal output of format_policies_for_prompt.

Precedents → v1_resolution · Sonnet

Before formatting, each case goes through annotate_by_motivo: six synonym groups decide whether it shares a pattern with the current case. The ones that match go first and carry a label.

CB-0038: Monto incorrecto, Caso cerrado sin resolución en 24d, merchant=Rappi

This one comes out with no label: “Monto incorrecto” and “No reconoce la compra” fall into different synonym groups, so there is no shared pattern to declare and the line ends there. When the match came from the observations and not from the reason field, the line says so, because an indirect match is worth less and it is better to be able to say that than to present them all as equivalent.

06The return trip: the index changes on its own No deploy, no touching code

A RAG that is only read is a search engine. What makes it the backbone of the system is that the index is written live through two paths, and neither of them goes through a release.

Editing a policy

PUT /api/policies/{code} saves to SQLite and reindexes the point in Qdrant in the same request. The point's identifier is a uuid5 of the code, so the rewrite is idempotent: no duplicates and no ghosts are left behind.

Policies are data, not code. Changing a threshold is an HTTP call, not a deploy — and that is why the evaluation also has to belong to the model and not to an if in Python: if the rule is editable, whoever applies it has to be able to read it.

Closing a case

When an analyst endorses a resolution and the Judge scored it 8.0 or higher, the case is indexed as a precedent and becomes available to the next investigation.

Both conditions are necessary. Without the human endorsement, a case nobody reviewed would become the example the next one is resolved by; without the Judge's threshold, the corpus would fill up with mediocre resolutions that later get cited as precedent.

Joining the RAG to the database

It is the pattern the brief asked for, and here the split is literal: SQLite answers what happened —this transaction, these logs, this history— and Qdrant answers what is done about it —which rules apply, what was decided before in similar cases—. Neither one alone is enough to justify a resolution.

Why none of this uses a model

Building the query, picking how many results to bring back and ranking them are decisions with a known correct answer. Delegating them to a model adds cost, latency and variability in exchange for nothing. The model comes in where there is no mechanical answer: interpreting a policy and writing the justification.

Where the detail lives

docs/rag_explanation.md works through each decision with the alternatives it discarded. The code lives in api/app/rag/: indexer.py, retriever.py, formatter.py, embedder.py and updater.py.