Search
AI Tutorial

Claude, ChatGPT, Gemini, Copilot: Router in 12 Steps [2026]

Daniel Okafor
Daniel OkaforSenior AI Reporter
24 min read
Claude, ChatGPT, Gemini, Copilot: Router in 12 Steps [2026]

Picking a single AI assistant in October 2026 means leaving real capability on the table. Claude Opus 5.5 handles a half-million-word contract without losing track of clause three. GPT-6.1 Sol, the model family now powering ChatGPT, answers everyday questions with less delay. Gemini 3.8 Flash pulls in live search results and reads a screenshot in the same turn. GitHub Copilot reviews a pull request before a human teammate even opens the tab. Running all four side by side, and sending each task to whichever one actually wins it, beats betting the whole workflow on one vendor.

The sections below cover through setting up accounts and API access for Claude vs ChatGPT vs Gemini vs Copilot, then building a small router script that sends writing, coding, research, and multimodal tasks to the model built to handle them. By the end you will have a working multi-model stack, a cost tracker, and a fallback chain for the moment one provider throttles you mid-task. For background on how these three model families stack up on raw pricing before you start building, see our breakdown of GPT-6.1 Sol vs Sonnet 5.5 vs Gemini 3.8 Flash, and browse the rest of our AI and machine learning coverage for ongoing model updates.

Google · Preferred Sources

Don't miss new tech stories on Google

Add TrendinTech once in the Google app and our stories appear in your news suggestions.

Add Now

Why One AI Assistant Isn’t Enough Anymore

The four tools behind the claude vs chatgpt vs gemini vs copilot question are no longer interchangeable. Each one shipped a distinct architecture update in the last quarter, and each one now wins specific categories of work rather than all of them at once. Anthropic’s Claude Opus 5.5 and Sonnet 5.5 carry a 1 million token context window as standard, which makes them the obvious pick for legal review, codebase-wide refactors, or any task where losing the thread halfway through a document ruins the output. OpenAI’s GPT-6.1 Sol, marketed through ChatGPT’s Instant and Reasoning modes, trades some of that raw context ceiling for faster turnaround on shorter, high-volume conversational work. Google’s Gemini 3.8 Flash leans into multimodal input and search grounding, while the newer Gemini 4 Argon is rolling out gradually inside GitHub Copilot’s paid tiers rather than shipping as a clean standalone release.

GitHub Copilot sits apart from the other three because it is not really a single model. It is a routing layer that lets a developer call Claude, GPT, or Gemini models from inside an IDE, a pull request, or a terminal, billed through one unified AI-credit system. That structure matters for this tutorial: once you understand how Copilot already does internal routing for code, you can copy the same pattern for writing, research, and support tasks outside of GitHub entirely.

Developer adoption backs up the idea that most engineers already use more than one of these tools. The 2025 Stack Overflow Developer Survey found that among developers using out-of-the-box AI assistants, 81.7% selected ChatGPT, 67.9% selected GitHub Copilot, 47.4% selected Google Gemini, and 40.8% selected Claude Code. Those percentages overlap heavily, which means a large share of respondents already run two or three of these side by side without a formal router. This tutorial just makes that overlap intentional instead of accidental.

Prerequisites: Accounts, Keys, and Costs

Before writing any code, line up accounts and local tooling. None of this requires enterprise budget, but you do need paid API access on at least Claude and OpenAI to run the full router, since their free consumer tiers do not expose API keys.

  • A computer running macOS, Windows 11, or Linux with at least 8GB of RAM
  • Python 3.11 or later installed and confirmed with python3 --version
  • Node.js 20 LTS or later, only needed if you plan to wrap the router in a web interface later
  • A code editor such as Visual Studio Code 1.95 or later, since this is also where GitHub Copilot plugs in directly
  • An Anthropic Console account with billing enabled, for Claude Opus 5.5, Sonnet 5.5, and Haiku 5.5 API access
  • An OpenAI Platform account with billing enabled, for GPT-6.1 Sol API access
  • A Google AI Studio account, for Gemini 3.8 Flash API access
  • A GitHub account with a Copilot Pro, Pro+, Business, or Enterprise subscription
  • Roughly $20 to $50 set aside for API testing credits across the three providers combined
  • Basic comfort reading JSON responses and editing a .env file

