bifrost

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 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 bifrost is remora's client for the front door's management API. It speaks to the engine over loopback HTTP with the admin credentials remora generated; nothing it returns is meant for a remora user.

Index

Constants

View Source
const (
	SonioxProvider   = "remora-soniox"
	SonioxPublicName = "soniox"
)

SonioxProvider is the custom provider for the speech adapter; the public name is now a built-in provider.

View Source
const MaxLogLimit = 1000

MaxLogLimit is the largest page the front door's log search accepts; a larger limit is answered 400.

View Source
const OAuthProvider = "remora-oauth"

OAuthProvider is the OAuth engine's front-door provider (plan 03); its routing rules are named "remora-oauth-<name>".

Variables

View Source
var ErrInvalidVirtualKey = errors.New("invalid virtual key")

ErrInvalidVirtualKey marks a rejected virtual-key create or update.

View Source
var ErrNotFound = errors.New("bifrost: not found")

ErrNotFound is matched by errors.Is when the engine answers 404.

Functions

func IsStandardProvider

func IsStandardProvider(name string) bool

IsStandardProvider reports whether name is one of the engine's built-in providers.

func PublicProvider added in v0.8.0

func PublicProvider(name string) string

PublicProvider returns the public name of the speech adapter's engine provider.

Types

type APIError

type APIError struct {
	Status  int
	Message string
}

APIError is a non-2xx answer from the engine. Its text never reaches a client: the proxy maps errors itself.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is makes a 404 match ErrNotFound.

type Client

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

Client calls the front door's management API. It logs in once and sends the session token as a Bearer: the engine checks a Basic credential with bcrypt on every call, which costs tens of milliseconds of CPU each time.

func New

func New(baseURL, user, password string, hc *http.Client) *Client

New returns a client for the engine at baseURL (for example "http://127.0.0.1:18080"). A nil hc uses a fresh http.Client with no timeout; callers bound each call with its context.

func (*Client) CostHistogram added in v0.2.0

func (c *Client) CostHistogram(ctx context.Context, f LogFilter) ([]CostBucket, error)

CostHistogram calls GET /api/logs/histogram/cost.

func (*Client) CreateKey

func (c *Client) CreateKey(ctx context.Context, provider string, k Key) error

CreateKey adds a key to a provider. An empty ID lets the engine generate one. The engine wants key IDs and names unique across all providers.

func (*Client) CreateProvider

func (c *Client) CreateProvider(ctx context.Context, p Provider) error

CreateProvider adds a provider.

func (*Client) CreateRoutingRule

func (c *Client) CreateRoutingRule(ctx context.Context, r RoutingRule) (RoutingRule, error)

CreateRoutingRule adds a routing rule and returns it with the engine's ID.

func (*Client) CreateVirtualKey

func (c *Client) CreateVirtualKey(ctx context.Context, v VirtualKey) (VirtualKey, error)

CreateVirtualKey adds a virtual key and returns it with the engine's ID and Value.

func (*Client) DeleteKey

func (c *Client) DeleteKey(ctx context.Context, provider, id string) error

DeleteKey removes a key from a provider.

func (*Client) DeleteProvider

func (c *Client) DeleteProvider(ctx context.Context, name string) error

DeleteProvider removes a provider and its keys. The engine answers success for a provider it does not have.

func (*Client) DeleteRoutingRule

func (c *Client) DeleteRoutingRule(ctx context.Context, id string) error

DeleteRoutingRule removes a routing rule.

func (*Client) DeleteVirtualKey

func (c *Client) DeleteVirtualKey(ctx context.Context, id string) error

DeleteVirtualKey removes a virtual key.

func (*Client) GetLog

func (c *Client) GetLog(ctx context.Context, id string) (Log, error)

GetLog calls GET /api/logs/{id}, which carries the row's error details. A missing row matches ErrNotFound.

func (*Client) Health

func (c *Client) Health(ctx context.Context) error

Health reports whether the engine answers GET /health with status "ok".

func (*Client) Histogram

func (c *Client) Histogram(ctx context.Context, f LogFilter) ([]HistogramBucket, error)

Histogram calls GET /api/logs/histogram: request counts by outcome.

func (*Client) ListKeys

func (c *Client) ListKeys(ctx context.Context, provider string) ([]Key, error)

ListKeys returns a provider's keys without their values.

func (*Client) ListProviders

func (c *Client) ListProviders(ctx context.Context) ([]Provider, error)

ListProviders returns every provider the engine has configured.

func (*Client) ListRoutingRules

func (c *Client) ListRoutingRules(ctx context.Context) ([]RoutingRule, error)

ListRoutingRules returns every routing rule.

func (*Client) ListVirtualKeys

func (c *Client) ListVirtualKeys(ctx context.Context) ([]VirtualKey, error)

ListVirtualKeys returns every virtual key.

func (*Client) LogModels added in v0.1.5

func (c *Client) LogModels(ctx context.Context, query string) ([]string, error)

LogModels calls GET /api/logs/filterdata for the distinct models in the log whose name contains query.

func (*Client) LogStats

func (c *Client) LogStats(ctx context.Context, f LogFilter) (LogStats, error)

LogStats calls GET /api/logs/stats; paging and sorting fields of f are ignored.

func (*Client) ModelUsage added in v0.2.0

func (c *Client) ModelUsage(ctx context.Context, f LogFilter) ([]ModelUsage, error)

ModelUsage calls GET /api/logs/rankings: the provider and model pairs that served requests matching f, busiest first, at most the engine's ranking cap (100).

func (*Client) ProviderModels added in v0.7.0

func (c *Client) ProviderModels(ctx context.Context, name string) ([]string, error)

ProviderModels reads the provider's catalog without contacting the upstream.

func (*Client) RefreshProviderModels added in v0.1.5

func (c *Client) RefreshProviderModels(ctx context.Context, name string) ([]KeyStatus, error)

RefreshProviderModels calls POST /api/providers/{name}/refresh-models, which lists models with every enabled key of the provider and answers each key's status.

func (*Client) SearchLogs

func (c *Client) SearchLogs(ctx context.Context, f LogFilter) (LogPage, error)

SearchLogs calls GET /api/logs.

func (*Client) TokenHistogram added in v0.2.0

func (c *Client) TokenHistogram(ctx context.Context, f LogFilter) ([]TokenBucket, error)

TokenHistogram calls GET /api/logs/histogram/tokens.

func (*Client) UpdateKey

func (c *Client) UpdateKey(ctx context.Context, provider string, k Key) error

UpdateKey replaces a key. The engine refuses an empty Value.

func (*Client) UpdateProvider

func (c *Client) UpdateProvider(ctx context.Context, p Provider) error

UpdateProvider replaces a provider's network, concurrency and (for a custom provider) custom configuration. The engine creates the provider when it does not have it.

func (*Client) UpdateRoutingRule

func (c *Client) UpdateRoutingRule(ctx context.Context, r RoutingRule) error

UpdateRoutingRule replaces a routing rule's name, expression, target, fallbacks and priority.

func (*Client) UpdateVirtualKey

func (c *Client) UpdateVirtualKey(ctx context.Context, v VirtualKey) error

UpdateVirtualKey sets a virtual key's name and active flag.

type CostBucket added in v0.2.0

type CostBucket struct {
	Timestamp time.Time `json:"timestamp"`
	TotalCost float64   `json:"total_cost"`
}

CostBucket is one time bucket of GET /api/logs/histogram/cost, in dollars.

type HistogramBucket

type HistogramBucket struct {
	Timestamp time.Time `json:"timestamp"`
	Count     int64     `json:"count"`
	Success   int64     `json:"success"`
	Error     int64     `json:"error"`
}

HistogramBucket is one time bucket of GET /api/logs/histogram: the rows that started in it, by outcome.

type Key

type Key struct {
	ID, Name, Value string
	Enabled         bool
}

Key is one upstream key of a provider. Value is write-only: lists leave it empty, and the engine refuses an update without it.

type KeyStatus added in v0.1.5

type KeyStatus struct {
	ID          string `json:"id"`
	Status      string `json:"status"`
	Description string `json:"description"`
}

KeyStatus is what listing models with one provider key found: Status "success", "list_models_failed", or "unknown" when the provider lists no models; Description carries the failure.

type Log

type Log struct {
	ID              string    `json:"id"`
	ParentRequestID *string   `json:"parent_request_id"`
	Timestamp       time.Time `json:"timestamp"`
	Provider        string    `json:"provider"`
	Model           string    `json:"model"`
	Status          string    `json:"status"` // "processing", "success", "error" or "cancelled"
	// FallbackIndex is the attempt: 0 for the request itself, n for its nth fallback, whose ParentRequestID is the
	// request's id.
	FallbackIndex int         `json:"fallback_index"`
	VirtualKeyID  *string     `json:"virtual_key_id"`
	RoutingRuleID *string     `json:"routing_rule_id"`
	SelectedKeyID string      `json:"selected_key_id"`
	Latency       *float64    `json:"latency"` // milliseconds
	Cost          *float64    `json:"cost"`    // dollars
	Stream        bool        `json:"stream"`
	TokenUsage    *TokenUsage `json:"token_usage"`
	// ErrorDetails is filled by GetLog only: the list leaves it out.
	ErrorDetails json.RawMessage `json:"error_details,omitempty"`
	// The bodies, filled by GetLog only.
	InputHistory  json.RawMessage `json:"input_history,omitempty"`
	OutputMessage json.RawMessage `json:"output_message,omitempty"`
	Params        json.RawMessage `json:"params,omitempty"`
}

Log is one row of the front door's request log. Timestamp is when the request started; the row is written when it completes.

func (Log) Failure

func (l Log) Failure() (statusCode int, retryAfter time.Duration)

Failure reads the upstream status code and its retry hint from the row's error details. It returns zeros when the row has no details or they carry no status code. The engine clamps the hint to 1s..5m before logging it.

type LogFilter

type LogFilter struct {
	Status          []string   // "processing", "success", "error"
	Providers       []string   // front-door provider names
	Models          []string   // front-door model names
	VirtualKeyIDs   []string   // the virtual keys the requests came in on
	RoutingRuleIDs  []string   // the routing rules that routed the requests
	Start           *time.Time // rows whose timestamp is at or after Start
	End             *time.Time // rows whose timestamp is at or before End
	ContentSearch   string     // free text over the request and response content
	ParentRequestID string     // the fallback attempts of one request
	NoContent       bool       // omit request and response content from list rows
	Limit           int        // 1..MaxLogLimit
	Offset          int
	SortBy          string // "timestamp", "latency", "tokens" or "cost"
	Order           string // "asc" or "desc"
}

LogFilter narrows GET /api/logs and the stats and histogram built on the same filters. Zero fields are left out of the query, so the engine's defaults apply (limit 50, sort_by timestamp, order desc). List fields are sent comma-joined.

func (LogFilter) Query added in v0.7.2

func (f LogFilter) Query(page bool) url.Values

Query encodes f; page adds projection, paging and sorting options, which only the list reads.

type LogPage

type LogPage struct {
	Logs  []Log
	Total int64
}

LogPage is one page of a log search. Total counts every row the filter matches.

type LogSource

type LogSource interface {
	SearchLogs(ctx context.Context, f LogFilter) (LogPage, error)
	GetLog(ctx context.Context, id string) (Log, error)
}

LogSource is what a Tail polls; *Client satisfies it.

type LogStats

type LogStats struct {
	Completed        *int64  `json:"cache_hit_rate_total_requests"`
	SuccessRate      float64 `json:"success_rate"`
	PromptTokens     int64   `json:"prompt_tokens"`
	CompletionTokens int64   `json:"completion_tokens"`
	TotalTokens      int64   `json:"total_tokens"`
	TotalCost        float64 `json:"total_cost"`
}

LogStats is GET /api/logs/stats over a filter, counted per log row: Completed is the rows that finished and SuccessRate the percentage of them that succeeded. Completed is nil when the filter matches nothing.

type ModelUsage added in v0.2.0

