AI AgentsLangChain

How do you route model calls with dynamic model middleware?

Question 321 of 324 · Updated

On this page

Direct answer#

Use @wrap_model_call middleware to choose a model immediately before each model step. The middleware receives a ModelRequest, selects an approved chat-model instance and passes request.override(model=selected_model) to the next handler.

This lets one LangChain agent use different models for different tasks without rebuilding the agent. Unlike choosing a model once at invocation time, the decision can change after a tool result or a change in the agent's state.

1. Practical example: a support agent#

Imagine an agent that answers basic FAQs and investigates complicated technical problems.

Current model stepPreferred route
Simple explanation without toolsFast, economical model
Difficult troubleshootingModel qualified for complex reasoning
Tool calling requiredModel with verified tool support
Large requestModel with sufficient context capacity
No compatible approved modelControlled failure, not an unsafe fallback

Complexity can come from a trusted task classifier, an application-defined task phase or evaluation-backed rules. Message count alone is a weak proxy: one short debugging question can be harder than a long routine conversation.

Loading diagram…

2. Implement the routing rule#

Keep the routing policy independent of the framework so you can test it without calling a paid model. These profiles are synthetic, not specifications for real models.

PYTHON
from dataclasses import dataclass @dataclass(frozen=True) class Profile: name: str context: int tools: bool advanced: bool approved: bool = True def choose_model(profiles, *, complex_task, needs_tools, required_tokens): if type(required_tokens) is not int or required_tokens <= 0: raise ValueError('invalid token estimate') for p in profiles: # ordered by measured cost/latency preference if (p.approved and required_tokens <= p.context and (not needs_tools or p.tools) and (not complex_task or p.advanced)): return p.name raise ValueError('no compatible approved model')

For example, suppose the fast profile supports 8,000 combined context tokens but has not qualified for tool use or complex tasks. The strong profile supports 32,000 and both capabilities. Supply the profiles in preferred order: fast, then strong.

A simple 2,000-token request selects fast. A complex task, a tool-enabled request or an 8,001-token request selects strong. If neither model qualifies, the function rejects the request.

Local verification: This exact policy passed 10 executed checks on Python 3.13.5, covering the normal route, complex tasks, tools, context boundaries, disabled profiles, incompatible models and invalid token estimates. The profiles and estimates are synthetic.

3. Connect the rule to LangChain middleware#

Use preinitialized, approved chat-model instances. The following integration accepts a trusted assessment function rather than pretending that counting messages measures complexity or tokens.

PYTHON
from langchain.agents import create_agent from langchain.agents.middleware import wrap_model_call, ModelRequest def make_agent(models, profiles, tools, assess): @wrap_model_call def route_model(request: ModelRequest, handler): requirements = assess(request) name = choose_model(profiles, **requirements) return handler(request.override(model=models[name])) return create_agent( model=models["strong"], tools=tools, middleware=[route_model], )

The host supplies the model registry, ordered profiles and registered tools. The assess function returns complex_task, needs_tools and required_tokens for the current request, using validated state or runtime context and a compatible token estimator. Include the output reserve and tool schemas in the estimate. If the candidate models have different tokenizers, use conservative estimates or assess capacity separately for each.

Treat tools as required whenever the effective request exposes them or requires compatible tool-call history. A fast profile without tool support is not eligible simply because the current user question looks easy. If another middleware filters tools, verify the final effective request and the composition order.

This integration is illustrative and unexecuted: langchain, langchain_core and langgraph are absent locally. Confirm the installed API and use unbound chat models where required; let the agent bind its effective tools. This example does not configure structured output or multimodal requests.

4. Cost, latency and provider compatibility#

Routing is useful only if it improves the actual task outcome. For a hypothetical workload of 100 calls, suppose 80 can use the economical model at 1 cost unit each and 20 require the strong model at 4 units each. Routing costs 160 units instead of 400 units for always using the strong model: a 60% reduction before routing overhead and retries.

These are illustrative costs, not provider prices. A fast model may need more attempts to finish a task; compare cost per verified completed task and end-to-end latency, not just cost per individual call.

Before routing across providers, check the capabilities required by the effective request:

  • Tool-call and tool-result protocol, including earlier messages.
  • Structured-output strategy and supported schema, if configured.
  • Context limits, modalities, streaming and provider-specific settings.
  • Approved data handling and processing location.

The common chat-model interface does not guarantee that two models support the same features. In particular, verify the pinned SDK's restrictions for dynamic models and structured-output strategies.

5. Common mistakes#

Do not let a model or user choose arbitrary provider endpoints or credentials. Route only within a host-approved registry. If a larger model is required, do not silently fall back to a smaller incompatible one. A router chooses a model before execution; a retry or fallback handles a failure afterward. They need different policies.

Test the actual middleware with a scripted model, multiple agent iterations and incompatible tool requests. Track route decisions, verified task success, cost and latency by task category. Independently enforce run budgets and permissions.

Key takeaway#

Use wrap_model_call to select an eligible model for the current request, then delegate with request.override(model=...). Filter by required capabilities first; optimize cost and latency only among models that satisfy the task.

References

  1. 1.
    LangChain agentsdocs.langchain.com
  2. 2.
    LangChain custom middlewaredocs.langchain.com
  3. 3.
    LangChain modelsdocs.langchain.com
  4. 4.
    LangChain API referencereference.langchain.com

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps