AI AgentsLangChain
How do you switch models without changing agent logic?
Question 287 of 324 · Updated
On this page
- Direct answer
- 1. Separate stable logic from replaceable dependencies
- 2. Static model substitution in LangChain
- 3. Configurable models and controlled runtime selection
- 4. Provider portability: a capability contract, not just an interface
- 5. Normalize message and tool contracts carefully
- 6. Preserve structured outputs across models
- 7. Locally tested example: swap model implementations while preserving business rules
- 8. Model migration and regression testing
- 9. Numerical example: measure success-adjusted cost
- 10. Production trade-offs and common mistakes
- Interview-ready answer
- Official reference leads and verification status
Direct answer#
Separate the agent's orchestration and business rules from its model dependency. Define the tools, instructions, authorization checks and output contract once; initialize or select an approved chat model separately and inject it into the LangChain agent. LangChain's common chat-model interfaces help preserve application code when replacing a model or provider. They do not guarantee identical tool use, message formatting, structured-output support, quality, latency or cost.
For example, a support agent can use the same authorized order-status tool and response validator with two different chat-model integrations. The model configuration changes; the tool implementation and domain policy do not. Both models must pass capability and behavior tests before they can serve that workload.
This lesson extends the prior initialization lesson (#285) and provider credentials lesson (#286). It focuses on substitution contracts, migration and behavior preservation rather than repeating factory setup or secret management. Dynamic middleware routing and fallback algorithms receive separate treatment later in the curriculum.
1. Separate stable logic from replaceable dependencies#
Treat the model as a dependency of the agent, not as the owner of the application.
| Keep stable across model changes | Allow controlled variation |
|---|---|
| User authorization and tenant isolation | Approved model identifier and provider |
| Tool names, argument contracts and business services | Provider adapter and connection configuration |
| Task instructions and acceptance criteria | Supported sampling or reasoning options |
| Required output schema and domain validation | Provider-native structured-output mechanism |
| Side-effect policy and idempotency | Streaming event translation and usage accounting |
| Evaluation datasets and release gates | Model version, latency, quality and cost |
This distinction is central to dependency injection: the application receives an already configured model interface rather than constructing a particular provider inside every business function. Model-specific settings live in a factory or profile registry. The same agent builder and domain services are then reused.
The factory selects a dependency. It must not weaken the application's security policy. For example, the fact that a new model supports computer use does not authorize the support agent to browse arbitrary websites.
2. Static model substitution in LangChain#
A practical pattern is to define a single agent builder that takes a chat-model instance. Choose the approved model outside this builder. The following illustrative SDK example uses a synthetic read-only order service, an authenticated order scope supplied by trusted application code, and a common tool contract.
PYTHONfrom langchain.agents import create_agent from langchain.chat_models import init_chat_model def build_agent(model, authorized_order_id: str): def lookup_order(order_id: str) -> str: """Read the shipping status of the authorized synthetic order.""" if order_id != authorized_order_id: return "Access denied" return {"A12": "shipped"}.get(order_id, "not found") return create_agent( model=model, tools=[lookup_order], system_prompt=( "Use authorized order evidence. Do not invent a status." ), ) # Illustrative identifiers, not a live provider availability guarantee. primary = init_chat_model("openai:gpt-4o-mini") candidate = init_chat_model("anthropic:claude-sonnet-4-5") # Use one implementation with independently configured dependencies. primary_agent = build_agent(primary, "A12") candidate_agent = build_agent(candidate, "A12") request = {"messages": [ {"role": "user", "content": "What is the status of order A12?"} ]} # Run individually in a controlled integration environment: # primary_result = primary_agent.invoke(request) # candidate_result = candidate_agent.invoke(request)
Install compatible provider integrations and supply approved credentials separately. Exact model identifiers, provider capabilities, imports and SDK signatures must be checked for the installed release and account. The snippet is not a production authorization implementation: the order scope must originate from authenticated access checks, not a user-provided claim or model-generated value.
The two agent objects share the same builder, tool behavior and instructions but use different model instances. A change of model does not require changing the agent's business logic. It may still require rebuilding the agent configuration, changing an adapter, or adjusting the model's approved options.
SDK verification status: LangChain, LangGraph, langchain_core and the checked OpenAI and Anthropic integrations were absent from the local environment. The SDK snippets were not executed; the standalone contract test in section 7 was executed. Model identifiers are illustrative and not live-verified.
3. Configurable models and controlled runtime selection#
For services that need multiple approved profiles, the application can select a prebuilt model or construct a model from an approved registry at invocation time. Supported modern LangChain releases also offer configurable chat-model wrappers. A wrapper can defer resolution and override selected fields through runtime configuration.
PYTHONfrom langchain.chat_models import init_chat_model model = init_chat_model( "gpt-4o-mini", model_provider="openai", configurable_fields=("model", "model_provider"), config_prefix="support", ) # Only after the application has approved this provider/model profile: config = { "configurable": { "support_model": "claude-sonnet-4-5", "support_model_provider": "anthropic", } } # result = model.invoke("Return a short greeting.", config=config)
This illustrates direct invocation of a configurable chat model. The exact supported field names, prefix convention and behavior of configurable wrappers inside create_agent vary by version and integration. Confirm compatibility before using the wrapper in an agent graph, especially when tools, middleware or structured response formats are involved. If the installed runtime does not support the intended configuration path, explicitly choose the model and construct the agent using the stable builder.
Avoid carrying provider-specific arguments from the default model into a replacement model unless they are supported by both. For example, a retry parameter, output-token setting or reasoning option might have different meaning or validation rules.
Never let a caller supply arbitrary model names, provider endpoints, credentials or an unrestricted configuration dictionary. Resolve a public profile alias such as support-standard to application-owned deployment settings. Enforce tenant and data-classification restrictions before any request is sent. A model switch can change where sensitive data is processed and how it is retained.
4. Provider portability: a capability contract, not just an interface#
A common BaseChatModel-style interface reduces coupling at the code level. It cannot erase differences between remote model services. Before switching, make the workload's required capabilities explicit.
| Capability | Compatibility test | Failure if ignored |
|---|---|---|
| Input message roles | Send the actual system and user message pattern | Instructions interpreted differently or rejected |
| Tool calling | Verify required names, argument schemas and call/result IDs | Invalid or missing tool requests |
| Parallel tool calls | Check supported concurrency and dependency semantics | Incorrect execution order or incompatible responses |
| Structured output | Validate the full schema against representative results | Parsed object missing fields or silently malformed |
| Context capacity | Test realistic message lengths and tool observations | Truncation or context errors |
| Multimodal input | Exercise required image or audio content types | Input rejected or information discarded |
| Streaming | Check event types, partial calls and cancellation | Broken UI or prematurely executed tools |
| Usage metadata | Inspect provider-reported usage and accounting | Incorrect budgets and cost estimates |
| Data handling | Verify approved deployment, region and contract | Policy or compliance violation |
A candidate can support basic text generation but still be unsuitable for a tool-using agent. A successful model.invoke call does not establish tool-calling or structured-output compatibility. Record the model revision, provider integration package and version, test date, required capabilities and actual results.
A capability mismatch is not always a reason to abandon the model. The application can implement a tested adapter for a missing convenience feature, narrow the workload or use a supported alternative. However, it must never simulate a capability by treating unvalidated generated text as permission to execute an action.
5. Normalize message and tool contracts carefully#
LangChain uses common message types such as HumanMessage, AIMessage and ToolMessage. Adapters translate provider responses into these interfaces. The application should consume supported normalized fields and avoid relying on one provider's raw response shape.
For a model-directed read-only order lookup, the application contract might require:
- An approved tool name and validated order identifier.
- A unique, nonempty tool-call ID to associate the result with the request.
- A tool observation containing the authoritative status or a controlled error.
- A final answer consistent with the observed evidence.
Different providers may emit different call IDs, content blocks, finish reasons, raw metadata or multiple tool calls in one model turn. Do not compare provider-generated IDs literally across candidate runs. Compare whether each call is internally correlated with its own result and whether the action satisfies the same policy.
Do not flatten all messages into text merely to switch providers. That can discard tool correlation, multimodal content, structured metadata or provider-specific continuation information. Some reasoning or signature-bearing content is tied to a provider's protocol and cannot safely be replayed to another model. Preserve the original state for audit and use a deliberately designed migration boundary that reconstructs only the information the replacement is allowed and able to consume.
For a long-running agent, the simplest safe default is to pin a model profile for the duration of a run. Switch newly created runs first. If a suspended workflow must migrate, confirm compatibility of the persisted state, pending tool requests, approvals and partial outputs. A mid-run switch is not equivalent to an ordinary new invocation.
6. Preserve structured outputs across models#
Suppose the application requires an order result with order_id, status and an evidence reference. One provider may support a native structured-response schema; another may use a tool-calling mechanism to generate a structured response. LangChain can offer common schema-oriented interfaces, but supported modes and error behavior remain provider-dependent.
An illustrative agent configuration uses a Pydantic output schema:
PYTHONfrom typing import Literal from pydantic import BaseModel, ConfigDict from langchain.agents import create_agent class OrderResult(BaseModel): model_config = ConfigDict(extra="forbid") order_id: str status: Literal["shipped", "pending", "not_found"] evidence_ref: str def build_structured_agent(model, tools): return create_agent( model=model, tools=tools, response_format=OrderResult, system_prompt="Return an order status supported by tool evidence.", )
In supported modern releases, passing a schema can select an appropriate response-format strategy; explicit provider-native or tool-based strategies may also be available. Verify the installed version's strategy selection and compatibility with ordinary tools. The SDK example is unexecuted.
Schema conformance does not establish truth. A structurally valid result can still contain a fabricated status or evidence reference. After the framework returns a structured response, verify the order identity, access permission and evidence reference against trusted domain records. A candidate that frequently generates valid but unsupported claims fails the workload's behavior contract.
For streaming structured output, validate the completed object before accepting it or performing downstream actions. Partial JSON or incremental tool arguments are not a final validated request.
7. Locally tested example: swap model implementations while preserving business rules#
The following standard-library Python example defines a minimal model port, two model substitutes, normalized tool requests and a shared agent function. Both substitutes follow the same tool and response contract with different call IDs. The purpose is to test application-level portability without provider credentials, not to reproduce the actual LangChain runtime.
PYTHONfrom dataclasses import dataclass from typing import Protocol @dataclass(frozen=True) class Request: call_id: str tool: str order_id: str @dataclass(frozen=True) class Reply: calls: tuple[Request, ...] = () status: str | None = None class ModelPort(Protocol): def invoke(self, history: tuple) -> Reply: ... class ContractError(Exception): pass def run(model: ModelPort, order_id: str, lookup, limit=3): history = [('user', order_id)] seen = set() evidence = None for _ in range(limit): reply = model.invoke(tuple(history)) history.append(('model', reply)) if reply.calls: ids = [call.call_id for call in reply.calls] if (any(not cid for cid in ids) or len(set(ids)) != len(ids) or seen.intersection(ids)): raise ContractError('invalid_call_id') for call in reply.calls: if call.tool != 'lookup_order' or call.order_id != order_id: raise ContractError('unauthorized_call') for call in reply.calls: seen.add(call.call_id) evidence = lookup(call.order_id) history.append(('tool', call.call_id, evidence)) else: if evidence is None or reply.status != evidence: raise ContractError('ungrounded_output') return reply.status raise ContractError('budget_exhausted') class FakeModel: def __init__(self, call_id, final='shipped'): self.call_id = call_id self.final = final def invoke(self, history): if history[-1][0] == 'user': return Reply((Request(self.call_id, 'lookup_order', history[0][1]),)) assert history[-1] == ('tool', self.call_id, 'shipped') return Reply(status=self.final) class Scripted: def __init__(self, *replies): self.replies = iter(replies) def invoke(self, history): return next(self.replies) reads = [] def lookup(order_id): reads.append(order_id) return 'shipped' def reject(model, reason, **kw): try: run(model, 'A12', lookup, **kw) except ContractError as exc: assert str(exc) == reason else: raise AssertionError('expected contract rejection') assert run(FakeModel('a-1'), 'A12', lookup) == 'shipped' assert run(FakeModel('b-9'), 'A12', lookup) == 'shipped' assert reads == ['A12', 'A12'] reject(FakeModel('c-1', 'delivered'), 'ungrounded_output') before = len(reads) reject(Scripted(Reply((Request('d', 'lookup_order', 'OTHER'),))), 'unauthorized_call') assert len(reads) == before reject(Scripted(Reply((Request('e', 'delete_order', 'A12'),))), 'unauthorized_call') assert len(reads) == before call = Request('f', 'lookup_order', 'A12') reject(Scripted(Reply((call, call))), 'invalid_call_id') assert len(reads) == before reject(Scripted(Reply(status='shipped')), 'ungrounded_output') reject(FakeModel('g'), 'budget_exhausted', limit=1) print('8 scenarios passed')
Actual local execution: Python 3.13.5 printed 8 scenarios passed.
| Scenario | Expected outcome |
|---|---|
| Model substitute A | Verified shipped status |
| Model substitute B | Same verified result with a different call ID |
| Unsupported final status | Rejected |
| Another order | Rejected before reading |
| Unapproved tool | Rejected before reading |
| Duplicate IDs in one turn | Rejected before reading |
| Final claim without evidence | Rejected |
| Model-call limit reached | Controlled failure |
The same run function is used in every scenario. It checks all proposed calls in a turn before executing any of them, rejects duplicate call IDs, validates the authorized order and checks the final status against evidence. The authenticated order scope must be provided by the real host. The example deliberately handles one read-only tool and one resource; it does not implement complete provider message normalization, real identity checks, external timeouts, structured-output parsing, persistence or production concurrency. A real model adapter must validate raw message types and malformed payloads before constructing these domain objects. The test does not demonstrate equivalence of real provider models.
8. Model migration and regression testing#
A model upgrade is a behavioral change, even if the application code and tool schemas remain unchanged. Use the current approved model as a baseline and evaluate the candidate with the same representative tasks, permissions and acceptance criteria.
Include cases with:
- Straightforward questions with authoritative data.
- Ambiguous requests that should trigger clarification.
- Missing or contradictory evidence.
- Malformed tool arguments, unknown tools and unauthorized resource requests.
- Structured-response schema edge cases.
- Long contexts, multiple tool calls, timeouts and interruption.
- Prompt injection attempts in retrieved content or tool responses.
Compare outcome correctness rather than exact wording. Tool-call sequences may differ while still satisfying the contract. Some tasks require a particular sequence for safety; those requirements should be explicit and verified deterministically.
Measure the rate of valid tool arguments, completed tasks, grounded responses, unsafe execution, unnecessary actions, cost and end-to-end latency. Compare model versions under equivalent conditions and use multiple runs when sampling variability matters. A candidate with higher average correctness but unacceptable failure on a protected tenant cohort should not be automatically promoted.
Shadow evaluation must not duplicate live write actions. Use recorded fixtures, sandboxed tools or a read-only simulation; obtain the required permission before transmitting real user data to an additional provider. Do not assume that a second provider is automatically an authorized recipient.
Canary new runs first and keep in-flight state pinned to its approved model profile. Roll back by restoring the approved profile for future runs, not by blindly replaying prior side effects. Persist a stable operation key for transactional tools, and reconcile uncertain external outcomes before retrying any action.
9. Numerical example: measure success-adjusted cost#
Suppose a baseline model and candidate are evaluated on the same 200 synthetic support cases. These numbers are hypothetical, not provider prices or measured benchmarks.
| Metric | Baseline | Candidate |
|---|---|---|
| Successful outcomes | 194 | 196 |
| Total model and tool charges | $4.00 | $3.60 |
| Cost per successful outcome | $0.02062 | $0.01837 |
| p95 latency | 2.4 s | 2.9 s |
| Unauthorized actions executed | 0 | 0 |
| Schema-valid results | 198 | 199 |
The candidate appears to lower cost per successful task by approximately 10.9%, while p95 latency increases by about 20.8%. Both models have zero observed unauthorized executions, which is a necessary safety check in this example but not proof of zero future risk. If a workload requires p95 below 2.5 seconds, the candidate fails the latency gate despite its cost advantage. The two-task success difference in this sample is not strong evidence of superiority without further trials and uncertainty analysis.
A cheaper model can also be more expensive per completed task when it requires more retries or tool calls. Measure total cost across the complete agent trajectory rather than compare only advertised per-token prices.
10. Production trade-offs and common mistakes#
| Mistake | Better approach |
|---|---|
| Hard-code a provider class inside domain logic | Inject the approved model dependency through a builder |
| Assume all models support the same parameters | Validate provider-specific configuration and capability requirements |
| Allow arbitrary runtime model overrides | Resolve only server-owned profile aliases |
| Compare exact generated text | Compare task outcomes, schema and safety invariants |
| Drop tool IDs while adapting messages | Preserve call/result correlation and valid sequencing |
| Assume structured output means factual accuracy | Validate evidence and domain constraints separately |
| Switch providers in the middle of an unresolved action | Pin active runs or use explicit validated migration boundaries |
| Use another provider automatically after any error | Respect authorization, data policy and bounded retry rules |
| Run shadow experiments with live write tools | Use read-only, simulated or sandboxed tools |
| Ignore dependency and behavioral changes | Pin versions, retest and maintain a rollback path |
Avoid recreating model clients on every call unnecessarily; reuse approved clients only when their thread-safety, credential scope and lifecycle contracts permit it. Do not share mutable configuration across tenants. Record the selected provider/model revision and profile version with run metadata, without exposing credentials or unnecessary private message content.
Interview-ready answer#
I separate model selection from the agent's tool contracts, instructions, authorization and output validation. I pass an approved LangChain chat-model instance into a reusable create_agent builder or use a narrowly configured, supported runtime model wrapper. I verify that candidate models support the required message roles, tool calling, structured output, context and streaming behavior. I run identical regression cases against the baseline and candidate, compare grounded task success, safety, latency and cost, and canary new sessions before promotion. A common interface makes substitution easier, but actual behavior and provider protocols must still be verified.
Official reference leads and verification status#
- LangChain models
- LangChain agents
- LangChain messages
- LangChain structured output
- LangChain OpenAI integration
- LangChain Anthropic integration
- LangChain API reference
Authorized offline research exception applied. These are official documentation research leads, not live-accessed or version-verified citations. The dependency-free model-substitution example was actually executed on Python 3.13.5 and passed eight scenarios. The real SDK snippets were not executed because the checked LangChain packages and provider integrations were absent. Mermaid diagrams are fenced but live rendering was not verified. No real model calls, benchmark measurements or provider compatibility claims are implied.
References
- 1.LangChain modelsdocs.langchain.com
- 2.LangChain agentsdocs.langchain.com
- 3.LangChain messagesdocs.langchain.com
- 4.LangChain structured outputdocs.langchain.com
- 5.LangChain OpenAI integrationdocs.langchain.com
- 6.LangChain Anthropic integrationdocs.langchain.com
- 7.LangChain API referencereference.langchain.com
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps