Skip to main content

Runtime Model Routing

A small model answers most questions well and costs little. A bigger one is worth its price for the hard questions. Runtime model routing lets one conversation move from one model to another, or to another model service, between two messages, and the new model still knows everything said before. This tutorial explains when a conversation can move, and moves a maths tutor's conversation from gpt-5.6-luna to gpt-5.6-sol halfway through.

How Runtime Model Routing Works​

Where the conversation lives decides whether it can move​

Changing which model gets the next request is the easy part. The new model also needs the conversation so far. Microsoft's guide to routing puts it this way: Whether it can receive that context depends on where the chat history is stored and who controls it. Chat History Storage and Compaction showed the two places a conversation can live:

Where the history livesCan the conversation move?
In your app, kept by the agent's chat history provider (caller-managed)Yes. The app sends the history with every request, so it can send it to any model
In the model service, which keeps it and gives you an ID (inference-service-managed)Not to another service. The guide: A client for another service can't use the identifier to retrieve the messages.

So routing starts with a model service that keeps no conversation, such as a Foundry project's Chat Completions API. The agent keeps the history in its session, and any model can continue it.

A routing chat client​

The agent doesn't talk to one model. It talks to a routing chat client, which holds several chat clients, called routes, each with a name, and picks one for every request. In Agent Framework that's RoutePersistingRoutingChatClient. It keeps each session's active route in the session itself, so the choice belongs to the conversation, and you change it with SetActiveRoute:

Microsoft's guide describes each request in five steps:

  1. The chat history provider loads the conversation history.
  2. The agent combines the history with the input for the current turn.
  3. The routing client selects the active chat client for the session.
  4. The selected client receives the complete request.
  5. The chat history provider stores the new messages after the run.

RoutePersistingRoutingChatClient is experimental in Agent Framework 1.28: its API can still change, and the compiler says so with the diagnostic MAAI001. Microsoft.Extensions.AI has more routing clients, also experimental, such as one that chooses a route by the meaning of the message and others that fail over to another client when one fails.

The Example​

A console app called StudyBuddy is a maths tutor with two routes: everyday, on gpt-5.6-luna, and expert, on gpt-5.6-sol. The student introduces herself and asks an easy question on the everyday route. Then the app moves the conversation to the expert route and asks a harder question that needs her name from the first message. Finally it saves the session as JSON, the way a server would between requests, and restores it.

What It Costs​

The expert route costs much more: at the time of writing, gpt-5.6-sol was $4.00 per million input tokens and $20.00 per million output tokens, against $0.20 and $1.20 for gpt-5.6-luna. In my run, the everyday answer used 53 input and 33 output tokens, and the expert answer 116 and 77, about forty times as much money for one answer. Both together cost about a fifth of a cent.

Prerequisites​

  • The agent from Chat History Storage and Compaction, and the setup it uses: the .NET 10 SDK, the Azure CLI signed in, a Foundry project endpoint and the Foundry User role.
  • Two chat model deployments in the project, such as gpt-5.6-luna and gpt-5.6-sol. Any two chat models work.

Step 1: Create a Console App​

In a terminal, in the folder where you keep your projects, run:

Terminal
dotnet new console -n StudyBuddy
cd StudyBuddy
dotnet add package Microsoft.Agents.AI.Foundry --version 1.28.0-preview.261106.1
dotnet add package Azure.Identity --version 1.21.0

The same two packages as the earlier tutorials. Microsoft.Agents.AI.Foundry is a preview, and it brings in Microsoft.Agents.AI, where the routing client lives.

Step 2: Two Routes on Chat Completions​

Replace everything in Program.cs with the two chat clients:

Program.cs (the routes)
using System.Text.Json;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

// Both routes use the project's Chat Completions API, which keeps no conversation on the service.
// The agent's session keeps it, so either route can continue it.
var openAI = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.GetProjectOpenAIClient();

Dictionary<string, IChatClient> routes = new()
{
["everyday"] = openAI.GetChatClient("gpt-5.6-luna").AsIChatClient(),
["expert"] = openAI.GetChatClient("gpt-5.6-sol").AsIChatClient(),
};
  • GetChatClient(...).AsIChatClient() gives a chat client on the Chat Completions API for one deployment, as in the previous tutorial. Both routes use it, so neither keeps the conversation in the service. Microsoft's routing guide: Every chat client registered as a route must use caller-managed history supplied by a chat history provider.
  • routes names each chat client. The names are yours: here everyday and expert.

Use your own project endpoint and deployment names.

Step 3: The Router​

Program.cs (the router)
// The router picks one of the routes for every request, from the route stored in the session.
// It's experimental in Agent Framework 1.28 (MAAI001), so its API can still change.
#pragma warning disable MAAI001
RoutePersistingRoutingChatClient router = new(routes, new RoutePersistingRoutingChatClientOptions { DefaultRoute = "everyday" });
#pragma warning restore MAAI001
  • RoutePersistingRoutingChatClient is itself a chat client, so an agent can use it like any other. It receives every request and passes it on to the route that the request's session is on.
  • DefaultRoute is the route a new session starts on. Without it, a new session starts on the first route in the dictionary.
  • #pragma warning disable MAAI001 accepts the experimental API for that one line. Without it, the build fails, as Fixed: MAAI001 'Microsoft.Agents.AI.RoutePersistingRoutingChatClient' is for evaluation purposes only shows.

Step 4: An Agent on the Router​

Program.cs (the agent)
AIAgent tutor = router.AsAIAgent(
instructions: "You are a patient maths tutor. Answer in two or three short sentences of plain text, without LaTeX or Markdown.",
name: "StudyBuddy");

AgentSession session = await tutor.CreateSessionAsync();

router.AsAIAgent(...) creates the agent around the router. The agent gets no chat history provider of its own, so it uses InMemoryChatHistoryProvider, which keeps the conversation in the session, as the previous tutorial showed. My first run had only Answer in two or three short sentences., and both models answered in LaTeX, such as \( \frac{3}{4} \), which a console can't display, so the instructions now ask for plain text.

Step 5: Ask, Then Switch the Route​

Program.cs (the conversation)
await AskAsync("My name is Priya. What is 3/4 + 1/8?");

// Move this conversation to the stronger model for a harder question.
router.SetActiveRoute(session, "expert");
await AskAsync("Why does dividing by a fraction give the same result as multiplying by its reciprocal? Use my name.");
  • The first question runs on the session's default route, everyday.
  • SetActiveRoute(session, "expert") moves this session, and only this session, to the expert route. An app decides when: when the user asks for a better answer, when a question is long or hard, or when the everyday model is unavailable.
  • The second question asks the expert model to use the student's name, which only the first message contains.

A macOS-style code window titled Program.cs — StudyBuddy showing the two routes, everyday on gpt-5.6-luna and expert on gpt-5.6-sol, the RoutePersistingRoutingChatClient with everyday as its default route inside a MAAI001 pragma, the tutor agent created from the router, a session, the first question, SetActiveRoute to expert and the second question

AskAsync is a small function at the end of the file:

Program.cs (the helper)
async Task AskAsync(string question)
{
AgentResponse answer = await tutor.RunAsync(question, session);
string? model = (answer.RawRepresentation as ChatResponse)?.ModelId;
Console.WriteLine($"[{router.GetActiveRoute(session)} -> {model}] {answer.Text}");
Console.WriteLine($" {answer.Usage?.InputTokenCount} input tokens, {answer.Usage?.OutputTokenCount} output tokens");
}

Step 6: See Where the Route Is Kept​

Program.cs (the session)
// The active route is saved with the session, next to its chat history.
JsonElement saved = await tutor.SerializeSessionAsync(session);
foreach (JsonProperty state in saved.GetProperty("stateBag").EnumerateObject())
{
string value = state.Name == "InMemoryChatHistoryProvider"
? $"{state.Value.GetProperty("messages").GetArrayLength()} messages"
: state.Value.GetRawText();
Console.WriteLine($"Session state {state.Name}: {value}");
}

// A session restored from that JSON, as after a restart, is still on the expert route.
AgentSession restored = await tutor.DeserializeSessionAsync(saved);
Console.WriteLine($"Restored session's route: {router.GetActiveRoute(restored)}");

SerializeSessionAsync turns the session into JSON, as Sessions showed. Its state bag holds each component's state under its own key, and the loop prints what's there: the router's state, and the number of messages the chat history provider keeps. DeserializeSessionAsync turns the JSON back into a session, as a server does with a saved conversation, and the loop's last line asks it which route it's on.

The complete file:

Program.cs
using System.Text.Json;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

// Both routes use the project's Chat Completions API, which keeps no conversation on the service.
// The agent's session keeps it, so either route can continue it.
var openAI = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.GetProjectOpenAIClient();

Dictionary<string, IChatClient> routes = new()
{
["everyday"] = openAI.GetChatClient("gpt-5.6-luna").AsIChatClient(),
["expert"] = openAI.GetChatClient("gpt-5.6-sol").AsIChatClient(),
};

// The router picks one of the routes for every request, from the route stored in the session.
// It's experimental in Agent Framework 1.28 (MAAI001), so its API can still change.
#pragma warning disable MAAI001
RoutePersistingRoutingChatClient router = new(routes, new RoutePersistingRoutingChatClientOptions { DefaultRoute = "everyday" });
#pragma warning restore MAAI001

AIAgent tutor = router.AsAIAgent(
instructions: "You are a patient maths tutor. Answer in two or three short sentences of plain text, without LaTeX or Markdown.",
name: "StudyBuddy");

AgentSession session = await tutor.CreateSessionAsync();

await AskAsync("My name is Priya. What is 3/4 + 1/8?");

// Move this conversation to the stronger model for a harder question.
router.SetActiveRoute(session, "expert");
await AskAsync("Why does dividing by a fraction give the same result as multiplying by its reciprocal? Use my name.");

// The active route is saved with the session, next to its chat history.
JsonElement saved = await tutor.SerializeSessionAsync(session);
foreach (JsonProperty state in saved.GetProperty("stateBag").EnumerateObject())
{
string value = state.Name == "InMemoryChatHistoryProvider"
? $"{state.Value.GetProperty("messages").GetArrayLength()} messages"
: state.Value.GetRawText();
Console.WriteLine($"Session state {state.Name}: {value}");
}

// A session restored from that JSON, as after a restart, is still on the expert route.
AgentSession restored = await tutor.DeserializeSessionAsync(saved);
Console.WriteLine($"Restored session's route: {router.GetActiveRoute(restored)}");

async Task AskAsync(string question)
{
AgentResponse answer = await tutor.RunAsync(question, session);
string? model = (answer.RawRepresentation as ChatResponse)?.ModelId;
Console.WriteLine($"[{router.GetActiveRoute(session)} -> {model}] {answer.Text}");
Console.WriteLine($" {answer.Usage?.InputTokenCount} input tokens, {answer.Usage?.OutputTokenCount} output tokens");
}

Step 7: Run It​

Terminal
dotnet run
Output
[everyday -> gpt-5.6-luna-2026-07-09] Hi Priya! 3/4 equals 6/8, so 6/8 + 1/8 = 7/8.
53 input tokens, 33 output tokens
[expert -> gpt-5.6-sol-2026-07-09] Priya, dividing by a number means multiplying by whatever makes that number equal 1. For a fraction like 2/3, its reciprocal 3/2 makes 1, so dividing by 2/3 is the same as multiplying by 3/2.
116 input tokens, 77 output tokens
Session state RoutePersistingRoutingChatClient: {"activeRoute":"expert"}
Session state InMemoryChatHistoryProvider: 4 messages
Restored session's route: expert

A macOS-style terminal window titled Terminal — StudyBuddy showing dotnet run: the everyday route answered by gpt-5.6-luna-2026-07-09 with 7/8 in 53 input and 33 output tokens, the expert route answered by gpt-5.6-sol-2026-07-09, addressing Priya by name, in 116 input and 77 output tokens, then the session state with the active route expert and four messages, and the restored session's route expert

  • The first answer came from gpt-5.6-luna-2026-07-09, the everyday route.
  • The second answer came from gpt-5.6-sol-2026-07-09, and it starts with Priya. The expert model never saw the first message itself: the chat history provider sent it, with the first answer, as part of the second request, which is why that request has 116 input tokens.
  • The router's state in the session is {"activeRoute":"expert"}, beside the four messages of the conversation: two questions and two answers.
  • The restored session is still on expert, so a conversation keeps its route across requests and restarts, as long as you save its session.

What You Can Do Now​

  • Tell whether a conversation can move to another model, from where its history lives.
  • Put several chat clients behind one RoutePersistingRoutingChatClient, and choose the route a new session starts on.
  • Move one session to another route with SetActiveRoute, and read its route with GetActiveRoute.
  • Check which model answered a run, and keep a conversation's route with its saved session.

Common Mistakes​

MistakeWhat happensDo this instead
Routing an agent whose service keeps the conversation, such as AsAIAgent on the projectThe other route can't read that conversation. Microsoft's guide: Don't register a route that uses inference-service-managed conversation historyGive every route a client whose service keeps no history, as in Step 2
Leaving out the #pragmaThe build fails with MAAI001 (Fixed)Accept the experimental API around the line that uses it
Setting the route on a different session objectThe conversation stays on its old routePass the same session to SetActiveRoute and RunAsync
Switching to a route whose model can't read earlier contentMicrosoft's guide: The new model must support the message and content types used in earlier turnsRoute only between models that support what the conversation already holds, such as images or tool calls
Forgetting the price of the expensive routeA conversation left on it costs many times more per answerMove back to the everyday route when the hard part is done

Frequently Asked Questions​

Can a route be a different model service, not another deployment?​

Yes, as long as it keeps no conversation itself and accepts the messages already in it. Microsoft's guide: The new provider must accept the roles, content types, tool-call messages, and tool-result messages used in earlier turns. Any IChatClient can be a route.

Who decides when to switch?​

Your code. RoutePersistingRoutingChatClient follows the route you set for the session. Microsoft.Extensions.AI also has routing clients that choose by themselves, for example by the meaning of the message or by failing over when a client fails. They're experimental too.

Does the IT Service Desk use routing?​

No. Its agent uses the Responses API, where Foundry keeps each conversation, and Part 15 keeps only the session, with the conversation's ID, in Azure Cosmos DB. To route it, the conversation would have to move into the app first.

Does switching the route change the instructions or the tools?​

No. They belong to the agent, and every route gets the same request: the instructions, the tools and the history. Only the model that answers changes.

Conclusion​

A conversation can move to another model only if its history lives in your app. With Chat Completions routes and the agent's chat history provider, RoutePersistingRoutingChatClient sends every request to the route the session is on. SetActiveRoute moves one conversation to another model between two messages, the new model gets the whole history with the next request, and the route is saved with the session.

Next: Retrieval-Augmented Generation (RAG) — answer from your own documents.

Additional Resources​