classifier

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package classifier asks an external model which tier and activity a prompt needs. It holds the shared contract (criteria, instructions, advice shape), one adapter per wire protocol (system-one, ollama), and a client with a total deadline, two attempts, and a breaker. Configured builds the client the config selects, from the selected name, its definitions and an env lookup, and says why it is off. Input carries only the prompt and clipped dialogue: Codex headers cannot reach an adapter by construction. Ported from claude-model-router lib/classifier-*.mjs.

Index

Constants

View Source
const (
	RetryDelay      = 100 * time.Millisecond
	ActivityStepMin = 300 * time.Millisecond
	FailuresToPause = 3
	PauseDuration   = 60 * time.Second
	MaxAnswerChars  = 16 * 1024
	MaxAttempts     = 2
)

Retry and breaker rules shared by every protocol.

Variables

This section is empty.

Functions

This section is empty.

Types

type ActivityAdvice

type ActivityAdvice struct {
	Choice        config.Activity
	Probabilities map[config.Activity]float64
}

ActivityAdvice is the task goal, using the existing activity wire name. It is nil when no valid answer was given.

type ActivityStep

type ActivityStep interface {
	BuildActivity(model string, in Input) ([]byte, error)
	ParseActivity(body []byte) *ActivityAdvice
}

ActivityStep is an Adapter whose protocol asks the activity in a second request. The Client sends it only with ActivityStepMin of the deadline left; ParseActivity returns nil for any answer it cannot read.

type Adapter

type Adapter interface {
	Build(model string, in Input) ([]byte, error)
	Parse(body []byte) (Advice, error)
}

Adapter builds a request body for a protocol and parses its answer.

func Ollama

func Ollama() Adapter

Ollama is Ollama's native chat API with a one-token answer: the model writes one letter per option, and the probability of each letter among the top candidates is the option's probability. It asks no continuation; the activity is a second request with the same system message and state prefix, so Ollama reuses the cached prefix.

func OpenAIDecisions added in v0.5.0

func OpenAIDecisions() Adapter

OpenAIDecisions is the OpenAI Decisions protocol (POST /v1/decisions): the state travels as JSON text in `input`, and the questions come back as named answers. The route and the activity are choices, the continuation a predicate.

func SystemOne

func SystemOne() Adapter

SystemOne is the typed-questions protocol of Jev and Clef: the route and the activity as choices, the continuation as a noul, all in one request. Cloudflare wraps the answer in `result`; Parse reads both shapes.

type Advice

type Advice struct {
	Choice        Choice
	Probabilities map[Choice]float64
	Continuation  *float64
	Activity      *ActivityAdvice
	Phase         *PhaseAdvice
	Latency       time.Duration
}

Advice is the shared answer shape every adapter returns. Continuation is nil when the protocol does not ask it.

type Asker

type Asker interface {
	Ask(ctx context.Context, in Input) (Advice, error)
	Health() Health
}

Asker is what the router depends on; Client implements it.

func Configured added in v0.7.2

func Configured(name string, defs map[string]config.Classifier, getenv func(string) string) (Asker, string)

Configured returns the classifier that name selects among defs, ready to ask its endpoint, or nil and the reason it is off. The key and each {NAME} placeholder of the endpoint come from the env var of that name, read with getenv, else from the classifier's envFile. A value found in neither turns it off: the router still runs and pins still work. The reason never holds a value.

type Choice

type Choice string

Choice is a route answer: a config.Tier or ChoiceUncertain.

const ChoiceUncertain Choice = "uncertain"

ChoiceUncertain is the route answer for a request that is unclear or not a task.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client asks one classifier endpoint. It allows one request at a time: a call waits, under its context, while another is in flight, and a request abandoned at the deadline holds the slot until it settles, so a late answer never overlaps the next turn's. now measures the budget, the breaker and the service latency, which excludes time waiting for the slot; the context carries the same timeout as a duration, so an injected clock never makes the request expire early or late.

func New

func New(cfg config.Classifier, key string, adapter Adapter, doer Doer, now func() time.Time) *Client

New returns a client for cfg. key is the bearer key read from cfg.KeyEnv; it is the only credential the client ever sends.

func (*Client) Ask

func (c *Client) Ask(ctx context.Context, in Input) (Advice, error)

Ask returns the classifier's advice for in, or a Code error. Cancellation and pause answers do not count toward the breaker.

func (*Client) Health

func (c *Client) Health() Health

Health returns the breaker state.

type Code

type Code string

Code is a classifier failure reason.

const (
	ErrTimeout     Code = "timeout"
	ErrMalformed   Code = "malformed"
	ErrAuth        Code = "auth"
	ErrHTTP        Code = "http"
	ErrUnreachable Code = "unreachable"
	ErrPaused      Code = "paused"
	ErrCancelled   Code = "cancelled"
)

func (Code) Error

func (c Code) Error() string

Error makes Code an error.

type Doer

type Doer interface {
	Do(req *http.Request) (*http.Response, error)
}

Doer sends one HTTP request; *http.Client satisfies it.

type Health

type Health struct {
	Failures      int           `json:"Failures"`
	PausedUntil   time.Time     `json:"PausedUntil"`
	Latency       time.Duration `json:"Latency"`
	QueueWait     time.Duration `json:"QueueWait"`
	QueueTimeouts uint64        `json:"QueueTimeouts"`
	// LastError is why the last call failed, as a short code such as
	// "timeout" or "http 503". Never the key or a response body. Empty after
	// a success.
	LastError string `json:"LastError"`
}

Health is the client's breaker state. A Snapshot carries it on the control wire, so its JSON names are spelled out and pinned by internal/control's protocol-v2 fixtures.

type Input

type Input struct {
	Prompt      string
	CurrentStep string
	GoalAnchor  string
	Dialogue    []Message
	Routes      map[config.Tier]config.Route
}

Input is everything a classifier request may contain.

type Message

type Message struct {
	Role string `json:"role"`
	Text string `json:"text"`
}

Message is one dialogue entry shown to the classifier.

type Phase added in v0.12.1

type Phase string

Phase identifies the current bounded stage of a task.

const (
	PhaseProduce   Phase = "produce"
	PhaseReason    Phase = "reason"
	PhaseVerify    Phase = "verify"
	PhaseExecute   Phase = "execute"
	PhaseReport    Phase = "report"
	PhaseUncertain Phase = "uncertain"
)

type PhaseAdvice added in v0.12.1

type PhaseAdvice struct {
	Choice        Phase
	Probabilities map[Phase]float64
}

PhaseAdvice is absent when a protocol cannot provide a valid phase.

Jump to

Keyboard shortcuts

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