Step 1: Create Accounts on All Four Platforms

Start with Anthropic. Sign up for the Anthropic Console, add a payment method, and confirm you can see Claude Opus 5.5, Claude Sonnet 5.5, and Claude Haiku 5.5 listed under available models. Haiku 5.5 only shipped on October 7, 2026, so if your console still shows an older Haiku build, refresh the model list or check your organization’s model access settings.

Next, create an OpenAI Platform account separate from a personal ChatGPT login, since API keys live under the developer platform, not the consumer chat app. Add billing there too. For Google, open Google AI Studio with any Google account and generate a project; Gemini 3.8 Flash API access is available immediately without a waitlist as of this writing. Finally, confirm your GitHub account has an active Copilot subscription at Pro+ or higher if you want access to Gemini 4 Argon, since GitHub currently gates that model to Pro+, Max, Business, and Enterprise plans rather than the base Pro tier.

Step 2: Generate and Store API Keys Safely

Each provider issues keys from a different settings page. Anthropic keys live under the Console’s API Keys tab, OpenAI keys live under the Platform’s API Keys section, and Google issues keys directly from AI Studio’s Get API Key button. GitHub Copilot does not need a separate API key for this tutorial since you will interact with it through the IDE and CLI rather than raw HTTP calls.

Create a project folder and store every key in a single .env file that never gets committed to version control. Add that file to .gitignore immediately, before you paste in a single key.

# .env
ANTHROPIC_API_KEY=sk-ant-api03-REPLACE_ME
OPENAI_API_KEY=sk-proj-REPLACE_ME
GOOGLE_API_KEY=AIzaSy-REPLACE_ME

# .gitignore
.env
__pycache__/
*.pyc

Treat these keys like passwords. A leaked Anthropic or OpenAI key can rack up real charges within minutes if it ends up in a public repository, so rotate any key you suspect has been exposed before continuing.

Step 3: Compare Specs Side by Side Before You Build Anything

Before writing a line of routing logic, it helps to see the actual numbers next to each other. Pricing and context windows are what decide which model gets which task, not brand preference.

ModelMakerContext WindowInput Price / 1M TokensOutput Price / 1M TokensStrongest Use Case
Claude Opus 5.5Anthropic1,000,000 tokens$4.00$20.00Long-running agentic coding, deep document review
Claude Sonnet 5.5Anthropic1,000,000 tokens$2.00$10.00Everyday feature work and bug fixes
Claude Haiku 5.5AnthropicUp to 100K / above 100K tiers$0.10 / $0.50$0.50 / $2.50High-volume, low-latency requests
GPT-6.1 Sol (Instant)OpenAI54K to 128K (plan dependent)Not published per seat tierNot published per seat tierFast conversational replies
GPT-6.1 Sol (Reasoning / chat-latest)OpenAIUp to 400,000 tokens$5.00 ($0.50 cached)$30.00Deep reasoning and complex analysis
Gemini 3.8 FlashGoogle1,000,000 tokens (64K max output)$0.75 (intro, through Dec 31 2026)$3.75 (intro, through Dec 31 2026)Multimodal input and search-grounded answers
Gemini 4 Argon (via Copilot)Google / GitHubRolling out gradually$2.00 ($0.10 cached)$10.00Coding agent tasks inside Copilot Pro+ and above

Two things jump out. First, Anthropic bills long-context requests at the same per-token rate across the whole window, so a 900,000 token request costs the same per token as a 9,000 token request rather than carrying a long-context surcharge. Second, Gemini 3.8 Flash’s current rate is an introductory price that rises on January 1, 2027, to $1.50 input and $7.50 output per million tokens, so budget forecasts built today need a revision date on the calendar.

Context Window Differences Explained

A context window is the total amount of text, measured in tokens, a model can hold in memory for a single request, counting both your input and its output. Claude and Gemini both advertise 1 million token ceilings on their current flagship tiers, while ChatGPT’s window still depends heavily on which internal mode answers your prompt and which plan you are on. That inconsistency is exactly why a router matters: sending a 300-page PDF to GPT Instant’s 54,000 token window just truncates the document silently, while the same file fits cleanly inside Claude Opus 5.5 or Gemini 3.8 Flash.

