AI Agent Observablity - spinningideas/resources GitHub Wiki
AI Agent Observability: Deterministic Verification Pipelines for LLM Output
A structured reference for building deterministic verification layers around LLM output. It covers constrained generation, schema validation, grounding checks, security scanning, repair loops, and verdict policies - plus concrete how-to setups for local inference, Google Genkit, and OpenRouter.
Scope: This document is about catching bad outputs before they escape - verification logic that runs in the request path and produces a deterministic pass/warn/repair/block verdict. For the telemetry side (traces, metrics, dashboards, cost attribution, alerting on these signals), see
AI-Agent-Monitoring.md. The two are complementary: verification decides whether an output ships; monitoring records what verification decided and how often.
1. Summary
LLMs optimize next-token plausibility, not correctness, so every output should be treated as untrusted until verified [6]. The reliable pattern is a deterministic verification pipeline: a layer between generation and delivery that applies ordered, deterministic checks - structure, grounding, domain rules, security - and emits a verdict the application acts on. Key principles drawn from reference architectures (LGL, HALO, QWED) [1][5][6]:
- Zero trust - every LLM output is potentially wrong until proven otherwise [6].
- Prevention beats detection - constrained decoding (JSON Schema, regex, grammars) makes entire classes of malformed output impossible at generation time rather than catching them after [7][9].
- Cheap checks first, expensive checks last - regex and schema parse are sub-millisecond; NLI grounding is tens of ms; LLM judges cost a full inference [17].
- Fail-safe default - if a check cannot complete (timeout, unsupported domain), reject or abstain rather than pass the output [6].
- Every check emits an auditable verdict - PASSED / WARNED / FAILED / REPAIRED / BLOCKED / ABSTAINED, logged to the observability stack [4].
- The model never sees production data unguarded - PII/secrets scanning applies to input and output; a pass-through leak is an escape, not a model error [15][16].
Hallucination "escapes" are reduced not by trusting the model more, but by shrinking what the model is allowed to emit (constrained generation) and shrinking what unverified output is allowed to reach (deterministic gates + calibrated abstention) [5].
2. Verification vs. monitoring: the boundary
| Concern | Verification pipeline (this doc) | Monitoring (see AI-Agent-Monitoring.md) |
|---|---|---|
| Question | "Is this output safe to ship?" | "How is the system behaving over time?" |
| Timing | Synchronous, in request path | Async, aggregate, dashboards/alerts |
| Output | Verdict + repaired/blocked output | Traces, metrics, logs, eval scores |
| Failure mode caught | Single bad output (escape) | Drift, regression, rising escape rate, cost spikes |
| Determinism | Deterministic wherever possible | Statistical; judges and evals are fine here |
The link: every verification verdict should be emitted as a span attribute or metric (validation_passed, validator.name, verdict) so the monitoring stack can alert on escape rates, repair rates, and per-check failure trends [13][14].
3. The layered verification pipeline
Checks run in order of cost and certainty. Each layer is independent - bypassing or failing one does not bypass the others; a response must satisfy all applicable layers before delivery [4].
input βββΊ L0 input checks βββΊ LLM generate βββΊ L1 structure βββΊ L2 grounding βββΊ L3 domain rules βββΊ L4 security βββΊ L5 action gate βββΊ deliver / repair / block / abstain
(injection, PII, (schema, regex, (NLI entailment, (math, SQL, code, (PII leak, secrets, (tool-call schema,
length, policy) JSON parse) citation check) referential, logic) toxicity, policy) permissions, HITL)
| Layer | What it verifies | Technique | Verdict on failure |
|---|---|---|---|
| L0 Input | Prompt injection, PII in input, length limits, banned topics | Regex/Unicode normalization, injection classifiers, Presidio [15][16][18] | Block / sanitize |
| L1 Structure | Output parses and matches schema | Constrained decoding + JSON Schema/Pydantic/Zod validation [7][10] | Repair or re-ask |
| L2 Grounding | Claims are entailed by sources/context | Sentence split β NLI verifier (HHEM, MiniCheck, AlignScore) or citation resolution [2][19][20] | Warn / regenerate / abstain |
| L3 Domain rules | Math, logic, SQL safety, code compiles, referential integrity | SymPy, Z3 SMT, sqlglot dry-run, linters, unit tests, business rule engine [6] | Repair / block |
| L4 Security | PII/secrets leak, toxic content, malicious URLs, dangerous code | Presidio redact, Llama Guard / ShieldGemma, regex, Model Armor [15][16][18] | Redact / block |
| L5 Action gate | Tool calls match registered schema, args in range, permission allowlist | JSON Schema on tool args, allowlist, human-in-the-loop for irreversible actions [4] | Block / escalate |
Decision model: each check emits one of PASSED / WARNED / FAILED / SKIPPED / ERROR / TIMEOUT [4]. Aggregate deterministically: any FAILED β repair or block; all PASS β ship; WARN β ship with flag; TIMEOUT/ERROR β treat as FAILED (fail-safe). When multiple constraints fire, the highest-severity action wins - BLOCK overrides WARN [4].
4. Techniques in detail
4.1 Constrained generation (prevention at decode time)
The strongest guarantee: make invalid output impossible to generate. The inference engine masks logits so only schema-legal tokens can be sampled at each step - JSON Schema, regex, or full context-free grammars [7][9].
| Engine / library | Constraint types | Notes |
|---|---|---|
| vLLM structured outputs | choice, regex, json, grammar, structural_tag |
Backends: xgrammar (fast, CFG), outlines, guidance, lm-format-enforcer [7] |
| XGrammar | JSON Schema, regex, CFG | Precomputes >99% of token masks; up to ~5x faster TPOT than FSM backends under load [7][9] |
| Outlines | JSON Schema, regex, grammar (via backend) | Works with Transformers, llama.cpp, MLX; pluggable backends outlines_core, llguidance, xgrammar [8] |
| SGLang | regex, json_schema, EBNF grammar |
RadixAttention-friendly; xgrammar backend |
| llama.cpp | GBNF grammar, JSON Schema | Local CPU/GPU inference; --grammar or json_schema in server |
| OpenAI / OpenRouter strict mode | response_format: {type: "json_schema", strict: true} |
Provider-side enforcement; support is per endpoint, not per model [10][11] |
| Gemini (Genkit/Vertex) | responseSchema / output: {schema} |
Enforced server-side for supported models [21] |
Caveat: constrained decoding guarantees form, not truth - it eliminates structural escapes but not factual ones. Combine with L2 grounding.
4.2 Structural validation and repair loops
If constraints can't be applied at decode time (closed API without strict mode), validate after generation and loop.
- Pydantic (Python) / Zod (TS) - pure CPU validation;
model_validate_jsonraisesValidationErroryou can feed back to the model [12]. - Instructor - patches the OpenAI-compatible client with
response_model; handles prompt injection of the schema, parsing, validation, and automatic retry with the error message appended [12][14]. - Guardrails AI -
Guard+ validators; per-validator failure action:reask,fix,fix_reask,filter,refrain,exception,noop. Ships a REST Guardrails Server with an OpenAI-compatible endpoint, and emits OTel spans withvalidation_passed,validator.name,validator.on_fail[13][14]. - NeMo Guardrails - declarative YAML + Colang rails across input/dialog/retrieval/execution/output; policy lives in version-controlled files rather than code. Emits metrics like
guardrails.requests.blockedandguardrails.request.duration[13]. - JSON repair - libraries like
json-repair/ OpenRouter's Response Healing fix truncated or fenced JSON. Useful as a first repair step, but always re-validate after repair - repair can silently change semantics [11].
Pattern: validate β on failure, re-ask with the validation error in the prompt (bounded retries, e.g. max 2β3) β escalate to a stronger model β block. Every retry is real token spend; cap and meter it [14].
4.3 Grounding / hallucination checks (L2)
Deterministic-adjacent: small NLI classifiers give a deterministic score for a fixed input and are ~100x cheaper per call than an LLM judge.
- Claim extraction - split output into sentences/claims (wtpsplit, Claimify), then verify each
(source, claim)pair; response score = min over claims (any unsupported sentence flags the whole response - the HALT-RAG convention) [2][20]. - HHEM-2.1-Open (Vectara) - small Apache-2.0 entailment scorer, ~$0.0002/check; also runs hosted inside Vectara [19][20].
- MiniCheck (Flan-T5-Large) - trained on synthetic claim decompositions; strong on grounding docs [20].
- AlignScore - 355M-param general alignment function trained on 4.7M examples across 7 tasks; matches or beats GPT-4-based metrics on many benchmarks [19][20].
- Patronus Lynx, SelfCheckGPT (no source doc needed; samples N completions and measures consistency), Cleanlab TLM (hosted uncertainty scoring) [20].
- Citation verification - simplest deterministic check: require
[n]citations, then verify each citation index resolves to a retrieved chunk and that the chunk text supports (NLI) or literally contains the cited span.
Benchmark result worth noting: a dual ensemble of HHEM + MiniCheck (min aggregation) matched a Claude Sonnet judge's hallucination-detection quality on RAGTruth at <1/100th the per-call cost [20]. Reserve LLM judges for the cases NLI flags as uncertain.
4.4 Consistency methods (when no source exists)
- Self-consistency - sample N reasoning paths at temperature >0, majority-vote the final answer [22].
- Cross-model consistency - a different (even weaker) model answers the same prompt; agreement raises confidence, disagreement flags review. Two-stage: only call the verifier model when self-consistency confidence falls in an uncertainty band - keeps most of the gain at a fraction of the cost [22].
- Chain-of-Verification (CoVe) - draft β plan verification questions β answer them independently β produce final verified response. Reduces hallucination on fact-heavy tasks without external tools [22].
These are statistical, not deterministic - use them to score and route, backed by deterministic gates.
4.5 Formal and domain verifiers (L3)
Where a ground truth exists, verify deterministically - the QWED protocol treats the LLM as an "untrusted translator" and checks outputs with established formal tools [6]:
| Domain | Deterministic verifier |
|---|---|
| Math / units | SymPy symbolic re-evaluation; pint for unit consistency; recompute every numeric claim |
| Logic / constraints | Z3 SMT solver - encode output claims, check satisfiability |
| SQL | Parse (sqlglot), EXPLAIN/dry-run against schema, denylist destructive ops, check tables/columns exist |
| Code | Compile/lint (tsc, ruff, go vet), run generated tests, static analysis (semgrep, Bandit) |
| Data / extraction | Re-query source DB/API; check every extracted entity resolves; referential integrity |
| Temporal/logic | Date arithmetic, interval checks, ordering invariants |
Benchmarks cited by QWED: 100% error detection in verifiable domains where the model itself was 73β85% accurate - including a compound-interest miscalculation invisible to prompting or confidence scoring [6]. Where a domain can't be verified deterministically, abstain rather than pass.
4.6 Security checks (L0 + L4)
- Prompt injection - normalize Unicode (homoglyphs, zero-width chars), regex known-injection patterns, classifier models (Protect AI LLM Guard scanners, Azure Prompt Shields, Lakera). Treat retrieved context as untrusted input too - indirect injection is a real escape path [15][17][18].
- PII / secrets - Microsoft Presidio (NER + recognizers) to anonymize on input and deanonymize on output; regex for keys/tokens; scan output for secrets the model may have leaked from context [15][18].
- Content safety - Llama Guard / ShieldGemma classify prompts and responses against a harm taxonomy [14][16].
- Managed service - Google Cloud Model Armor is a model-agnostic REST API that screens prompts, responses, and tool interactions for prompt injection, jailbreak, malware URLs, and sensitive data (via Sensitive Data Protection). Works with any LLM, not just Gemini [16].
- Malicious URLs / tool args - check generated URLs against allowlists/reputation; injection cross-check on generated tool arguments [4].
Rule of thumb on latency budget per check [17]:
| Check | Typical latency |
|---|---|
| Regex / schema parse | sub-ms |
| PII NER | msβtens of ms |
| Safety classifier | tens of ms |
| NLI grounding | tens of ms |
| LLM judge | hundreds of ms (full inference) |
4.7 Tool-call and action gating (L5)
For agents, the output is often a tool call - verify it like code:
- Validate tool name is in the registered set and arguments match the tool's JSON Schema.
- Range-check arguments (amounts, dates, IDs) against business limits, not just types.
- Cross-check generated args for injected instructions (an attacker string in retrieved context can flow into a
send_emailarg) [4]. - Allowlist irreversible/destructive actions behind human approval; log every gated decision.
5. How-to: local setup
Goal: a fully self-hosted verification pipeline - no data leaves your machine.
Stack: Ollama or vLLM (inference) + llama.cpp GBNF / vLLM structured outputs (constraints) + Pydantic/Instructor (validation) + Presidio (PII) + HHEM or MiniCheck (grounding) + Langfuse/Phoenix (telemetry - see monitoring doc).
# 1. Constrained generation with vLLM (xgrammar backend, zero schema escapes)
from vllm import LLM, SamplingParams
from pydantic import BaseModel
class Invoice(BaseModel):
vendor: str
total: float
currency: str
llm = LLM(model="Qwen/Qwen2.5-7B-Instruct")
sp = SamplingParams(guided_decoding_params={
"json": Invoice.model_json_schema() # or regex / grammar / choice
})
resp = llm.generate(prompt, sp)
# 2. Validate anyway - belt and suspenders, and catches semantic type issues
invoice = Invoice.model_validate_json(resp.outputs[0].text)
# 3. Grounding check with a local NLI verifier
# HHEM-2.1-Open or MiniCheck-Flan-T5-Large run fine on CPU/cheap GPU
score = nli_scorer.score_pairs([(source_text, sentence) for sentence in claims])
verdict = "PASS" if min(score) >= THRESHOLD else "ABSTAIN"
# 4. PII scan on output before delivery
from presidio_analyzer import AnalyzerEngine
results = AnalyzerEngine().analyze(text=resp.outputs[0].text, language="en")
# Instructor + local OpenAI-compatible endpoint (Ollama / vLLM server)
import instructor
from openai import OpenAI
client = instructor.from_openai(
OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
)
invoice = client.chat.completions.create(
model="qwen2.5",
response_model=Invoice, # schema injection + parse + validate
max_retries=2, # re-ask with the ValidationError appended
messages=[{"role": "user", "content": prompt}],
)
For grammar-level control on llama.cpp, pass a GBNF grammar (e.g. restrict to an enum, a date format, or a mini-language) - useful even without JSON. Guardrails AI's Guard also works against any OpenAI-compatible local endpoint and centralizes validators + re-ask logic [13][14].
6. How-to: production with Google Genkit
Genkit gives you schema-typed flows and enforced model output in one framework.
// TypeScript: Zod schemas on both the flow and the generate call
import { z } from 'genkit';
const InvoiceSchema = z.object({ vendor: z.string(), total: z.number() });
export const invoiceFlow = ai.defineFlow(
{
name: 'extractInvoice',
inputSchema: z.object({ document: z.string() }), // L0: validated input
outputSchema: InvoiceSchema,
},
async ({ document }) => {
const { output } = await ai.generate({
model: googleAI.model('gemini-flash-latest'),
prompt: `Extract vendor and total.\n\n${document}`,
output: { schema: InvoiceSchema }, // L1: enforced output
});
if (!output) throw new Error('Model output failed schema'); // null = invalid
// L3 domain checks here (e.g. re-query source, range checks)
return output;
}
);
# Python: Pydantic output_schema
response = await ai.generate(prompt=..., output_schema=InvoiceSchema)
if response.output is None:
raise RuntimeError(f'Response did not satisfy schema: {response.error}')
Production checklist for Genkit [21]:
- Define
inputSchema/outputSchemaon every flow - input validation is free injection surface. - Use
output: {schema}ongenerate(); checkoutput == nullas the L1 gate - a null output is a schema escape. - Add domain verification inside the flow after generation (re-query, range checks) - deterministic code you control.
- Register evaluators via plugins and run inference-based evals in the Dev UI and CI on golden datasets [21].
- Put Model Armor in front of the flow (REST call or integrated with Vertex AI) for managed injection/PII/harm screening [16].
- Export traces (Genkit ships OTel-compatible telemetry) into your monitoring backend and tag flow runs with verification verdicts.
7. How-to: production with OpenRouter
OpenRouter is a gateway to many providers - verification must account for per-endpoint capability differences.
{
"model": "anthropic/claude-sonnet-4.5",
"messages": [{"role": "user", "content": "..."}],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "invoice",
"strict": true,
"schema": { "type": "object", "properties": {...}, "required": [...], "additionalProperties": false }
}
},
"provider": {
"require_parameters": true, // only route to endpoints that support json_schema
"zdr": true, // zero data retention endpoints only (compliance)
"allow_fallbacks": true
}
}
OpenRouter-specific rules [10][11]:
- Support is per endpoint, not per model. The same model may be served by providers where only some support
json_schema. Withoutrequire_parameters, your schema may be silently ignored - one test saw 0/24 valid outputs on an endpoint that dropped the schema. - Always set
provider.require_parameters: truewhen the schema matters; the request fails with 404 rather than returning unverifiable output. - Validate client-side regardless. Some endpoints accept a strict schema and still break it; OpenRouter's own guidance is "validate every reply yourself." Keep Response Healing on for broken-JSON repair, but re-validate after healing [11].
- Fallback path for tools-only models: put your schema in a single tool definition and force the tool call; if the model only supports labels, a decision model that returns class probabilities avoids parsing entirely [11].
- Watch
strictrouting: the Vercel AI SDK's OpenRouter provider hardcodesstrict: true, which can exclude endpoints that support schema but not strict mode - yielding a misleading "no endpoints" 404. Work around withgenerateText+ client-side validation when needed [11]. zdr: true+data_collectionfor compliance-sensitive traffic; combine with Presidio client-side so PII never reaches the gateway in the first place.- Log
provideractually used + validation verdict per request - endpoint drift is an observability signal (see monitoring doc).
8. Verdict policy: what to do when a check fails
| Verdict | Meaning | Action |
|---|---|---|
| PASS | All checks passed | Deliver |
| WARN | Non-critical check flagged (e.g. grounding score in gray zone) | Deliver + flag for review queue |
| REPAIR | Auto-fixable (broken JSON, redactable PII, fixable format) | Fix β re-validate β deliver or re-ask model |
| RE-ASK | Failed but recoverable | Regenerate with error feedback, bounded retries, optionally escalate model |
| BLOCK | Policy violation (injection, harmful content, failed security check) | Refuse + log + alert |
| ABSTAIN | Cannot verify (no source, unsupported domain, timeout) | Decline/escalate to human - fail-safe [5][6] |
| ESCALATE | High-stakes or irreversible action | Human-in-the-loop approval |
Two calibration practices:
- Calibrated abstention - when grounding confidence is low, declining is better than guessing; set abstention thresholds from a labeled eval set, not vibes [5].
- Error localization - verify claims in reverse order of generation (final output β intermediate steps β source) to identify which stage introduced the hallucination; feeds prompt/retrieval fixes [2].
9. Offline evals and CI gating
Verification logic itself needs testing. Build a golden dataset of inputs β expected outputs (and known-bad outputs that must be caught), then gate releases on it.
- DeepEval - pytest-style
assert_testwithFaithfulnessMetric,HallucinationMetric,AnswerRelevancyMetric, G-Eval; supports LLM-judge, hybrid, and deterministic "system_one" modes [23]. - RAGAS - faithfulness, answer relevancy, contextual precision/recall for RAG pipelines.
- Phoenix / Langfuse evals - run evaluators over traces collected from production; turn real escapes into regression tests.
- Adversarial set - maintain a corpus of prompt injections, schema-breaking prompts, and known hallucination traps; every pipeline change must keep the catch rate.
@pytest.mark.parametrize("golden", dataset.goldens)
def test_pipeline(golden):
answer, ctx = pipeline(golden.input)
assert_test(LLMTestCase(input=golden.input, actual_output=answer,
retrieval_context=ctx),
metrics=[FaithfulnessMetric(threshold=0.7)])
10. Emitting verification telemetry
Minimal attributes per check, emitted as OTel span events / structured logs (ingested by the backends in AI-Agent-Monitoring.md):
verdict(pass/warn/repair/reask/block/abstain),validator.name,validator.layer(L0βL5),validator.latency_ms,repair.attempts,gen_ai.request.model,endpoint.provider.- Derived metrics to dashboard/alert: escape rate (bad outputs found post-hoc Γ· delivered), block rate by layer, repair success rate, abstain rate, per-validator failure trend, retry token spend.
- Keep a searchable audit trail: input β raw output β verdicts β final delivered output. This is what lets you trace a reported hallucination back to the layer that missed it [1][4].
11. Best practices
- Constrain at decode time wherever possible - a schema enforced by logit masking cannot be escaped; post-validation is the fallback, not the first line [7][9].
- Never trust
response_formatalone - validate client-side even with strict mode; provider support varies and "accepts schema" β "obeys schema" [11]. - Order checks cheapβexpensive - structure β grounding β domain β LLM judge; short-circuit on hard failures [17].
- Bound every retry - cap re-ask loops (2β3), meter the token spend, escalate model only on final attempt [14].
- Fail closed - timeouts, unparseable errors, and unsupported domains produce ABSTAIN/BLOCK, not PASS [6].
- Verify each claim, not the whole response - sentence/claim-level NLI with min-aggregation catches a single unsupported sentence that a whole-response score would average away [20].
- Use small verifiers at scale, judges at the margin - dual-ensemble NLI matches judge quality at ~1/100 cost; call the LLM judge only for the uncertain band [20][22].
- Gate actions, not just text - a perfectly-grounded
delete_all()tool call is still an escape; schema + range + permission checks on every tool call [4]. - Scan output for leaks, not just harm - models can regurgitate PII/secrets from context even without an attack [15][18].
- Treat verification config as code - version-control schemas, thresholds, and rails; review changes like application logic (NeMo's Colang/YAML model makes this natural) [13].
- Convert every production escape into a regression test - your golden dataset should grow monotonically [23].
- Pair every verdict with a span - verification without telemetry can't be improved; monitoring without verification can't prevent [1].
12. Tool & library comparison
| Tool | Layer | Local? | Cloud/managed? | Notes |
|---|---|---|---|---|
| vLLM structured outputs (xgrammar) | L1 | Yes | Self-host | Fastest constrained decoding; choice/regex/json/grammar [7] |
| Outlines | L1 | Yes | Self-host | Multi-backend, multi-engine [8] |
| llama.cpp GBNF | L1 | Yes | Self-host | Grammar constraints on CPU |
| OpenAI/OpenRouter strict json_schema | L1 | No | API | Per-endpoint support; require_parameters [10][11] |
| Genkit output schema | L1 | Dev UI local | GCP | Zod/Pydantic, enforced output, evals [21] |
| Pydantic / Zod | L1 | Yes | Anywhere | Pure validation, no LLM awareness [12] |
| Instructor | L1+repair | Yes | Any OpenAI-compat | response_model + auto-retry [12] |
| Guardrails AI | L0βL5 | Yes | Hub + server | Validators with on-fail actions; OTel spans [13][14] |
| NeMo Guardrails | L0βL5 | Yes | Self-host | Colang rails; policy-as-code; OTel metrics [13] |
| Presidio | L0/L4 | Yes | Self-host | PII detect/anonymize/deanonymize [15][18] |
| LLM Guard (Protect AI) | L0/L4 | Yes | Self-host | Input/output scanners [15] |
| Llama Guard / ShieldGemma | L4 | Yes | Self-host | Safety taxonomy classifier [16] |
| Model Armor | L0/L4 | No | GCP REST, model-agnostic | Injection, PII, malware URL screening [16] |
| HHEM-2.1 / MiniCheck / AlignScore | L2 | Yes | Self-host | Cheap NLI grounding scores [19][20] |
| SelfCheckGPT | L2 | Yes | Any | No source needed; sampling consistency [20] |
| SymPy / Z3 / sqlglot / linters | L3 | Yes | Anywhere | Formal verification [6] |
| DeepEval / RAGAS | Offline eval | Yes | Any | pytest-integrated metrics [23] |
13. References
- Martin Russmann β A Software Architecture for Deterministic Post-Generation Validation of LLM Outputs (Logic-Guard-Layer) β https://martinrussmann.com/a-software-architecture-for-deterministic-post-generation-validation-of-llm-outputs
- Microsoft Research β VeriTrail: Detecting hallucination and tracing provenance in multi-step AI workflows β https://www.microsoft.com/en-us/research/blog/veritrail-detecting-hallucination-and-tracing-provenance-in-multi-step-ai-workflows/
- James Hu β AI Engineering, Ch. 11: Observability, Structured Output & Guardrails β https://jameshu.io/books/ai-engineering/ch11-observability-guardrails/index.html
- G8KEPR β Verification Engine (4-layer pipeline & verdict model) β https://g8kepr.com/features/verification-engine
- arXiv β Zero Hallucination, by Construction: HALO β https://arxiv.org/pdf/2607.17883
- QWED β Deterministic verification protocol whitepaper β https://docs.qwedai.tech/whitepaper
- vLLM β Structured Outputs β https://docs.vllm.ai/en/stable/features/structured_outputs/ ; Structured Decoding intro β https://vllm.ai/blog/2025-01-14-struct-decode-intro
- Outlines β Structured Generation Backends β https://dottxt-ai.github.io/outlines/latest/features/advanced/backends/
- MLC β XGrammar: efficient structured generation β https://blog.mlc.ai/2024/11/22/achieving-efficient-flexible-portable-structured-generation-with-xgrammar ; https://github.com/mlc-ai/xgrammar/blob/main/docs/start/constrained_decoding.md
- OpenRouter β Structured Outputs β https://openrouter.ai/docs/guides/features/structured-outputs ; Provider Routing β https://openrouter.ai/docs/guides/routing/provider-selection
- OpenRouter β How to Get Structured Output from Any LLM β https://openrouter.ai/blog/tutorials/structured-output-llm/
- n4n β Pydantic vs Instructor vs Guardrails for LLM outputs β https://n4n.ai/blog/pydantic-vs-instructor-vs-guardrails-for-llm-outputs/
- Promptise β NeMo Guardrails vs Guardrails AI β https://www.promptise.com/guides/view/guardrails-ai-vs-nemo-guardrails ; SpanObserver β traces & metrics comparison β https://dev.to/spanobserver/nemo-guardrails-vs-guardrails-ai-traces-metrics-and-exported-data-3ekp
- ICSGen LLM Book β Output Guardrails: Llama Guard, NeMo, ShieldGemma, Guardrails AI β https://llmbook.icsgen-ai.org/part-10-llm-security-runtime-safety/module-48-guardrails-runtime-safety/section-48.3.html
- Langfuse β LLM Security & Guardrails β https://langfuse.com/docs/security-and-guardrails
- Google Cloud β Model Armor β https://cloud.google.com/security/products/model-armor
- ClickHouse β LLM guardrails in production β https://clickhouse.com/resources/engineering/llm-guardrails
- Datadog β LLM guardrails best practices β https://www.datadoghq.com/blog/llm-guardrails-best-practices/
- Vectara β HHEM v2 factual consistency β https://www.vectara.com/blog/hhem-v2-a-new-and-improved-factual-consistency-scoring-model ; AlignScore β https://doi.org/10.18653/v1/2023.acl-long.634
- verifiable-rag β Verified RAG: every sentence checked β https://firish.github.io/rag-rack/blog/03_verified_rag/ ; ai moderation tools β Hallucination detection tools compared β https://aimoderationtools.com/posts/hallucination-detection-tools-compared/
- Genkit β Defining AI workflows (flows) β https://genkit.dev/docs/js/flows/ ; Evaluation β https://firebase.google.com/docs/genkit/evaluation
- arXiv β Verify when Uncertain (cross-model consistency) β https://arxiv.org/html/2502.15845v2 ; Chain-of-Verification β https://aclanthology.org/2024.findings-acl.212/ ; Self-Consistency β https://arxiv.org/html/2203.11171v4
- DeepEval β Faithfulness / Hallucination metrics β https://deepeval.com/docs/metrics-faithfulness ; https://deepeval.com/docs/metrics-hallucination
Solutions
Integration points for Devin and OpenCode
Before picking tools, know where verification plugs into each agent:
| Agent | Integration point | What you can verify |
|---|---|---|
| Devin CLI / Desktop | .devin/hooks.v1.json lifecycle hooks - PreToolUse, PostToolUse, PermissionRequest, UserPromptSubmit, Stop [24] |
Block/rewrite tool calls before execution, validate file writes and shell commands, require tests to pass before the agent stops, custom approval logic. Exit code 2 or {"decision":"block"} blocks the action. |
| Devin | MCP servers (.devin/ config) |
Expose verifiers as tools the agent calls (verify_output, check_grounding); gate mcp__* calls via PreToolUse matcher regex. |
| Devin | CI on agent-authored PRs | promptfoo / DeepEval / lint / secret scans run as normal CI gates on every PR the agent opens. |
| OpenCode | Custom provider baseURL in opencode.json [25] |
Route all model traffic through a verification gateway (LiteLLM, Portkey, Guardrails Server) - checks apply to every request without touching agent code. |
| OpenCode | JS/TS plugin files (plugin dir) |
tool.execute.before/after hooks - validate or block tool calls in-agent, same role as Devin's PreToolUse. |
| OpenCode | MCP servers | Same as Devin - verifiers exposed as tools. |
Note: Devin's model traffic can't be routed through a custom gateway (managed model catalog), so for Devin the verification boundary is hooks + MCP + CI on PRs rather than the LLM request path.
A. LLM gateways - verify at the API boundary
Best fit for OpenCode (point baseURL at the gateway) and any app code. One config change puts a deterministic pipeline in front of every model call.
LiteLLM Proxy - https://github.com/BerriAI/litellm
Open-source LLM gateway with a built-in guardrails framework: Presidio PII masking, Guardrails AI, Lakera, Aporia, Bedrock, and a generic_guardrail_api webhook for custom checks. Modes: pre_call, during_call, post_call, logging_only - plus routing, fallbacks, spend tracking, and OTel export. Cost: free OSS; enterprise features paid. Use: litellm --config config.yaml then set OpenCode baseURL to http://localhost:4000/v1; declare guardrails in the same YAML.
Portkey (PRISMA AIRS AI Gateway) - https://github.com/Portkey-AI/gateway
AI gateway with 40+ guardrails: JSON Schema match, regex, contains-code, PII redaction, prompt-injection and gibberish detection, plus partner checks (Patronus, Palo Alto AIRS) and bring-your-own webhooks. Also retries/fallbacks, caching, and observability. Cost: free developer tier (basic guardrails); paid Production/Enterprise tiers. Use: hosted or self-hosted; swap baseURL to Portkey's OpenAI-compatible endpoint and attach guardrail configs.
OpenRouter - https://openrouter.ai
Multi-provider gateway; structured outputs via strict json_schema, require_parameters routing, zdr endpoints, and Response Healing for broken JSON - see Β§7. Cost: pay-per-token passthrough, no subscription. Use: baseURL: https://openrouter.ai/api/v1 in OpenCode or any OpenAI-compatible client.
Guardrails AI Server - https://github.com/guardrails-ai/guardrails
Runs Guard configs as a REST service with an OpenAI-compatible endpoint; validators from the Guardrails Hub (regex, schema, PII, topic, jailbreak, hallucination checks) with per-validator failure actions (reask, fix, filter, refrain). Cost: free OSS; Hub has free and paid validators. Use: guardrails start, point clients at it, or use the Guard SDK directly (see Β§4.2).
B. Agent-side hooks and plugins - verify inside the loop
Devin lifecycle hooks - https://devin.ai (built-in)
Deterministic gates as shell commands wired to lifecycle events - the closest thing to an in-band verification pipeline for Devin [24]. Cost: free (part of Devin; model usage billed normally via ACUs). Use: .devin/hooks.v1.json:
{
"PreToolUse": [
{ "matcher": "exec",
"hooks": [{ "type": "command", "command": "./scripts/verify-command.sh" }] },
{ "matcher": "^(edit|write|apply_patch)$",
"hooks": [{ "type": "command", "command": "gitleaks stdin || exit 2" }] }
],
"Stop": [
{ "matcher": "",
"hooks": [{ "type": "command",
"command": "./scripts/tests-pass.sh || echo '{\"decision\":\"block\",\"reason\":\"Tests must pass before stopping.\"}'" }] }
]
}
PreToolUse on exec/edit blocks destructive commands or secret-bearing writes; updatedInput can rewrite args; a Stop hook that blocks until CI checks pass is a hard quality gate. Works in CLI, Desktop, and cloud sessions.
OpenCode plugins - https://opencode.ai/docs/plugins/
Drop-in JS/TS files in the project or global plugin/ dir; hook tool.execute.before/after to inspect or block tool calls, or hook model events to post-check output. Cost: free (OpenCode is OSS; you pay provider token costs). Use: write a plugin that shells out to your verifier; throwing in tool.execute.before blocks the call.
Static checkers as verification scripts - gitleaks, TruffleHog, Semgrep, project linters
The hook/plugin scripts above should just call deterministic tools: gitleaks/trufflehog on file contents (secrets escape), semgrep on generated code (dangerous patterns), tsc/ruff/go vet (does it compile), sqlglot on generated SQL. Cost: free OSS (Semgrep has paid tiers). Use: invoke from Devin PreToolUse/PostToolUse, OpenCode plugins, or pre-commit hooks - same scripts work in all three.
C. Self-hosted verification services and libraries
Microsoft Presidio - https://github.com/microsoft/presidio
PII detection and anonymization (NER + recognizers); anonymize input, deanonymize output. Cost: free OSS. Use: Docker services (presidio-analyzer, presidio-anonymizer) behind LiteLLM's presidio guardrail or called directly.
NLI grounding models - HHEM-2.1-open, MiniCheck, AlignScore - see Β§4.3
Small classifiers scoring (source, claim) entailment; the cheap deterministic-ish L2 check. Cost: free open weights; runs on CPU. Use: wrap in a FastAPI/Flask scorer called by your pipeline, gateway webhook, or an MCP tool the agent must call before finishing.
NeMo Guardrails - https://github.com/NVIDIA-NeMo/Guardrails
Declarative rails (Colang + YAML) for input/dialog/retrieval/execution/output; policy-as-code with OTel metrics. Cost: free OSS (Apache 2.0). Use: nemoguardrails server exposes the guarded app as a service; or embed in Python.
Llama Guard / ShieldGemma - Meta/Google open-weight safety classifiers Classify prompts and responses against harm taxonomies - the L4 check. Cost: free weights; self-host inference. Use: run on Ollama/vLLM; call from gateway webhook or post-call hook.
LLM Guard (Protect AI) - https://github.com/protectai/llm-guard Input scanners (injection, PII, toxicity, topics) and output scanners (moderation, malicious URLs, deanonymization). Cost: free OSS. Use: Python library or its API server behind a gateway.
Instructor / BAML - https://github.com/instructor-ai/instructor , https://baml.ai Client-side structured output: schema β prompt injection β parse β validate β bounded retries (see Β§4.2). BAML adds typed function definitions, multi-provider fallbacks, and a deterministic parser. Cost: free OSS. Use: in application code; works with OpenRouter, Genkit-adjacent Gemini calls, and local Ollama/vLLM endpoints.
QWED - https://docs.qwedai.tech Deterministic formal verification (SymPy, Z3, static analysis) across math/logic/code/SQL domains - fail-safe rejects anything unverifiable [6]. Cost: free OSS (Apache 2.0). Use: library integration with LangChain/CrewAI/agent frameworks.
D. CI quality gates and eval harnesses - verify before merge
promptfoo - https://github.com/promptfoo/promptfoo
Eval + red-team in CI: promptfoo eval on golden prompts, promptfoo redteam run for injection/jailbreak/PII attack suites; quality gates via --fail-on-error / --pass-rate-threshold; official GitHub Action posts PR comments [26]. Cost: free OSS (MIT); paid cloud/enterprise. Use: npx promptfoo@latest eval -c promptfooconfig.yaml in a PR workflow on agent-authored changes; scheduled redteam for model drift.
DeepEval - https://github.com/confident-ai/deepeval
pytest-integrated evals - assert_test with faithfulness/hallucination/relevancy metrics; hybrid and deterministic "system_one" modes reduce judge cost [23]. Cost: free OSS; Confident AI platform has free tier + paid. Use: normal pytest job in CI; parametrize over a golden dataset.
RAGAS - https://github.com/explodinggradients/ragas RAG quality metrics (faithfulness, relevancy, contextual precision/recall) for offline eval. Cost: free OSS. Use: batch eval script in CI or against logged production traces.
Langfuse / Phoenix evaluators - https://langfuse.com , https://github.com/Arize-ai/phoenix
Run evaluators over production traces; turn real escapes into regression cases. Cost: both free OSS self-hosted; managed cloud tiers. Use: trace ingest (see AI-Agent-Monitoring.md) + evaluator pipelines + export flagged cases to the golden dataset.
E. Managed cloud security services
Google Cloud Model Armor - https://cloud.google.com/security/products/model-armor REST API screening prompts/responses/tool calls for injection, jailbreak, malware URLs, and sensitive data (via Sensitive Data Protection); model-agnostic - works in front of Gemini, OpenRouter, or local models [16]. Cost: paid GCP service, usage-based. Use: REST call in your pipeline or integrated with Vertex AI / Genkit flows (Β§6).
Azure AI Content Safety / Prompt Shields - https://azure.microsoft.com/products/ai-services/ai-content-safety Managed injection and harmful-content classifiers. Cost: Azure usage-based, free tier for low volume. Use: REST call in L0/L4 checks.
AWS Bedrock Guardrails - https://aws.amazon.com/bedrock/guardrails/
Managed filters (topics, PII, grounding/contextual-grounding check for RAG) attachable to any model through Bedrock - also usable as a standalone ApplyGuardrail API on arbitrary text. Cost: per-unit AWS pricing. Use: apply to output text from any provider, or natively on Bedrock models.
References for solutions
- Devin CLI docs β Lifecycle Hooks / Hooks overview β local docs
share/devin/docs/extensibility/hooks/ - OpenCode docs β Providers (custom baseURL) β https://opencode.ai/docs/providers/ ; Plugins β https://opencode.ai/docs/plugins/
- promptfoo β CI/CD integration β https://www.promptfoo.dev/docs/integrations/ci-cd/ ; promptfoo-action β https://github.com/promptfoo/promptfoo-action