By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A support agent should not know that a particular provider exists. The chat model is a dependency you choose per environment, not a fact baked into the agent module. init_chat_model turns the choice into one provider:model string and returns the same interface every time: messages in, messages out, tools bindable. Swapping provider then becomes a configuration change plus a test run, not a rewrite of the loop, the tools or the prompt.
from langchain.agents import create_agent
from langchain.agents.middleware import ModelFallbackMiddleware
from langchain.chat_models import init_chat_model
MODELS = {
"primary": "openai:gpt-4.1-mini",
"backup": "google_genai:gemini-2.0-flash",
"budget": "groq:llama-3.3-70b-versatile",
}
def build_model(role: str, **overrides):
"""One constructor for every provider; only the spec changes."""
return init_chat_model(MODELS[role], temperature=0, **overrides)
primary = build_model("primary")
backup = build_model("backup")
budget = build_model("budget") # a third provider, for routine low-risk traffic
# Standalone chains: the Runnable tries the primary, then the backup.
standalone = primary.with_fallbacks([backup])
# Inside the agent: each failed model call is retried on the backup model.
agent = create_agent(
model=primary,
tools=support_tools, # the tools from the earlier lessons
system_prompt="You are Harbor Helper, the support agent for Harbor Supply.",
middleware=[ModelFallbackMiddleware(backup)],
)ModelFallbackMiddleware is the agent-level form: pass the primary model to create_agent and the fallback models to the middleware. with_fallbacks is the Runnable-level form for standalone chains such as prompt | model | parser. Both wrap the same logical call, so the rest of the system never learns which provider answered. The third entry in the registry is not a fallback: routing routine, low-risk questions to the cheaper Groq-backed model is a per-request decision, and it needs its own quality check because it is a different model doing the work.
Portable is not identical. Two models that both accept messages and tools still differ in context window, tool-calling reliability, structured-output support, modalities, streaming details, latency and price. A swap can compile, pass the type-checker and quietly regress answer quality. Treat the model as a dependency with a compatibility contract, not as a drop-in replacement.
| Capability | Where it bites | Check before the swap |
|---|---|---|
| Tool calling | The loop stalls, or calls the wrong tool with valid JSON | Re-run the trajectory cases from Lesson 18 on the new model |
| Structured output | with_structured_output rejects the schema or drifts | Validate the same Pydantic schema and required fields |
| Context window | Long retrieval prompts overflow mid-conversation | Count system, history, passages and max_tokens against the window |
| Modalities | An image ticket fails only after the swap | Keep a vision-capable model for image tickets, or route them |
| Usage and latency | Token counts, p95 latency and price all move | Read usage metadata from responses; measure p95 per model |
If one model covers the whole workload, keep one. If routine questions can use a cheap model while damaged-item tickets need vision or stronger reasoning, make that a routing rule with a test for each branch. The rule must also cover the fallback: a backup that cannot bind the same tools or honour the same schema must be restricted to answer-only work, or not used for that request at all. A fallback that silently does less than the primary is a quality incident waiting for a bad day.
Three different questions hide behind 'it failed'. Retry means the same model again, because the error was transient. Fallback means a different model, because the provider is down, rate-limited or too slow. Degrade means no model at all: a short apology and a human hand-off. Provider integrations already retry network errors, rate limits and 5xx responses with backoff, and do not retry authentication or invalid-request errors; set timeout and max_retries when you build the model instead of inheriting whatever the default happens to be. LangChain 1.x exposes the same split to the agent loop as middleware: ModelRetryMiddleware for bounded retries and ModelFallbackMiddleware for a second model.
RETRYABLE = {"timeout", "rate_limit", "server_error"}
HAND_OFF = {"auth_error", "invalid_request", "context_overflow"}
def route(error: str) -> str:
"""Retry only what is safe to repeat; hand off everything else."""
if error in RETRYABLE:
return "retry, then fall back"
if error in HAND_OFF:
return "hand off, never retry"
return "fall back and alert"
for error in ("timeout", "auth_error", "context_overflow", "server_error"):
print(f"{error}: {route(error)}")Retries and fallbacks both cost something. A retry consumes another rate-limit slot and more of the request deadline; a fallback doubles the number of models you must evaluate and log. Neither is free resilience.
Key takeaways
The model is configuration: init_chat_model resolves a provider:model spec to the same interface, so tools, prompts and the agent loop stay provider-agnostic.
Portable is not identical — check tool calling, structured output, context window, modalities and usage before a swap, and re-run the eval suite.
Retry, fall back and degrade are three different decisions; classify errors so auth and context failures never retry, and never retry a write.
Bound attempts with backoff and jitter, fall back across an independent provider, log which model answered, and test the fallback path on purpose.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.