Documentation
¶
Overview ¶
Package router selects an authorized, compatible text model and performs one non-streaming inference. It supports application-executed function tools, a bounded JSON Schema subset, and reasoning passthrough. It does not execute tools, persist conversations, stream, or serve HTTP.
Construct shared providers, adapt each with Connector, register them as Targets and call New. With no Selector, Generate resolves Request.Model exactly. A Selector may choose only one of the eligible candidates it is given. Hosts own authentication and supply trusted identity through context; Target.Allow and an optional Admission implementation enforce it on every request.
Errors returned by Generate carry a transport-neutral Kind. The dialect codecs under router/dialect translate public API shapes (OpenAI Chat Completions, OpenAI Responses, Anthropic Messages) to and from Request and Result and map kinds to status codes.
See ExampleNew and Documentation/router.md for complete construction examples.
Index ¶
- Constants
- func Connector(model llms.Model) (llms.InferenceModel, error)
- func Invalid(param, format string, args ...any) error
- func NewError(kind Kind, param, format string, args ...any) error
- func Unsupported(param, format string, args ...any) error
- type Admission
- type AdmissionRequest
- type Candidate
- type Config
- type Decision
- type Error
- type Features
- type Kind
- type Observation
- type Request
- type Result
- type Router
- type SelectionInput
- type Selector
- type SelectorFunc
- type Target
Examples ¶
Constants ¶
const FallbackRequested = "requested"
FallbackRequested configures Config.Fallback to use the requested model when the selector fails.
Variables ¶
This section is empty.
Functions ¶
func Connector ¶
func Connector(model llms.Model) (llms.InferenceModel, error)
Connector exposes the optional lossless inference contract of a constructed model. Legacy-only models are rejected rather than silently losing controls.
func NewError ¶
NewError creates a classified error without a cause. The message is a fmt format string when args are supplied and used verbatim otherwise.
func Unsupported ¶
Unsupported reports a well-formed control that cannot be honored.
Types ¶
type Admission ¶
type Admission interface {
// Admit blocks or rejects until the request may proceed.
Admit(context.Context, AdmissionRequest) (release func(), err error)
}
Admission decides whether a request may proceed to selection and inference. Implementations may return a *Error to control the reported kind; any other error is reported as KindRateLimited. The release function is called exactly once when the request finishes, whether or not inference happened.
func ConcurrencyLimit ¶
ConcurrencyLimit returns an Admission that allows n concurrent requests and rejects further requests immediately with KindRateLimited. n must be positive.
type AdmissionRequest ¶
AdmissionRequest is what an Admission implementation may inspect. Trusted identity is expected in the context, not in the request.
type Config ¶
type Config struct {
Targets []Target
Selector Selector
// SelectorTimeout bounds one selector call; zero selects 5s.
SelectorTimeout time.Duration
// Timeout bounds the whole request; zero imposes no router deadline.
Timeout time.Duration
// Admission is optional host-supplied admission control; nil admits everything.
Admission Admission
// Fallback is an explicit target ID, or FallbackRequested for the incoming model.
// It applies only to selector failures; inference is never retried.
Fallback string
MinimumConfidence float64
// Observe must be concurrency-safe, return promptly, and must not panic.
Observe func(context.Context, Observation)
}
Config supplies immutable routing policy and finite operational limits.
type Decision ¶
type Decision struct {
TargetID string
Classification string
Confidence *float64
Usage llms.Usage
UsageKnown bool
}
Decision selects a registered candidate and records optional classification usage.
type Error ¶
Error is a transport-neutral routing failure with a client-safe message and a retained diagnostic cause. Message never contains provider text.
type Features ¶
type Features struct {
Tools bool
JSON bool
JSONSchema bool
StrictSchema bool
StrictTools bool
SchemaWithTools bool
DeveloperRole bool
Reasoning bool
Seed bool
}
Features describes model-specific combinations an operator has certified.
type Kind ¶
type Kind string
Kind classifies a routing failure independently of any transport. Dialect codecs map kinds to their own status codes and envelopes.
const ( // KindInvalidRequest is a malformed or out-of-bounds request. KindInvalidRequest Kind = "invalid_request" // KindUnsupported is a well-formed control the selected model cannot honor. KindUnsupported Kind = "unsupported" // KindModelNotFound is an unknown, unregistered or invisible model name. KindModelNotFound Kind = "model_not_found" KindSelectionUnavailable Kind = "selection_unavailable" // KindRateLimited is an admission rejection or an upstream rate limit. KindRateLimited Kind = "rate_limited" // KindUpstream is a provider failure or an invalid provider response. KindUpstream Kind = "upstream_error" // KindTimeout is an exhausted deadline before a response was available. KindTimeout Kind = "timeout" // KindCancelled is a caller cancellation. KindCancelled Kind = "cancelled" // KindInternal is an unexpected failure inside the router or a callback. KindInternal Kind = "internal_error" )
type Observation ¶
type Observation struct {
RequestID string
TargetID string
BackendModel string
Classification string
Duration time.Duration
SelectorUsage llms.Usage
SelectorUsageKnown bool
Usage llms.Usage
UsageKnown bool
// UsageInconsistent is set when the provider's counters did not add up and
// Usage was therefore reported as unknown to the caller.
UsageInconsistent bool
Err error
}
Observation reports one routing attempt without request content or credentials. Err retains internal diagnostics; do not serialize it into a client response.
type Request ¶
type Request struct {
Model string
Input llms.InferenceRequest
Metadata map[string]string
}
Request contains a public model/alias and the portable inference input. Input.Model is ignored; only the registered target selects the backend model.
type Result ¶
type Result struct {
ID string
CreatedAt int64
Model string
BackendModel string
Classification string
Response llms.InferenceResponse
}
Result identifies the selected public model and preserves ordered generation data, including reasoning blocks the application may store or strip.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is safe for concurrent requests when supplied callbacks and connectors are.
func New ¶
New validates a catalog and installs defaults. It never invokes a provider.
Example ¶
package main
import (
"context"
"fmt"
"github.com/effective-security/gogentic/pkg/llms"
"github.com/effective-security/gogentic/router"
)
type exampleModel struct{}
func (exampleModel) ValidateInference(llms.InferenceRequest) error { return nil }
func (exampleModel) Infer(context.Context, llms.InferenceRequest) (*llms.InferenceResponse, error) {
return &llms.InferenceResponse{
Content: []llms.InferenceBlock{{
Type: llms.BlockText,
Text: "Hello",
}},
FinishReason: llms.FinishStop,
}, nil
}
func main() {
r, err := router.New(router.Config{
Targets: []router.Target{{
ID: "chat",
BackendModel: "configured-model",
Connector: exampleModel{},
}},
})
if err != nil {
panic(err)
}
result, err := r.Generate(context.Background(), router.Request{
Model: "chat",
Input: llms.InferenceRequest{
Messages: []llms.InferenceMessage{{
Role: llms.InferenceRoleUser,
Content: []llms.InferenceBlock{{
Type: llms.BlockText,
Text: "Hello",
}},
}},
},
})
if err != nil {
panic(err)
}
fmt.Println(result.Model, result.Response.Content[0].Text)
}
Output: chat Hello
type SelectionInput ¶
SelectionInput is a private request copy with only authorized, compatible candidates.
type Selector ¶
type Selector interface {
// Select classifies the request and returns one eligible target ID.
Select(context.Context, SelectionInput) (Decision, error)
}
Selector chooses one candidate. Implementations must honor context cancellation.
type SelectorFunc ¶
type SelectorFunc func(context.Context, SelectionInput) (Decision, error)
SelectorFunc adapts a callback to Selector.
Example ¶
package main
import (
"context"
"fmt"
"github.com/effective-security/gogentic/pkg/llms"
"github.com/effective-security/gogentic/router"
)
type exampleModel struct{}
func (exampleModel) ValidateInference(llms.InferenceRequest) error { return nil }
func (exampleModel) Infer(context.Context, llms.InferenceRequest) (*llms.InferenceResponse, error) {
return &llms.InferenceResponse{
Content: []llms.InferenceBlock{{
Type: llms.BlockText,
Text: "Hello",
}},
FinishReason: llms.FinishStop,
}, nil
}
func main() {
selector := router.SelectorFunc(func(_ context.Context, in router.SelectionInput) (router.Decision, error) {
// Route by operator tags; a real selector classifies the request first.
for _, c := range in.Candidates {
if c.Tags["tier"] == "fast" {
return router.Decision{
TargetID: c.ID,
Classification: "simple",
}, nil
}
}
return router.Decision{}, fmt.Errorf("no fast tier candidate")
})
r, err := router.New(router.Config{
Selector: selector,
Admission: router.ConcurrencyLimit(8),
Targets: []router.Target{{
ID: "chat",
BackendModel: "configured-model",
Connector: exampleModel{},
Tags: map[string]string{
"tier": "fast",
},
}},
})
if err != nil {
panic(err)
}
result, err := r.Generate(context.Background(), router.Request{
Model: "auto",
Input: llms.InferenceRequest{
Messages: []llms.InferenceMessage{{
Role: llms.InferenceRoleUser,
Content: []llms.InferenceBlock{{
Type: llms.BlockText,
Text: "Hello",
}},
}},
},
})
if err != nil {
panic(err)
}
fmt.Println(result.Model, result.Classification)
}
Output: chat simple
func (SelectorFunc) Select ¶
func (f SelectorFunc) Select(ctx context.Context, in SelectionInput) (Decision, error)
Select invokes the callback.
type Target ¶
type Target struct {
ID string
Aliases []string
BackendModel string
Connector llms.InferenceModel
Features Features
// Tags is bounded operator metadata (tier, cost class, region, ...) exposed
// to selectors. It is never sent to providers.
Tags map[string]string
MaxOutputTokens int
// Allow checks trusted context on every request. Nil allows all callers.
Allow func(context.Context) bool
}
Target describes one permitted deployment and its connector. Features are operator claims about that deployment, further restricted by connector validation.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package dialect holds what the public API codecs share: decode and encode options, lenient/strict JSON object parsing with dialect-aware null handling, the sealed envelope for opaque reasoning state, and the mapping from router error kinds to HTTP status codes.
|
Package dialect holds what the public API codecs share: decode and encode options, lenient/strict JSON object parsing with dialect-aware null handling, the sealed envelope for opaque reasoning state, and the mapping from router error kinds to HTTP status codes. |
|
anthropic
Package anthropic is the Anthropic Messages codec for the router.
|
Package anthropic is the Anthropic Messages codec for the router. |
|
openai
Package openai translates the OpenAI Chat Completions and Responses request and response shapes to and from the portable router contract.
|
Package openai translates the OpenAI Chat Completions and Responses request and response shapes to and from the portable router contract. |