Model-Agnostic AI Inside the Product: Layers That Survive a Provider Swap

Architecture for an internal AI platform: contracts, tools, prompts-as-config, validation, eval, routing and observability — so model swaps, cross-model drift and same-model changes do not break process outcomes.

Model-Agnostic AI Inside the Product: Layers That Survive a Provider Swap

If swapping the model requires rewriting your product logic, you did not integrate an LLM. You married a vendor.

That is only the obvious failure mode. In production the harder failures look quieter:

  1. Provider swap — OpenAI → Anthropic → Azure OpenAI / Gemini / a self-hosted vLLM endpoint. Tool schemas, streaming events, and refusal styles do not match 1:1.
  2. Cross-model behaviour — GPT-4.1, Claude Sonnet, and Gemini Flash on the same prompt and tools classify a Zendesk ticket differently, emit different JSON field names, or call a CRM tool with different argument shapes.
  3. Same-model drift — you never changed the vendor string, yet behaviour moved: a silent model alias upgrade, a temperature / top_p tweak, a system-prompt edit in a shared library, noisier RAG context, or a provider-side safety filter that starts refusing a previously accepted case.

The platform job is the same for all three: keep the process outcome inside a measured threshold. Bit-identical prose is not the KPI.

This article is for architects and product engineers building an internal AI platform inside a product: classify, route, draft, extract, decide. It sits next to SDLC vs ADLC when the feature is an agent, and next to AI trends that change delivery when you choose what to fund.

The layer stack (centre of the design)

Read from the process down to the vendor. Anything that must survive a swap or a drift lives above the inference call.

Model-agnostic AI platform layers: contract through observability above a swappable LLM

# Layer Owns Breaks when missing
1 Process / step contract Typed input and output for each step (fields, enums, error codes) Downstream services parse free text forever
2 Tool / data adapters CRM, tickets, docs, internal APIs, MCP-style tool calling Salesforce / Jira / Stripe rewired per vendor SDK
3 Prompt / policy config System instructions, tone, escalation rules (versioned) Behaviour buried in vendor-specific code
4 Structured output + validation Schema parse, reject/repair, retry or HITL “Almost JSON” updates production records
5 Evaluation harness Fixed cases + thresholds (quality, latency, cost per task) Cutover and drift detection are guesses
6 Routing / fallback Primary, secondary, rule-based path on failure Single-vendor outage stops the process
7 Observability & cost Logs by step_id, process_id, model_id You cannot prove “no impact” after a change

The LLM sits under this stack. It fills the contract. It does not define the product.

Concrete product steps (what “platform” means in practice)

Think in steps, not chat windows. Three product patterns that force the stack:

Product step Contract fields (sketch) Side effect only after validation
Support triage in Zendesk / Jira Service Management category, priority, confidence, escalate Set fields / route queue; never invent a category outside the enum
Invoice / PO extraction into NetSuite / SAP / a custom ERP vendor, invoice number, currency, line items Create draft bill; HITL if confidence is below threshold or schema fails
CRM enrichment from a call transcript (HubSpot / Salesforce) account id, next action, owner hint, summary Patch Opportunity; block if account id is not in your CRM adapter

Each row is a step id in the platform (support.triage.v1, finance.invoice_extract.v1, …). The model is only the candidate generator for that step’s output schema.

Runtime flow (one step)

flowchart TD
  UI[Product process / UI] --> C[1 Contract: typed step in]
  C --> T[2 Tools / data adapters]
  T --> P[3 Prompt / policy version]
  P --> R[6 Router: primary / secondary / rules]
  R --> M[LLM provider]
  M --> V[4 Validate against contract]
  V -->|valid| SE[Side effect: Zendesk / ERP / CRM]
  V -->|invalid| RP{Repair once?}
  RP -->|yes| R
  RP -->|no| HITL[HITL or deterministic fallback]
  HITL --> SE
  SE --> O[7 Observe + cost by step_id / model_id]
  E[5 Eval suite] -.->|gates cutover and drift checks| R

Eval (layer 5) is not on every request; it gates cutovers and scheduled drift checks. Validation (layer 4) is on the hot path before any write.

1. Process contract above the model

Own a DTO per step: fields, enums, ranges, error codes — expressed as JSON Schema, Protobuf, or your service’s usual schema tool. Example shape for triage:

Field Type / constraint Used for side effects?
category enum: billing, bug, access, other Yes — queue / label
priority enum: p1, p2, p3 Yes — SLA path
confidence number 0–1 Yes — escalate threshold
escalate boolean Yes — human queue
rationale short string No — UI / audit only

The platform validates against that contract before any Zendesk field update or Jira transition. Models produce candidates. The contract is the product API.

This is why structured decisions matter more than chat fluency. Related reading: System One Models and Jev; here the point is the platform contract, whoever supplies the tokens.

2. Tool and data adapters separate from inference

Normalize vendor tool calling into your tool names:

  • OpenAI / Anthropic / Gemini tool formats and MCP tool servers all map to one adapter surface: get account, create ticket comment, search docs.
  • The adapter owns OAuth, retries, idempotency keys, and PII redaction for HubSpot, Salesforce, Jira, Confluence, object storage, and so on.

When you change provider, you change how the model is invoked. You do not rewrite how Opportunity records are patched. Hardcoding one vendor’s tool payload shape into a domain service is how a “quick model trial” becomes a rewrite.

Buy-side help here is partial: MCP servers, Composio-style connector products, or an iPaaS for ops workflows. The product’s permission model and ERP/CRM semantics stay yours.

3. Prompt and policy as versioned config

Store system prompts and policies as versioned artefacts ([email protected]), with environment pins (dev / stage / prod). Managed options: Langfuse prompt management, PromptLayer, Humanloop, or a simple Git + config service with an immutable version id logged on every run.

A cutover then means: same policy version, new model id, same eval suite. If behaviour must change, bump the policy deliberately — not by editing a string inside one team’s vendor SDK wrapper.

4. Structured output and a validation gate

Never trust free text as a side-effect trigger.

flowchart LR
  M[Model candidate] --> VS[Vendor structured output if available]
  VS --> LV[Local schema validation]
  LV -->|pass| W[Allow write]
  LV -->|fail| RP[Repair prompt once]
  RP --> M2[Model again]
  M2 --> LV
  LV -->|fail again| FB[HITL or rules fallback]
  FB --> W

Ask for structured output where the vendor supports it (OpenAI Structured Outputs, Anthropic schema-shaped tool choice, Gemini controlled generation). Always re-validate locally — vendor guarantees still fail on truncated streams, partial tool args, and cross-model trials. Libraries (Instructor, Outlines, BAML) help; the gate is yours: no NetSuite write until the contract passes.

Without this gate, “almost correct” answers from one model look like regressions even when another was only lucky on your golden set. The gate also absorbs same-model variance when sampling is not deterministic.

5. Evaluation harness as CI

Before any provider change — and on a schedule for drift — run a fixed suite of real cases: redacted production tickets and documents, edge cases (empty body, mixed language, OCR noise, prompt injection), and cost / latency outliers.

Thresholds live next to the suite, for example: at least 95% schema-valid, at least 90% label agreement with human gold, escalation rate within ±2 pp of baseline, p95 under 4 s, cost per successful step within budget.

Buy-side: Promptfoo, LangSmith datasets and evaluators, Braintrust, Arize / Galileo-class LLM eval. Soft talk about “better models” without your cases is marketing. Treat the harness like CI for agent lifecycles when the feature decides at runtime.

6. Routing and fallback

This is the layer where OpenRouter belongs: a unified API across many providers, with routing and failover. It is not the contract and not validation — it decides where the call goes and what happens when primary fails or is too expensive.

flowchart TD
  Step[platform.runStep support.triage.v1] --> Pol{Routing policy}
  Pol -->|happy path| P[Primary model]
  Pol -->|timeout / 429 / 5xx| S[Secondary model]
  Pol -->|binary cheap check| Rules[Deterministic rules]
  P --> Out[Candidate output]
  S --> Out
  Rules --> Out
  Out --> Val[Layer 4 validation]

Options beyond a fully custom gateway:

Option Role
OpenRouter Multi-provider API, routing, fallbacks
LiteLLM (proxy or cloud) Same pattern, often self-hosted as an internal gateway
Portkey Gateway with routing, retries, guardrails, logs
Cloudflare AI Gateway Proxy, cache, limits, analytics, fallbacks
AWS Bedrock / Azure AI / Vertex Multi-model inside one cloud
Intelligent routers (e.g. Not Diamond, Martian) Choose a model per request for quality / cost — still above your contract

The feature should call runStep(stepId, input), not a hard-coded model string. Swapping primary is a config change gated by the eval suite. Business rules such as “confidence below threshold → secondary, then escalate” still live in your policy, even when OpenRouter or LiteLLM carries the bytes.

7. Observability and cost attribution

Log one trace per step attempt: prompt/policy version, tool calls, raw model output, validation errors, latency, token and dollar cost — keyed by process_id, step_id, model_id, provider.

Buy-side: Langfuse, LangSmith, Helicone, Arize Phoenix, Datadog LLM observability, OpenTelemetry exporters. Without this, “we switched provider and nothing broke” is folklore: you cannot compare category distributions, repair rates, or cost per successful Zendesk update.

Buy vs build by layer

Almost nobody sells the full seven-layer stack as one box. Teams buy slices and keep process semantics in-house:

Layer Usually buy / adopt Usually build
1 Contract Schema tooling only Step DTOs and enums tied to the product
2 Tools / adapters MCP servers, connector products, iPaaS for ops Permissions, idempotency, ERP/CRM semantics
3 Prompt / policy Langfuse, PromptLayer, Humanloop Escalation and locale policy content
4 Validation / guardrails Guardrails AI, Bedrock Guardrails, BAML / Instructor-class tools Gate before your side effects
5 Eval Promptfoo, LangSmith, Braintrust Golden cases from real processes
6 Routing / fallback OpenRouter, LiteLLM, Portkey, cloud AI gateways Per-step routing policy
7 Observability / cost Langfuse, Helicone, Arize, APM LLM packs step_id taxonomy and unit economics

HITL on money, identity, and irreversible posts is process design — not a checkbox in a model vendor console.

Human-in-the-loop stays on risk, not on every token

Control points — refunds, identity changes, irreversible ERP posts — belong to the process, not the vendor. A model swap should not move those points unless evaluation showed a new failure mode (for example, a cheaper model that under-escalates P1 tickets).

Learning stage → autopilot after process-owner sign-off still applies. The platform encodes where HITL is mandatory (invoice extract always drafts; a human posts).

What “does not affect the result” really means

Two LLMs will not emit identical paragraphs. The same model at temperature 0.7 will not either.

Stable result means: same route taken, same fields filled within validation, same escalation behaviour, same user-visible state in Zendesk / ERP / CRM — measured on the eval suite and live monitors. Bit-identical text is the wrong success criterion; business outcome within threshold is the right one — across providers, across models, and across time on one model id.

Minimal platform vs overbuilt theatre

You do not need an “AI centre of excellence” slide deck. You need:

  1. Contracts for the steps you automate
  2. One tool adapter surface
  3. Versioned prompts / policies
  4. Validation before side effects
  5. A small eval suite before any model or provider change
  6. Basic routing (OpenRouter, LiteLLM, or equivalent) and structured logging

Start with one step. Expand when a second product team shares the same stack. For why demos stall without these layers, see AI transformation blockers.

What to do next

Pick one product step with a clear schema. Put validation and logging around it. Freeze twenty eval cases from real tickets or documents. Only then compare two models — or the same model a month apart — on that suite.

If you want a partner to design that platform layer while senior engineers stay accountable for production behaviour, talk to us about AI development or AI automation, or contact us.