scoring

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 14 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 scoring brings the fixed-choice classification pattern — score a small set of single-token options, normalize over exactly those labels, and let a policy decide what may act — into the kernel.

It is deliberately a PREPARER, not an Action. Enforcement happens in the supervisor's pre-check, which evaluates the REQUEST envelope; a scoring step that lived inside an action would run after the gate had already said yes. So this package turns a prompt into a Decision, and a Decision into the envelope you hand to ExecuteByName:

dec, err := scorer.Score(ctx, prompt, []string{"A", "B", "C"}, teams)
th, err := scoring.ThresholdsFromPolicyScaled(ctx, client.Engine(), "threshold_pm", scoring.PerMille)
env := scoring.Request(req, dec, th)
out, err := client.ExecuteByName(ctx, "route_ticket", env)

Division of labour (ADR-005): **Go measures and formats; the policy decides.** Request publishes the observation as per-mille integers — choice/1, score_pm/2 per class, score_lcb_pm/2 when bounded, score_source/1 — and the policy compares them with :lt/:ge against its own bars:

halt("Req", "low_confidence_send_to_review", "T1") :-
    action_operation("Req", "route_ticket"),
    choice(C), score_pm(C, P), class_bar(C, B), :lt(P, B).

Mangle's comparison builtins are integer-only (a float operand fails the evaluation with "value 0.9 is not a number"), which is why probabilities are scaled; cross-fact comparison itself works fine, so the arithmetic — and therefore the decision — genuinely lives in the policy, and the Explain tree shows it ("740 < 800" as a [builtin] step).

Thresholds/Flags still exist for reporting and for policies that prefer Go-computed booleans, but they are no longer what makes the gate decide.

A label whose probability cannot be observed is handled with bounds, not guesses: a truncated top-K view yields sound LOWER bounds (Truncated, Lower, Missing) because every unlisted token has p <= p_K <= p_top, so truncation cannot change the winner. Only when NO option is observable does it become ErrLabelsUnobserved, published as unobserved_distribution so the policy refuses. Nothing here ever renormalizes over survivors and calls it confidence.

Index

Constants

View Source
const PerMille = 1000

PerMille is the integer scale used when publishing probabilities to a policy: Mangle's :lt/:le/:gt/:ge are integer-only and reject floats loudly, so a probability becomes per-mille (0.740 -> 740). Per-mille matches the granularity of the thresholds people actually write (0.80, 0.70) and reads naturally in a proof tree ("740 < 800").

Variables

View Source
var ErrLabelsUnobserved = errors.New("scoring: option labels not all observable")

ErrLabelsUnobserved means one or more option labels had no observable probability (e.g. a hosted API returned a truncated top_logprobs list). The distribution over the options is unknowable, so no Decision is produced.

Functions

func FromPerMille added in v0.12.0

func FromPerMille(pm int64) float64

FromPerMille is the inverse, for reporting and calibration.

func Request

func Request(payload any, d *Decision, t Thresholds) core.Envelope

Request builds the envelope to pass to client.ExecuteByName for a routing call: the meta flags derived from the policy thresholds, plus the model's own numbers as explicit facts so a proof tree can ground them (confidence / margin_value / entropy_value).

payload may be the action's input value OR an already-built core.Envelope — ExecuteByName accepts both, so nesting an envelope inside an envelope would silently break the action's type assertion. When payload is an Envelope its facts, labels and metadata are preserved and the scoring facts/flags are merged in (scoring flags win on key collision).

A nil decision marks the distribution unobservable and publishes no numbers: the policy then decides, via the unobserved_distribution flag, that the request must not be auto-routed.

func RequestNoScore added in v0.12.0

func RequestNoScore(payload any, choice string) core.Envelope

RequestNoScore builds the envelope for a decision that has a CHOICE but no distribution — the generation lane: the model wrote a letter and that is all the evidence there is. It deliberately publishes no number, because a fabricated 1.0 would let any confidence bar pass and the proof tree would look authoritative about a value nobody measured. The policy gates on the ABSENCE of a score instead:

halt("Req", "no_score_present_review", "T1") :-
    action_operation("Req", "route_ticket"),
    meta("no_score_present", "true").

func Softmax

func Softmax(logProbs []float64) []float64

Softmax converts log-probabilities to probabilities (numerically stable). Provided so backends do not each re-derive exp(logp).

func ToPerMille added in v0.12.0

func ToPerMille(p float64) int64

ToPerMille scales a probability to the integer form a policy compares. It TRUNCATES toward zero: a borderline value rounds DOWN, so it fails the bar and lands in review/escalate rather than auto-routing. Fail-closed by construction — rounding half-up would let 0.7996 clear a 0.80 bar.

func ValidateSingleTokens

func ValidateSingleTokens(ctx context.Context, tk Tokenizer, labels []string) error

ValidateSingleTokens rejects any label that is not exactly one token — the trap where " A" and "A" are different token IDs, and a two-token label makes reading a single logit meaningless.

Scope: this guards the label_token_ids path (ScoreServer), which reads one logit per label and therefore cannot tolerate a split label. The hosted logprob path (ChatScorer) matches labels against returned token surfaces instead, so a split label simply never matches and surfaces as ErrLabelsUnobserved — safe, but reported differently.

Types

type ChatConfig

type ChatConfig struct {
	// BaseURL is the API root INCLUDING the version segment, e.g.
	// "https://api.openai.com/v1" or "http://localhost:8080/v1".
	BaseURL string
	// APIKey is sent as a bearer token; empty means no Authorization header
	// (useful against a local gateway).
	APIKey string
	// Model is the served model name.
	Model string
	// TopLogProbs is how many candidate tokens to request at the answer
	// position. Providers cap this (commonly 20); too small a value makes
	// labels unobservable, which the policy then escalates rather than
	// guessing. Defaults to 20.
	TopLogProbs int
	// HTTPClient overrides transport settings (timeouts, proxies, tests).
	HTTPClient *http.Client
}

ChatConfig configures the hosted, key-only backend: an OpenAI-compatible chat endpoint that returns token log-probabilities.

type ChatScorer

type ChatScorer struct {
	BaseURL     string
	APIKey      string
	Model       string
	TopLogProbs int
	Client      *http.Client
}

ChatScorer scores fixed-choice options through a hosted chat API by asking for ONE token with logprobs enabled, then reading the option labels out of the returned top_logprobs and renormalizing over exactly those.

It needs no scoring server, which is what makes it the practical default for hosted models — at one honest cost: top_logprobs is a TRUNCATED view of the vocabulary, so a label outside the returned set is unobservable. That is reported as ErrLabelsUnobserved rather than silently normalized away.

Token usage from the response is NOT retained: measurement (latency, tokens-per-case, calibration, permutation studies) is application-layer and lives with the caller, not in the kernel.

func NewChatScorer

func NewChatScorer(cfg ChatConfig) (*ChatScorer, error)

NewChatScorer validates cfg and builds a ChatScorer.

func (*ChatScorer) Score

func (s *ChatScorer) Score(ctx context.Context, prompt string, labels, options []string) (*Decision, error)

Score implements Scorer.

type Decision

type Decision struct {
	// Choice is a business option (the label's meaning), never a raw token.
	Choice string
	// Distribution maps option -> probability, normalized to sum to 1 over
	// exactly the options given. All other vocabulary mass is discarded —
	// that is what "restricted" softmax means.
	//
	// When Truncated is set these are sound LOWER bounds (see Truncated), so a
	// consumer that ignores the flag under-estimates confidence instead of
	// over-estimating it.
	Distribution map[string]float64
	// Margin is top minus runner-up; Entropy is Shannon entropy in nats.
	Margin  float64
	Entropy float64

	// Source names where the numbers came from, e.g. "score_server",
	// "chat_logprobs", "chat_logprobs_truncated", "mock". It is published to
	// the policy as score_source/1 so a policy can refuse to auto-route on
	// evidence it considers too soft — the tier of the evidence is a policy
	// input, not a Go default.
	Source string

	// Truncated reports that some option's probability was NOT observable
	// (a hosted top_logprobs list is a truncated view of the vocabulary).
	// Missing names them, and Lower carries the sound lower bound per option.
	Truncated bool
	Missing   []string
	Lower     map[string]float64
	// Upper is the survivor-normalized view (what you would get pretending the
	// unobserved options do not exist). Reporting only — never gate on it when
	// Truncated is set; gate on Distribution/Lower, which are sound bounds.
	Upper map[string]float64
}

