router

package
v1.809.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 15, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package router turns a chat request into a concrete model id. It backs the virtual `auto`/`zen-router` model: classify the request into a coarse task, then pick the preferred servable model for that task. The classifier is a faithful port of hanzo-router's Rust Heuristic (engine/hanzo-router/ src/classify.rs); the Client can instead consult a learned zen-router served by hanzo-engine, falling back to this heuristic on ANY error so `auto` works with zero extra infrastructure.

Index

Constants

View Source
const (
	SourceEngine    = "engine"
	SourceHeuristic = "heuristic"
)

Source labels which strategy produced a Decision.

View Source
const DefaultTaskKey = "default"

DefaultTaskKey is the catch-all preference list consulted when a task has no entry of its own. Mirrors hanzo-router policy's General fallback.

View Source
const DefaultTimeout = 150 * time.Millisecond

DefaultTimeout is the hard cap on the engine round-trip. Routing must add negligible latency to a completion, so a slow/unreachable engine falls through to the local heuristic well within budget.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// Endpoint is the zen-router base URL (e.g. http://engine.hanzo.svc:3000).
	// Empty disables the engine strategy — heuristic only.
	Endpoint string
	// Timeout hard-caps the engine round-trip (default DefaultTimeout).
	Timeout time.Duration
	// Policy is the heuristic task→model table (and the map for an engine reply
	// that returns only a task).
	Policy Policy
	// HTTP is the client used for the engine call (default http.DefaultClient).
	HTTP *http.Client
	// Known, if set, restricts choices to models the caller can serve; a choice
	// it rejects is skipped. nil accepts all.
	Known func(string) bool
}

Client resolves a Request to a concrete model id. Strategy order:

  1. engine — POST {Endpoint}/route and use its choice (a learned zen-router served OpenAI-compatibly by hanzo-engine); hard-capped by Timeout.
  2. heuristic — Classify + Policy, a pure-Go port of the Rust rule router.

Any engine error (unreachable, timeout, non-200, bad body, unservable choice) falls through to the heuristic, so `auto` always resolves with zero extra infrastructure.

func (Client) Route

func (c Client) Route(ctx context.Context, req Request, slo Slo) (model string, task Task)

Route resolves req to a concrete model id and the task it was classified as. It never errors: on any engine failure it returns the heuristic decision. It is a thin projection of RouteDecision for callers that only need the id.

func (Client) RouteDecision

func (c Client) RouteDecision(ctx context.Context, req Request, slo Slo) Decision

RouteDecision resolves req to a full Decision (model, task, confidence, source, features). It never errors: on any engine failure it returns the heuristic decision (Source == SourceHeuristic, no confidence or features).

type Decision

type Decision struct {
	Model      string
	Task       Task
	Confidence float64
	Source     string
	Features   []float64
}

Decision is the full outcome of resolving a request: the chosen model, the task it was classified as, the engine confidence (0 for the heuristic), the Source that produced it, and the engine's optional feature vector. It carries exactly what the routing ledger records — no prompt text.

type Policy

type Policy struct {
	// Prefer maps a task tag (Task values, plus "default") to an ordered list of
	// model ids. The first entry accepted by the `known` predicate wins.
	Prefer map[string][]string
	// CostCeiling is an optional advisory per-1k cost cap forwarded to the engine
	// SLO; it does not filter the heuristic table (the table is already curated).
	CostCeiling float64
}

Policy is the per-task model preference table plus a cost knob. It mirrors the declarative shape of hanzo-router's router_policy.yaml: ordered model-id preference per task, first usable wins, with a General/`default` catch-all.

func (Policy) ForTask

func (p Policy) ForTask(task Task, known func(string) bool) string

ForTask returns the preferred model id for a task: the first entry in Prefer[task] accepted by `known`, else the first in Prefer["default"]. `known` (nil = accept all) lets the caller restrict the choice to models it can actually serve for this org. Returns "" when neither list yields a match.

type Request

type Request struct {
	// Text is the concatenated user text (the last user turn is enough).
	Text string
	// ApproxTokens is the approximate prompt length in tokens (drives
	// long-context routing).
	ApproxTokens int
	// HasMedia is true when the request carries image/video input.
	HasMedia bool
	// TaskHint is an optional explicit task override; "" skips it.
	TaskHint Task
}

Request is the value the router reasons about — extracted from the chat request by the caller so classification stays pure. Mirrors classify.rs's Request.

type Slo

type Slo struct {
	MaxCost      float64 `json:"max_cost"`
	MaxLatencyMs int     `json:"max_latency_ms"`
}

Slo is the per-request service-level objective forwarded to the engine. `0` fields disable the corresponding ceiling. It mirrors hanzo-router's Slo (the operator's budget for this request), distinct from a user's learned taste.

type Task

type Task string

Task is the coarse task bucket a request is classified into. Values mirror the snake_case tags of hanzo-router's registry::Task so a learned classifier and this heuristic produce interchangeable labels.

const (
	TaskCode        Task = "code"
	TaskReasoning   Task = "reasoning"
	TaskMath        Task = "math"
	TaskCreative    Task = "creative"
	TaskVision      Task = "vision"
	TaskLongContext Task = "long_context"
	TaskCheapChat   Task = "cheap_chat"
	TaskGeneral     Task = "general"
)

func Classify

func Classify(req Request) Task

Classify maps a request to a Task using keyword/length/media heuristics. This is a faithful port of hanzo-router's Heuristic::classify — same order, same keyword sets, same thresholds — so routing matches the Rust engine's rule path.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL