tempest_fastapi_sdk.genai.rag¶
RAG: contexto para o LLM a partir de busca na web e de PDFs.
rag
¶
RAG context — feed LLMs with web search + PDF knowledge.
Retrieve grounding for a local LLM without shipping data to a third
party: search a self-hosted SearXNG, extract page bodies, read PDFs, and
assemble it all into a prompt-ready context block. The heavy bits
(httpx / trafilatura / pymupdf) live behind the
[genai-rag] extra and import lazily, so this package imports without
it — you only need the extra to actually fetch and read.
AnnIndex
module-attribute
¶
The approximate index methods :meth:PgVectorStore.ensure_schema builds.
ChatMemory
¶
ChatMemory(
embedder: SupportsEmbed,
*,
client: Any | None = None,
persist_directory: str | None = None,
collection_name: str = "chat_memory",
top_k: int = 5,
min_similarity: float = 0.55,
recency_halflife_days: float = 14.0,
recency_weight: float = 0.5,
max_entries_per_user: int = 50000,
min_content_chars: int = 6,
candidate_multiplier: int = 4,
)
Recency-aware long-term memory for chat messages, backed by ChromaDB.
Ports the algorithm the leviathan llm-api hand-rolls: each message
is embedded and upserted with metadata (user_id, chat_id,
role, created_at); recall pulls the top-K for a single user
(optionally excluding the active chat), drops hits below a similarity
floor, then re-ranks by blending similarity with an exponential recency
decay so recently-said things can outrank semantically-equal older
ones. Recall over-fetches top_k * candidate_multiplier nearest
messages before the re-rank, so a recent message just outside the raw
top-K can still surface. A soft per-user quota evicts the oldest
entries (by UTC instant) when exceeded.
The embedder is injected (any :class:SupportsEmbed — Embedder or
OllamaEmbedder both fit), so this class is embedder-agnostic.
Scope note: this deliberately does not port the app-lifecycle
retry queue / background retry loop from llm-api. :meth:index
embeds and upserts directly and surfaces failures to the caller
(embedding/Chroma exceptions propagate); retry policy is a caller
concern.
Requires the [genai-chroma] extra (chromadb). The collection is
opened lazily on first use.
Attributes:
| Name | Type | Description |
|---|---|---|
collection_name |
str
|
The Chroma collection name. |
top_k |
int
|
Default number of hits returned by :meth: |
min_similarity |
float
|
Default similarity floor. |
recency_halflife_days |
float
|
Age (days) at which the decay factor halves. |
recency_weight |
float
|
Blend weight for the recency decay in
|
max_entries_per_user |
int
|
Soft per-user quota; |
min_content_chars |
int
|
Messages shorter than this (stripped) are
skipped by :meth: |
candidate_multiplier |
int
|
How many nearest messages per returned
hit :meth: |
Initialize chat memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedder
|
SupportsEmbed
|
Turns text into vectors. |
required |
client
|
Any | None
|
Pre-built Chroma client. When |
None
|
persist_directory
|
str | None
|
Path for a persistent client;
|
None
|
collection_name
|
str
|
Collection to get-or-create. |
'chat_memory'
|
top_k
|
int
|
Default hit count for :meth: |
5
|
min_similarity
|
float
|
Default similarity floor in |
0.55
|
recency_halflife_days
|
float
|
Half-life of the recency decay. |
14.0
|
recency_weight
|
float
|
Recency blend weight in |
0.5
|
max_entries_per_user
|
int
|
Soft per-user quota ( |
50000
|
min_content_chars
|
int
|
Minimum stripped length to index. |
6
|
candidate_multiplier
|
int
|
Over-fetch factor for :meth: |
4
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
delete_for_chat
async
¶
Remove one user's vectors for a chat.
chat_id is not unique across users — the chat router takes it
from the request body — so the delete is keyed on the owner too:
removing a chat never touches another user's rows that share the
id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | UUID
|
The owner whose entries to delete. |
required |
chat_id
|
str | UUID
|
The chat whose entries to delete. |
required |
delete_for_user
async
¶
Remove every vector belonging to a user (account erasure).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | UUID
|
The owner whose entries to delete. |
required |
index
async
¶
index(
*,
user_id: str | UUID,
chat_id: str | UUID,
message_id: str | UUID,
role: str,
content: str,
created_at: datetime,
) -> bool
Embed a chat message and upsert it into the collection.
Short messages (stripped length below min_content_chars) are
skipped. Embedding is done via the injected embedder; the upsert is
keyed by message_id so re-indexing the same message is
idempotent. When the per-user quota is exceeded, the oldest entries
for that user are evicted first.
The collection is shared by every user, so a message_id already
indexed for a different user is refused instead of being
overwritten, which would move that row (text and owner) to
user_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | UUID
|
Owner of the message. |
required |
chat_id
|
str | UUID
|
Chat the message belongs to. |
required |
message_id
|
str | UUID
|
Unique id (used as the Chroma id). |
required |
role
|
str
|
The message role. |
required |
content
|
str
|
The message text. |
required |
created_at
|
datetime
|
Creation timestamp (UTC recommended). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
was skipped for being too short. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Exception
|
Embedding or Chroma failures propagate to the caller (no internal retry — see the class scope note). |
reembed_all
async
¶
Recompute every stored message's vector with this memory's embedder.
Message ids, text, owner, chat and timestamps stay as they are, so
recall, the per-user quota and deletes keep working. Run it once
after the embedder changed how it maps text to vectors — for
instance after adding **NOMIC_EMBED_TEXT_PREFIXES to an embedder
that indexed without them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Messages per step. |
DEFAULT_REEMBED_BATCH
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many messages were re-embedded. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
search
async
¶
search(
*,
user_id: str | UUID,
query: str,
exclude_chat_id: str | UUID | None = None,
top_k: int | None = None,
min_similarity: float | None = None,
) -> list[MemoryHit]
Return the most relevant past messages for a user.
Embeds query, runs a metadata-filtered Chroma query scoped to
user_id (and excluding exclude_chat_id when given) for the
top_k * candidate_multiplier nearest messages, drops hits below
the similarity floor, then re-ranks by the recency-decay blend
before returning at most top_k hits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | UUID
|
Whose memory to search. |
required |
query
|
str
|
The natural-language query. |
required |
exclude_chat_id
|
str | UUID | None
|
Chat to exclude (typically the active conversation, so it does not match itself). |
None
|
top_k
|
int | None
|
Override for the default hit count. |
None
|
min_similarity
|
float | None
|
Override for the similarity floor. |
None
|
Returns:
| Type | Description |
|---|---|
list[MemoryHit]
|
list[MemoryHit]: Up to |
list[MemoryHit]
|
final score. Empty when the query is blank, |
list[MemoryHit]
|
nothing clears the floor. |
ChromaVectorStore
¶
ChromaVectorStore(
*,
collection_name: str = "genai_rag",
client: Any | None = None,
persist_directory: str | None = None,
distance: str = "cosine",
)
A :class:VectorStore backed by ChromaDB.
Mirrors :class:InMemoryVectorStore / :class:PgVectorStore: add
replaces every chunk stored for the sources in the batch and writes the
batch, search returns the nearest chunks with
score = 1 - distance. Each chunk's Chroma id is the SHA-256 of
(source, index, text) — source::index collided whenever
:func:chunk_text was called twice for one source. Chunk fields ride
along in Chroma metadata and are reconstructed on read. The blocking
chromadb calls run inside :func:asyncio.to_thread.
Requires the [genai-chroma] extra (chromadb). The collection is
opened lazily on first use, so constructing the store never touches the
filesystem or imports chromadb.
Attributes:
| Name | Type | Description |
|---|---|---|
collection_name |
str
|
The Chroma collection name. |
Initialize the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection_name
|
str
|
Collection to get-or-create. |
'genai_rag'
|
client
|
Any | None
|
Pre-built Chroma client. When |
None
|
persist_directory
|
str | None
|
Path for a persistent client;
|
None
|
distance
|
str
|
HNSW distance space. Defaults to |
'cosine'
|
add
async
¶
add(chunks: Sequence[Chunk], vectors: Sequence[list[float]]) -> None
Store chunks, replacing what their sources held before.
The batch is upserted first; then every other row whose source
metadata matches a source in chunks is deleted (rows written by
older SDK versions, keyed source::index, included). Chroma has
no transactions, so this order means a failed upsert leaves the
previous version in place rather than an empty source. Identical
chunks in the batch are written once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
Sequence[Chunk]
|
The chunks to store — every chunk of a source in one call. |
required |
vectors
|
Sequence[list[float]]
|
One vector per chunk, aligned. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the counts differ. |
reembed_all
async
¶
reembed_all(embedder: SupportsEmbed, *, batch_size: int = DEFAULT_REEMBED_BATCH) -> int
Recompute every stored chunk's vector with embedder.
Ids, text and metadata stay as they are. Run it once after the embedder changes how it maps text to vectors (task prefixes, a model of the same dimension); a store holding both kinds ranks by accident.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedder
|
SupportsEmbed
|
The embedder now in use. |
required |
batch_size
|
int
|
Rows per step. |
DEFAULT_REEMBED_BATCH
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many chunks were re-embedded. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
search
async
¶
search(vector: list[float], *, top_k: int = 5) -> list[Chunk]
Return the top_k chunks most similar to vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
list[float]
|
The query vector. |
required |
top_k
|
int
|
How many chunks to return. |
5
|
Returns:
| Type | Description |
|---|---|
list[Chunk]
|
list[Chunk]: Nearest chunks, each with |
Chunk
¶
Bases: BaseSchema
A slice of source text sized to drop into a prompt.
Attributes:
| Name | Type | Description |
|---|---|---|
text |
str
|
The chunk body. |
source |
str
|
Where it came from (a URL or a PDF path). |
index |
int
|
0-based position of the chunk within its source. |
page |
int | None
|
Originating PDF page (1-based), when applicable. |
score |
float | None
|
Relevance score when returned by a vector
search (higher = closer); |
ContentExtractor
¶
ContentExtractor(
*,
http_client: AsyncClient,
user_agent: str = "tempest-fastapi-sdk/genai",
timeout: float = 10.0,
allow_private_networks: bool = False,
max_redirects: int = DEFAULT_MAX_REDIRECTS,
max_response_bytes: int = DEFAULT_MAX_RESPONSE_BYTES,
resolver: Resolver | None = None,
)
Fetch URLs and extract their main text via trafilatura.
The httpx.AsyncClient is injected so the connection pool is shared.
By default every fetch is guarded against server-side request forgery:
the scheme must be http/https, the host (an IP literal, or every
address a hostname resolves to) must be public, and the same check
runs again on each redirect hop, which the extractor follows by hand up
to max_redirects. The body is streamed and the fetch is abandoned
once it exceeds max_response_bytes. Any refusal comes back as
failed=True, like every other failure.
The connection goes to the address that passed the check: the hop is
sent to scheme://<validated-ip>:<port> with the original Host
header and sni_hostname extension, so a DNS answer that changes
after the check (DNS rebinding) is never connected, and HTTPS still
validates the certificate against the hostname. Because the pool keys
connections by IP, an HTTPS response that arrives on a connection whose
TLS session was negotiated for another hostname is discarded and the
hop retried on a fresh connection (see :data:MAX_TLS_NAME_RETRIES).
Through an HTTP proxy, httpcore 1.0.9 tunnels to the pinned IP and
does not send sni_hostname, so certificate validation fails and
HTTPS fetches come back failed=True; allow_private_networks=True
turns pinning off along with the address check, leaving the proxy as
the egress guard.
Attributes:
| Name | Type | Description |
|---|---|---|
user_agent |
str
|
|
timeout |
float
|
Per-request timeout in seconds. |
allow_private_networks |
bool
|
Whether the private-address check is disabled. |
max_redirects |
int
|
Redirect hops followed before giving up. |
max_response_bytes |
int
|
Largest body read before giving up. |
Initialize the extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
http_client
|
AsyncClient
|
Injected async client. Its own
|
required |
user_agent
|
str
|
|
'tempest-fastapi-sdk/genai'
|
timeout
|
float
|
Per-request timeout in seconds. |
10.0
|
allow_private_networks
|
bool
|
Skip the private-address check, for an extractor that must read intranet pages. The scheme check, the redirect bound and the body cap still apply. Only turn this on when the URLs are not attacker-controlled. |
False
|
max_redirects
|
int
|
Redirect hops followed before the fetch is reported as failed. |
DEFAULT_MAX_REDIRECTS
|
max_response_bytes
|
int
|
Largest body, in bytes, read before the fetch is reported as failed. |
DEFAULT_MAX_RESPONSE_BYTES
|
resolver
|
Resolver | None
|
Async hostname → addresses lookup
used by the private-address check, called once per hop;
the first address it returns is the one the hop connects
to. |
None
|
extract
async
¶
extract(url: str) -> ExtractionResult
Fetch url and return its extracted main text.
Never raises: fetch/extraction failures and refused destinations
come back as ExtractionResult(text="", failed=True). The
CPU-bound trafilatura pass runs in a worker thread
(asyncio.to_thread), so a large page does not stall the event
loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The page to fetch. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ExtractionResult |
ExtractionResult
|
The extracted text or a failure marker. |
extract_many
async
¶
extract_many(urls: Sequence[str], *, concurrency: int = 5) -> list[ExtractionResult]
Extract many URLs concurrently, capped at concurrency.
Results are returned in the same order as urls. Individual
failures are absorbed into their :class:ExtractionResult (never
raised), so one bad page can't sink the batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
urls
|
Sequence[str]
|
The pages to fetch. |
required |
concurrency
|
int
|
Max simultaneous fetches. |
5
|
Returns:
| Type | Description |
|---|---|
list[ExtractionResult]
|
list[ExtractionResult]: One result per URL, in input order. |
Document
¶
Bases: BaseSchema
A read document (e.g. a PDF) with its full text and page breakdown.
Attributes:
| Name | Type | Description |
|---|---|---|
source |
str
|
Path or identifier the document was read from. |
text |
str
|
The full concatenated text. |
pages |
list[PdfPage]
|
Per-page text (empty when not paginated). |
metadata |
dict[str, str]
|
Extra metadata (title, author, …) when the reader exposes it. |
ExtractionResult
dataclass
¶
Outcome of fetching + extracting one URL.
Attributes:
| Name | Type | Description |
|---|---|---|
text |
str
|
The cleaned page body, or |
failed |
bool
|
|
HybridNameIndex
¶
HybridNameIndex(
embedder: SupportsEmbed, entries: Iterable[tuple[str, T]] = (), *, rrf_k: int = 60
)
Spelling and meaning together: fuzzy lookup and embeddings, fused.
A name typed with a typo ranks high in the lexical list; a name the user described with other words ranks high in the semantic list; reciprocal rank fusion merges the two without putting edit distance and cosine similarity on one scale.
The lexical side works word by word: "camizeta basica" is two
typo-tolerant word lookups against the words of every name, so it finds
"Camiseta básica de algodão" although the whole strings are far
apart. A name ranks by the share of the query's words it spells.
Example::
index = HybridNameIndex(embedder, [("Rio de Janeiro", 3304557)])
await index.search("rio de janiero") # spelling
await index.search("cidade maravilhosa") # meaning
Build both indexes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedder
|
SupportsEmbed
|
Turns texts into vectors. |
required |
entries
|
Iterable[tuple[str, T]]
|
|
()
|
rrf_k
|
int
|
RRF damping constant
(:func: |
60
|
add
¶
Store value under name in both indexes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name. Blank names are ignored. |
required |
value
|
T
|
The value to return for it. |
required |
search
async
¶
search(
query: str,
*,
limit: int | None = 5,
cutoff: float = 0.8,
candidates: int = 20,
min_semantic_score: float = 0.0,
) -> list[NameMatch[T]]
Return the entries whose name is spelled or means like query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
What the user wrote. |
required |
limit
|
int | None
|
Most matches to return; |
5
|
cutoff
|
float
|
Lowest spelling similarity for the lexical side. |
0.8
|
candidates
|
int
|
How many entries each side ranks before the fusion. |
20
|
min_semantic_score
|
float
|
Lowest cosine similarity the semantic side keeps. |
0.0
|
Returns:
| Type | Description |
|---|---|
list[NameMatch[T]]
|
list[NameMatch[T]]: Best fused first; |
list[NameMatch[T]]
|
and |
list[NameMatch[T]]
|
each entry. |
HybridRetriever
¶
HybridRetriever(embedder: SupportsEmbed, store: VectorStore, *, k_rrf: int = 60)
Dense + BM25 retrieval fused with Reciprocal Rank Fusion.
Chunks are identified by (source, index, text), and each
:meth:index call replaces whatever was indexed before for the sources
in the batch — so index every chunk of a source in one call. The SDK's
stores (:class:InMemoryVectorStore, :class:PgVectorStore,
:class:ChromaVectorStore) apply the same replacement on the dense side;
a third-party store that only appends still returns the replaced rows,
and those are dropped here before fusion (they only cost candidate slots).
Example:
>>> from tempest_fastapi_sdk.genai import Embedder
>>> from tempest_fastapi_sdk.genai.rag import (
... HybridRetriever,
... InMemoryVectorStore,
... )
>>> rag = HybridRetriever(
... Embedder("...", normalize=True), InMemoryVectorStore(),
... )
>>> await rag.index(chunks) # builds dense + BM25 index
>>> best = await rag.search("what is CNPJ?", top_k=5)
Attributes:
| Name | Type | Description |
|---|---|---|
retriever |
Retriever
|
The dense half (embedder + store). |
k_rrf |
int
|
RRF damping constant. |
Initialize the hybrid retriever.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedder
|
SupportsEmbed
|
The embedding model for the dense half. |
required |
store
|
VectorStore
|
The vector store for the dense half. |
required |
k_rrf
|
int
|
RRF damping constant passed to
:func: |
60
|
index
async
¶
index(chunks: Sequence[Chunk]) -> int
Index chunks into both the dense store and the BM25 index.
Every chunk previously indexed for a source that appears in
chunks is replaced, in the sparse index here and — for the SDK's
stores — in the dense store too. Identical chunks (same source,
index and text) are kept once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
Sequence[Chunk]
|
Chunks to index — pass every chunk of a source in the same call. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of chunks received. |
retrieve
async
¶
retrieve(
query: str,
*,
top_k: int = 5,
candidates: int = 20,
long_text: bool = True,
max_chars: int = 2000,
) -> str
Search (hybrid) and build a prompt-ready context block.
The one-shot helper mirroring :meth:Retriever.retrieve, so a
HybridRetriever drops into make_genai_router's /rag
endpoint (it satisfies SupportsRetrieve).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The natural-language query. |
required |
top_k
|
int
|
How many chunks to include. |
5
|
candidates
|
int
|
Candidates each retriever contributes to fusion. |
20
|
long_text
|
bool
|
Full chunk bodies or truncate to |
True
|
max_chars
|
int
|
Per-chunk truncation cap when |
2000
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A prompt-ready context block (see :func: |
search
async
¶
search(query: str, *, top_k: int = 5, candidates: int = 20) -> list[Chunk]
Return the top_k chunks by fused dense + BM25 relevance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The natural-language query. |
required |
top_k
|
int
|
How many chunks to return. |
5
|
candidates
|
int
|
How many candidates each retriever contributes to
the fusion before truncating to |
20
|
Returns:
| Type | Description |
|---|---|
list[Chunk]
|
list[Chunk]: The fused best chunks, best first. Empty when |
list[Chunk]
|
|
InMemoryVectorStore
¶
A dict-backed vector store — dev, tests, small corpora.
Cosine similarity over every stored vector (linear scan). Fine up to a
few thousand chunks; use :class:PgVectorStore (or Qdrant, etc.)
beyond that.
Initialize an empty store.
add
async
¶
add(chunks: Sequence[Chunk], vectors: Sequence[list[float]]) -> None
Store chunks, replacing what their sources held before.
Every chunk already stored for a source named in chunks is
dropped first; identical chunks in the batch are kept once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
Sequence[Chunk]
|
The chunks to store — every chunk of a source in one call. |
required |
vectors
|
Sequence[list[float]]
|
One vector per chunk, aligned. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the counts differ. |
search
async
¶
search(vector: list[float], *, top_k: int = 5) -> list[Chunk]
Return the top_k most similar chunks (with score set).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
list[float]
|
The query vector. |
required |
top_k
|
int
|
How many chunks to return. |
5
|
Returns:
| Type | Description |
|---|---|
list[Chunk]
|
list[Chunk]: Chunks ordered by descending cosine similarity, |
list[Chunk]
|
each with its |
list[Chunk]
|
the same contract as |
list[Chunk]
|
|
list[Chunk]
|
every chunk but the last three. |
MemoryHit
¶
Bases: BaseSchema
One recalled chat message, ranked for relevance and recency.
Attributes:
| Name | Type | Description |
|---|---|---|
content |
str
|
The message text. |
role |
str
|
The originating role ( |
chat_id |
str
|
The chat the message belongs to. |
created_at |
datetime | None
|
When the message was created (UTC),
or |
similarity |
float
|
Raw cosine similarity in |
score |
float
|
Final ranking score after the recency-decay blend
(equals |
NameMatch
dataclass
¶
NameMatch(
key: str,
value: T,
score: float,
lexical_score: float | None = None,
semantic_score: float | None = None,
)
One entry a name search returned.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
The name as it was added. |
value |
T
|
The value stored under it. |
score |
float
|
The ranking score: cosine similarity for
:class: |
lexical_score |
float | None
|
How well the query's words are spelled
in the name: the mean, over the query words, of the best
:func: |
semantic_score |
float | None
|
The cosine similarity, when the semantic index ranked the name. |
PdfPage
¶
Bases: BaseSchema
The text of one page extracted from a PDF.
Attributes:
| Name | Type | Description |
|---|---|---|
number |
int
|
1-based page number. |
text |
str
|
Extracted text for the page. |
PdfReader
¶
Extract text, pages and chunks from a PDF via PyMuPDF.
Attributes:
| Name | Type | Description |
|---|---|---|
text_mode |
str
|
PyMuPDF |
Initialize the reader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text_mode
|
str
|
The |
'text'
|
chunks
¶
chunks(
path: str, *, max_chars: int = 2000, overlap: int = 200, per_page: bool = True
) -> list[Chunk]
Read a PDF and slice it into overlapping chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Filesystem path to the PDF. |
required |
max_chars
|
int
|
Max characters per chunk (~500 tokens at
2000). Defaults to |
2000
|
overlap
|
int
|
Characters shared between adjacent chunks, so a
fact split across a boundary still lands whole in one.
Defaults to |
200
|
per_page
|
bool
|
When |
True
|
Returns:
| Type | Description |
|---|---|
list[Chunk]
|
list[Chunk]: The chunks in document order. |
read
¶
read(path: str) -> Document
Read a PDF into a :class:Document (full text + pages + metadata).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Filesystem path to the PDF. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Document |
Document
|
The extracted document. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
PgChatMemory
¶
PgChatMemory(
embedder: SupportsEmbed,
db: AsyncDatabaseManager,
*,
dim: int,
table: str = "chat_memory",
top_k: int = 5,
min_similarity: float = 0.55,
recency_halflife_days: float = 14.0,
recency_weight: float = 0.5,
max_entries_per_user: int = 50000,
min_content_chars: int = 6,
candidate_multiplier: int = 4,
ef_search: int | None = None,
probes: int | None = None,
)
Recency-aware long-term chat memory stored in Postgres with pgvector.
A sibling of :class:~tempest_fastapi_sdk.genai.rag.ChatMemory with the
same index / search / delete_for_chat / delete_for_user
surface and the same ranking, so either one fits wherever the other
does (AIChatPipeline(memory=...) accepts both).
One row per message, keyed by message_id: user_id, chat_id,
role, content, created_at (timestamptz) and
embedding vector(dim). Every search is
WHERE user_id = :user_id (plus chat_id <> :exclude when asked)
ordered by the cosine distance <=>, so one user's recall never
reads another user's rows. Without an approximate index the search is
an exact scan of that user's rows; :meth:ensure_schema can build an
HNSW or IVFFlat index for large tables.
Sessions come from the service's
:class:~tempest_fastapi_sdk.db.connection.AsyncDatabaseManager. The
two deletes also accept the caller's session, so erasing a chat or
an account and its memory commit or roll back together.
Attributes:
| Name | Type | Description |
|---|---|---|
table |
str
|
The table holding messages + embeddings. |
dim |
int
|
The embedding dimension (must match the model). |
top_k |
int
|
Default number of hits returned by :meth: |
min_similarity |
float
|
Default similarity floor. |
recency_halflife_days |
float
|
Age (days) at which the decay factor halves. |
recency_weight |
float
|
Blend weight for the recency decay in
|
max_entries_per_user |
int
|
Soft per-user quota; |
min_content_chars |
int
|
Messages shorter than this (stripped) are
skipped by :meth: |
candidate_multiplier |
int
|
How many nearest messages per returned
hit :meth: |
ef_search |
int | None
|
|
probes |
int | None
|
|
Initialize chat memory over a pgvector table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedder
|
SupportsEmbed
|
Turns text into vectors. |
required |
db
|
AsyncDatabaseManager
|
The service's database manager. |
required |
dim
|
int
|
Embedding dimension (e.g. 768 for
|
required |
table
|
str
|
Table name, bare or |
'chat_memory'
|
top_k
|
int
|
Default hit count for :meth: |
5
|
min_similarity
|
float
|
Default similarity floor in |
0.55
|
recency_halflife_days
|
float
|
Half-life of the recency decay. |
14.0
|
recency_weight
|
float
|
Recency blend weight in |
0.5
|
max_entries_per_user
|
int
|
Soft per-user quota ( |
50000
|
min_content_chars
|
int
|
Minimum stripped length to index. |
6
|
candidate_multiplier
|
int
|
Over-fetch factor for :meth: |
4
|
ef_search
|
int | None
|
|
None
|
probes
|
int | None
|
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ann_index_name
property
¶
The approximate index's name, schema-qualified like table.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
63-byte identifier limit. |
delete_for_chat
async
¶
delete_for_chat(
*, user_id: str | UUID, chat_id: str | UUID, session: AsyncSession | None = None
) -> None
Remove one user's rows for a chat.
chat_id is not unique across users, so the delete is keyed on
the owner too: another user's rows that share the id stay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | UUID
|
The owner whose rows to delete. |
required |
chat_id
|
str | UUID
|
The chat whose rows to delete. |
required |
session
|
AsyncSession | None
|
The caller's session. When given,
the |
None
|
delete_for_user
async
¶
Remove every row belonging to a user (account erasure).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | UUID
|
The owner whose rows to delete. |
required |
session
|
AsyncSession | None
|
The caller's session, so the
erasure joins its transaction; |
None
|
ensure_schema
async
¶
ensure_schema(
*,
ann_index: AnnIndex | None = None,
m: int | None = None,
ef_construction: int | None = None,
lists: int | None = None,
) -> None
Create the pgvector extension, the memory table and its indexes.
Always creates two B-tree indexes: (user_id, created_at) for the
per-user filter and the quota's oldest-first eviction, and
(user_id, chat_id) for :meth:delete_for_chat. With
ann_index it also builds an approximate index on embedding
(vector_cosine_ops), exactly as
:meth:PgVectorStore.ensure_schema does. Called lazily, without an
approximate index, by the first operation that needs the table.
CREATE EXTENSION needs a role allowed to create it; where the
application role is not, run it once as a superuser beforehand.
An approximate index needs pgvector 0.8.0 or newer: every search
filters by user_id, and only iterative index scans (which
:meth:search turns on for its own transaction) keep scanning
until enough of that user's rows are found. Without them an
HNSW scan stops after hnsw.ef_search rows of any user, and a
user owning a small share of the table gets fewer hits than exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ann_index
|
AnnIndex | None
|
|
None
|
m
|
int | None
|
HNSW max connections per layer. |
None
|
ef_construction
|
int | None
|
HNSW candidate list size while building. |
None
|
lists
|
int | None
|
IVFFlat inverted list count. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When a parameter is invalid for |
RuntimeError
|
When |
index
async
¶
index(
*,
user_id: str | UUID,
chat_id: str | UUID,
message_id: str | UUID,
role: str,
content: str,
created_at: datetime,
) -> bool
Embed a chat message and upsert it, keyed by message_id.
Short messages (stripped length below min_content_chars) are
skipped. Re-indexing the same message_id replaces the row. The
quota eviction and the upsert run in one transaction: when the user
is over max_entries_per_user, the oldest rows (by created_at,
a timestamptz, so the UTC instant) are deleted first, never the
message being written.
A message_id already stored for a different user is refused
(the upsert's WHERE matches nothing) and the transaction rolls
back, eviction included.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | UUID
|
Owner of the message. |
required |
chat_id
|
str | UUID
|
Chat the message belongs to. |
required |
message_id
|
str | UUID
|
Unique id (the primary key). |
required |
role
|
str
|
The message role. |
required |
content
|
str
|
The message text. |
required |
created_at
|
datetime
|
Creation timestamp; naive values are read as UTC. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
was skipped for being too short. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Exception
|
Embedding or database failures propagate to the caller (no internal retry). |
search
async
¶
search(
*,
user_id: str | UUID,
query: str,
exclude_chat_id: str | UUID | None = None,
top_k: int | None = None,
min_similarity: float | None = None,
) -> list[MemoryHit]
Return the most relevant past messages for a user.
Embeds query and reads the top_k * candidate_multiplier
nearest rows WHERE user_id = :user_id (and
chat_id <> :exclude_chat_id when given) ordered by <=>, then
drops hits below the similarity floor and re-ranks by the
recency-decay blend — the same ranking as ChatMemory.search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
str | UUID
|
Whose memory to search. |
required |
query
|
str
|
The natural-language query. |
required |
exclude_chat_id
|
str | UUID | None
|
Chat to exclude (typically the active conversation, so it does not match itself). |
None
|
top_k
|
int | None
|
Override for the default hit count. |
None
|
min_similarity
|
float | None
|
Override for the similarity floor. |
None
|
Returns:
| Type | Description |
|---|---|
list[MemoryHit]
|
list[MemoryHit]: Up to |
list[MemoryHit]
|
final score. Empty when the query is blank, |
list[MemoryHit]
|
nothing clears the floor. |
PgVectorStore
¶
PgVectorStore(db: AsyncDatabaseManager, *, dim: int, table: str = 'rag_chunks')
A Postgres-backed vector store using the pgvector extension.
Reuses the service's existing database (no new infra). The table and a
B-tree index on source are created on demand; search orders by
pgvector's cosine-distance operator (<=>). Without an approximate
index that is an exact sequential scan; ensure_schema(ann_index=...)
builds an HNSW or IVFFlat index (vector_cosine_ops) that trades
recall for latency, tuned per search with ef_search / probes.
Requires the [genai-rag] extra (pgvector package) plus a
Postgres with CREATE EXTENSION vector.
Attributes:
| Name | Type | Description |
|---|---|---|
table |
str
|
The table holding chunks + embeddings. |
dim |
int
|
The embedding dimension (must match the model). |
Initialize the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
AsyncDatabaseManager
|
The database manager (own sessions). |
required |
dim
|
int
|
Embedding dimension (e.g. 384 for MiniLM). |
required |
table
|
str
|
Table name, bare or |
'rag_chunks'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ann_index_name
property
¶
The approximate index's name, schema-qualified like table.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
name fits Postgres' 63-byte identifier limit. |
add
async
¶
add(chunks: Sequence[Chunk], vectors: Sequence[list[float]]) -> None
Store chunks, replacing what their sources held before.
One transaction: the rows of every source named in chunks are
deleted, then the batch is inserted in a single executemany.
Identical chunks in the batch are inserted once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
Sequence[Chunk]
|
The chunks to store — every chunk of a source in one call. |
required |
vectors
|
Sequence[list[float]]
|
One vector per chunk. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the counts differ. |
ensure_schema
async
¶
ensure_schema(
*,
ann_index: AnnIndex | None = None,
m: int | None = None,
ef_construction: int | None = None,
lists: int | None = None,
) -> None
Create the pgvector extension, the chunk table and its indexes.
Always creates the B-tree index on source. With ann_index it
also builds an approximate index on embedding, named
:attr:ann_index_name, with the vector_cosine_ops operator class
— the one that matches the <=> distance :meth:search orders
by. A parameter left as None is omitted from the WITH clause,
so pgvector's own default applies.
An IVFFlat index computes its list centroids from the rows present
when it is built, so call this with ann_index="ivfflat" after
loading the corpus, not before the first add.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ann_index
|
AnnIndex | None
|
|
None
|
m
|
int | None
|
HNSW max connections per layer. |
None
|
ef_construction
|
int | None
|
HNSW candidate list size while building. |
None
|
lists
|
int | None
|
IVFFlat inverted list count. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When a parameter is not a positive integer, belongs
to the other method or is given without |
RuntimeError
|
When |
search
async
¶
search(
vector: list[float],
*,
top_k: int = 5,
ef_search: int | None = None,
probes: int | None = None,
) -> list[Chunk]
Return the top_k nearest chunks by cosine distance.
ef_search and probes are set with
set_config(..., is_local => true) — the function form of
SET LOCAL — so they last for this search's transaction only and
never leak to another session sharing the pooled connection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
list[float]
|
The query vector. |
required |
top_k
|
int
|
How many chunks to return. |
5
|
ef_search
|
int | None
|
|
None
|
probes
|
int | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
list[Chunk]
|
list[Chunk]: Nearest chunks, each with |
list[Chunk]
|
similarity ( |
list[Chunk]
|
without a query, since Postgres rejects a negative |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Reranker
¶
Reranker(
model_id: str,
*,
device: str = "auto",
dtype: str | ModelDtypeEnum = "auto",
cache_dir: str | None = None,
hf_token: str | None = None,
revision: str | None = None,
local_files_only: bool | None = None,
trust_remote_code: bool = False,
max_length: int = 512,
idle_unload_seconds: float | None = None,
hardware: HardwareInfo | None = None,
)
A lazily-loaded cross-encoder that reranks retrieved chunks.
Example:
>>> from tempest_fastapi_sdk.genai.rag import Reranker
>>> reranker = Reranker("cross-encoder/ms-marco-MiniLM-L-6-v2")
>>> best = await reranker.rerank("how to refund?", candidates, top_k=5)
Attributes:
| Name | Type | Description |
|---|---|---|
model_id |
str
|
The HuggingFace cross-encoder id. |
device |
str
|
The resolved device ( |
dtype |
ModelDtypeEnum
|
The resolved compute precision. |
idle_unload_seconds |
float | None
|
Idle threshold for
:meth: |
Configure the reranker (does not load weights yet).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
HuggingFace cross-encoder id. |
required |
device
|
str
|
|
'auto'
|
dtype
|
str | ModelDtypeEnum
|
Compute precision, or |
'auto'
|
cache_dir
|
str | None
|
Where the downloaded weights are
written and read back from. |
None
|
hf_token
|
str | None
|
Hub token for gated/private models. |
None
|
revision
|
str | None
|
Branch, tag or commit sha to load;
|
None
|
local_files_only
|
bool | None
|
Load from the cache without
touching the network — what an air-gapped or deploy-frozen
host wants. |
None
|
trust_remote_code
|
bool
|
Allow the repository's own Python to run at load time. |
False
|
max_length
|
int
|
Max tokens per |
512
|
idle_unload_seconds
|
float | None
|
When set,
:meth: |
None
|
hardware
|
HardwareInfo | None
|
Injected snapshot for device
resolution (tests); probed when |
None
|
seconds_idle
property
¶
Return seconds since the model was last in use.
Reads 0.0 while a rerank is in flight.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Idle time in seconds. |
load
¶
Download (if needed) and load the cross-encoder + tokenizer.
Idempotent — a no-op once loaded. Called automatically by
:meth:rerank. Safe to call from several threads at once:
concurrent callers on a cold instance wait for one build.
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
rerank
async
¶
Reorder chunks by cross-encoder relevance to query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The query text. |
required |
chunks
|
Sequence[Chunk]
|
Candidate chunks (e.g. a retriever's
top-N). Each chunk's |
required |
top_k
|
int | None
|
Keep only the best |
None
|
Returns:
| Type | Description |
|---|---|
list[Chunk]
|
list[Chunk]: Reranked chunks, best first. Empty input → empty list. |
unload
¶
Free the model and its memory (VRAM/RAM). Safe when not loaded.
While a rerank is in flight the release waits for it: the last call to finish drops the weights.
unload_if_idle
¶
Unload the model when idle past idle_unload_seconds.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
while a rerank is in flight. |
Retriever
¶
Retriever(
embedder: SupportsEmbed,
store: VectorStore,
*,
reranker: SupportsRerank | None = None,
)
Index chunks and retrieve the most relevant ones for a query.
Example:
>>> from tempest_fastapi_sdk.genai import Embedder
>>> from tempest_fastapi_sdk.genai.rag import (
... InMemoryVectorStore, PdfReader, Retriever,
... )
>>> rag = Retriever(Embedder("...", normalize=True), InMemoryVectorStore())
>>> await rag.index(PdfReader().chunks("/kb/manual.pdf")) # once
>>> context = await rag.retrieve("how to refund?", top_k=5) # cheap, repeatable
>>> answer = await generator.generate(context)
Attributes:
| Name | Type | Description |
|---|---|---|
embedder |
SupportsEmbed
|
Turns text into vectors. |
store |
VectorStore
|
Persists and searches the vectors. |
Initialize the retriever.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedder
|
SupportsEmbed
|
The embedding model (e.g. |
required |
store
|
VectorStore
|
The vector store to index into and search. |
required |
reranker
|
SupportsRerank | None
|
Optional cross-encoder
(:class: |
None
|
index
async
¶
index(chunks: Sequence[Chunk]) -> int
Embed chunks and add them to the store.
An embedder with embed_passages (Embedder) is called through
it, so its passage_prefix lands on every chunk; :meth:search
does the same with embed_query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
Sequence[Chunk]
|
Chunks (e.g. from |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of chunks indexed. |
retrieve
async
¶
Search the corpus and build a prompt-ready context block.
The one-shot corpus-RAG helper: query in, context string out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The natural-language query. |
required |
top_k
|
int
|
How many chunks to include. |
5
|
long_text
|
bool
|
Full chunk bodies ( |
True
|
max_chars
|
int
|
Per-chunk truncation cap when |
2000
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A prompt-ready context block (see :func: |
search
async
¶
search(query: str, *, top_k: int = 5, rerank_candidates: int = 20) -> list[Chunk]
Return the top_k chunks most relevant to query.
With a reranker configured, the store is queried for
max(top_k, rerank_candidates) nearest chunks and the cross-encoder
reorders them down to top_k; otherwise the dense top_k is
returned directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The natural-language query. |
required |
top_k
|
int
|
How many chunks to return. |
5
|
rerank_candidates
|
int
|
How many dense candidates to fetch before
reranking (ignored when no |
20
|
Returns:
| Type | Description |
|---|---|
list[Chunk]
|
list[Chunk]: The nearest chunks, each with its |
SearchResult
¶
Bases: BaseSchema
One source returned by a web search backend.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
str
|
Page title reported by the search engine. |
url |
str
|
Canonical URL of the source. |
snippet |
str
|
Short summary from the search engine. |
content |
str
|
Full page body once extracted (empty until an extractor fills it, or when extraction failed). |
score |
float | None
|
Relevance score when the backend provides
one; |
SearxngBackend
¶
SearxngBackend(
base_url: str,
*,
http_client: HTTPClient,
language: str = "auto",
timeout: float = 10.0,
)
Web search over a self-hosted SearXNG instance (JSON API).
Example:
>>> from tempest_fastapi_sdk.utils.http_client import HTTPClient
>>> client = HTTPClient()
>>> backend = SearxngBackend("http://localhost:8080", http_client=client)
>>> results = await backend.search("what is PIX?", max_results=5)
Attributes:
| Name | Type | Description |
|---|---|---|
base_url |
str
|
The SearXNG base URL (without |
language |
str
|
Query language passed to SearXNG. |
Initialize the backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_url
|
str
|
SearXNG base URL, e.g.
|
required |
http_client
|
HTTPClient
|
Injected
:class: |
required |
language
|
str
|
Search language ( |
'auto'
|
timeout
|
float
|
Per-request timeout in seconds. |
10.0
|
search
async
¶
search(query: str, *, max_results: int = 5) -> list[SearchResult]
Run query against SearXNG and return parsed results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The natural-language query. |
required |
max_results
|
int
|
Cap on results returned (post-slice). |
5
|
Returns:
| Type | Description |
|---|---|
list[SearchResult]
|
list[SearchResult]: Parsed results in SearXNG order (no |
list[SearchResult]
|
re-ranking). Empty list when SearXNG returns nothing. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the SearXNG request fails or returns a
non-JSON / malformed payload (enable |
SemanticNameIndex
¶
SemanticNameIndex(embedder: SupportsEmbed, entries: Iterable[tuple[str, T]] = ())
Names mapped to values, ranked by meaning through an embedder.
Names are embedded lazily, all at once, on the first :meth:search after
an :meth:add (or explicitly with :meth:build), so adding many names
costs one batched embedding call, not one per name.
Example::
index = SemanticNameIndex(embedder, [("Calçado esportivo", 1)])
matches = await index.search("tênis de corrida")
Build the index; nothing is embedded yet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedder
|
SupportsEmbed
|
Turns texts into vectors. |
required |
entries
|
Iterable[tuple[str, T]]
|
|
()
|
add
¶
Store value under name; it is embedded on the next search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name. Blank names are ignored. |
required |
value
|
T
|
The value to return for it. |
required |
search
async
¶
search(
query: str, *, limit: int | None = 5, min_score: float = 0.0
) -> list[NameMatch[T]]
Return the names closest in meaning to query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
What the user wrote. |
required |
limit
|
int | None
|
Most matches to return; |
5
|
min_score
|
float
|
Lowest cosine similarity kept. What counts as "close" depends on the model; measure it on your names. |
0.0
|
Returns:
| Type | Description |
|---|---|
list[NameMatch[T]]
|
list[NameMatch[T]]: Best first, with |
SupportsEmbed
¶
Bases: Protocol
Anything that turns texts into vectors (e.g. Embedder).
embed
async
¶
Return one vector per input text.
SupportsRerank
¶
SupportsRetrieve
¶
Bases: Protocol
A one-shot corpus-RAG helper: query in, context block out.
Implemented by both :class:Retriever and
:class:~tempest_fastapi_sdk.genai.rag.HybridRetriever, so either backs
:func:~tempest_fastapi_sdk.genai.make_genai_router's /rag endpoint.
retrieve
async
¶
Search the corpus and return a prompt-ready context block.
VectorStore
¶
Bases: Protocol
Persist chunk vectors and search them by similarity.
add
async
¶
add(chunks: Sequence[Chunk], vectors: Sequence[list[float]]) -> None
Store chunks with their aligned vectors.
The SDK's stores replace every chunk previously stored for the
sources in chunks; a custom store should do the same, or
re-indexing a source leaves its old chunks searchable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
Sequence[Chunk]
|
The chunks to index. |
required |
vectors
|
Sequence[list[float]]
|
One embedding per chunk, in the same order. |
required |
WebSearch
¶
WebSearch(backend: WebSearchBackend)
Thin facade over a :class:WebSearchBackend.
Wraps any backend so call sites depend on this class, not on a
specific provider. Defaults to SearXNG when you pass a backend built
with :class:SearxngBackend.
Attributes:
| Name | Type | Description |
|---|---|---|
backend |
WebSearchBackend
|
The active search backend. |
Initialize the facade.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
WebSearchBackend
|
The backend to delegate to. |
required |
retrieve
async
¶
retrieve(
query: str,
*,
max_results: int = 5,
extractor: ContentExtractor | None = None,
long_text: bool = True,
max_chars: int = 2000,
) -> str
Search, optionally extract page bodies, and build a context block.
The one-shot RAG helper: from a question to a prompt-ready context
string in one call. Without extractor the block uses search
snippets; with one, it fetches and extracts each page body (in
parallel) for real ground truth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The natural-language question. |
required |
max_results
|
int
|
How many sources to include. |
5
|
extractor
|
ContentExtractor | None
|
When given, fetch + extract each result's full text; otherwise use snippets only. |
None
|
long_text
|
bool
|
Include full bodies ( |
True
|
max_chars
|
int
|
Per-source truncation cap when
|
2000
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A prompt-ready context block (see :func: |
search
async
¶
search(query: str, *, max_results: int = 5) -> list[SearchResult]
Search query through the backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The natural-language query. |
required |
max_results
|
int
|
Cap on results. |
5
|
Returns:
| Type | Description |
|---|---|
list[SearchResult]
|
list[SearchResult]: The results. |
WebSearchBackend
¶
Bases: Protocol
A source of web results for a natural-language query.
search
async
¶
search(query: str, *, max_results: int) -> list[SearchResult]
Return up to max_results sources for query.
build_context
¶
build_context(
question: str,
sources: Sequence[SearchResult | Chunk],
*,
long_text: bool = True,
max_chars: int = 2000,
) -> str
Render retrieved sources into a single context string for an LLM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
The user's question, echoed at the top so the model has the task in view. |
required |
sources
|
Sequence[SearchResult | Chunk]
|
Web results and/or PDF chunks, in the order they should appear. |
required |
long_text
|
bool
|
When |
True
|
max_chars
|
int
|
Per-source truncation cap when |
2000
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A prompt-ready block. Sources are delimited by |
str
|
labeled with their origin; returns a short notice when |
|
str
|
is empty. |
chunk_text
¶
chunk_text(
text: str,
*,
source: str,
max_chars: int = 2000,
overlap: int = 200,
page: int | None = None,
start_index: int = 0,
) -> list[Chunk]
Split text into overlapping :class:Chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The text to chunk. |
required |
source
|
str
|
Origin label carried on each chunk (URL, PDF path…). |
required |
max_chars
|
int
|
Max characters per chunk (~500 tokens at 2000). |
2000
|
overlap
|
int
|
Characters shared between adjacent chunks. |
200
|
page
|
int | None
|
Originating page number, when applicable. |
None
|
start_index
|
int
|
Index the first produced chunk gets (so chunks from many sources can share one running counter). |
0
|
Returns:
| Type | Description |
|---|---|
list[Chunk]
|
list[Chunk]: The chunks in order; empty when |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
reciprocal_rank_fusion
¶
Fuse several ranked id lists into a single ranking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rankings
|
Sequence[Sequence[str]]
|
One ranked list of ids per retriever (best first). Ids absent from a list simply do not contribute that list's term. An id repeated inside one list contributes only its first (best) rank; the repeats still occupy their positions, so the ranks of the ids after them do not move. |
required |
k
|
int
|
RRF damping constant; larger flattens the rank weighting. |
60
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The fused ids, best first. Ties keep first-seen order. |