AI retrieval¶
TL;DR
- Every retrieval mode is a
RetrievalPipelineon one exact version. The mode is the call's, else the library's, else the instance's, else the best default the eval suite allows (onlybm25today). - Models come from provider profiles bound to roles (
llm,judge,reranker, embedding). Bootstrap builds every client with explicit URLs and keys, never the SDKs' environment variables. - No AI step fails a search. A missing model, a budget, a timeout or an error answers with a
cheaper mode and a
fallback_reason. - With nothing configured, the
[ai]and[local]extras are never imported.
Decided in AI retrieval decisions (#240) for the Next: AI retrieval milestone, and built:
| Part | Issue |
|---|---|
| mode selection | #89 |
| provider profiles | #241 |
| hybrid search | #92 |
| HyDE | #94 |
| the reranker | #93 |
| LLM judge | #96 |
| local models | #245 |
| agentic search, with its answer cache and repo guidance | #98, #100, #101 (Agentic search) |
Profiles and roles (#241)¶
What retrieval's models hold¶
ProviderProfile: a named endpoint with akind, validated per kind. Never a plaintext key: a stored key is sealed, a file is named, an environment key stays in bootstrap.InstanceRoles.- A library's
LibraryAioverrides: AI on or off, its ownllm/judge/reranker; never the embedding. bind_roleresolves which<profile>:<model>a role uses for a library: the library's, else the instance's; the judge, else the LLM.
AiProviders¶
AiProviders (in use_cases):
- puts the configured profiles (read-only, injected by bootstrap from
EXACTDOCS_AI__...and theEXACTDOCS_CONFIG_FILETOML) in front of theProviderProfilesport (retrieval_ai_providers, managed over REST); - implements
ModelRoles(ProfileModelRoles): a role counts when it resolves to an existing profile, and a library with AI off has none.
Keys sent over REST go through retrieval's SecretBox port, which bootstrap fills with the Fernet
box under its own HKDF purpose (AI_KEYS_PURPOSE).
AiProviders.model_for(role, library) is the path every AI pipeline takes, so a profile edited over
REST counts at the next call.
The ModelFactory¶
The ModelFactory port (unsupported, chat_model, embedder, reranker, check) is implemented
in bootstrap by ai_models.PydanticAiModels, which imports no SDK itself.
- The first call loads
ai_sdk.py(pydantic-ai, the OpenAI, Anthropic and Google SDKs, azure-identity) and builds every client with explicit values. - Before that it removes
OPENAI_CUSTOM_HEADERS/ANTHROPIC_CUSTOM_HEADERSfrom the process: the SDKs merge them over the key, in the constructor, socopy()cannot undo them.
One HTTP client per profile¶
Each profile has one httpx2 client, built under a per-profile lock, rebuilt when the profile
changes and closed when it is deleted (ModelFactory.release). The client has:
- a proxy on the transport: the profile's own, else the instance's outbound proxy when
ai.use_instance_proxyis on andNO_PROXYdoes not list the endpoint; - the instance's CA bundle;
trust_env=False, extra headers;- no transport retries, so the SDK's are the one layer;
- an overall timeout;
- a request hook that:
- refuses any scheme, host or port but the profile's endpoint;
- drops
OpenAI-Organization/OpenAI-Projectfilled from the environment; - for Claude on Foundry with Entra ID, signs each request with a fresh token.
An Entra ID token provider is built once per profile: a chain of client secret or certificate,
workload identity and managed identity. The profile's proxy, or the instance's with
ai.use_instance_proxy, goes to the first two only.
Cloud-identity profiles¶
Profiles signed with the server's own cloud identity (ADC, a service-account file, Entra ID, Claude on Bedrock):
- come from configuration only and take no
base_url(ProviderProfilerefuses both), so their endpoint is always derived; resource,locationandprojectare single DNS labels;ai_sdk._official_urlbuilds a derived endpoint withhttpx2.URL(scheme=..., host=...)and refuses a host that is not the provider's exact endpoint form (AZURE_OPENAI_HOST,FOUNDRY_HOST,BEDROCK_HOST,VERTEX_HOST).
Checks¶
exactdocs ai checkandPOST /api/v1/ai/providers/{name}/checkmake one minimal call per role.- The socket-guard test (
tests/bootstrap/test_ai_no_outbound.py) runs with the SDKs' variables pointing at a trap.
Mode selection (#89)¶
Each mode is a RetrievalPipeline driven port: run(PipelineRequest) -> PipelineAnswer. One exact
version goes in; hits and the mode that really answered come out, with a fallback_reason when a
cheaper one did.
RetrievalModule.buildregistersBm25Pipelineand any further pipelines it is given.RetrievalModes(inuse_cases):- asks the
ModelRolesport which roles the searched library may use (per library: one with AI off has none); - builds a
ModeRegistry(a mode can run when it has a pipeline and its roles); - picks the mode: the call's, else the library's (
LibraryModesport,retrieval_library_settings), else the instance's (EXACTDOCS_AI__MODE), else the best ofDEFAULT_MODE_ORDER.
- asks the
DEFAULT_MODE_ORDERlists a mode only once the eval suite marks iteligible_as_default(Retrieval evals). Onlybm25is listed yet, so an operator, a library or a call chooseshybrid.- Removing a library drops its mode too (
ForgetLibrary, called by the removal bridge after the catalog).
The vector store port (#242)¶
- The
VectorIndexdriven port: create, activate and retire a space, upsert and delete vectors byChunkKey, nearest within one manifest, a manifest's coverage and missing chunks. - It has an in-memory reference and the SQLite adapter (see
Vector store), and one contract test for both
(
tests/retrieval/test_vector_index.py), which the pgvector adapter (#243) runs too. OpenEmbeddingSpacefinds the space of a model, or creates a new one when the model, its dimensions or the input format changed, so two models never share one.RetrievalModesasksVectorIndex.available()once an embedding role is configured. When its extension cannot load (sqlite-vec, or pgvector'svector), the hybrid modes are unavailable and a setting that needs them falls back to BM25 withfallback_reason: vector_store_unavailable.
Hybrid search (#92)¶
HybridPipeline (in use_cases) is registered for hybrid whenever a vector store exists (SQLite
with sqlite-vec, PostgreSQL with pgvector).
- It asks the
SearchIndexfor the version's bestRRF_DEPTH(50) BM25 hits. - It embeds the query with the configured model (
Embeddings.embed_query, in a<search>.embed_queryspan without the query text, withinQUERY_EMBEDDING_TIMEOUTseconds). A paid embedding model is first checked against the budgets of the embedding, instance, library and caller scopes, and its usage is recorded once to the same rows throughAiSpend.record. - It asks
VectorIndex.nearestfor the 50 nearest chunks of the same manifest inPipelineRequest.space. - It fuses the two rankings with reciprocal rank fusion (
reciprocal_rank_fusion,k= 60). Ties go to BM25's order, so an exact identifier stays first.
Rules:
- Both halves are scoped to the version's manifest and filtered by tags before ranking, so no chunk of another version can come in.
- The vector half always runs, also when BM25 matches nothing (a synonym the docs never use). A hybrid answer has hits whenever the version has embedded chunks that pass the tag filter; there is no similarity floor.
- A chunk only the vectors found gets the first 24 words of its text as its snippet.
coverage.candidatescounts the chunks of both halves once.- Reranking (below) runs after the pipeline, on the fused order, like for any mode. The pipeline is asked for the reranker's top N when that is more than the limit.
The pipeline never fails a search. BM25 answers with:
fallback_reason |
When |
|---|---|
embedding_in_progress |
the space no longer matches the configured model (a switch of models) |
llm_budget_reached |
a budget the query embedding counts to is used up (as a paid rerank over budget) |
embedding_unavailable |
the model failed, timed out or answered an unusable vector (or the key could not be opened) |
vector_store_unavailable |
the store cannot search |
HyDE (#94)¶
HydePipeline (in use_cases) is registered for hybrid_hyde when a vector store exists and a
HypotheticalAnswers writer is given.
- It resolves the library's
llmrole (AiProviders.profile_for, from the profile as it is now; nothing is sent for a library with AI off). - It looks the answer up in the
HypotheticalAnswerCacheport byHydeKey: the searched manifest, the model (<profile>:<model>) and a SHA-256 of the normalized query (case folded, whitespace collapsed; never the text). - On a miss, in a
<search>.hydespan without the query, withinHYDE_TIMEOUT(10 s), it builds the chat model (ModelFactory.chat_model) and calls the writer. - The answer is then embedded for the vector half
(
HybridPipeline.fuse(embed=answer, mode=hybrid_hyde)), while BM25 searches the query itself.
Keys and removal:
- A new manifest of the version is a new key.
- The removal use cases (
CollectChunks,RemoveChunks,DiscardPendingChunks) forget the answers of the manifests they remove.
The writer¶
ai_hyde.PydanticAiHypotheticalAnswers loads ai_hyde_sdk only then, which runs:
- one pydantic-ai
Agent(output_type=str)with the fixedHYDE_INSTRUCTIONSandmax_tokens = HYDE_MAX_TOKENS; - inside
agent_limits: the harnessSpendLimitsover the ledger (so its spend lands in the caller's instance, library and user rows, priced by the price book) and pydantic-ai'sUsageLimits.
The budgets it gets come from AiSpend.budgets_for(library_ai), the seam where per-library budgets
(#102) merge in.
Fallbacks¶
- Budgets and the rate limit are checked before (
within_budgetturns the choice intohybrid). - A
SpendLimitExceededat the request answershybridwithllm_budget_reached. - An LLM error, an empty answer, a model that cannot be built or a timeout answers
hybridwithllm_unavailable. Only the error's class is logged. - When hybrid's own query embedding fails too, the reason given is hybrid's (it names the mode that answered, BM25).
A rare lost spend
A timeout that strikes after the provider answered may cancel the harness while it records the spend, which is then lost. This is as rare as the in-flight overshoot the budgets already accept.
The cache¶
- The cache is
retrieval_hyde_answers(SqliteHypothesisCache, SQLite and PostgreSQL). - A read-only process (
serve --stdio) reads it and keeps its own answers in a bounded LRU (ReadOnlyHypothesisCache,HYDE_MEMORY_CACHE_SIZE). - A cache that cannot be read is a miss, and one that cannot be written costs a call next time. Only the error's class is logged.
- A cached answer is no LLM call.
RetrievalModes.within_budgetreads it first (HydePipeline.cached_answer) and passes it on inModeChoice.hypothesis(one cache read per search), so a hit answershybrid_hydeeven with a budget used up, and is not counted against the LLM search rate limit. - A search whose hypothetical answer came from the cache is counted in
exactdocs.ai.cache_hits(cachehyde_answer, #100).
PruneHypotheses deletes:
- answers older than
[ai.hyde] cache_ttl(30 days); - those of an
llmmodel no longer configured (neither the instance's nor any library's override, or its profile is gone).
It runs at start, once a day just after UTC midnight with the embedding re-queue
(Container.nightly, the same single leader on PostgreSQL as requeue_daily), and after every
collection (CollectChunks).
Data at rest¶
- The table stores the hypothetical answers in plain text. They are written from user queries and often restate them.
- The query itself is stored only as an HMAC-SHA256 of its normalized text, keyed with a key derived
from the instance's secret key (
EXACTDOCS_SECRET_KEYor the key file) for its own HKDF purpose,exactdocs hyde cache v1(HYDE_CACHE_PURPOSE). The hashes cannot be checked against a list of likely queries without that key. - A read-only process without a secret key caches nothing.
- Rotating the secret key only makes every cached answer a miss.
Reranker (#93)¶
Reranking is a flag on top of any mode (ModeChoice.rerank, with the library's rerank_top_n or
the instance's [ai.reranker] top_n).
RetrievalModes.runasks the pipeline for the top N when that is more than the call's limit.- The search use cases open a
rerankstage span (no query, no text) and callRetrievalModes.rerank, which hands the answer toReranking(inuse_cases). Rerankingreads the candidates' chunk text. It is handed back to the use case, which reads only the chunks it lacks; a candidate whose chunk is gone is dropped and no longer counted incoverage.candidates.- Under
asyncio.timeout(RerankLimits.timeout_forthe profile's kind), it builds the library's reranker (theModelFactory'sreranker, typed as theRerankerdriven port: query and documents in, one score each out) and calls it. models.reorderorders the scored head by score (ties keep the mode's order) and keeps the rest after it. The use case then cuts to the limit (PipelineAnswer.cut).
One profile read per search¶
- The reranker's model and profile are read once per search (
Reranking.profile, carried onModeChoice.reranker_profile):- by
within_budgetwhen a budget needs the profile's kind; - else by
RetrievalModes.rerank, from the library settingsRetrievalModes.chooseread once for the search.
- by
- The kind, the timeout, the build and the recorded spend all use that read.
- The read is bounded by
RerankLimits.longestand guarded like the call. A stored profile that cannot be read in time or at all answersreranker_timeout/reranker_failed(#284).
Errors¶
- Any build failure, and anything the call raises (a client closed under it, an
ExceptionGroupof its batches), is re-raised as aRerankerErrornaming only the exception's class. Cancellation passes through. - A timeout, a
RerankerErroror aProviderUnsupportedErrorkeeps the mode's order withfallback_reasonreranker_timeout/reranker_failed, and is logged without the query.
Loading the SDKs¶
The provider SDKs are loaded in a worker thread, never on the event loop:
- at start when a profile other than
localexists (Container.running,PydanticAiModels.warm). A failed load is logged as a warning and never stops the start; - else on first use.
The HTTP adapter¶
adapters/driven/http_reranker.py, HttpReranker:
- speaks the Cohere-compatible
/rerank(openai-compatible,vllm,litellmprofiles; Voyage'sdataanswer too) or TEI's (teiprofiles); - cuts the texts to
MAX_RERANK_*_CHARS; - sends batches the endpoint accepts concurrently (a
TaskGroup: one failed batch cancels the rest); - turns every failure into a
RerankerErrorwithout the URL, key or text.
Bootstrap's ai_sdk.reranker builds it on the profile's one guarded httpx2 client.
LLM judge (#96)¶
What reranks¶
RetrievalModes.choose decides what reranks with models.pick_reranker:
- the library's
rerank_with, else the instance's (EXACTDOCS_AI__RERANK_WITH,cross_encoderby default); - the judge reranks only when chosen and its role resolves (
judge, elsellm); - else the cross-encoder does, when there is one (
ModeChoice.reranker).
The window¶
Reranking hands the best of the same candidates that fit one bounded call
(models.judge_window) to the CandidateJudge driven port:
- at most
JUDGE_MAX_CANDIDATES(64); - while the input stays within
JUDGE_INPUT_TOKEN_BUDGET(18,500) together with the largest output cap under the step'sLLM_TOKEN_LIMIT1.
The input is the text as cut and escaped, estimated by models.estimated_tokens:
| Text | Counted as |
|---|---|
| ASCII | CHARS_PER_TOKEN characters per token |
| long ASCII runs without whitespace, such as base64 | DENSE_CHARS_PER_TOKEN (1.5) characters per token |
| a code point above U+FFFF | its 4 UTF-8 bytes |
| every other character, control characters included | one token each, since CJK runs at about one token per character |
The budget's headroom covers 3 real tokens per estimated one: ASCII code with escaped entities runs at about 1.7 characters per token, base64 broken by spaces at about 1.4, and rare BMP scripts such as Yi at about 3 tokens a character.
The call:
- runs under
asyncio.timeout([ai.judge] timeout, 10 s); - with an
LlmStepwhose budgets areAiSpend.budgets_for(library_ai); - the candidates beyond the window keep their order after the judged ones.
A timeout that strikes after the provider answered may cancel SpendLimits while it records the
spend, which is then lost, as for HyDE: the in-flight overshoot the decision record already accepts.
The adapter¶
adapters/driven/ai_judge.py, with the SDK side in ai_judge_sdk.py, loaded on first use. It runs
one Agent(output_type=list[Rating]):
- Each rating is a positional ID (
c1...cN,models.judge_id) and anintfrom 0 toJUDGE_MAX_SCORE(bounded by the schema, strict, no extra fields). The ID is never a chunk ID: short to answer and nothing a candidate could imitate usefully. - Instructions: the fixed
JUDGE_INSTRUCTIONSsay the query and the candidates are untrusted data. - The user prompt comes from
models.judge_prompt: the query in<query>, each candidate in<candidate id="...">, cut toMAX_JUDGE_*_CHARSand with&,<,>escaped, so no text can close or forge a delimiter. - An output validator over
models.judged_scores: exactly one rating per candidate given, each ID mapped back exactly, no unknown ID. It runs withretries=0, so a refused answer is never asked for again. max_tokensfrommodels.judge_max_tokens: 512, plus 48 per candidate, so a pretty-printed answer fits with room for a model's reasoning.agent_limits:SpendLimitsover the ledger,UsageLimits.
Reranking checks the ratings again with judged_scores before models.reorder, so the judge can
only reorder what it was given.
| Outcome | fallback_reason |
|---|---|
| a budget refusal | llm_budget_reached |
| a timeout | reranker_timeout |
| anything else (refused ratings, an error, a profile that cannot chat) | reranker_failed, logged with the fault's fixed text only |
Its spend is recorded by the harness, not by RetrievalModes._record_rerank.
Local models (#245)¶
Bootstrap's ModelFactory is AiModels: local profiles go to LocalModels
(bootstrap/local_models.py), every other kind to PydanticAiModels.
Pulling and checking¶
LocalModelsimports nothing heavy. A model is known by its folder inEXACTDOCS_MODELS_DIRand the marker thatexactdocs models pullwrites last.exactdocs models pull(bootstrap/models_pull.py) is the only code that contacts the Hub, at the commitsPINNED_MODEL_REVISIONSfixes for the defaults.- At build time
_ai_configurationturns off, with an error naming the pull command, every instance role whose local model is missing or was pulled at another pinned commit. It warns about alocal:role with nolocalprofile.
Loading¶
- Its first use, or
Container.running's warm-up for the instance's roles, importsbootstrap/local_sdk.py(fastembed). - It loads the model in a worker thread (the load lock is only ever taken there), once per process,
with:
specific_model_pathandlocal_files_only, which never reach Hub code;- half the cores for ONNX Runtime;
- no CPU memory arena.
The adapters¶
retrieval/adapters/driven/local_models.py: LocalEmbeddings, LocalReranker.
- They never import fastembed: they call the loaded model through small structural types.
- Document batches (at most 16 texts) run on a one-worker pool; query embeddings and reranks on a two-worker pool of their own. A search never waits behind an embedding job (up to three calls at once, each with half the cores).
- ONNX Runtime's errors become
EmbeddingFailedError/RerankerError. Container.runningshuts both pools down when it ends.AiEmbeddingModelswraps aLocalEmbedderhandle with them, and a pydantic-aiEmbedderwithPydanticAiEmbeddings.
Timeouts and spend¶
- An unset reranker timeout is 5 s when the search's reranker (the instance's or a library's own) is
on a
localprofile, 2 s otherwise (RerankLimits.timeout_for, per search). - A
localmodel's tokens are recorded in the spend ledger'slocal_tokensand count toward no token budget. No budget stops its embedding job or a search's call to it (#284).
How it fits the structure¶
Every mode is a pipeline, and its models come through the ports below. The [ai] extra is declared
and installed for development; the model-free test proves none of it is imported when no model is
configured.
- All in
retrieval. No new domain: every consumer is retrieval.- New driven ports:
Embeddings,Reranker,VectorIndex, theSpendLedger(whose adapter also implements the harnessBatchSpendStore), and ports for the HyDE writer, the judge and the agent explorer. - Their adapters (pydantic-ai, fastembed, sqlite-vec, pgvector) live in
retrieval/adapters/driven/, and the architecture test lists those libraries among the ones the core may not import.
- New driven ports:
- Wiring.
- Bootstrap turns the configured provider profiles into pydantic-ai models and HTTP clients, and
imports any of it only when a role is configured. With nothing configured the
exactdocs[ai]andexactdocs[local]extras are never imported (the model-free test). - Bootstrap implements retrieval's
ModelFactoryport (a resolved provider profile in, a callable model, embedder or reranker out), always with explicit URLs and keys, never the SDKs' environment variables. - Retrieval declares its own secret-box port. The Fernet adapter that seals repository
credentials moved from ingestion to
bootstrap(#248), so no domain depends on another's adapter.
- Bootstrap turns the configured provider profiles into pydantic-ai models and HTTP clients, and
imports any of it only when a role is configured. With nothing configured the
- Storage.
retrieval_embedding_spacesrecords each (model, dimensions, input format). Its vectors sit in one adapter-managed table per space, keyed byretrieval_chunksrow, searched exactly within the active manifest (sqlite-vec on SQLite, pgvector on PostgreSQL and Supabase). - Jobs. Embedding runs are an
embedingestion job kind with resumable steps, reaching retrieval through a bridge, like indexing. - PostgreSQL (#103, see Persistence):
- psycopg 3;
- DBOS's tables in the same database (
system_database_urlplusdbos_system_schema); - a per-library advisory lock replacing
TagLocks; - PostgreSQL full-text search, the adapter databases without
pg_search(such as Supabase) keep; pg_search's BM25 (#104) where the extension is installed, chosen at start.
-
pydantic-ai checks that limit only after a request, so a larger prompt would be sent, paid for and then refused. ↩