Skip to main content

routewise (Python SDK)

Thin client for the routewise cost-aware LLM router. No routing logic lives here -- it's a convenience wrapper around HTTP calls to the real API.

Install

pip install routewise

Quick start

from routewise import RouteWiseClient

client = RouteWiseClient(api_key="rw_your_key_here")

result = client.ask("What is the capital of France?")
print(result["response"])
print(result["routed_to"], result["cost_usd"])

Pick a model (difficulty policy)

ask() accepts a product name that chooses which routing policy to use:

model Policy Who it's for
emma generic General-purpose routing (default)
lisa 3-tier support Customer support — cheap / mid / frontier
kate 2-tier support Customer support — cheap / frontier only
# customer support, scored by the support-specific difficulty model
result = client.ask("I want a refund", model="lisa")

# 2-tier support policy — no mid tier
result = client.ask("I was charged twice", model="kate")

# raw policy id wins over the name
result = client.ask("My order is late", support_mode="3tier")

# ask_stream works the same way; the final meta dict includes support_mode
for item in client.ask_stream("Where is my order?", model="lisa"):
    if isinstance(item, str):
        print(item, end="", flush=True)
    else:
        print(f"\n--- {item['tier']} {item['support_mode']} ---")

# the OpenAI-compatible chat path accepts the same names
client.chat([{"role": "user", "content": "Refund please"}], model="kate")

# discover all models + their cuts/evals
client.get_models()

Bring your own model

Override any tier with your own provider and model. Unset tiers fall back to defaults automatically.

# set custom models for any combination of tiers
client.configure(
    cheap={"provider": "openrouter", "model_id": "deepseek/deepseek-v4-flash", "api_key": "sk-or-v1-..."},
    frontier={"provider": "openai", "model_id": "gpt-4o", "api_key": "your-openai-key"},
    # mid not set -- uses default
)

# config is stored in memory and sent with every ask() as a per-request
# BYOM override -- your API keys never touch the router's database.
result = client.ask("Design a distributed rate limiter")
print(result["response"])

configure() applies the config client-side on every request (works with a plain rw_ API key — no sign-in needed). reset() clears it.

Spend tags

Two optional tags label who is paying, so the dashboard can group spend by team instead of showing a single total. They travel as HTTP headers, so the request body is unchanged.

# default for every call on this client
client = RouteWiseClient(api_key="rw_your_key_here", team="growth", feature="onboarding")

# per-call override (team wins over the client default)
client.ask("draft a launch tweet", team="marketing", feature="launch")

# read the grouped spend back, most expensive team first
for row in client.get_teams():
    print(row["team_id"], row["cost_usd"], row["saved_usd"], row["savings_pct"])

Tags are optional and never fail a request. Untagged calls group under team_id: None. The server lowercases them and keeps a-z, digits, dots and hyphens, so Growth Team and growth_team land in one row.

Budgets

Every response carries a budget block. It names the cap that decided the answer (scope), how much is spent, what is left and the state. When a cap runs out the request is downgraded to the cheap tier, never rejected, and the block explains why:

result = client.ask("design a distributed rate limiter")
print(result["routed_to"])              # "cheap" -- forced by the budget
print(result["budget"]["state"])        # "exhausted"
print(result["budget"]["scope"])        # "team_monthly"
print(result["budget"]["remaining_usd"])  # 0.0

# or ask for just the budget posture
budget = client.get_budget()
print(budget["state"], budget["downgrades_this_month"])

States are ok, warning (from 80%), exhausted and unlimited. The OpenAI-compatible path exposes the same block as response["x-routewise-budget"] and via x-routewise-budget-* headers, so a client that logs headers still sees why a cheaper model answered.

Explain a route first

explain() runs the same score, policy and threshold as ask() but stops before any provider call: no tokens spent, no cache read or write, no log row. It returns the score, the chosen tier, both cuts, the boundary that decided it and a plain-language summary.

plan = client.explain("design a distributed rate limiter")
print(plan["summary"])
print(plan["tier"], plan["difficulty_score"], plan["boundary"])

# the same options as ask()
plan = client.explain("I want a refund", model="lisa", threshold=2)

Feedback and human labels

Thumbs up/down and the "which tier should this have used?" label are separate, so you can review the routing without judging the answer.

result = client.ask("summarize this contract")
client.feedback(result["request_log_id"], "down", reason="missed the cap")
client.label(result["request_log_id"], "frontier")   # None clears it

# down-voted and unlabeled rows float to the top
queue = client.get_labeling_queue(limit=25)
print(queue["stats"], queue["items"][0]["query"])

Insights, evaluation and export

# score queries with no provider call and no key
client.evaluate(["what is 2+2", "design a rate limiter"])

# what did routing save over a window?
client.get_savings_report(days=30)

