Index
groundlens
¶
Groundlens — Verifiable agent triage.
Deterministic. Auditable. No second LLM in the loop.
Groundlens triages outputs from individual LLMs and from multi-agent pipelines (routing, RAG, specialized / tool-using agents). Two layers:
- Geometric layer. SGI and DGI score grounding via embedding geometry, sub-second and deterministic. Apply to any agent's natural-language output.
- Rule-based layer. Domain-specific rule sets with per-rule
citations to academic, industrial, and regulatory sources. Per-agent
factories live in :mod:
groundlens.agents: :func:groundlens.agents.routing_rules, :func:groundlens.agents.rag_rules, :func:groundlens.agents.specialized_agent_rules.
Quick start::
>>> from groundlens import compute_sgi, compute_dgi, evaluate
>>>
>>> # With context (RAG verification) — uses SGI
>>> result = compute_sgi(
... question="What is the capital of France?",
... context="France is in Western Europe. Its capital is Paris.",
... response="The capital of France is Paris.",
... )
>>> result.flagged
False
>>>
>>> # Without context — uses DGI
>>> result = compute_dgi(
... question="What causes seasons?",
... response="Seasons are caused by Earth's 23.5-degree axial tilt.",
... )
>>> result.flagged
False
>>>
>>> # Auto-select method
>>> score = evaluate(question="Q?", response="A.", context="Source.")
>>> score.method
'sgi'
>>>
>>> # Agent-specific rule triage
>>> from groundlens.agents import routing_rules, rag_rules, specialized_agent_rules
>>> rag = rag_rules()
>>> rag.name
'groundlens_banking_v1'
References
Marin (2025). Semantic Grounding Index. arXiv:2512.13771. Marin (2026). A Geometric Taxonomy of Hallucinations. arXiv:2602.13224v3. Marin (2026). Rotational Dynamics of Factual Constraint Processing. arXiv:2603.13259. Marin (2026). Defendable Rules for LLM Rationale Evaluation in Banking Governance: A Multi-Source Provenance Framework.
Attributes¶
DEFAULT_MODEL: str = 'Snowflake/snowflake-arctic-embed-l-v2.0'
module-attribute
¶
Default sentence transformer model.
Snowflake Arctic Embed L v2.0 — 1024 dims, 568M params, multilingual
(100+ languages including Spanish/Catalan/Galician/English/Portuguese),
8192 token context window. Requires trust_remote_code=True on load
(the model ships custom pooling code).
Why this is the default:
- Verified on RAGTruth (n=2,700) and RAGBench (n=8,838) with consistent SGI/DGI behavior; calibrations in cookbooks ship against this encoder.
- L2-normalizes embeddings naturally (contrastive training), which keeps the canonical angular SGI formulation numerically stable.
- Multilingual out-of-the-box — relevant for European bank deployments.
When to override:
- Lightweight deployment (CPU-only, latency-critical): use
LIGHTWEIGHT_MINILM = "all-MiniLM-L6-v2"(22M params, 384 dims). The previous default through 2026.6.17. - Spanish/multilingual smaller footprint: use
MULTILINGUAL_MINI(118M params, 384 dims). - Higher quality multilingual at higher cost: use
MULTILINGUAL_E5(560M params, 1024 dims) with required "query: "/"passage: " prefixes.
To override globally, pass model="..." to compute_sgi,
compute_dgi, or the corresponding scorer classes.
LIGHTWEIGHT_MINILM: str = 'all-MiniLM-L6-v2'
module-attribute
¶
Lightweight English-only encoder (22M params, 384 dims). Was the default through groundlens 2026.6.17. Use for latency-critical CPU-only deployments where the trade-off in grounding signal quality is acceptable.
MULTILINGUAL_E5: str = 'intfloat/multilingual-e5-large'
module-attribute
¶
Multilingual E5 (560M params, 1024 dims, 100+ languages). Higher
quality than MULTILINGUAL_MINI at ~5x the inference cost. Choose
when latency budget allows it (e.g. batch evaluation, audit replay) and
the deployment domain has shown weak separation under MiniLM. Requires
prefixing queries with "query: " and passages with "passage: "
to match the encoder's training recipe; see model card on HuggingFace.
MULTILINGUAL_MINI: str = 'paraphrase-multilingual-MiniLM-L12-v2'
module-attribute
¶
Multilingual MiniLM (118M params, 384 dims, 50+ languages including
Spanish, Catalan, Galician, English). Sub-second on CPU. Recommended
default for European-bank customer-support deployments where the
WhatsApp / app channel receives queries across the bank's operating
languages. Calibrate mu_hat and SGI threshold on a multilingual
verified-grounded corpus for the expected query distribution.
Classes¶
CalibrationResult(model: str, n_pairs: int, embedding_dim: int, mu_hat: NDArray[np.float32], concentration: float, metadata: dict[str, str] = dict())
dataclass
¶
Result of DGI calibration.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
str
|
Sentence transformer model used for calibration. |
n_pairs |
int
|
Number of (question, response) pairs used. |
embedding_dim |
int
|
Dimensionality of the embedding space. |
mu_hat |
NDArray[float32]
|
The computed reference direction vector. |
concentration |
float
|
Estimated concentration parameter (kappa) of the von Mises-Fisher distribution. Higher values indicate more consistent displacement directions in the reference data. |
Methods:¶
save(path: str | Path) -> None
¶
Save calibration result to JSON.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Output file path. The mu_hat vector is stored as a list. |
required |
Source code in src/groundlens/calibrate.py
load(path: str | Path) -> CalibrationResult
classmethod
¶
Load a saved calibration result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to JSON calibration file. |
required |
Returns:
| Type | Description |
|---|---|
CalibrationResult
|
CalibrationResult instance with restored mu_hat vector. |
Source code in src/groundlens/calibrate.py
ThresholdFit(sgi_review: float | None, dgi_pass: float | None, n: int, model: str, metric: str = 'youden_j')
dataclass
¶
Fitted decision thresholds for SGI and DGI on a labeled set.
Thresholds are chosen by maximizing Youden's J for the rule "value >= threshold implies grounded" over the supplied examples.
Attributes:
| Name | Type | Description |
|---|---|---|
sgi_review |
float | None
|
Fitted SGI review threshold, or |
dgi_pass |
float | None
|
Fitted DGI pass threshold, or |
n |
int
|
Number of examples used for fitting. |
model |
str
|
Sentence transformer model the scores were computed with. |
metric |
str
|
Name of the criterion used to pick thresholds. |
DGI(model: str = DEFAULT_MODEL, reference_csv: str | None = None, encoder: EmbeddingFn | None = None)
¶
Reusable DGI scorer with pre-configured model and calibration.
Use this class when evaluating multiple responses against the same reference direction. Supports both bundled and custom calibration.
Example
dgi = DGI() result = dgi.score( ... question="What is ML?", ... response="ML is a branch of AI.", ... ) result.flagged False
dgi = DGI(reference_csv="my_domain_pairs.csv") result = dgi.score(question="...", response="...")
Initialize DGI scorer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Sentence transformer model name. |
DEFAULT_MODEL
|
reference_csv
|
str | None
|
Path to domain-specific calibration CSV. |
None
|
encoder
|
EmbeddingFn | None
|
Optional bring-your-own-embeddings callable. When set, both calibration and scoring bypass sentence-transformers (no torch required). |
None
|
Source code in src/groundlens/dgi.py
Methods:¶
calibrate(pairs: list[tuple[str, str]] | None = None, csv_path: str | None = None) -> None
¶
Set custom calibration data.
Either provide pairs directly or a path to a CSV file. This replaces any previously cached reference direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
list[tuple[str, str]] | None
|
List of verified (question, response) tuples. |
None
|
csv_path
|
str | None
|
Path to a calibration CSV file. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither |
Source code in src/groundlens/dgi.py
score(question: str, response: str) -> DGIResult
¶
Compute DGI for a single response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
The input query. |
required |
response
|
str
|
The LLM output to evaluate. |
required |
Returns:
| Type | Description |
|---|---|
DGIResult
|
DGIResult with score and flag status. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in src/groundlens/dgi.py
propose_labels(*, seeds: list[SeedExample], llm_generate: Callable[[str], str], n_candidates: int = 50, n_to_label: int = 10, strategies: str | tuple[str | tuple[str, str], ...] = 'default', diverse_fraction: float = 0.3, seed: int = 42) -> PropositionBatch
¶
Active-learning bootstrap of a verified-grounded calibration set.
Given 10-50 verified-grounded :class:SeedExample triples and a
text-generation callable, this method:
- Picks a seed at random for each candidate and rewrites its
groundedresponse under one of the named confabulation strategies, using the seed's owncontextas the source of truth in the prompt. Coherence is preserved by design -- the prompt never sees a mismatched context+question pair. - Scores each generated candidate with this DGI.
- Ranks candidates by acquisition score (70% uncertainty /
30% strategy diversity) and returns the top
n_to_labelfor a human reviewer.
The method DOES NOT label and DOES NOT calibrate. The human
reviewer assigns the labels; the caller then passes the labelled
grounded subset to :meth:calibrate. The loop is non-circular
by design.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seeds
|
list[SeedExample]
|
10-50 verified-grounded :class: |
required |
llm_generate
|
Callable[[str], str]
|
A callable |
required |
n_candidates
|
int
|
Total candidates to generate across all strategies. Default 50 (≈5 minutes at 4 s/call). |
50
|
n_to_label
|
int
|
How many candidates the batch should contain.
Default 10. The rest are returned in
|
10
|
strategies
|
str | tuple[str | tuple[str, str], ...]
|
|
'default'
|
diverse_fraction
|
float
|
Fraction of the batch reserved for strategy diversity (the rest is filled by uncertainty). Default 0.3. |
0.3
|
seed
|
int
|
Random seed for sampling seeds across rounds. Determinism is required for reproducible audits. |
42
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
PropositionBatch
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Source code in src/groundlens/dgi.py
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 | |
ProposedLabel(question: str, candidate_response: str, dgi_score: float, strategy: str, context_excerpt: str, uncertainty: float)
dataclass
¶
One candidate (question, response) pair ready for human review.
Attributes:
| Name | Type | Description |
|---|---|---|
question |
str
|
A question grounded in one of the FAQ-corpus entries. |
candidate_response |
str
|
A confabulated response written by the
generation LLM under the named |
dgi_score |
float
|
The DGI normalized score of the candidate against
the current |
strategy |
str
|
The name of the confabulation strategy that produced
this candidate (e.g. |
context_excerpt |
str
|
The FAQ excerpt the question was anchored to. |
uncertainty |
float
|
Distance of |
PropositionBatch(items: tuple[ProposedLabel, ...], review_template: str, all_candidates: tuple[ProposedLabel, ...] = tuple(), strategies_used: tuple[str, ...] = tuple())
dataclass
¶
A batch of candidates returned by :meth:groundlens.DGI.propose_labels.
Attributes:
| Name | Type | Description |
|---|---|---|
items |
tuple[ProposedLabel, ...]
|
Candidates ordered by acquisition score (most useful to
label first). Length up to |
review_template |
str
|
A Markdown template instructing the human reviewer how to label the items in the batch. |
all_candidates |
tuple[ProposedLabel, ...]
|
Every candidate generated in the round, ordered by acquisition score. Useful for audit and debugging. |
strategies_used |
tuple[str, ...]
|
The tuple of strategy names actually used. |
SeedExample(context: str, question: str, grounded: str)
dataclass
¶
One verified-grounded triple you supply to DGI.propose_labels.
A SeedExample binds a FAQ paragraph (context) to a question
that paragraph answers (question) and the verified-grounded
response to that question (grounded). Bundling the three
together is what keeps the candidate generation coherent: the
confabulation prompt receives the same context, question and
grounded answer rather than randomly-paired pieces.
Attributes:
| Name | Type | Description |
|---|---|---|
context |
str
|
A paragraph from the deployment's FAQ corpus that supports the grounded response. |
question |
str
|
A question whose answer is contained in |
grounded |
str
|
The verified-grounded response to |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any field is empty or whitespace-only. |
Methods:¶
__post_init__() -> None
¶
Validate that every field is a non-empty, non-whitespace string.
Source code in src/groundlens/propose.py
ChecklistRule(id: str, description: str, weight: float, sub_score: str, check: Callable[[str, str, str | None, dict[str, Any]], RuleEvidence], citation: str = '')
dataclass
¶
A single rule with an id, a pattern check, and a weight.
Rules are designed to be readable: id and description are
surfaced verbatim in the audit explanation. The check callable
returns a :class:RuleEvidence so the audit trail records why the
rule fired, not just that it did.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Stable identifier (e.g. |
description |
str
|
One-line human-readable description of the rule. |
weight |
float
|
Contribution to the parent sub-score when matched, in [0, 1]. Sub-scores are capped at 1.0 even when weights sum higher. |
sub_score |
str
|
Which sub-score this rule contributes to. For the legacy
|
check |
Callable[[str, str, str | None, dict[str, Any]], RuleEvidence]
|
Pure function |
citation |
str
|
Free-text academic / industry / regulatory provenance for
the rule, suitable for inclusion in an audit explanation or a
regulatory submission. Empty string when no citation is provided.
Example: |
RuleEvidence(matched: bool, span: str, explanation: str)
dataclass
¶
A single piece of evidence supporting a rule's pass/fail decision.
Attributes:
| Name | Type | Description |
|---|---|---|
matched |
bool
|
Whether the rule pattern matched the input text. |
span |
str
|
The substring (lowercased) that triggered the match, or
|
explanation |
str
|
Short human-readable note describing what was checked. |
RuleResult(rule_id: str, sub_score: str, weight: float, matched: bool, evidence_span: str, explanation: str)
dataclass
¶
Outcome of evaluating a single rule.
Attributes:
| Name | Type | Description |
|---|---|---|
rule_id |
str
|
The :attr: |
sub_score |
str
|
Which sub-score this rule contributes to. |
weight |
float
|
The weight of the rule (echo of :attr: |
matched |
bool
|
Whether the rule fired. |
evidence_span |
str
|
The substring that triggered the match, if any. |
explanation |
str
|
The rule's human-readable explanation. |
RuleSet(name: str, rules: tuple[ChecklistRule, ...], sub_scores: tuple[str, ...] = ('spec', 'expl', 'bshift'), quality_floor: float = _DEFAULT_QUALITY_FLOOR, flag_predicate: Callable[[dict[str, float]], bool] | None = None)
dataclass
¶
A collection of rules evaluated together against a (q, r, ctx) triple.
Use :func:groundlens_banking_rules for the current canonical
five-category ruleset, :func:banking_rules for the legacy three-category
ruleset, or construct your own by passing a sequence of
:class:ChecklistRule along with the list of sub-score categories the
rules contribute to.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Identifier (e.g. |
rules |
tuple[ChecklistRule, ...]
|
The rules to evaluate. |
sub_scores |
tuple[str, ...]
|
Ordered tuple of sub-score category names this ruleset
produces. Rules whose |
quality_floor |
float
|
Default flag-predicate threshold below which a sub-score
triggers the audit-deficiency flag. Applied to |
flag_predicate |
Callable[[dict[str, float]], bool] | None
|
Optional pure function |
Methods:¶
evaluate(*, question: str, response: str, context: str | None = None, metadata: dict[str, Any] | None = None) -> RuleSetResult
¶
Evaluate the ruleset against a single (question, response) pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
The user query / prompt the LLM received. |
required |
response
|
str
|
The LLM's rationale text being audited. |
required |
context
|
str | None
|
Optional retrieved context (RAG-style). May be |
None
|
metadata
|
dict[str, Any] | None
|
Optional dict carrying domain-specific structured data that some rules may consult (e.g. the case parameters in a banking decision: risk score, flags, amount, etc.). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
RuleSetResult
|
class: |
RuleSetResult
|
quality, and a full audit explanation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/groundlens/rules.py
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
RuleSetResult(sub_scores: dict[str, float], quality: float, flagged: bool, rule_results: tuple[RuleResult, ...], audit_explanation: str)
dataclass
¶
Aggregated result of evaluating a :class:RuleSet against a response.
Each sub-score is a capped weight sum of matched rules in that category,
stored in the :attr:sub_scores mapping. quality is the geometric
mean of all sub-score values: any zero sub-score yields quality = 0.0,
reflecting that a rationale missing any audited dimension is structurally
incomplete for human review.
Backward-compatible read accessors are exposed for the legacy De-La-Chica
style sub-scores (spec, expl, bshift) and for the current
GroundLens five-category skeleton (groundedness, completeness,
calibration, traceability, robustness). Accessors return
0.0 when the underlying ruleset did not define the requested sub-score.
Attributes:
| Name | Type | Description |
|---|---|---|
sub_scores |
dict[str, float]
|
Mapping from sub-score name to its capped value in [0, 1]. By convention, do not mutate. |
quality |
float
|
Geometric mean of all sub-score values in :attr: |
flagged |
bool
|
|
rule_results |
tuple[RuleResult, ...]
|
One :class: |
audit_explanation |
str
|
Multi-line human-readable summary suitable for inclusion in an audit log. |
Attributes¶
spec: float
property
¶
Legacy specificity sub-score. Returns 0.0 if not defined by ruleset.
expl: float
property
¶
Legacy explanatory-linkage sub-score. Returns 0.0 if not defined by ruleset.
bshift: float
property
¶
Legacy boundary-shift sub-score. Returns 0.0 if not defined by ruleset.
groundedness: float
property
¶
Groundedness sub-score. Returns 0.0 if not defined by ruleset.
completeness: float
property
¶
Completeness sub-score. Returns 0.0 if not defined by ruleset.
calibration: float
property
¶
Calibration sub-score. Returns 0.0 if not defined by ruleset.
traceability: float
property
¶
Traceability sub-score. Returns 0.0 if not defined by ruleset.
robustness: float
property
¶
Robustness sub-score. Returns 0.0 if not defined by ruleset.
DGIResult(value: float, normalized: float, flagged: bool, method: str = 'dgi', explanation: str = '')
dataclass
¶
Result of Directional Grounding Index computation.
DGI measures whether the question-to-response displacement vector aligns with the mean displacement of verified grounded pairs. Higher values indicate alignment with grounded patterns.
Attributes:
| Name | Type | Description |
|---|---|---|
value |
float
|
Raw DGI score = cosine similarity to reference direction. Range: [-1, 1]. |
normalized |
float
|
Score mapped to [0, 1] via linear normalization. |
flagged |
bool
|
|
method |
str
|
Always |
explanation |
str
|
Human-readable interpretation of the score. |
Methods:¶
__post_init__() -> None
¶
Generate explanation from score if not provided.
Source code in src/groundlens/score.py
GroundlensScore(value: float, normalized: float, flagged: bool, method: str, explanation: str, detail: SGIResult | DGIResult)
dataclass
¶
Unified score container returned by high-level evaluate() calls.
Wraps either an SGIResult or DGIResult with additional metadata.
Attributes:
| Name | Type | Description |
|---|---|---|
value |
float
|
Raw score from the underlying method. |
normalized |
float
|
Score in [0, 1]. |
flagged |
bool
|
Whether human review is recommended. |
method |
str
|
|
explanation |
str
|
Human-readable interpretation. |
detail |
SGIResult | DGIResult
|
The full SGIResult or DGIResult for method-specific fields. |
SGIResult(value: float, normalized: float, flagged: bool, q_dist: float, ctx_dist: float, method: str = 'sgi', explanation: str = '')
dataclass
¶
Result of Semantic Grounding Index computation.
SGI measures whether a response engaged with the provided context or stayed anchored to the question. Higher values indicate stronger context engagement (grounded).
Attributes:
| Name | Type | Description |
|---|---|---|
value |
float
|
Raw SGI score = dist(response, question) / dist(response, context). |
normalized |
float
|
Score mapped to [0, 1] via tanh normalization. |
flagged |
bool
|
|
q_dist |
float
|
Euclidean distance from response to question embedding. |
ctx_dist |
float
|
Euclidean distance from response to context embedding. |
method |
str
|
Always |
explanation |
str
|
Human-readable interpretation of the score. |
Methods:¶
__post_init__() -> None
¶
Generate explanation from score if not provided.
Source code in src/groundlens/score.py
SGI(model: str = DEFAULT_MODEL, encoder: EmbeddingFn | None = None)
¶
Reusable SGI scorer with a pre-configured embedding model.
Use this class when evaluating multiple responses with the same model
to avoid repeating the model parameter.
Example
sgi = SGI(model="all-MiniLM-L6-v2") result = sgi.score( ... question="What is X?", ... context="X is Y.", ... response="X is Y.", ... ) result.flagged False
Initialize SGI scorer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Sentence transformer model name or path. |
DEFAULT_MODEL
|
encoder
|
EmbeddingFn | None
|
Optional bring-your-own-embeddings callable. When set, scoring bypasses sentence-transformers (no torch required). |
None
|
Source code in src/groundlens/sgi.py
Methods:¶
score(question: str, context: str, response: str) -> SGIResult
¶
Compute SGI for a single response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
The input query. |
required |
context
|
str
|
Source document or reference text. |
required |
response
|
str
|
The LLM output to evaluate. |
required |
Returns:
| Type | Description |
|---|---|
SGIResult
|
SGIResult with score and flag status. |
Source code in src/groundlens/sgi.py
Functions:¶
get_default_encoder() -> EmbeddingFn | None
¶
Return the process-global embedding callable, or None if unset.
Returns:
| Type | Description |
|---|---|
EmbeddingFn | None
|
The encoder previously set via :func: |
Source code in src/groundlens/_internal/embeddings.py
set_default_encoder(encoder: EmbeddingFn | None) -> None
¶
Set (or clear) the process-global embedding callable.
When a default encoder is set, every encode_texts call that does not
receive an explicit encoder= argument routes through it, bypassing
sentence-transformers entirely (so no torch import is triggered). Pass
None to clear and restore the sentence-transformers path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder
|
EmbeddingFn | None
|
A callable taking |
required |
Source code in src/groundlens/_internal/embeddings.py
customer_support_rag_rules() -> RuleSet
¶
Deprecated alias — use :func:customer_support_rules (with rag=True).
Preserved for one or more releases for backwards compatibility with
code written against groundlens 2026.6.11 / 2026.6.12. The returned
rule set is byte-for-byte identical to
customer_support_rules(rag=True, domain="general", language="en")
except for the RuleSet.name field, which keeps the legacy
"customer_support_rag_v1" value so existing audit logs continue to
match.
.. deprecated:: 2026.6.13
Use :func:customer_support_rules instead.
Source code in src/groundlens/agents/customer_support.py
customer_support_rules(rag: bool = True, domain: str = 'general', language: str = 'en') -> RuleSet
¶
Rule set for customer-support informational agents.
Designed for informational customer-facing assistants. Selects between the RAG and no-RAG sub-score taxonomies and adjusts the stopword / speculative-marker vocabulary to the deployment domain and language.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rag
|
bool
|
Whether the agent retrieves context (FAQ) before answering.
|
True
|
domain
|
str
|
Deployment domain. Affects stopwords and speculative-procedure markers; does not add or remove rules. One of: |
'general'
|
language
|
str
|
Deployment language. Affects stopwords, speculative-procedure markers, and the legal-reference regular expression. One of: |
'en'
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
RuleSet
|
class: |
RuleSet
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Default — FAQ-RAG, general domain, English::
from groundlens.agents import customer_support_rules
rs = customer_support_rules()
result = rs.evaluate(
question="What is the Bizum daily limit?",
response="The Bizum daily limit is 1,000 EUR per transaction.",
context=(
"The daily Bizum transfer limit is 1,000 EUR per "
"transaction and 2,000 EUR per day in total."
),
)
assert not result.flagged
No-RAG chat in Spanish finance vocabulary::
rs = customer_support_rules(rag=False, domain="finance", language="es")
assert "completeness" in rs.sub_scores
assert "groundedness" not in rs.sub_scores
Source code in src/groundlens/agents/customer_support.py
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 | |
rag_rules(domain: str = 'banking') -> RuleSet
¶
Deprecated dispatcher — use the archetype-named factories directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
domain
|
str
|
|
'banking'
|
Returns:
| Type | Description |
|---|---|
RuleSet
|
The selected :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
.. deprecated:: 2026.6.13
Call the canonical factory directly:
:func:groundlens.rules.decision_rationale_rules for credit / AML /
KYC decision rationales, or
:func:groundlens.agents.customer_support_rules for informational
FAQ-RAG agents. The :func:rag_rules dispatcher will be removed in a
future release.
Source code in src/groundlens/agents/rag.py
routing_rules(domain: str = 'general') -> RuleSet
¶
Rule set for routing / intent classification agents.
Returns a 10-rule set across 4 sub-scores: intent_clarity, classification_confidence, fallback_appropriateness, disambiguation_quality. Each rule carries a citation to its academic, industrial, or regulatory source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
domain
|
str
|
Deployment domain. Currently the routing rule set is domain-agnostic by design — the rules check structural properties of routing decisions (single intent, top-1 margin, fallback appropriateness, clarification quality) that hold across verticals. The kwarg is accepted for API symmetry with the other archetype factories and to leave a slot for domain-specific routing extensions in a future release. One of: |
'general'
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
RuleSet
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example::
from groundlens.agents import routing_rules
rs = routing_rules()
result = rs.evaluate(
question="transfer 500 to my brother and check my balance",
response="I will transfer 500 EUR.",
metadata={
"predicted_intent": "transfer",
"top1_score": 0.62,
"margin": 0.08,
"fallback_fired": False,
"query_in_scope": True,
},
)
assert result.flagged # low confidence + multi-intent
Source code in src/groundlens/agents/routing.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 | |
specialized_agent_rules(domain: str = 'general', tools: tuple[str, ...] = ()) -> RuleSet
¶
Rule set for specialized / tool-using agents.
Returns a 10-rule set across 4 sub-scores: entity_groundedness, entity_completeness, entity_calibration, execution_readiness.
The flag predicate is stricter than for RAG agents because specialized agents execute irreversible operations (move money, open accounts, send messages on behalf of the customer).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
domain
|
str
|
Deployment domain. Today this kwarg is accepted for API symmetry with the other archetype factories; the bundled rules check structural properties (entity groundedness, schema completeness, execution readiness) that hold across verticals. Reserved for domain-specific entity validators in a future release. One of: |
'general'
|
tools
|
tuple[str, ...]
|
Optional tuple of validator keys. Today the bundled rule
set ships IBAN, amount, and card-number checks
unconditionally — they abstain when the corresponding
metadata field is absent. The kwarg is reserved for future
releases that will let deployments opt in to additional
domain-specific validators (e.g. NPI for healthcare,
DNI/NIE for Spain). Currently a non-empty value is validated
against :data: |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
RuleSet
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example::
from groundlens.agents import specialized_agent_rules
rs = specialized_agent_rules()
result = rs.evaluate(
question="send 500 to my brother",
response="OK, I'll send 500 EUR to IBAN ES12...",
metadata={
"dialog": "send 500 to my brother. yes go ahead.",
"entities": {"amount": 500, "iban": "ES1234567890123456789012"},
"required_entities": ["amount", "iban"],
"confirmed": True,
"operation": "wire_transfer",
},
)
Source code in src/groundlens/agents/specialized.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 | |
fit_thresholds(examples: list[Mapping[str, object]], *, model: str = DEFAULT_MODEL, encoder: EmbeddingFn | None = None, reference_csv: str | None = None) -> ThresholdFit
¶
Fit SGI/DGI decision thresholds on a labeled set via Youden's J.
For each example this computes DGI (and SGI when a context is
present), then picks each threshold by maximizing Youden's J for the
rule "value >= threshold implies grounded".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
examples
|
list[Mapping[str, object]]
|
A list of mappings, each with keys |
required |
model
|
str
|
Sentence transformer model name. |
DEFAULT_MODEL
|
encoder
|
EmbeddingFn | None
|
Optional bring-your-own-embeddings callable. Passed through
to |
None
|
reference_csv
|
str | None
|
Optional DGI calibration CSV passed to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ThresholdFit
|
class: |
ThresholdFit
|
contexts were supplied) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
fit = fit_thresholds( ... [ ... {"question": "Q1?", "response": "A1.", "label": 0}, ... {"question": "Q2?", "response": "off-topic", "label": 1}, ... ] ... ) fit.metric 'youden_j'
Source code in src/groundlens/calibrate.py
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
compute_dgi(question: str, response: str, *, model: str = DEFAULT_MODEL, reference_csv: str | None = None, encoder: EmbeddingFn | None = None) -> DGIResult
¶
Compute the Directional Grounding Index for a response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
The input query. |
required |
response
|
str
|
The LLM output to evaluate. |
required |
model
|
str
|
Sentence transformer model name. |
DEFAULT_MODEL
|
reference_csv
|
str | None
|
Path to domain-specific calibration CSV.
If |
None
|
encoder
|
EmbeddingFn | None
|
Optional bring-your-own-embeddings callable taking
|
None
|
Returns:
| Type | Description |
|---|---|
DGIResult
|
DGIResult with raw score, normalized score, and flag status. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If question or response is empty. |
Example
from groundlens import compute_dgi result = compute_dgi( ... question="What causes seasons on Earth?", ... response="Seasons are caused by Earth's 23.5-degree axial tilt.", ... ) result.flagged False
Source code in src/groundlens/dgi.py
evaluate_batch(items: list[dict[str, str]], *, model: str = DEFAULT_MODEL, reference_csv: str | None = None) -> list[GroundlensScore]
¶
Evaluate a batch of LLM responses.
Each item in the list is a dict with keys
question(required)response(required)context(optional — triggers SGI when present)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[dict[str, str]]
|
List of dicts, each containing question, response, and optionally context. |
required |
model
|
str
|
Sentence transformer model name. |
DEFAULT_MODEL
|
reference_csv
|
str | None
|
DGI calibration CSV path. |
None
|
Returns:
| Type | Description |
|---|---|
list[GroundlensScore]
|
List of GroundlensScore results, one per input item. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If any item is missing |
Example
from groundlens import evaluate_batch items = [ ... {"question": "Q1?", "response": "A1.", "context": "C1."}, ... {"question": "Q2?", "response": "A2."}, ... ] results = evaluate_batch(items) len(results) 2
Source code in src/groundlens/evaluate.py
banking_rules(quality_floor: float = _DEFAULT_QUALITY_FLOOR) -> RuleSet
¶
Curated ruleset for regulated banking governance decisions.
The rules cover the three sub-scores that an auditor or compliance officer typically inspects in a deferral or escalation rationale:
- Specificity (spec): does the rationale cite the case parameters that triggered the decision? Flags, risk score, numeric thresholds, gates, completeness, jurisdictional details, sufficient length, and specificity-marking language.
- Explanatory linkage (expl): does the rationale link the case facts to the decision? Conditional structure, pending actions, causal connectives, epistemic limits, domain references, modal verbs, length, and temporal ordering.
- Boundary shift (bshift): does the rationale state what would change the decision? Conditional approval pathways, information requests, risk-reduction proposals, alternative framings, threshold references, and length.
The default quality_floor=0.3 follows the cosmetic-deadlock
threshold introduced in the financial-decisions governance literature.
A response that falls below this floor on either spec or expl
is flagged as audit-deficient even if the geometric SGI/DGI score
looks acceptable in isolation — a structurally typical "false
negative" of embedding-based detection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quality_floor
|
float
|
Threshold below which a sub-score triggers the cosmetic-deadlock flag. Tune per deployment risk tolerance. |
_DEFAULT_QUALITY_FLOOR
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
RuleSet
|
class: |
Source code in src/groundlens/rules.py
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 | |
decision_rationale_rules(domain: str = 'finance', regulations: tuple[str, ...] = (), quality_floor: float = _DEFAULT_QUALITY_FLOOR) -> RuleSet
¶
Rule set for decision-rationale agents (credit / AML / KYC / sanctions).
Canonical factory for the 20-rule, 5-sub-score decision-rationale
rule set. Replaces :func:groundlens_banking_rules under the
archetype-as-function naming convention introduced in ADR 0001
(release 2026.6.13).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
domain
|
str
|
Deployment domain. Currently only |
'finance'
|
regulations
|
tuple[str, ...]
|
Optional tuple of regulation keys. When non-empty,
Implementation note (2026.6.13): the kwarg is accepted and
validated, but provenance-filtered rendering of
|
()
|
quality_floor
|
float
|
Threshold below which a sub-score triggers the
cosmetic-deadlock flag. Kept for compatibility with the
legacy |
_DEFAULT_QUALITY_FLOOR
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
RuleSet
|
class: |
RuleSet
|
five sub-scores and 20 rules. The rules and weights are identical |
|
RuleSet
|
to those of :func: |
|
RuleSet
|
name is updated. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example::
from groundlens import decision_rationale_rules
rs = decision_rationale_rules(
domain="finance",
regulations=("eu_ai_act", "sr_26_2"),
)
result = rs.evaluate(question=q, response=r, context=ctx)
Source code in src/groundlens/rules.py
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 | |
groundlens_banking_rules(quality_floor: float = _DEFAULT_QUALITY_FLOOR) -> RuleSet
¶
Canonical rule set for LLM rationale evaluation in banking governance.
Returns the 20-rule reference set whose provenance is triangulated across five independent research tracks: peer-reviewed NLP literature, tier-1 bank public reports, banking regulator whitepapers, cross-industry frameworks, and financial-domain NLP benchmarks. The rules are organized into five empirically-emergent sub-score categories:
- groundedness (5 rules): claims linked to and supported by source.
- completeness (3 rules): coverage of the governance question.
- calibration (4 rules): uncertainty expression and abstention.
- traceability (5 rules): citation, audit trail, validation references.
- robustness (3 rules): resistance to noise, conflict, injection.
Each rule carries a citation field pointing to at least one of its
academic, industrial, or regulatory provenance sources. The companion
paper (Marin, 2026) documents the full per-rule provenance.
The default flag predicate :func:_groundlens_banking_flag_predicate
triggers when any regulator-non-negotiable sub-score falls below its
threshold (groundedness < 0.5, calibration < 0.3, or traceability < 0.4).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quality_floor
|
float
|
Legacy floor exposed for users who want a uniform
threshold across sub-scores. Not used by the default flag
predicate; kept for compatibility with the legacy |
_DEFAULT_QUALITY_FLOOR
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
RuleSet
|
class: |
RuleSet
|
sub-scores and 20 rules. |
Source code in src/groundlens/rules.py
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 | |
compute_sgi(question: str, context: str, response: str, *, model: str = DEFAULT_MODEL, encoder: EmbeddingFn | None = None) -> SGIResult
¶
Compute the Semantic Grounding Index for a response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
The input query. |
required |
context
|
str
|
Source document, retrieved chunks, or reference text. |
required |
response
|
str
|
The LLM output to evaluate. |
required |
model
|
str
|
Sentence transformer model name. Default |
DEFAULT_MODEL
|
encoder
|
EmbeddingFn | None
|
Optional bring-your-own-embeddings callable taking
|
None
|
Returns:
| Type | Description |
|---|---|
SGIResult
|
SGIResult with raw score, normalized score, and flag status. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any input string is empty. |
Example
from groundlens import compute_sgi result = compute_sgi( ... question="What is the capital of France?", ... context="France is in Western Europe. Its capital is Paris.", ... response="The capital of France is Paris.", ... ) result.flagged False
Source code in src/groundlens/sgi.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | |