Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Beyond Prototypes: Engineering Resilient AI Systems with Deterministic Guardrails

This article details a production-grade AI engineering framework that wraps probabilistic LLMs in deterministic harnesses, covering four-layer guardrails, multi-provider failover, dynamic few-shot prompting, and CI/CD quality gates with manifest-driven evaluation.

The article argues that moving AI from demo to production requires wrapping probabilistic LLMs in deterministic software harnesses, not just better prompts. It presents a four-layer Harness architecture that constrains non-determinism at every stage.

Harness Architecture: Four Deterministic Layers

Each request passes through four layers:

Input Guardrails – content sanitization, prompt injection detection, rate limiting and authentication.

Orchestration Layer – assembles dynamic context: RAG fragments, dynamic few-shot examples retrieved by semantic similarity, and system prompt rendering.

LLM Core Engine – locks model version, sets temperature=0 for maximum determinism, enforces strict latency/timeouts with automatic failover.

Output Validation Layer – schema parsing (e.g., Pydantic), AST/SQL constraint checks (blocking DROP, UPDATE, etc.), graceful fallback on failure.

Guardrails: Infrastructure-Level Safety Boundaries

Prompt engineering is not security. Safety must live in infrastructure, decoupled from prompts.

Rule 1: Isolation & Least Privilege

AI services connect via dedicated, heavily restricted service accounts. For read-only tasks, use a read-only DB user limited to SELECT on whitelisted tables. Write credentials never appear in the agent's runtime environment.

Rule 2: Non-Negotiable Input/Output Validation

For Text-to-SQL, every generated statement must pass an AST validator before hitting the database. The article provides a complete validate_sql implementation:

# security/sql_validator.py
import re

_BANNED_KEYWORDS = {"INSERT", "UPDATE", "DELETE", "DROP", "ALTER", "TRUNCATE", "CREATE", "EXEC", "EXECUTE"}
_TABLE_REF_RE = re.compile(r"\bFROM\s+([\[\]\w\.]+)", re.IGNORECASE)

def validate_sql(sql: str, allowed_tables: set[str], default_row_limit: int | None = 50) -> str:
    if not sql or not sql.strip():
        raise ValueError("SQL string is empty.")
    sql = sql.strip()
    # Reject any non-SELECT immediately
    if not re.match(r"^\s*SELECT\b", sql, re.IGNORECASE):
        raise ValueError(f"Only SELECT queries are allowed. Got: {sql[:80]!r}")
    upper_sql = sql.upper()
    for keyword in _BANNED_KEYWORDS:
        if re.search(rf"\b{keyword}\b", upper_sql):
            raise ValueError(f"Prohibited keyword detected in query: {keyword}")
    # Validate table references against whitelist
    table_refs = _TABLE_REF_RE.findall(sql)
    if not table_refs:
        raise ValueError("Query contains no explicit FROM clause.")
    expanded_allowed = allowed_tables | {t.split('.')[-1] for t in allowed_tables}
    for ref in table_refs:
        normalized = re.sub(r"[\[\]]", "", ref.upper()).strip()
        if normalized not in expanded_allowed:
            raise ValueError(f"Unauthorized table reference: {ref!r}. Allowed tables: {', '.join(sorted(allowed_tables))}")
    # Auto-append LIMIT to prevent OOM
    if default_row_limit is not None and "LIMIT" not in upper_sql:
        sql = f"{sql} LIMIT {default_row_limit}"
    return sql

This deterministic safety net enforces read-only execution, blocks destructive commands, enforces table whitelists, and prevents unbounded result sets.

Multi-Provider Failover Pattern

Production systems cannot depend on a single LLM vendor. The article shows a ProviderManager using LangChain that initializes primary (Anthropic Claude) and fallback (Azure OpenAI) models, and an async wrapper that enforces hard timeouts and seamless failover:

# llm/provider_manager.py
import logging
from langchain_anthropic import ChatAnthropic
from langchain_core.language_models import BaseChatModel
from langchain_openai import AzureChatOpenAI
from config import CONFIG

logger = logging.getLogger(__name__)

class ProviderManager:
    def __init__(self) -> None:
        self._use_fallback = False
        self.primary: BaseChatModel = ChatAnthropic(
            anthropic_api_url=CONFIG.AZURE_CLAUDE_ENDPOINT,
            anthropic_api_key=CONFIG.AZURE_CLAUDE_API_KEY,
            model=CONFIG.AZURE_CLAUDE_DEPLOYMENT,
            temperature=0,
            max_retries=0,
        )
        self.fallback: BaseChatModel = AzureChatOpenAI(
            azure_endpoint=CONFIG.AZURE_OPENAI_ENDPOINT,
            api_key=CONFIG.AZURE_OPENAI_API_KEY,
            api_version=CONFIG.AZURE_OPENAI_API_VERSION,
            azure_deployment=CONFIG.AZURE_OPENAI_DEPLOYMENT,
            temperature=0,
        )
    @property
    def active(self) -> BaseChatModel:
        return self.fallback if self._use_fallback else self.primary
    @property
    def is_fallback_active(self) -> bool:
        return self._use_fallback
    def switch_to_fallback(self) -> None:
        if not self._use_fallback:
            logger.warning("LLM provider switching to fallback (Azure OpenAI) for remainder of session")
            self._use_fallback = True

provider_manager = ProviderManager()
# llm/failover.py
import asyncio
import logging
from collections.abc import Callable
from typing import Any
from langchain_core.runnables import Runnable
from config import CONFIG
from llm.provider_manager import provider_manager

logger = logging.getLogger(__name__)

async def invoke_with_failover(
    primary_runnable: Runnable,
    fallback_runnable: Runnable,
    inputs: dict,
    invoke_config: dict | None = None,
) -> Any:
    """Invoke primary with timeout; on failure, persistently switch to fallback."""
    if provider_manager.is_fallback_active:
        return await fallback_runnable.ainvoke(inputs, config=invoke_config)
    try:
        return await asyncio.wait_for(
            primary_runnable.ainvoke(inputs, config=invoke_config),
            timeout=float(CONFIG.LLM_FAILOVER_TIMEOUT),
        )
    except Exception as exc:
        logger.error(
            "Primary LLM call failed (%s: %s) — switching to fallback for session",
            type(exc).__name__, exc,
        )
        provider_manager.switch_to_fallback()
        return await fallback_runnable.ainvoke(inputs, config=invoke_config)

async def invoke_agent_with_failover(
    build_fn: Callable[[], Any],
    invoke_inputs: dict,
    invoke_config: dict | None = None,
) -> Any:
    """Build and invoke a LangGraph agent with failover; rebuild graph on fallback."""
    agent = build_fn()
    if provider_manager.is_fallback_active:
        return await agent.ainvoke(invoke_inputs, config=invoke_config)
    try:
        return await asyncio.wait_for(
            agent.ainvoke(invoke_inputs, config=invoke_config),
            timeout=float(CONFIG.LLM_FAILOVER_TIMEOUT),
        )
    except Exception as exc:
        logger.error(
            "Agent LLM call failed (%s: %s) — switching to fallback for session",
            type(exc).__name__, exc,
        )
        provider_manager.switch_to_fallback()
        agent = build_fn()
        return await agent.ainvoke(invoke_inputs, config=invoke_config)

Context Engineering: Managing High-Value Tokens

Treat the context window as precious memory bandwidth. Organize context hierarchically by authority, relevance, recency:

System instructions (role, boundaries, format rules)

Context blocks (RAG chunks, tool outputs, wrapped in delimiters like <context>…</context>)

Few-shot examples

Conversation history (aggressively trimmed/summarized)

Current user payload (placed last for prefix caching)

Dynamic Few-Shot via Semantic Retrieval

Static few-shot is an anti-pattern. Instead, maintain an example store and retrieve semantically similar examples at runtime:

# prompt/dynamic_context.py
from langchain_core.vectorstores import VectorStore

async def build_dynamic_few_shot_context(
    user_input: str,
    example_store: VectorStore,
    k: int = 3,
) -> str:
    """Fetch top-k semantically similar historical examples to shape tone, structure, reasoning."""
    relevant_examples = await example_store.similarity_search(user_input, k=k)
    formatted_blocks = []
    for ex in relevant_examples:
        block = f"<example>
Input: {ex.metadata['input']}
Output: {ex.metadata['output']}
</example>"
        formatted_blocks.append(block)
    formatted = "

".join(formatted_blocks)
    return f"<examples>
{formatted}
</examples>"

This often eliminates the need for fine-tuning by giving the base model the exact context patterns it needs at inference time.

Evaluation Sets & CI/CD Quality Gates