# why did spend move? current window vs the previous one
client.get_spend_insights(window_hours=24)

# spend by feature tag, per-policy replay, calibration and tier reliability
client.get_tag_analytics(days=30)
client.get_policy_analytics()
client.get_reliability()

# threshold recompute and policy replay, both estimates
client.get_compare()
client.get_calibrate()
client.simulate(source="queries", queries=["a", "b"], policy="3tier")

# provider circuit-breaker and key-pool state
client.get_provider_health()
client.get_provider_timeline(limit=50, hours=24)

# CSV for a spreadsheet or finance
open("logs.csv", "w").write(client.export_logs_csv(limit=1000))
open("chargeback.csv", "w").write(client.export_chargeback_csv(days=30))

All methods

# routing
client.ask("query")                          # auto-route by difficulty
client.ask("query", override_tier="frontier") # force a specific tier
client.ask("query", model="lisa")             # use the 3-tier support policy
client.ask("query", user_api_keys={"frontier": "sk-..."})  # per-request key override
client.explain("query")                      # same score, no provider call

# feedback and review
client.feedback(log_id, "up|down", reason=None, expected_tier=None)
client.label(log_id, "cheap|mid|frontier|None")
client.get_labeling_queue(limit=25)

# spend tags -- grouped per team in the dashboard
client.ask("query", team="growth", feature="onboarding")
client.get_teams()      # per-team spend, all-frontier cost, savings
client.get_budget()     # binding cap, spend, remaining, state, downgrades

# byom config — set one, two, or all three tiers; unset tiers keep defaults
client.configure(cheap={...}, mid={...}, frontier={...})  # set custom models
client.get_config()     # see currently active config (no keys returned)
client.get_models()     # list available models + policies (cuts, tiers, evals)
client.get_providers()  # list all supported providers + models
client.reset()          # revert all tiers to defaults, clears in-memory keys

# logs and analytics
client.stats()          # total requests, cost saved, tier distribution, etc.
client.get_logs(limit=50, team=None, feature=None, tier=None,
                cache_hit=None, budget_capped=None, query=None)
client.get_log_detail(log_id)
client.get_analytics()
client.get_savings_report(days=30)
client.get_spend_insights(window_hours=24)
client.get_tag_analytics(days=30)
client.get_policy_analytics()
client.get_reliability()
client.get_compare()
client.get_calibrate()

# evaluation and export
client.evaluate(["query"])
client.simulate(source="logs|queries", limit=100, queries=None,
                policy="generic|2tier|3tier", threshold=1.0, max_tier=None)
client.export_logs_csv(limit=1000)
client.export_chargeback_csv(days=30)

# provider health
client.get_provider_health()
client.get_provider_timeline(limit=50, hours=24)

Supported providers

providers = client.get_providers()
# returns: groq, openrouter, openai, anthropic, gemini, deepseek, perplexity,
#          mistral, xai, ollama
# each with a list of known models + "custom" option

Errors

Exception When
RouteWiseError Base class for all errors
ValidationError Bad input — empty query, unsupported provider, invalid model (400)
AuthError Invalid/missing API key or rate limit hit (401/429)
AllTiersFailedError Every provider tier failed, no response returned (503)
from routewise import RouteWiseClient, ValidationError, AuthError, AllTiersFailedError

try:
    result = client.ask("hello")
except AllTiersFailedError:
    print("all providers down")
except AuthError:
    print("check your api key")
except ValidationError as e:
    print(f"bad request: {e}")

Metadata

Release files for routewise 0.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for routewise 0.6.0
File Size Uploaded Provenance Actions
routewise-0.6.0.tar.gz 15.5 kB Without provenance Details for routewise-0.6.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for routewise 0.6.0
File Interpreter ABI Platform Actions
routewise-0.6.0-py3-none-any.whl Python 3 none any Details for routewise-0.6.0-py3-none-any.whl

Total release size: 27.7 kB

Release files / routewise-0.6.0.tar.gz

Download URL routewise-0.6.0.tar.gz
Size 15.5 kB
Tags Source
SHA-256 checksum
How to use checksums
ab20b14c8bda8b5db5356ec2d3e98ab750ceb97ed1500381648f4cccd9cc303b
BLAKE2b-256 checksum
How to use checksums
6ad37af5580126addeb384f01586cbc87bbb2cfe4a0ebb906b936da6257de5b9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.2

Release files / routewise-0.6.0-py3-none-any.whl

Download URL routewise-0.6.0-py3-none-any.whl
Size 12.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
da30ef29713ed26c6cbc3d0739433c18943ed13380784c6049e2275ac84312a1
BLAKE2b-256 checksum
How to use checksums
00f9c1f4f6f5c325a8810c1a1c070299248b6779e77ff7f32db61985d55cea92
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.2

Security for routewise 0.6.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page