Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Opencode Model Routing: Quality, Speed, API Cost

· 8 min read · Home Tech

In this article
  1. What Opencode Model Routing Does
  2. How Routing Decisions Are Made
  3. Defining Your Quality-Speed-Cost Triangle
  4. Concrete Routing Rules to Start With
  5. Monitoring and Adjusting for Cost
  6. Common Misconceptions About Routing
  7. Alternatives to Rule-Based Routing
  8. Frequently Asked Questions

Balancing quality, speed, and API cost in Opencode model routing means setting up a policy that decides which model handles each request based on the task's difficulty, your latency budget, and the price you're willing to pay. The core idea is to send simple requests to cheap, fast models and reserve expensive, high-quality models for complex ones. This article explains how to configure Opencode's routing rules, what factors to weigh, and how to avoid common pitfalls that inflate your bill or degrade response quality.

What Opencode Model Routing Does

Opencode is a terminal-based AI coding assistant that can connect to multiple large language models (LLMs) from different providers. Model routing is the mechanism that automatically selects which model answers a given prompt. Instead of manually switching between models for every query, you define routing criteria that Opencode evaluates in real time. These criteria can be based on the prompt's length, the presence of certain keywords, the estimated complexity of the task, or even the current load on your API endpoints.

The practical effect is that you get a tiered service: trivial questions like "what does this function do?" go to a small, inexpensive model, while architectural refactoring or debugging a cryptic stack trace goes to a frontier model. This is the same pattern used by many production AI gateways, but Opencode puts it directly in your developer workflow.

How Routing Decisions Are Made

Opencode evaluates routing rules in the order you define them. Each rule has a condition and a target model. When a new prompt arrives, the router checks the first rule; if the condition matches, it sends the prompt to that rule's model and stops. If not, it moves to the next rule. If no rule matches, Opencode uses the default model you've configured.

Conditions can be built from several signals:

  • Prompt length: Short prompts are usually simpler, so you can route anything under a certain character count to a cheap model.
  • Keyword patterns: Words like "refactor," "optimize," "security," or "architecture" often indicate complex tasks that deserve a stronger model.
  • File size or project size: Requests that reference large files or many files may need more context, which only larger-context models can handle.
  • Manual override: You can always force a specific model for a single request, which is useful when you know the task is harder than the router's heuristic.

Some setups also use a two-pass approach: the cheap model gives a quick answer, and if its confidence score is low, the request is escalated to the expensive model. Opencode doesn't expose confidence scores directly, but you can simulate this by checking the output for phrases like "I'm not sure" or by setting a rule that routes follow-up questions to a stronger model.

Defining Your Quality-Speed-Cost Triangle

Before writing routing rules, you need to decide what each dimension means for your workflow. Quality is usually measured by how often the model's output is correct, secure, and maintainable. Speed is the time from sending a prompt to receiving the full response, which includes network latency and token generation rate. Cost is the total API spend per request, which depends on the model's price per million input and output tokens.

These three factors trade off against each other. A frontier model might be 10 times more expensive per token and 3 times slower than a small model, but it could reduce debugging time by 50% if it gets the answer right the first time. Conversely, using a small model for everything will save money but likely increase the number of failed attempts and manual corrections.

A practical way to start is to classify your prompts into three buckets:

  1. Trivial (e.g., "explain this regex", "convert this JSON to YAML") — use the cheapest model that can handle basic syntax and common patterns.
  2. Moderate (e.g., "write a unit test for this function", "fix this TypeScript error") — use a mid-tier model with better reasoning and code generation.
  3. Complex (e.g., "design a database schema for a multi-tenant app", "refactor this monolith into microservices") — use the strongest model available, regardless of cost.

Once you have these buckets, write rules that match the prompt characteristics to each bucket.

Concrete Routing Rules to Start With

Opencode's configuration file (usually opencode.json or a similar config) lets you define a router section. Here's a realistic example structure, though exact syntax may vary by version:

{
  "router": {
    "rules": [
      {
        "name": "short-simple",
        "condition": { "promptLength": { "lt": 200 } },
        "model": "cheap-fast-model"
      },
      {
        "name": "complex-keywords",
        "condition": { "contains": ["refactor", "optimize", "security", "architecture"] },
        "model": "frontier-model"
      },
      {
        "name": "default-moderate",
        "condition": {},
        "model": "mid-tier-model"
      }
    ]
  }
}

This configuration sends any prompt under 200 characters to the cheap model, escalates prompts with complexity keywords to the frontier model, and uses the mid-tier model for everything else. You can refine this by adding conditions on file extensions, directory paths, or even the number of lines in the attached code block.

One important detail: the order of rules matters. If you put the keyword rule before the length rule, a short prompt containing "security" will go to the expensive model. That might be exactly what you want, or you might prefer to keep short prompts cheap. Decide on your priority and order accordingly.

Monitoring and Adjusting for Cost

Routing is not a set-and-forget configuration. You need to monitor your API usage and response quality to see if your rules are working as intended. Most API providers offer dashboards showing token counts and costs per model. Track these metrics over a week and compare them against your baseline without routing.

Common signs that your routing needs adjustment:

  • Cost is too high: Too many prompts are hitting the expensive model. Check if your keyword list is too broad or if the length threshold is too high.
  • Quality is too low: You're seeing frequent errors or nonsensical answers from the cheap model. Raise the length threshold or add more keywords to escalate those cases.
  • Speed is inconsistent: Some responses take far longer than expected. This could be because the router is sending complex prompts to a slow model, or because the cheap model is struggling and retrying.

You can also set up a simple logging mechanism to record which model handled each request and the user's follow-up action. If a request routed to the cheap model is immediately followed by a rephrase or a "that didn't work" message, that's a signal the rule should be tightened.

Common Misconceptions About Routing

One widespread misconception is that routing always saves money. In practice, a poorly configured router can cost more than using a single mid-tier model for everything, because you're paying for the expensive model's high token price plus the cheap model's output that gets discarded when it's wrong. The key is to measure the effective cost per successful task, not just per API call.

Another misconception is that the cheapest model is always the worst. For well-defined tasks with clear instructions, small models can perform surprisingly well. The quality gap narrows when the prompt is specific and the expected output format is simple. Routing works best when you exploit these cases.

Finally, some users think routing adds noticeable latency. In reality, the routing decision itself takes microseconds because it's just string matching and integer comparisons. The dominant latency is the model's generation time, which routing reduces by sending simple tasks to faster models.

Alternatives to Rule-Based Routing

If you find that manual rules are too brittle, there are alternatives. One is to use a semantic router that embeds the prompt into a vector and compares it against predefined intent categories. This is more flexible for natural language variations but requires a separate embedding model and a vector database, adding infrastructure overhead.

Another approach is to use a single model but with different sampling parameters. For simple tasks, you can set a lower temperature and a smaller max token limit, which speeds up generation and reduces cost. For complex tasks, you increase temperature and max tokens. This avoids the complexity of multiple models but doesn't give you the quality boost of a frontier model.

You can also use a cascade strategy: start with the cheap model, and if its response is below a quality threshold (e.g., contains "I don't know" or fails a simple validation), re-run the prompt on the expensive model. This is more robust than keyword matching but doubles the latency for failed attempts.

Frequently Asked Questions

How do I know which models Opencode supports for routing?

Check your Opencode version's documentation for the list of supported providers and models. Typically, any model you can configure as a default can also be used in routing rules. The configuration file will list available models, and you can add new ones by specifying the provider and model ID.

Can I route based on the programming language of the code?

Yes, if your prompt includes a file path or a code block with a language identifier, you can write conditions that match on those strings. For example, a rule that routes prompts containing "Python" or ".py" to a model known for strong Python support. This requires that the prompt includes that context, which it usually does when you're working in a project.

What happens if no routing rule matches?

Opencode falls back to the default model you've set in your configuration. It's good practice to make this default a mid-tier model so that unexpected prompts get a reasonable response rather than either the cheapest or most expensive option.

Does routing affect the conversation history?

Routing applies per request, but the conversation history is typically maintained across requests. If you switch models mid-conversation, the new model receives the full context, so it can continue the thread. However, different models may have different context windows, so a long conversation might need to be truncated or summarized if the new model has a smaller limit.

Is it better to route based on prompt length or keywords?

Both have trade-offs. Length is a simple heuristic that works well for obvious cases (very short questions are usually simple), but it can misclassify a short, dense question like "Why is this segfaulting?" as trivial. Keywords are more precise but require you to anticipate every complex term. A combination, with length as a first filter and keywords as a second, is often the most effective approach.