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.ThresholdsFromPolicy(ctx, client.Engine(), "threshold")
env := scoring.Request(prompt, dec, th)
out, err := client.ExecuteByName(ctx, "route_ticket", env)
The thresholds are NOT owned here. They are policy facts; this package only does the arithmetic the Datalog engine deliberately refuses to do (cross-fact :lt on floats) and publishes the result as meta flags — the same boundary devops_policy_gate documents: Go computes, the policy gates.
A label whose probability cannot be observed (a truncated top-K view) is reported as ErrLabelsUnobserved and published as an unobserved_distribution flag, so the policy — not a Go fallback that invents a number — decides that the request must not be auto-routed.
Index ¶
- Variables
- func Request(payload any, d *Decision, t Thresholds) core.Envelope
- func Softmax(logProbs []float64) []float64
- func ValidateSingleTokens(ctx context.Context, tk Tokenizer, labels []string) error
- type ChatConfig
- type ChatScorer
- type Decision
- type HTTPTokenizer
- type PolicyQuery
- type ScoreConfig
- type ScoreServer
- type Scorer
- type Thresholds
- type TokenIDResolver
- type Tokenizer
Constants ¶
This section is empty.
Variables ¶
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 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 Softmax ¶
Softmax converts log-probabilities to probabilities (numerically stable). Provided so backends do not each re-derive exp(logp).
func ValidateSingleTokens ¶
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.
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.
Distribution map[string]float64
// Margin is top minus runner-up; Entropy is Shannon entropy in nats.
Margin float64
Entropy float64
}
Decision is one fixed-choice read: the winning business option plus the probability the model assigned to every option.
func Build ¶
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.
type HTTPTokenizer ¶
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 ¶
SingleTokenID returns the token id when text occupies exactly one token.
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.
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.
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.