Confidence to deploy requires two test architectures: unit tests with fully mocked LLMs, and integration/regression tests scoring real LLM responses on versioned evaluation sets.

Deterministic vs Probabilistic Metrics

Deterministic metrics (accuracy, precision, recall, F1, ROC AUC) for tasks with clear ground truth (SQL generation, entity extraction). Fast, free, fully reproducible.

LLM-Judge metrics (faithfulness, answer relevancy, semantic similarity, context recall) for open-ended generation (RAG, summarization). Require live LLM calls, adding latency and token cost.

Manifest Files as Single Source of Truth

Evaluation logic lives in declarative YAML manifests (e.g., eval_sets/<workflow>/manifest.yaml), decoupling thresholds and dataset locations from test code:

# eval_sets/sql_generation_chain/manifest.yaml
workflow: sql_generation_chain
version: v1
blob_path: eval-sets/sql_generation_chain/v1.jsonl
thresholds:
  accuracy: 0.95
# eval_sets/rag_workflow/manifest.yaml
workflow: rag_workflow
version: v1
blob_path: eval-sets/rag_workflow/v1.jsonl
thresholds:
  faithfulness: 0.85
  answer_relevancy: 0.80
  context_recall: 0.75

Parity Checks Over String Matching

For Text-to-SQL, compare result sets on a static evaluation DB snapshot, not SQL strings:

# testing/eval_methods.py
from typing import Any
import pytest

async def test_sql_example(
    workflow: Any,
    example: Any,
    db_connection: Any,
) -> bool:
    """Evaluate by comparing result arrays from generated vs expected SQL."""
    generated_sql = await workflow.generate(example.input)
    validated_query = validate_sql(generated_sql, allowed_tables={"USERS", "METRICS"})
    expected_rows = await db_connection.fetch_all(example.expected_sql)
    actual_rows = await db_connection.fetch_all(validated_query)
    assert set(map(tuple, actual_rows)) == set(map(tuple, expected_rows))

CI/CD Integration

The test runner reads the manifest, pulls version-locked evaluation data from blob storage, scores the workflow, logs to MLflow (tagged with Git commit), and blocks deployment on any threshold regression:

# tests/integration/test_quality_gates.py
import os
import json
import yaml
import pytest
import mlflow
from azure.storage.blob import BlobServiceClient
from src.workflows.infosec_rag import InfosecRagChain
from tests.integration.eval_runner import EvalRunner

MANIFEST_PATH = "eval_sets/infosec_rag/manifest.yaml"

@pytest.fixture(scope="module")
def manifest():
    with open(MANIFEST_PATH) as f:
        return yaml.safe_load(f)

@pytest.fixture(scope="module")
def eval_set(manifest):
    client = BlobServiceClient.from_connection_string(os.environ["AZURE_STORAGE_CONNECTION_STRING"])
    blob = client.get_blob_client(container=os.environ["EVAL_BLOB_CONTAINER"], blob=manifest["blob_path"])
    lines = blob.download_blob().readall().decode().strip().splitlines()
    return [json.loads(line) for line in lines]

@pytest.mark.integration
@pytest.mark.asyncio
async def test_infosec_rag_quality(manifest, eval_set):
    runner = EvalRunner(workflow=InfosecRagChain())
    with mlflow.start_run(run_name=f"{manifest['workflow']}_{manifest['version']}"):
        mlflow.set_tags({"workflow": manifest["workflow"], "version": manifest["version"]})
        results = await runner.run(eval_set, metrics=list(manifest["thresholds"].keys()))
        mlflow.log_metrics(results.aggregate())
        thresholds = manifest["thresholds"]
        aggregated_metrics = results.aggregate()
        for metric, threshold in thresholds.items():
            actual = aggregated_metrics[metric]
            assert actual >= threshold, f"{metric} has regressed. Found {actual:.3f}, requires >= {threshold}"

This pipeline enforces rigorous engineering discipline: every change must pass objective, versioned quality gates before reaching production.

Conclusion

Shipping AI features is not about clever prompts in a playground. It's about building resilient infrastructure around non-deterministic cores: strict I/O guardrails, vendor failover, dynamic context injection, and hard metric-driven evaluation gates. Treat LLMs as testable, verifiable software components — not magical black boxes. The AI landscape will keep evolving, but the discipline of rigorous engineering remains the only reliable path to production.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

LangChainAI engineeringfailoverproduction AISQL validationLLM guardrailsCI/CD evaluationdynamic few-shot

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion