Documentation
¶
Index ¶
- Constants
- func BlendedPrice(m *proxydb.Model) float64
- func Competencies(m *proxydb.Model) map[string]string
- func ConfigureOpenAI(a *adapters.OpenAIAdapter, m *proxydb.Model, engine string)
- func EffortLevel(effort string) string
- func Excess(m *proxydb.Model, needs map[string]string) int
- func FormatNeeds(needs map[string]string) string
- func HasCapability(m *proxydb.Model, capability string) bool
- func LevelEffort(level string) string
- func LevelRank(level string) int
- func Meets(m *proxydb.Model, topic, level string) bool
- func MeetsAll(m *proxydb.Model, needs map[string]string) bool
- func ParseNeeds(s string) (map[string]string, error)
- func RequestNeeds(needs map[string]string, effort string) (map[string]string, error)
- func RuleMatchesNeeds(ruleNeeds, needs map[string]string) bool
- func SamplingSupport(m *proxydb.Model) llm.SamplingSupport
- func Serves(m *proxydb.Model, effort string) bool
- func ServesLanguagePair(m *proxydb.Model, source, target string) bool
- func SoftSchema(m *proxydb.Model) bool
- func ThinkingOff(vendor, engine string) map[string]any
- func ValidEffort(e string) bool
- func ValidLanguageTag(tag string) bool
- func ValidLevel(level string) bool
- func ValidMCPName(name string) bool
- func ValidTopic(t string) bool
- func ValidVendor(v string) bool
- func Validate(models []*proxydb.Model, rules []*proxydb.Rule) error
- func ValidateLevels(m map[string]string) error
- func ValidateMCPServer(m *proxydb.MCPServer) error
- func ValidateModel(m *proxydb.Model) error
- type Loader
- type MCPServer
- type NodePoolResolver
- type Snapshot
- func (s *Snapshot) Adapter(apiKeyID string, m *proxydb.Model) (llm.ClientAdapter, error)
- func (s *Snapshot) CanCall(apiKeyID string, m *proxydb.Model) bool
- func (s *Snapshot) ClientModels(apiKeyID string) []*proxydb.Model
- func (s *Snapshot) Configured() bool
- func (s *Snapshot) Selects() bool
- func (s *Snapshot) SetAdapter(apiKeyID, modelID string, adapter llm.ClientAdapter)
- func (s *Snapshot) SetNodePool(np NodePoolResolver)
- func (s *Snapshot) SpendLimit(subjectType, subjectID, period string) int64
- func (s *Snapshot) Tracker() llm.UsageTracker
- func (s *Snapshot) UserRateLimit(userID, modelID string) *proxydb.UserRateLimit
- func (s *Snapshot) VendorKey(apiKeyID, vendor string) (string, bool)
- func (s *Snapshot) VendorKeyFingerprint(apiKeyID, vendor string) string
Constants ¶
const ( LevelBasic = "basic" LevelProficient = "proficient" LevelExpert = "expert" // TopicGeneral is the topic efforts stand for: low, medium and high are // general at basic, proficient and expert. TopicGeneral = "general" )
Levels of a competency or a need, in order: a model meets a need at its level or above.
const ( MCPStreamableHTTP = "streamable_http" MCPSSE = "sse" )
MCP transports.
const ( DefaultMCPTimeout = 60 * time.Second DefaultMCPMaxResponseBytes = 4 << 20 )
MCP server defaults for the 0 values of the spec.
const ( VendorOpenAI = "openai" VendorGoogle = "google" VendorDeepSeek = "deepseek" VendorOllama = "ollama" VendorTypeSafe = "typesafe" VendorAnthropic = "anthropic" VendorLocal = "local" VendorGroq = "groq" VendorMistral = "mistral" VendorAzure = "azure" VendorBedrock = "bedrock" )
Vendors the engine can construct adapters for. DeepSeek and Ollama ride the OpenAI adapter with a different base URL; Ollama is any self-hosted OpenAI-compatible server, so its endpoint is required and its key is its own. Local routes to self-registering local inference nodes.
const ( EffortLow = "low" EffortMedium = "medium" EffortHigh = "high" )
Efforts a model may serve and a request may ask for.
const ( CapabilityTTS = "tts" CapabilityImage = "image" )
CapabilityTTS and CapabilityImage mark models that can serve the speech and image RPCs. Opt-in: a chain filtered for one of these keeps only models that declare it, so a text model can never be handed audio work.
const ( CapabilityVision = "vision" CapabilityAudioInput = "audio_input" CapabilityPDFInput = "pdf_input" )
Multimodal input capabilities mark chat models capable of handling specific media. Opt-in: request parts require the matching capability on the candidate model.
const AnthropicDefaultEndpoint = "https://api.anthropic.com"
AnthropicDefaultEndpoint is used when an anthropic model has no endpoint override.
const AnyLanguage = "*"
AnyLanguage in a model's languages matches every tag.
const AzureDefaultAPIVersion = "2024-06-01"
AzureDefaultAPIVersion is used when an azure model has no api-version query override.
const BedrockDefaultRegion = "us-east-1"
BedrockDefaultRegion is used when a bedrock credential does not specify a region.
const CapabilityBatch = "batch"
CapabilityBatch marks models that support batch processing.
const CapabilityEmbedding = "embedding"
CapabilityEmbedding marks models that compute text vector embeddings.
const CapabilityEmbeddingInput = "embedding_input"
CapabilityEmbeddingInput marks judge models that score raw latent vectors. No text model reads one, so it is opt-in even among judges.
const CapabilityGoogleSearch = "google_search"
CapabilityGoogleSearch marks models that can serve enable_google_search.
const CapabilityJudge = "judge"
CapabilityJudge marks models that answer typed questions instead of writing text. Opt-in like the other modalities: a judge chain keeps only models that declare it, so a chat model can never be handed a judgment.
const CapabilityNoSampling = "no_sampling"
CapabilityNoSampling marks a model whose API rejects sampling fields the table below would send it: the proxy then sends none of them.
const CapabilityNoStructuredOutput = "no_structured_output"
CapabilityNoStructuredOutput marks models whose API cannot be handed a JSON schema (DeepSeek rejects response_format json_schema outright). The shape is asked for in the prompt and checked by the router instead. Stated as the exception so a model that says nothing keeps the enforced behaviour.
const CapabilityNoThinking = "no_thinking"
CapabilityNoThinking marks models that reason by default unless told not to (DeepSeek V4 thinks at high effort, billed as output). The proxy turns it off the way the vendor understands.
const CapabilityPromptCache = "prompt_cache"
CapabilityPromptCache asks Anthropic to cache each call's tools and system prompt: worth it for long instructions that repeat across calls.
const CapabilitySampling = "sampling"
CapabilitySampling marks a model that takes its vendor's sampling fields although its id looks like one that does not: an Azure deployment name, a Claude alias, a reasoning model run without reasoning.
const CapabilityTranslate = "translate"
CapabilityTranslate marks models that serve Translate: MT engines natively, chat models through a prompt. Their languages narrow which pairs they take.
const DeepSeekDefaultEndpoint = "https://api.deepseek.com"
DeepSeekDefaultEndpoint is used when a deepseek model has no endpoint override.
const EngineFreeToken = "freetoken"
EngineFreeToken is the node engine name of a FreeToken server (`ft serve`).
const EngineMT = "mt"
EngineMT is the node engine name of a machine-translation server speaking KTMS's MT contract (GET /v1/models, POST /v1/translate), such as ktms-mt.
const GroqDefaultEndpoint = "https://api.groq.com/openai/v1"
GroqDefaultEndpoint is used when a groq model has no endpoint override.
const MistralDefaultEndpoint = "https://api.mistral.ai/v1"
MistralDefaultEndpoint is used when a mistral model has no endpoint override.
const OpenAIDefaultEndpoint = "https://api.openai.com"
OpenAIDefaultEndpoint is used when an openai model has no endpoint override.
const ReservedMCPServer = "agents"
ReservedMCPServer is the built-in server of the agents' inbox (agents.Server).
const TypeSafeDefaultEndpoint = "https://api.typesafe.ai"
TypeSafeDefaultEndpoint is used when a typesafe model has no endpoint override.
Variables ¶
This section is empty.
Functions ¶
func BlendedPrice ¶ added in v1.7.0
BlendedPrice is the price per million tokens selection ranks by: (3 x input + output) / 4 at the standard rate, as chats read more than they write.
func Competencies ¶ added in v1.7.0
Competencies returns m's competencies with its efforts read as general at the highest effort listed, unless general is set explicitly.
func ConfigureOpenAI ¶
func ConfigureOpenAI(a *adapters.OpenAIAdapter, m *proxydb.Model, engine string)
ConfigureOpenAI applies the model's capabilities to an OpenAI-compatible adapter. Pool adapters pass the node's engine; direct vendors pass "".
func EffortLevel ¶ added in v1.7.0
EffortLevel maps an effort to the general level it stands for.
func Excess ¶ added in v1.7.0
Excess sums, over the needed topics, how many levels m has above the need, so an expert is not spent where a basic model does; 0 for an exact fit. Efforts count at the highest one listed, as in Competencies, so a model described by efforts does not win a selection on price alone.
func FormatNeeds ¶ added in v1.7.0
FormatNeeds writes needs as "general=basic,medical=proficient", sorted by topic: the form of usage meta, X-KTMS-Needs and the auto: model name.
func HasCapability ¶
HasCapability reports whether a model lists the capability.
func LevelEffort ¶ added in v1.7.0
LevelEffort is EffortLevel backwards, for meta["effort"] and old clients.
func LevelRank ¶ added in v1.7.0
LevelRank orders levels from 1 (basic) to 3 (expert); 0 is not a level.
func Meets ¶ added in v1.7.0
Meets reports whether m meets the need topic >= level. A model whose general comes from efforts meets a general need only at an effort it lists.
func ParseNeeds ¶ added in v1.7.0
ParseNeeds reads FormatNeeds' form; spaces around items are allowed.
func RequestNeeds ¶ added in v1.7.0
RequestNeeds merges a request's needs with its deprecated effort, read as general unless the needs name general themselves, and validates them.
func RuleMatchesNeeds ¶ added in v1.7.0
RuleMatchesNeeds reports whether a request's needs reach a rule's: each topic the rule names at least at the rule's level.
func SamplingSupport ¶ added in v1.5.0
func SamplingSupport(m *proxydb.Model) llm.SamplingSupport
SamplingSupport is the sampling a model's API takes. Adapters send only that, and responses name the rest in ignored_parameters.
func ServesLanguagePair ¶ added in v1.6.0
ServesLanguagePair reports whether m declares the pair. An empty source in the request matches any: the engine detects it. A declared tag covers its longer variants; an empty list (never on a valid translate model) is any.
func SoftSchema ¶
SoftSchema reports whether this model needs the prompt-and-verify path.
func ThinkingOff ¶
ThinkingOff returns the request fields that turn a vendor's default reasoning off: Ollama and FreeToken take reasoning_effort, DeepSeek a thinking switch. A local node is judged by its engine; engines without a known switch get none.
func ValidEffort ¶
func ValidLanguageTag ¶ added in v1.6.0
ValidLanguageTag accepts "*" and BCP-47-shaped tags: letters, digits and hyphens, a 2-3 letter primary subtag. Full registry validation is the engine's job; this catches typos such as "german" or "de_DE".
func ValidLevel ¶ added in v1.7.0
ValidLevel reports whether level is basic, proficient or expert.
func ValidMCPName ¶ added in v1.4.0
ValidMCPName reports whether name may name an MCP server.
func ValidTopic ¶ added in v1.7.0
ValidTopic reports whether t is a topic name: lowercase letters, digits, "_" and "-", up to 64 characters. Topics are free; an unknown one is no error.
func ValidVendor ¶
func Validate ¶
Validate checks the full config as it would take effect: enabled rules with chains filtered to enabled models. Runs inside every admin mutation transaction and on load, so an invalid state can never become active.
func ValidateLevels ¶ added in v1.7.0
ValidateLevels checks a topic -> level map of a model, rule or request.
func ValidateMCPServer ¶ added in v1.4.0
ValidateMCPServer checks a spec on its own; whether its host resolves to a private address is checked where the network is (the Admin API).
func ValidateModel ¶
ValidateModel checks a single spec before it reaches the database.
Types ¶
type Loader ¶
type Loader struct {
// contains filtered or unexported fields
}
Loader keeps the active Snapshot fresh: it polls config_state and rebuilds on version change. A failed rebuild keeps the last good snapshot serving.
func (*Loader) Load ¶
Load rebuilds the snapshot unconditionally. Called once at startup (an error is fatal there) and by the poll loop.
func (*Loader) Refresh ¶
func (l *Loader) Refresh()
Refresh asks the poll loop to rebuild now (after an admin mutation in this replica). Non-blocking; a pending request is enough.
func (*Loader) SetNodePool ¶
func (l *Loader) SetNodePool(np NodePoolResolver)
type MCPServer ¶ added in v1.4.0
type MCPServer struct {
proxydb.MCPServer
Header string // "" when the server has no credential
Value string
}
MCPServer is an enabled MCP server with its decrypted credential.
func (*MCPServer) Fingerprint ¶ added in v1.4.0
Fingerprint changes whenever anything a connection depends on does, so the gateway knows to drop a connection made with an older spec or credential.
func (*MCPServer) MaxResponse ¶ added in v1.4.0
MaxResponse bounds one tool result.
type NodePoolResolver ¶
type NodePoolResolver interface {
PoolAdapter(m *proxydb.Model) (llm.ClientAdapter, error)
}
NodePoolResolver builds an adapter for a local node pool model.
type Snapshot ¶
type Snapshot struct {
Version int64
Models map[string]*proxydb.Model // enabled only
Rules []*proxydb.Rule // enabled only, sorted by priority desc
// UserRateLimits[userID][modelID] = user rate limit overrides.
UserRateLimits map[string]map[string]*proxydb.UserRateLimit
// SpendLimits[subjectType+"\x00"+subjectID][period] = cap in nano-USD.
SpendLimits map[string]map[string]int64
// MCPServers[name] = enabled MCP server with its credential.
MCPServers map[string]*MCPServer
// contains filtered or unexported fields
}
Snapshot is one immutable view of the routing config: enabled models and rules plus decrypted vendor keys. Replaced wholesale on config change; decrypted keys live only here, in process memory.
func NewSnapshotForTest ¶
func NewSnapshotForTest(models []*proxydb.Model, rules []*proxydb.Rule, vendorKeys map[string]map[string]string, tracker llm.UsageTracker) *Snapshot
NewSnapshotForTest builds a snapshot without a database — for tests only. vendorKeys is keyed [apiKeyID][vendor] = plain credential.
func (*Snapshot) Adapter ¶
Adapter returns the vendor adapter for a (client, model) pair, built with the client's own decrypted credential and cached for the snapshot's lifetime. Concurrent first calls may build twice; LoadOrStore keeps one.
func (*Snapshot) CanCall ¶
CanCall reports whether the client may use m. Local models reach nodes with the node's own token, so they need no vendor key.
func (*Snapshot) ClientModels ¶
ClientModels lists enabled models the client can call, sorted by id for stable ListModels output.
func (*Snapshot) Configured ¶
Configured reports whether any routing config exists at all: models and either rules or competencies to select by.
func (*Snapshot) Selects ¶ added in v1.7.0
Selects reports whether requests no rule matches are routed by selection: some enabled model declares competencies. Configs from before 1.7 never do, and keep needing a catch-all rule.
func (*Snapshot) SetAdapter ¶
func (s *Snapshot) SetAdapter(apiKeyID, modelID string, adapter llm.ClientAdapter)
SetAdapter stores a mock adapter for tests.
func (*Snapshot) SetNodePool ¶
func (s *Snapshot) SetNodePool(np NodePoolResolver)
func (*Snapshot) SpendLimit ¶
SpendLimit returns the cap in nano-USD for a subject and period, falling back to the subject type's "*" default; 0 means no cap.
func (*Snapshot) Tracker ¶
func (s *Snapshot) Tracker() llm.UsageTracker
Tracker returns the usage tracker configured on the snapshot.
func (*Snapshot) UserRateLimit ¶
func (s *Snapshot) UserRateLimit(userID, modelID string) *proxydb.UserRateLimit
UserRateLimit returns the rate limit override for a user and model, or for the user wildcard "*".
func (*Snapshot) VendorKey ¶
VendorKey returns the calling client's decrypted credential for a vendor.
func (*Snapshot) VendorKeyFingerprint ¶ added in v0.13.1
VendorKeyFingerprint names the client's credential for vendor without revealing it, so clients sharing one vendor key share its rate limits.