> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.world/llms.txt
> Use this file to discover all available pages before exploring further.

# ModelRouter Guide

> Let a routing model pick the right LLM, system prompt and settings for each task, limit it to the models you have keys for, and route many tasks at once

A `ModelRouter` sends each task to the model that suits it. Every task takes two LLM calls. First a routing model (`model_name`) reads the task and replies with a decision: which model and provider to use, a cleaned-up version of the task, a system prompt, `max_tokens` and `temperature`. Then the router runs the rewritten task on `{provider}/{model}` with those settings and returns that model's answer as a string.

Use it when your tasks vary a lot, so cheap ones can go to a small model and hard ones to a large one.

Reference: [ModelRouter](https://docs.swarms.world/api/model-router.md).

## 1. Route between the models you can use

The `system_prompt` is the routing model's instructions. Replace it with a short list of the models you have API keys for, and the router only picks among them. Here simple tasks go to `gpt-5.4-mini` and harder ones to `gpt-5.4`, and a small model makes the routing call itself.

```python theme={null}
from swarms import ModelRouter

routing_prompt = """
You choose the model that will answer each task.
- Use model "gpt-5.4-mini" with provider "openai" for short, simple tasks such as
  classification, extraction and one-paragraph summaries.
- Use model "gpt-5.4" with provider "openai" for tasks that need careful reasoning,
  planning, math or code.
Rewrite the task clearly, write a system prompt for the chosen model, pick
max_tokens and temperature, and explain your choice in the rationale.
"""

router = ModelRouter(
    system_prompt=routing_prompt,
    model_name="gpt-5.4-mini",
    max_tokens=1000,
)

answer = router.run(
    "Classify the sentiment of this review as positive, negative or mixed: "
    "'Fast delivery, but the box was crushed.'"
)
print(answer)
```

The router prints its decision in a panel, then the chosen model's output, and `run()` returns that output:

```text theme={null}
Model: gpt-5.4-mini
Provider: openai
Task: Classify the sentiment of the following review as positive, negative, or mixed: "Fast delivery, but the box was crushed." Return only the label.
Max Tokens: 5
Temperature: 0.0
...
mixed
```

Name both the model and the provider in your prompt. The router calls `f"{provider}/{model}"` through LiteLLM, so the pair must form a model string LiteLLM accepts.

## 2. The default model list

Without a `system_prompt`, the router uses its built-in prompt, which lists these models and tells the routing model to pick one of them exactly:

```python theme={null}
from swarms.structs.model_router import model_recommendations

for model, info in model_recommendations.items():
    print(f"{info['provider']:<11} {model}")
```

```text theme={null}
openai      gpt-5.4
groq        openai/gpt-oss-120b
deepseek    deepseek-v4-pro
anthropic   claude-sonnet-5-5
anthropic   claude-opus-5-5
gemini      gemini-3.8-flash
openrouter  minimax/minimax-m3
openrouter  z-ai/glm-5.3
openrouter  z-ai/glm-5.3-flash
mistral     mistral-large-latest
anthropic   claude-fable-5-1
openai      gpt-5.4-mini
anthropic   claude-haiku-5-5
```

Any of them can be chosen, so the default needs a working key for every provider in the list: `OPENAI_API_KEY`, `GROQ_API_KEY`, `DEEPSEEK_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, `OPENROUTER_API_KEY` and `MISTRAL_API_KEY`. If the chosen provider's call fails, `run()` raises that error. When you only have some of these keys, write your own prompt as in section 1.

## 3. See the decision without running it

`router.model_caller` is the routing call on its own. Its reply is the JSON of a `ModelOutput`, so you can parse it and inspect the choice, log it, or apply your own rules before spending tokens on the answer. This block reuses the router from section 1:

```python theme={null}
from swarms.structs.model_router import ModelOutput

decision = ModelOutput.model_validate_json(
    router.model_caller.run("Plan a database migration from MySQL to Postgres with zero downtime.")
)
print(decision.provider, decision.model, decision.max_tokens)
print(decision.rationale)
```

```text theme={null}
openai gpt-5.4 1400
This is a planning task that requires careful reasoning about migration strategy, ...
```

`ModelOutput` has seven fields, all optional: `rationale`, `model`, `provider`, `task`, `max_tokens`, `temperature` and `system_prompt`.

## 4. Route many tasks at once

`concurrent_run()` routes and runs each task on its own thread, up to `max_workers` threads (default 10, or `"auto"` for one per CPU). Results come back in task order. Each task gets its own routing decision.

```python theme={null}
tasks = [
    "Extract the city from: 'Our new office opens in Lisbon next spring.'",
    "Write a Python function that checks whether a string is a palindrome, ignoring case and spaces.",
]

results = router.concurrent_run(tasks)

for task, result in zip(tasks, results):
    print(f"=== {task}\n{result}\n")
```

`batch_run(tasks)` does the same one task at a time. Both wrap the first failure in a `RuntimeError`. Inside async code, `await router.async_run(task)` runs one task in a worker thread, and you can `asyncio.gather` several.

## 5. Read the output

| Call | Returns |
| - | - |
| `router.run(task)`, `router(task)` | The chosen model's answer, as a string |
| `router.batch_run(tasks)`, `router.concurrent_run(tasks)` | A list of answers, in task order |
| `router.model_caller.run(task)` | The routing decision as `ModelOutput` JSON, without running it |

The settings the chosen model runs with come from the decision, with two limits from the router:

* **`max_tokens`:** the decision's value, or the router's when the decision leaves it out, and never more than the router's `max_tokens` (default 4000).
* **`temperature`:** the decision's value, except for the `anthropic` provider, which gets none. The router's own `temperature` applies only to the routing call.

## 6. Refine over several steps

With `max_loops` above 1, `run()` repeats the route-and-answer step, and each step's answer becomes the next step's task. The loop stops early if a step returns its input unchanged. Each step is two more LLM calls, and the next task is the previous answer rather than your original request, so word your prompts with that in mind.

## Tips

* **Keep the list short.** A routing prompt that names two or three models, each with a clear rule, gives steadier choices than a long catalogue.
* **Route with a small model.** The routing call only has to pick and rewrite, so `model_name="gpt-5.4-mini"` is usually enough.
* **Set a ceiling.** `max_tokens` on the router caps every answer, whatever the decision asks for.
* **Need agents, not models?** [AgentRouter](https://docs.swarms.world/examples/multi-agent/agent-router-example.md) picks among your agents by embedding similarity.

## Next steps

* [ModelRouter reference](https://docs.swarms.world/api/model-router.md)
* [AgentRouter guide](https://docs.swarms.world/examples/multi-agent/agent-router-example.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.