Search Tutorials
--Ads--Model-Agnostic RAG: Switching Between LLM Providers
Design a RAG pipeline that can switch LLM and embedding providers through one small interface.
LLM providers release new models every few months, prices change, regional availability differs, and outages happen. A RAG application that calls one provider's SDK from everywhere in its code is hard to move. A model-agnostic design puts every model call behind a small interface, so you can switch between Anthropic, OpenAI, Google Gemini, Amazon Bedrock or a local model through Ollama by changing configuration, compare them on the same test set, and fall back to another provider when one fails.
What you will learn
- Why provider lock-in hurts RAG applications, and what should and should not be abstracted
- How to define small chat and embedding interfaces with adapters for several providers
- How to choose providers from configuration and add automatic fallback
- How to keep prompts, embeddings and evaluation portable across models
Prerequisites
- Choosing an LLM for RAG
- Build a Minimal RAG System from Scratch
- API keys for the providers you want to try, set as environment variables
What to abstract, and what not to
| Abstract (behind an interface) | Keep provider-specific (inside adapters) |
|---|---|
| "Answer this prompt with this system instruction" | SDK clients, request formats, response parsing |
| "Embed these documents / this query" | Model names, query prefixes, batch limits |
| Errors that mean "try another provider" | Provider error classes and retry settings |
| Usage reporting (tokens, latency) | Optional features: caching, effort levels, tool formats |
Keep the interface small. A lowest-common-denominator API that tries to expose every feature of every provider becomes as complex as the SDKs themselves. Expose the few operations your RAG pipeline needs, and let each adapter use its provider's best settings internally.
Step 1: Define the interfaces
from dataclasses import dataclass, field
from typing import Protocol
@dataclass
class Answer:
text: str
provider: str
model: str
usage: dict = field(default_factory=dict)
class ChatModel(Protocol):
name: str
def generate(self, system: str, prompt: str, max_tokens: int = 1000) -> Answer: ...
class ProviderError(Exception):
"""Raised by adapters for failures where another provider may succeed (outage, rate limit, timeout)."""
The pipeline only ever sees ChatModel.generate and Answer. Adapters translate provider errors that are worth retrying elsewhere into ProviderError; configuration mistakes (a wrong API key, an unknown model) should still fail loudly.
Step 2: Write adapters
Each adapter is a few lines around the provider's official SDK. SDK imports happen inside the constructor, so you only need to install the packages for the providers you use.
class AnthropicChat:
def __init__(self, model: str = "claude-opus-5-5"):
import anthropic
self.client, self.model, self.name = anthropic.Anthropic(), model, f"anthropic:{model}"
self.errors = (anthropic.APIConnectionError, anthropic.RateLimitError, anthropic.InternalServerError)
def generate(self, system: str, prompt: str, max_tokens: int = 1000) -> Answer:
try:
r = self.client.messages.create(model=self.model, max_tokens=max_tokens, system=system,
messages=[{"role": "user", "content": prompt}],
output_config={"effort": "low"})
except self.errors as e:
raise ProviderError(str(e)) from e
text = "".join(b.text for b in r.content if b.type == "text")
return Answer(text, "anthropic", self.model, {"input": r.usage.input_tokens, "output": r.usage.output_tokens})
class OpenAIChat:
def __init__(self, model: str = "gpt-6.2-sol"):
import openai
self.client, self.model, self.name = openai.OpenAI(), model, f"openai:{model}"
self.errors = (openai.APIConnectionError, openai.RateLimitError)
def generate(self, system: str, prompt: str, max_tokens: int = 1000) -> Answer:
try:
r = self.client.responses.create(model=self.model, instructions=system, input=prompt,
max_output_tokens=max_tokens)
except self.errors as e:
raise ProviderError(str(e)) from e
return Answer(r.output_text, "openai", self.model)
class GeminiChat:
def __init__(self, model: str = "gemini-4-hydrogen"):
from google import genai
from google.genai import types
self.client, self.types, self.model, self.name = genai.Client(), types, model, f"gemini:{model}"
def generate(self, system: str, prompt: str, max_tokens: int = 1000) -> Answer:
r = self.client.models.generate_content(
model=self.model, contents=prompt,
config=self.types.GenerateContentConfig(system_instruction=system, max_output_tokens=max_tokens))
return Answer(r.text or "", "gemini", self.model)
class OllamaChat:
def __init__(self, model: str = "gemma4"):
import ollama
self.ollama, self.model, self.name = ollama, model, f"ollama:{model}"
def generate(self, system: str, prompt: str, max_tokens: int = 1000) -> Answer:
try:
r = self.ollama.chat(model=self.model, messages=[{"role": "system", "content": system},
{"role": "user", "content": prompt}])
except (self.ollama.ResponseError, ConnectionError) as e:
raise ProviderError(str(e)) from e
return Answer(r.message.content, "ollama", self.model)
class BedrockChat:
def __init__(self, model: str):
import boto3
self.client, self.model, self.name = boto3.client("bedrock-runtime"), model, f"bedrock:{model}"
def generate(self, system: str, prompt: str, max_tokens: int = 1000) -> Answer:
r = self.client.converse(modelId=self.model, system=[{"text": system}],
messages=[{"role": "user", "content": [{"text": prompt}]}],
inferenceConfig={"maxTokens": max_tokens})
return Answer(r["output"]["message"]["content"][0]["text"], "bedrock", self.model, r.get("usage", {}))
Notice what the adapters do not pass: sampling parameters such as temperature. Support differs between providers and models (for example, current Claude models do not accept them), so a shared temperature argument would break some providers. If you need such settings, add them per adapter. The model names are examples from each provider's documentation as of November 2026; take current names from their model pages.
Step 3: Choose providers from configuration
Select models with a provider:model string from an environment variable, so switching needs no code change:
import os
ADAPTERS = {"anthropic": AnthropicChat, "openai": OpenAIChat, "gemini": GeminiChat,
"ollama": OllamaChat, "bedrock": BedrockChat}
def chat_model(spec: str) -> ChatModel:
provider, _, model = spec.partition(":")
if provider not in ADAPTERS:
raise ValueError(f"unknown provider '{provider}'; choose one of {sorted(ADAPTERS)}")
return ADAPTERS[provider](model) if model else ADAPTERS[provider]()
# e.g. LLM_MODELS="anthropic:claude-opus-5-5,openai:gpt-6.2-sol,ollama:gemma4"
def models_from_env(default: str = "anthropic:claude-opus-5-5") -> list[ChatModel]:
return [chat_model(spec.strip()) for spec in os.environ.get("LLM_MODELS", default).split(",") if spec.strip()]
Step 4: Add fallback
A fallback chain tries each configured model in order and moves on only for ProviderError. It records which model answered, so you can monitor how often fallback happens:
import logging
import time
log = logging.getLogger("llm")
class FallbackChat:
def __init__(self, models: list[ChatModel]):
self.models, self.name = models, "fallback(" + ", ".join(m.name for m in models) + ")"
def generate(self, system: str, prompt: str, max_tokens: int = 1000) -> Answer:
errors = []
for model in self.models:
start = time.perf_counter()
try:
answer = model.generate(system, prompt, max_tokens)
except ProviderError as e:
log.warning("provider failed: %s: %s", model.name, e)
errors.append(f"{model.name}: {e}")
continue
answer.usage["latency_ms"] = round((time.perf_counter() - start) * 1000)
return answer
raise ProviderError("all providers failed: " + " | ".join(errors))
Fallback models must be approved for the same data. If a confidential question may only go to a model in your own cloud account, do not let it fall back to a public API.
Step 5: Use it in the RAG pipeline
from rag_helpers import embed
import numpy as np
SYSTEM = ("Answer only from the numbered sources and cite them like [1]. "
"If the sources do not contain the answer, say you could not find it.")
CHUNKS = ["Employees get 18 days of paid leave in their first year.",
"Up to 5 unused leave days can be carried over to next year."]
VECTORS = embed(CHUNKS)
def rag_answer(question: str, llm: ChatModel, k: int = 2) -> Answer:
scores = VECTORS @ embed(question, query=True)[0]
top = np.argsort(-scores)[:k]
sources = "\n".join(f"[{n}] {CHUNKS[i]}" for n, i in enumerate(top, start=1))
return llm.generate(SYSTEM, f"Sources:\n{sources}\n\nQuestion: {question}", max_tokens=400)
llm = FallbackChat(models_from_env())
answer = rag_answer("Can I carry over unused leave?", llm)
print(f"{answer.provider}/{answer.model}: {answer.text}")
anthropic/claude-opus-5-5: Yes. You can carry over up to 5 unused leave days to next year [2].
The retrieval code and the prompt do not change when you switch providers; only the LLM_MODELS setting does.
Step 6: Test without calling any provider
An interface also makes testing easy. A fake model checks that the pipeline builds the right prompt and handles fallback, without network calls or cost:
class FakeChat:
def __init__(self, name: str, reply: str = "", fail: bool = False):
self.name, self.reply, self.fail, self.prompts = name, reply, fail, []
def generate(self, system: str, prompt: str, max_tokens: int = 1000) -> Answer:
self.prompts.append(prompt)
if self.fail:
raise ProviderError("simulated outage")
return Answer(self.reply, "fake", self.name)
def test_fallback_uses_second_model():
broken, backup = FakeChat("primary", fail=True), FakeChat("backup", reply="ok [1]")
answer = FallbackChat([broken, backup]).generate("system", "Sources:\n[1] text\n\nQuestion: q")
assert answer.model == "backup" and answer.text == "ok [1]"
assert len(broken.prompts) == 1 and len(backup.prompts) == 1
test_fallback_uses_second_model()
print("fallback test passed")
fallback test passed
Embeddings are different: switching means re-indexing
Chat models can be swapped per request. Embedding models cannot: the query must be embedded by the same model (with the same settings) that embedded the documents. Hide embedding providers behind an interface too, but tie each index to one embedding configuration and switch with a migration, as described in Storing and Managing Embeddings:
class Embedder(Protocol):
space_id: str # model + settings; part of the index name
def embed_documents(self, texts: list[str]) -> list[list[float]]: ...
def embed_query(self, text: str) -> list[float]: ...
Never add an embedding fallback to a different model at query time: the results would look plausible but be close to random.
Keep prompts portable
- Put instructions in the system prompt and sources in clearly marked blocks; every major provider handles this layout well.
- Avoid relying on one provider's special features in the core prompt (for example a specific tool format); use them inside adapters.
- Ask for citations in a simple, checkable format such as
[1], and validate it in code rather than trusting each model to follow it identically. - Expect differences in answer length, refusals and formatting; normalise output where it matters.
Compare providers on your test set
Because every model implements the same interface, comparing them is a loop. Run your golden test set through each configured model and score the answers with the same metrics (RAGAS Tutorial):
def compare(models: list[ChatModel], questions: list[str]) -> dict[str, list[Answer]]:
results = {}
for model in models:
results[model.name] = [rag_answer(q, model) for q in questions]
return results # score each list with your evaluation metrics, then compare quality, latency and cost
Framework alternatives
Frameworks provide similar abstractions. LangChain's init_chat_model("provider:model") creates a chat model for many providers from one string (LangChain Chat Models), LlamaIndex has interchangeable LLM classes, and API gateways and proxy servers can expose many providers behind one endpoint. A small interface of your own is still useful: it documents exactly what your application needs and keeps framework changes contained.
Common errors and troubleshooting
- Unexpected parameter errors after switching: a shared setting (for example temperature) is not supported by the new model; move it into the adapter.
- Fallback hides a real problem: wrong keys or model names should raise immediately, not trigger fallback; only wrap transient errors in
ProviderError. - Poor results after changing the embedding model: the index was built with the old model; re-index.
- Answers differ in style between providers: tighten the prompt's format rules and post-process output.
Key takeaways
- Put LLM calls behind a small interface with one adapter per provider.
- Select models with configuration strings and use a fallback chain for transient failures.
- Keep sampling settings and special features inside adapters; keep prompts simple and portable.
- Chat models can be switched per request; embedding models require re-indexing.
Frequently asked questions
Does fallback change answer quality?
It can. Evaluate every model in the chain on your test set, and alert when fallback rates rise so you know when users are getting answers from the backup model.
Can I route questions to different models on purpose?
Yes. A router can send simple questions to a cheaper model and hard ones to a stronger model, using the same interface; see Cost Optimization and Query Routing.
Practice exercises
- Configure two providers and run ten test questions through each; compare answers, latency and token usage.
- Add a
stream()method to the interface and implement it for two providers.