Decision is one fixed-choice read: the winning business option plus the probability the model assigned to every option.

func Build

func Build(labels, options []string, probs []float64) (*Decision, error)

Build turns raw probabilities (any positive scale; they are renormalized) into a Decision over options. probs may be probabilities from a server-side restricted softmax, or exp(logprob) from a hosted API — either way the result sums to 1 over exactly the options given.

Ties break toward the FIRST option, so a Decision never depends on map iteration or on which duplicate happened to arrive last.

Passing log-probabilities by mistake fails loudly ("sum to zero") instead of producing confident nonsense: every logprob is <= 0 and clamps to 0.

func (*Decision) Prob

func (d *Decision) Prob(option string) float64

Prob returns the probability of an option (0 when absent).

func (*Decision) Top

func (d *Decision) Top() float64

Top returns the winning option's probability.

type HTTPTokenizer

type HTTPTokenizer struct {
	BaseURL string
	Client  *http.Client
}

HTTPTokenizer talks to an OpenAI-compatible /tokenize endpoint (SGLang and vLLM both expose one) to count tokens and resolve single-token ids.

func NewHTTPTokenizer

func NewHTTPTokenizer(baseURL string, client *http.Client) *HTTPTokenizer

NewHTTPTokenizer builds a tokenizer client for base (no /v1 suffix needed).

func (*HTTPTokenizer) SingleTokenID

func (t *HTTPTokenizer) SingleTokenID(ctx context.Context, text string) (int, error)

SingleTokenID returns the token id when text occupies exactly one token.

func (*HTTPTokenizer) TokenLen

func (t *HTTPTokenizer) TokenLen(ctx context.Context, text string) (int, error)

TokenLen returns the token count of text.

type IntThresholds added in v0.12.0

type IntThresholds struct {
	Auto   int64
	Margin int64
	Review int64
}

IntThresholds are threshold bars in the policy's own integer scale.

func ThresholdsFromPolicyInts added in v0.12.0

func ThresholdsFromPolicyInts(ctx context.Context, q PolicyQuery, predicate string) (IntThresholds, error)

ThresholdsFromPolicyInts reads integer bars without rescaling — useful when the caller wants to compare in the policy's own units.

type PolicyQuery

type PolicyQuery interface {
	Query(ctx context.Context, facts []string, query string) ([]map[string]string, error)
}

PolicyQuery is the slice of the engine surface needed to read policy facts (satisfied by core.Evaluator / client.Engine()).

type ScoreConfig

type ScoreConfig struct {
	BaseURL    string // e.g. "http://localhost:30000" (no /v1 suffix)
	Model      string
	HTTPClient *http.Client
	// Tokenizer resolves labels to token ids. Required unless LabelTokenIDs
	// supplies them directly.
	Tokenizer TokenIDResolver
	// LabelTokenIDs supplies label -> token id up front, for deployments
	// without a /tokenize endpoint. The caller asserts they are single tokens.
	LabelTokenIDs map[string]int
	// SpacePrefix scores " A" instead of "A" when the chat template glues a
	// space to the answer token — the case where the two are different ids.
	SpacePrefix bool
}

ScoreConfig configures an OpenAI-compatible /v1/score endpoint (SGLang native API).

type ScoreServer

type ScoreServer struct {
	BaseURL       string
	Model         string
	Client        *http.Client
	Tok           TokenIDResolver
	LabelTokenIDs map[string]int
	SpacePrefix   bool
	// contains filtered or unexported fields
}

ScoreServer scores through a /v1/score endpoint that accepts explicit label_token_ids, i.e. the exact path the fixed-choice recipe describes: the server restricts the softmax to the labels you name, so no candidate can be silently truncated the way a hosted top_logprobs list can.

func NewScoreServer

func NewScoreServer(cfg ScoreConfig) (*ScoreServer, error)

NewScoreServer validates cfg and builds the backend. Either Tokenizer or LabelTokenIDs must be able to resolve every label to one token id.

func (*ScoreServer) Score

func (s *ScoreServer) Score(ctx context.Context, prompt string, labels, options []string) (*Decision, error)

Score implements Scorer. One request per prompt: the server reads the vocabulary distribution at the answer position and returns the probability of exactly the label tokens.

type Scorer

type Scorer interface {
	// Score labels the prompt with labels (the single-token surfaces, in
	// option order) and reports the winner by business option name.
	Score(ctx context.Context, prompt string, labels, options []string) (*Decision, error)
}

Scorer produces a Decision for one prompt. Implementations must return a distribution normalized over exactly the supplied labels.

type Thresholds

type Thresholds struct {
	// Auto: the top probability must clear this to be auto-routed.
	Auto float64
	// Margin: the minimum lead over the runner-up (advisory by convention).
	Margin float64
	// Review: below this floor, escalate to a human rather than review-queue.
	Review float64
}

Thresholds are the confidence bars a routing policy applies to a Decision.

NOTE: since the per-class/comparison-in-policy design, these values are for REPORTING (logs, calibration, the deprecated Go-side Flags). The gate itself compares integers inside the policy with :lt/:ge — see Request and ADR-005.

func ThresholdsFromPolicy

func ThresholdsFromPolicy(ctx context.Context, q PolicyQuery, predicate string) (Thresholds, error)

ThresholdsFromPolicy reads threshold("<name>", V) facts from the ACTIVE policy program. After a client.ReloadPolicy these are the NEW numbers, which is the whole point: changing a bar needs no rebuild.

It expects facts named auto, margin and review, and errors if a name is missing, non-numeric, or ambiguous — a silently absent threshold would turn into a silently permissive 0.0. For integer (per-mille) policies use ThresholdsFromPolicyScaled.

func ThresholdsFromPolicyScaled added in v0.12.0

func ThresholdsFromPolicyScaled(ctx context.Context, q PolicyQuery, predicate string, scale int) (Thresholds, error)

ThresholdsFromPolicyScaled reads integer threshold facts (e.g. threshold_pm("auto", 800)) and converts them to probabilities using scale. It is the integer counterpart of ThresholdsFromPolicy: Mangle's comparison builtins are integer-only, so a policy that does its own :lt comparisons holds integers, while Go still wants floats for reporting and calibration.

The same distrust applies: missing, non-numeric, inverted or ambiguous bars are hard errors.

func (Thresholds) Flags

func (t Thresholds) Flags(d *Decision) map[string]string

Flags compares a Decision against the thresholds and returns the boolean meta flags a policy pattern-matches on. Only triggered flags are present: policy rules key on fact EXISTENCE, which is how the engine expresses "the comparison was true".

A nil decision (an unobservable distribution) yields just the unobserved_distribution flag — the policy, not Go, then refuses.

type TokenIDResolver

type TokenIDResolver interface {
	Tokenizer
	SingleTokenID(ctx context.Context, text string) (int, error)
}

TokenIDResolver extends Tokenizer with single-token id lookup, which the label_token_ids style of scoring needs.

type Tokenizer

type Tokenizer interface {
	TokenLen(ctx context.Context, text string) (int, error)
}

Tokenizer resolves text to its token count (and, for one-token text, its id) on the serving backend.

Jump to

Keyboard shortcuts

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