type ModelUsage struct {
	Provider      string `json:"provider"`
	Model         string `json:"model"`
	TotalRequests int64  `json:"total_requests"`
}

ModelUsage is one row of GET /api/logs/rankings: a front-door provider and model that served requests.

type Provider

type Provider struct {
	Name                string
	BaseType            string
	BaseURL             string
	AllowPrivateNetwork bool
	AllowedRequests     []string      // custom_provider_config.allowed_requests as {"<type>": true}; nil = omitted (all allowed)
	RequestTimeout      time.Duration // network_config.default_request_timeout_in_seconds; 0 = 600 s
}

Provider is one front-door provider. BaseType "" is a standard provider; "openai" or "typesafe" makes a custom provider on that base.

type Route

type Route struct{ Provider, Model string }

Route is a provider and model. In a rule target, Model "" is sent as null: the incoming model.

type RoutingRule

type RoutingRule struct {
	ID, Name, CEL string
	Target        Route
	Fallbacks     []Route
	Priority      int
}

RoutingRule is a global front-door routing rule with a target and an ordered fallback chain. The engine refuses two global rules with the same Priority, so each rule needs its own; rules whose CEL expressions never match the same request may take any distinct priorities.

type Tail

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

Tail follows the front door's request log by polling it, since the engine pushes no log rows. It delivers each completed row once to every subscriber, polls only while someone is subscribed, and never blocks on a subscriber: rows that do not fit a subscriber's channel wait in its backlog and are handed over on later polls.

func NewTail

func NewTail(src LogSource, interval time.Duration, status []string, log *slog.Logger) *Tail

NewTail returns a Tail over src that polls every interval (1s when interval ≤ 0) for rows of the given statuses (nil = every row). A nil log discards.

func (*Tail) Coverage added in v0.7.2

func (t *Tail) Coverage(rows <-chan Log) (first, settled time.Time)

Coverage returns the start of the first successful scan (even on an empty log) and the point before which an up-to-date subscriber can checkpoint. An undrained subscription cannot checkpoint yet.

func (*Tail) Live added in v0.6.1

func (t *Tail) Live() *Tail

Live tunes the tail for viewers of the log. A viewer wants what completes from now on, and it has the page it loaded for the rest, so when a viewer arrives at an idle tail Subscribe first reads the rows that exist, before the viewer is registered, and what completes after that reaches it. And most polls read only the last liveNarrow rather than the whole lookback: a row is written when its request completes and carries the start time, so a request that ran longer than that shows up on the next poll that reads everything, at most liveWideEvery polls later.

func (*Tail) Run

func (t *Tail) Run(ctx context.Context)

Run polls while subscribed, spacing retries farther apart after failed polls.

func (*Tail) Subscribe

func (t *Tail) Subscribe(ctx context.Context, buffer, backlog int) (<-chan Log, func())

Subscribe returns a channel of completed rows with room for buffer rows, and a function that ends the subscription. Up to backlog more rows wait in the tail and are handed over on later polls, so a subscriber that falls behind loses nothing; one that falls further behind is dropped: its channel is closed. The cancel function is safe to call more than once and after a drop. ctx bounds the read that primes an idle live tail (see Live).

type TokenBucket added in v0.2.0

type TokenBucket struct {
	Timestamp        time.Time `json:"timestamp"`
	PromptTokens     int64     `json:"prompt_tokens"`
	CompletionTokens int64     `json:"completion_tokens"`
	TotalTokens      int64     `json:"total_tokens"`
}

TokenBucket is one time bucket of GET /api/logs/histogram/tokens.

type TokenUsage

type TokenUsage struct {
	PromptTokens     int64 `json:"prompt_tokens"`
	CompletionTokens int64 `json:"completion_tokens"`
	TotalTokens      int64 `json:"total_tokens"`
}

TokenUsage is a row's token counts.

type VirtualKey

type VirtualKey struct {
	ID, Name, Value string
	Active          bool
}

VirtualKey is a front-door virtual key. Value (the engine's own key, sent upstream in x-bf-vk) is set by the engine and never reaches a user.

Jump to

Keyboard shortcuts

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