Step 4: Set Up Your Local Project and Install SDKs

Create a clean virtual environment and install the three official Python SDKs plus a helper library for loading the .env file.

mkdir ai-router && cd ai-router
python3 -m venv venv
source venv/bin/activate   # Windows: venv\Scripts\activate

pip install anthropic openai google-genai python-dotenv

python3 -c "import anthropic, openai, google.genai; print('SDKs ready')"

If any import fails, check that you installed inside the activated virtual environment rather than globally. Running which python3 should point inside the venv folder you just created, not your system Python.

Step 5: Write a Baseline Test Script for Each Model

Before building a router, confirm each provider actually answers a simple prompt. This script fires the same question at Claude Sonnet 5.5, GPT-6.1 Sol, and Gemini 3.8 Flash and prints the result from each.

import os
from dotenv import load_dotenv
import anthropic
import openai
from google import genai

load_dotenv()

prompt = "In two sentences, explain what a context window is."

# Claude
claude_client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
claude_reply = claude_client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=200,
    messages=[{"role": "user", "content": prompt}]
)
print("CLAUDE:", claude_reply.content[0].text)

# ChatGPT
openai_client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
gpt_reply = openai_client.chat.completions.create(
    model="chat-latest",
    messages=[{"role": "user", "content": prompt}]
)
print("CHATGPT:", gpt_reply.choices[0].message.content)

# Gemini
gemini_client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))
gemini_reply = gemini_client.models.generate_content(
    model="gemini-3.8-flash",
    contents=prompt
)
print("GEMINI:", gemini_reply.text)

Output example after running the script successfully looks like this:

CLAUDE: A context window is the maximum amount of text a model can process at once, measured in tokens. It includes both the prompt you send and the response it generates.
CHATGPT: A context window is the limit on how much text an AI model can "see" in a single conversation, combining input and output. Once that limit is reached, earlier content gets dropped or summarized.
GEMINI: A context window defines how much text, images, or code a model can hold in memory during one exchange. Larger windows let a model reason over longer documents without losing earlier details.

Model name strings change over time, so if a call returns a 404 or model-not-found error, check the provider’s current model list rather than assuming the script is broken.

Step 6: Build a Task Router Function

With all three APIs confirmed working, the next step is a function that looks at a task description and decides which model should handle it. This version uses simple keyword rules, which is enough for most personal and small-team workflows and easy to extend later with a classifier model if volume grows.

def choose_model(task_type: str, token_estimate: int) -> str:
    """Return which provider/model should handle a given task."""

    task_type = task_type.lower()

    if token_estimate > 150_000:
        return "claude-opus-5-5"  # only Claude/Gemini handle this size reliably

    if "code" in task_type or "refactor" in task_type or "agent" in task_type:
        return "claude-sonnet-5-5"

    if "image" in task_type or "screenshot" in task_type or "search" in task_type:
        return "gemini-3.8-flash"

    if "quick" in task_type or "chat" in task_type or "support" in task_type:
        return "gpt-6.1-sol-instant"

    # default to the balanced mid-tier model
    return "claude-sonnet-5-5"

Keep the rule set small on purpose. A router with twenty overlapping conditions is harder to debug than one with five clear ones, and most teams only need four or five real categories: long documents, code, multimodal or search-heavy work, fast chat, and everything else.

Step 7: Route Long Documents and Agentic Work to Claude

Claude Opus 5.5 and Sonnet 5.5 earn the long-document and agentic-coding lane because of two specific behaviors. The 1 million token context window holds an entire codebase or contract without chunking, and Anthropic’s flat per-token billing across that window means you are not punished for using the full context the way some long-context pricing models punish users elsewhere. You can confirm current rates any time on Anthropic’s published pricing documentation.

In practice, this means any task tagged with words like “refactor,” “audit,” “migrate,” or “review the full repo” in your router should go to Sonnet 5.5 by default, with Opus 5.5 reserved for the cases where accuracy on a single pass matters more than cost, such as a compliance document review nobody wants to redo. Claude Haiku 5.5, which launched October 7, 2026 as part of the pricing shift that pushed Anthropic into a wider AI price war, is the cheapest option for high-volume, low-stakes requests like tagging support tickets or summarizing short emails, at $0.10 per million input tokens for prompts up to 100,000 tokens.

Step 8: Route Fast Everyday Replies to ChatGPT

GPT-6.1 Sol splits into two operating modes inside ChatGPT: GPT Instant for quick answers and GPT Reasoning for anything that needs multiple steps of logic. Instant’s context window tops out around 54,000 tokens on the Plus plan and 128,000 on Pro, which is plenty for a single support conversation or a short code snippet but not enough for a full report. Reasoning stretches to 256,000 or 400,000 tokens depending on plan, closer to Claude’s territory but still billed differently through the chat-latest API alias at $5 per million input tokens and $30 per million output tokens.

For this tutorial’s router, send anything flagged “quick,” “chat,” or “support” straight to GPT Instant. The lower latency on short exchanges is noticeable in side-by-side testing, and most consumer-facing chat features do not need a reasoning pass for every single turn. Reserve GPT Reasoning for multi-step logic problems that are shorter than roughly 200,000 tokens, where Claude’s extra context headroom would otherwise go unused.

Step 9: Route Multimodal and Research Tasks to Gemini

Gemini 3.8 Flash is the strongest of the three for anything that mixes text with images, or needs a live search grounding pass baked into the same call. Its introductory pricing of $0.75 per million input tokens and $3.75 per million output tokens, both locked in only through December 31, 2026, makes it the cheapest full-size context window of the three right now, even though that rate doubles on January 1, 2027.

Google’s newer Gemini 4 Argon model complicates this step slightly, because it is not shipping as a standalone consumer release yet. Instead it is rolling out gradually inside GitHub Copilot’s Pro+, Max, Business, and Enterprise tiers, a path flagged for closer scrutiny after the UK AI Security Institute raised concerns about Argon’s behavior ahead of a full release. For this tutorial’s router, stick with Gemini 3.8 Flash for direct API calls outside of Copilot, and treat Argon as a Copilot-specific coding model rather than a general-purpose one until Google ships clearer standalone documentation.

Step 10: Wire GitHub Copilot Into Your Coding Workflow

Copilot does not plug into the Python router the same way the other three do, since most of its value lives inside the IDE, the pull request view, and the CLI rather than a raw API endpoint. Install the Copilot extension in VS Code, sign in with your GitHub account, and open the model picker inside Copilot Chat to confirm which models your plan unlocks.

PlanPriceBase AI CreditsFlex CreditsTotal Monthly Credits
Copilot Free$0Limited allowancen/aVaries
Copilot Pro$10 / month1,0005001,500
Copilot Pro+$39 / month3,9003,1007,000
Copilot Max$100 / month10,00010,00020,000
Copilot Business$19 / seat / month1,900 per usern/a1,900 per user
Copilot Enterprise$39 / seat / month3,900 per usern/a3,900 per user

These figures come straight from GitHub’s own Copilot plans documentation. Note that code completions and next-edit suggestions are unlimited and never consume AI credits on paid plans, so the credit math above only applies to chat, agent sessions, and model-specific requests. Overage beyond your plan’s pool bills at $0.01 per credit. For code review specifically, GitHub recently introduced ReviewBench, an internal benchmark built from real GitHub pull requests with multi-source ground truth, aimed at giving teams a production-aligned way to judge how well a coding agent catches real bugs rather than just passing a synthetic test.

Set your default model inside Copilot’s settings to Claude Sonnet 5.5 for day-to-day completions, and switch manually to Gemini 4 Argon or GPT-6.1 Sol for specific pull requests where you want a second opinion before merging. Running the same diff past two models before approval catches more mistakes than either one alone, and it is worth remembering that a recent METR study found developers using AI coding agents measured 19% slower on certain tasks despite feeling faster, so treat a second model’s review as a sanity check rather than a shortcut around testing. If you are coming from a different coding assistant entirely, our Cursor to Claude Code migration tutorial covers the switch in more detail.

Step 11: Track Cost Per Task Across All Four Models

Routing without tracking spend defeats the purpose, since the whole point is matching cost to task value. Extend the baseline script with simple logging that records which model answered, how many tokens it used, and what that request cost.

import json
from datetime import datetime

PRICING = {
    "claude-opus-5-5":    {"input": 4.00,  "output": 20.00},
    "claude-sonnet-5-5":  {"input": 2.00,  "output": 10.00},
    "claude-haiku-5-5":   {"input": 0.10,  "output": 0.50},
    "gpt-6.1-sol-reason": {"input": 5.00,  "output": 30.00},
    "gemini-3.8-flash":   {"input": 0.75,  "output": 3.75},
}

def log_request(model, input_tokens, output_tokens, log_path="usage_log.jsonl"):
    rate = PRICING.get(model, {"input": 0, "output": 0})
    cost = (input_tokens / 1_000_000 * rate["input"]) + \
           (output_tokens / 1_000_000 * rate["output"])

    entry = {
        "timestamp": datetime.utcnow().isoformat(),
        "model": model,
        "input_tokens": input_tokens,
        "output_tokens": output_tokens,
        "cost_usd": round(cost, 6)
    }

    with open(log_path, "a") as f:
        f.write(json.dumps(entry) + "\n")

    return entry

Sample output after logging a few requests:

{"timestamp": "2026-10-14T15:02:11", "model": "gemini-3.8-flash", "input_tokens": 1200, "output_tokens": 400, "cost_usd": 0.0024}
{"timestamp": "2026-10-14T15:03:47", "model": "claude-opus-5-5", "input_tokens": 85000, "output_tokens": 2200, "cost_usd": 0.384}
{"timestamp": "2026-10-14T15:05:02", "model": "claude-haiku-5-5", "input_tokens": 600, "output_tokens": 150, "cost_usd": 0.000135}

Running a weekly total against this log quickly shows whether your rules are actually saving money or just adding complexity. If every request is landing on Opus 5.5 regardless of size, your keyword rules in Step 6 need tightening.

Step 12: Automate Selection With Fallback Rules

Any provider can rate-limit or time out mid-task, and a router that just crashes when that happens defeats the point of running four models at once. Add a fallback chain so a failed call on one provider retries on the next-best option instead of stopping the whole workflow.

import time

def call_with_fallback(prompt, primary, fallback_chain, call_fn, max_retries=2):
    """Try the primary model, then fall back through the chain on failure."""

    models_to_try = [primary] + fallback_chain

    for model in models_to_try:
        for attempt in range(max_retries):
            try:
                return call_fn(model, prompt)
            except Exception as error:
                print(f"{model} failed (attempt {attempt + 1}): {error}")
                time.sleep(2 ** attempt)
        print(f"Moving on from {model} to next fallback option")

    raise RuntimeError("All models in the fallback chain failed")

A sensible default chain for most text tasks is Claude Sonnet 5.5 as primary, GPT-6.1 Sol Reasoning as the first fallback, and Gemini 3.8 Flash as the second. That order favors the model with the largest context window first, then balances cost against reliability for whatever is left.

Common Pitfalls When Running a Multi-Model Stack

  • Hardcoding a model name without a version check. Providers rename and retire model strings. Claude Haiku 5.5 replaced an earlier Haiku build within the same product cycle, so a router that never checks for deprecation warnings will quietly keep calling a model that is about to disappear.
  • Ignoring the cached-token discount. Anthropic bills cache reads at 5% of the standard input rate. Sending the same long system prompt on every call without using prompt caching means paying full price for text the model has already seen.
  • Routing every long task to the biggest model by default. Opus 5.5 at $20 output per million tokens is overkill for a 2,000 token summary. Match model size to task size, not just task importance.
  • Forgetting that ChatGPT’s context window shrinks by plan tier. A script that works fine against the Reasoning mode’s 400,000 token ceiling will silently truncate on Instant’s 54,000 token Plus-plan limit.
  • Treating Gemini 4 Argon as generally available everywhere. As of this writing it is rolling out gradually inside GitHub Copilot’s higher tiers only, not as a standalone API product, so code written against it will not run the same way outside Copilot.
  • Skipping rate-limit backoff. A tight retry loop without exponential backoff can get an API key temporarily suspended rather than just throttled.
  • Letting credentials live in shared notebooks. A .env file is only useful if it never gets pasted into a shared Jupyter notebook or Slack message by accident.

Troubleshooting Your Multi-AI Setup

Even a careful setup hits friction. Here are the issues that come up most often when running Claude, ChatGPT, Gemini, and Copilot together.

  • “Model not found” error from Anthropic or OpenAI. Double-check the exact model string against the provider’s current documentation. Model names change between preview and general availability.
  • 401 Unauthorized on every call. The API key usually was not loaded from .env correctly. Print os.getenv("ANTHROPIC_API_KEY") right after load_dotenv() to confirm it is not returning None.
  • 429 Too Many Requests. You hit a rate limit, not a billing problem. Add exponential backoff as shown in Step 12 rather than retrying instantly.
  • Responses get cut off mid-sentence. Increase the max_tokens parameter on the request. This is unrelated to the context window and purely caps the length of the reply.
  • Gemini calls return empty text. Check for a safety filter block in the response metadata before assuming the API itself failed.
  • GitHub Copilot model picker is missing Gemini 4 Argon. Confirm your plan is Pro+ or higher, since Argon is not available on the base Pro or Free tiers, and the rollout is still gradual even on eligible plans.
  • Cost tracker shows $0.00 for every request. The pricing dictionary in Step 11 only covers the models listed explicitly. Add an entry whenever you introduce a new model string, or the logger silently defaults to zero.
  • Router always picks the same model regardless of task. Print the task_type string right before the keyword checks in Step 6. A mismatch in casing or an unexpected label almost always explains this.
  • Virtual environment import errors after reopening the terminal. Reactivate the environment with source venv/bin/activate every new terminal session. It does not persist automatically.

Advanced Tips for Scaling the Router

Once the basic router is stable, a few upgrades make it hold up under real traffic instead of just personal testing.

  • Cache repeated system prompts explicitly with Anthropic’s prompt caching to collect the 5% cached-input rate on every repeat call instead of paying full price.
  • Replace the keyword-based router in Step 6 with a small, cheap classifier call, using Claude Haiku 5.5 or Gemini 3.8 Flash, that labels incoming tasks before routing them to the larger model. The classification call costs a fraction of a cent and prevents misrouted tasks from reaching an expensive model.
  • Batch low-priority requests, such as tagging or summarization, and send them during off-peak hours if your provider offers a discounted batch tier.
  • Build a simple dashboard off the usage_log.jsonl file from Step 11 so cost-per-model is visible weekly, not just discoverable after a surprise invoice.
  • Set a hard monthly spend cap in each provider’s billing dashboard. A router bug that loops unexpectedly should hit a wall before it hits your card.
  • Revisit the Gemini 3.8 Flash pricing in your cost dictionary before January 1, 2027, when introductory pricing expires and rates roughly double.

Data Privacy and Retention Settings to Check First

Running four providers at once means four separate data handling policies, and they are not identical. Before routing anything sensitive, such as customer records, source code under an NDA, or unreleased financial figures, check each provider’s current business-tier settings rather than assuming consumer defaults carry over to API usage.

  • Anthropic’s API traffic is not used to train models by default, and Claude’s Console lets an organization set a retention window separately from the consumer claude.ai product, which has its own settings.
  • OpenAI’s API traffic through the developer platform is excluded from model training by default as well, but anything typed into the consumer ChatGPT app follows a different, separately configurable retention and training toggle.
  • Google’s Gemini API traffic through AI Studio and Vertex AI carries its own data handling terms, and free-tier usage through AI Studio has historically been treated differently from paid Vertex AI traffic, so confirm which surface you are actually calling before sending anything confidential through a free-tier key.
  • GitHub Copilot’s enterprise and business tiers let an administrator block specific models entirely and restrict which repositories a coding agent can touch, which matters once Gemini 4 Argon or any third-party model is in the mix on a shared codebase.

A practical habit for this router: tag every task with a sensitivity flag alongside the task type from Step 6, and refuse to route anything flagged “confidential” to a free-tier key regardless of which model would otherwise win that task. The few seconds that check costs is cheaper than explaining a leak afterward.

Testing the Router Against Real Prompts

Before trusting this setup with production traffic, run it against a small batch of real prompts pulled from your own backlog rather than synthetic examples. Mixing task types in one batch exposes routing mistakes that a single clean test never catches.

Sample PromptEstimated TokensModel the Router Should PickWhy
Summarize a 40-page vendor contract~45,000Claude Sonnet 5.5Fits comfortably under Opus-level cost while keeping full context
Rewrite a 300,000-word internal wiki~310,000Claude Opus 5.5Exceeds the 150,000 token threshold set in Step 6
“What’s a quick way to fix this null pointer error?”~150GPT-6.1 Sol InstantShort, conversational, low stakes
Describe what’s wrong in this screenshot of a dashboard~800 plus imageGemini 3.8 FlashMultimodal input triggers the image keyword rule
Review this 200-line pull request diff~3,000GitHub Copilot (Sonnet 5.5 or Argon)Lives inside the IDE workflow from Step 10, not the Python router

Run ten to twenty prompts like these through router.py and check the printed model choice against what you would have picked manually. Disagreements usually point to a missing keyword in Step 6’s rules rather than a flaw in the underlying approach, and fixing them at this stage is far cheaper than discovering a misroute after it has already run against a real customer ticket.

The Complete Working Project

Putting every step together gives you a single script that routes a task, calls the right model with fallback protection, and logs the cost. Save this as router.py in the project folder created in Step 4.

import os, json, time
from datetime import datetime
from dotenv import load_dotenv
import anthropic, openai
from google import genai

load_dotenv()

PRICING = {
    "claude-opus-5-5":   {"input": 4.00, "output": 20.00},
    "claude-sonnet-5-5": {"input": 2.00, "output": 10.00},
    "claude-haiku-5-5":  {"input": 0.10, "output": 0.50},
    "gemini-3.8-flash":  {"input": 0.75, "output": 3.75},
}

claude = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
gpt = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
gemini = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))

def choose_model(task_type, token_estimate):
    task_type = task_type.lower()
    if token_estimate > 150_000:
        return "claude-opus-5-5"
    if "code" in task_type or "agent" in task_type:
        return "claude-sonnet-5-5"
    if "image" in task_type or "search" in task_type:
        return "gemini-3.8-flash"
    if "quick" in task_type or "chat" in task_type:
        return "chat-latest"
    return "claude-sonnet-5-5"

def call_model(model, prompt):
    if model.startswith("claude"):
        reply = claude.messages.create(model=model, max_tokens=500,
                                        messages=[{"role": "user", "content": prompt}])
        return reply.content[0].text, reply.usage.input_tokens, reply.usage.output_tokens
    if model == "chat-latest":
        reply = gpt.chat.completions.create(model=model, messages=[{"role": "user", "content": prompt}])
        usage = reply.usage
        return reply.choices[0].message.content, usage.prompt_tokens, usage.completion_tokens
    if model == "gemini-3.8-flash":
        reply = gemini.models.generate_content(model=model, contents=prompt)
        meta = reply.usage_metadata
        return reply.text, meta.prompt_token_count, meta.candidates_token_count
    raise ValueError(f"Unknown model: {model}")

def log_request(model, input_tokens, output_tokens):
    rate = PRICING.get(model, {"input": 0, "output": 0})
    cost = (input_tokens / 1_000_000 * rate["input"]) + (output_tokens / 1_000_000 * rate["output"])
    entry = {"timestamp": datetime.utcnow().isoformat(), "model": model,
              "input_tokens": input_tokens, "output_tokens": output_tokens, "cost_usd": round(cost, 6)}
    with open("usage_log.jsonl", "a") as f:
        f.write(json.dumps(entry) + "\n")
    return entry

def run_task(task_type, prompt, token_estimate=1000):
    model = choose_model(task_type, token_estimate)
    for attempt in range(2):
        try:
            text, in_tok, out_tok = call_model(model, prompt)
            log_request(model, in_tok, out_tok)
            return {"model": model, "response": text}
        except Exception as error:
            print(f"{model} failed: {error}")
            time.sleep(2 ** attempt)
    return {"model": model, "response": None, "error": "all retries failed"}

if __name__ == "__main__":
    result = run_task("quick chat", "Summarize this tutorial in one sentence.")
    print(result)

Run it with python3 router.py. A successful run prints the chosen model and its response, and appends a new line to usage_log.jsonl with the exact cost of that call. Swap the task description and prompt in the final block to test routing against your own real workloads, such as a document summary, a code review request, or a research question that needs search grounding.

2026 Pricing and Adoption at a Glance

Putting the adoption numbers next to the pricing data from Step 3 explains a lot about current usage patterns. ChatGPT’s dominant adoption share lines up with GPT-6.1 Sol Instant being the cheapest fast-response option for casual use, while Claude’s smaller but committed developer base tracks closely with Sonnet 5.5 and Opus 5.5’s strength on coding and long documents specifically.

AssistantShare of Developers Using ItPrimary Strength in This Tutorial’s Router
ChatGPT81.7%Fast, low-latency everyday replies
GitHub Copilot67.9%In-IDE code completion and PR review
Google Gemini47.4%Multimodal and search-grounded tasks
Claude Code40.8%Long-context coding and document work

Figures are drawn from the 2025 Stack Overflow Developer Survey’s reporting on out-of-the-box AI assistant usage among developers. None of these shares are mutually exclusive, which is exactly the point of building a router instead of picking a single favorite.

Frequently Asked Questions

Is it worth paying for all three API accounts instead of just one chat subscription?

For personal daily chat use, one consumer subscription is usually cheaper. Multi-model API access makes sense once you are building a workflow or product where task type varies enough that routing actually changes the output quality or cost per task, not just for casual browsing.

Which model Has the largest context window right now?

Claude Opus 5.5, Claude Sonnet 5.5, and Gemini 3.8 Flash all currently advertise a 1 million token context window, ahead of ChatGPT’s GPT-6.1 Sol Reasoning mode, which tops out around 400,000 tokens depending on plan.

Does GitHub Copilot actually use Claude, GPT, and Gemini models internally?

Yes. Copilot operates as a routing layer across multiple providers rather than running a single in-house model for everything, and it bills usage through a shared AI-credit system regardless of which underlying model answers a given request.

Why is Claude Haiku 5.5 so much cheaper than Opus 5.5?

Haiku 5.5 is Anthropic’s smaller, faster model tier, built for high-volume and low-latency tasks rather than deep reasoning. At $0.10 per million input tokens for prompts under 100,000 tokens, it costs a fraction of Opus 5.5’s $4.00 rate because it trades some reasoning depth for speed and cost efficiency.

Is Gemini 4 Argon available outside of GitHub Copilot yet?

As of this writing, Argon’s rollout is concentrated inside GitHub Copilot’s Pro+, Max, Business, and Enterprise plans, with gradual availability even among eligible users. A standalone Google AI Studio or Vertex AI listing for Argon had not appeared in official pricing documentation at the time this tutorial was written.

What happens if my router script picks the wrong model for a task?

Nothing catastrophic. Worst case, you pay slightly more than necessary for a simple task, or a very long document gets truncated if it is routed somewhere with a smaller context window. Reviewing the usage_log.jsonl file weekly, as covered in Step 11, catches these mismatches quickly.

Can I add more AI providers to this same router later?

Yes. The structure in the Complete Working Project section separates model selection, API calls, and cost logging into distinct functions specifically so a new provider only requires adding a new branch to call_model and a new entry in the PRICING dictionary, without touching the rest of the script.

How often do these model names and prices actually change?

Often enough that hardcoding them without a review schedule is risky. Claude Haiku 5.5 shipped on October 7, 2026, replacing an earlier build within the same year, and Gemini 3.8 Flash’s introductory pricing is already scheduled to change on January 1, 2027. Treat the pricing dictionary As a living document, not a one-time setup.

Related Coverage

Daniel Okafor

Daniel Okafor

Senior AI Reporter

Daniel Okafor is the Senior AI Reporter at TrendinTech, where he covers large language models, machine learning research and the practical use of artificial intelligence across business and government. He has a particular interest in evaluation: how models are benchmarked, where those benchmarks fail and what that means for the companies betting on them.

All stories by Daniel Okafor (356)

Related Articles