app

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 11 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

Index

Constants

View Source
const (
	OutcomeSucceeded        = "succeeded"
	OutcomeRetryableFailure = "retryable_failure"
	OutcomeUnavailable      = "unavailable"
	OutcomeFailed           = "failed"
)

Outcome constants reported in routing.attempts metadata.

Variables

View Source
var (
	ErrInvalidInput          = errors.New("invalid input")
	ErrUnknownModel          = errors.New("unknown model")
	ErrUnknownProvider       = errors.New("unknown provider")
	ErrProviderModelMismatch = errors.New("provider does not support model")
	ErrProviderDisabled      = errors.New("provider is disabled")
	ErrTimeout               = errors.New("completion timed out")
	ErrCanceled              = errors.New("completion canceled")
	ErrUpstream              = errors.New("upstream provider failure")
	ErrRouting               = errors.New("model routing failed")
	ErrEnsembleInsufficient  = errors.New("not enough ensemble results")
	ErrConversationNotFound  = errors.New("conversation not found")
	ErrConversationExpired   = errors.New("conversation expired")
	ErrConversationConflict  = errors.New("conversation version conflict")
	ErrConversationStore     = errors.New("conversation store failure")
)

Functions

func ConversationScope added in v0.1.4

func ConversationScope(ctx context.Context) string

ConversationScope returns the namespace attached to the request context.

func SupportedTaskCategories

func SupportedTaskCategories() []string

SupportedTaskCategories returns the task hints accepted by automatic routing.

func WithConversationScope added in v0.1.4

func WithConversationScope(ctx context.Context, scope string) context.Context

WithConversationScope marks the namespace used by persistent conversations. An empty scope preserves the local, single-user store behavior.

func WrapNetworkFailure

func WrapNetworkFailure(err error, provider, model string) error

WrapNetworkFailure classifies an http.Client transport error at the call site: caller cancellation and deadline exhaustion are permanent (retry or fallback must not continue), everything else is transient. status is 0.

Types

type Attempt

type Attempt struct {
	Model          string `json:"model"`
	Provider       string `json:"provider"`
	Attempt        int    `json:"attempt"`
	Outcome        string `json:"outcome"`
	DurationMillis int64  `json:"duration_ms,omitempty"`
}

Attempt records one provider call for routing.attempts metadata. It carries model, provider, outcome and elapsed time only; never prompts or answers.

type ChatCompletionResponse

type ChatCompletionResponse struct {
	ID             string       `json:"id"`
	Object         string       `json:"object"`
	Created        int64        `json:"created"`
	Model          string       `json:"model"`
	Provider       string       `json:"provider,omitempty"`
	ConversationID string       `json:"conversation_id,omitempty"`
	Routing        *RoutingInfo `json:"routing,omitempty"`
	Choices        []Choice     `json:"choices"`
	Usage          *Usage       `json:"usage,omitempty"`
}

type Choice

type Choice struct {
	Message      Message `json:"message"`
	Delta        *Delta  `json:"delta,omitempty"`
	FinishReason string  `json:"finish_reason,omitempty"`
	Index        int     `json:"index"`
}

type CompletionRequest

type CompletionRequest struct {
	Model          string                  `json:"model"`
	Provider       string                  `json:"provider,omitempty"`
	Strategy       Strategy                `json:"strategy,omitempty"`
	Task           string                  `json:"task,omitempty"`
	Models         []string                `json:"models,omitempty"`
	Ensemble       *EnsembleRequestOptions `json:"ensemble,omitempty"`
	Fallback       *FallbackOverride       `json:"fallback,omitempty"`
	ConversationID string                  `json:"conversation_id,omitempty"`
	Messages       []Message               `json:"messages"`
	OnProgress     func(ProgressEvent)     `json:"-"`
	// contains filtered or unexported fields
}

type Conversation

type Conversation struct {
	ID        string             `json:"id"`
	CreatedAt time.Time          `json:"created_at"`
	UpdatedAt time.Time          `json:"updated_at"`
	ExpiresAt time.Time          `json:"expires_at"`
	Version   int64              `json:"version"`
	Turns     []ConversationTurn `json:"turns"`
}

func (Conversation) ContextMessages

func (c Conversation) ContextMessages() []Message

type ConversationStore

type ConversationStore interface {
	Create(context.Context) (Conversation, error)
	Get(context.Context, string) (Conversation, error)
	List(context.Context) ([]ConversationSummary, error)
	Delete(context.Context, string) error
	AppendTurn(context.Context, string, int64, []Message, Message, RoutingInfo) (Conversation, error)
	CleanupExpired(context.Context, time.Time) (int, error)
}

ConversationStore persists opt-in local conversation state. Implementations must use optimistic versions so inference can happen outside a write lock.

type ConversationSummary

type ConversationSummary struct {
	ID           string    `json:"id"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
	ExpiresAt    time.Time `json:"expires_at"`
	Version      int64     `json:"version"`
	MessageCount int       `json:"message_count"`
}

type ConversationTurn

type ConversationTurn struct {
	UserMessages []Message   `json:"user_messages"`
	Assistant    Message     `json:"assistant"`
	Routing      RoutingInfo `json:"routing"`
	CreatedAt    time.Time   `json:"created_at"`
}

type Delta

type Delta struct {
	Role    string `json:"role,omitempty"`
	Content string `json:"content,omitempty"`
}

type EnsembleMode added in v0.1.3

type EnsembleMode string
const (
	EnsembleIndependent EnsembleMode = "independent"
	EnsembleChain       EnsembleMode = "chain"
	EnsembleDebate      EnsembleMode = "debate"
)

type EnsemblePolicy added in v0.1.3

type EnsemblePolicy struct {
	Mode                  EnsembleMode
	CandidateCount        int
	ChainAgents           int
	DebateTurns           int
	DebateTurnsConfigured bool
}

type EnsembleRequestOptions added in v0.1.3

type EnsembleRequestOptions struct {
	Mode           EnsembleMode `json:"mode,omitempty" jsonschema:"optional ensemble algorithm: independent, chain, or debate"`
	CandidateCount *int         `` /* 163-byte string literal not displayed */
	Models         []string     `` /* 132-byte string literal not displayed */
	ChainAgents    *int         `json:"chain_agents,omitempty" jsonschema:"optional legacy chain length for chain mode, from 2 to 5"`
	DebateTurns    *int         `json:"debate_turns,omitempty" jsonschema:"optional debate review rounds for debate mode, from 0 to 5"`
}

EnsembleRequestOptions overrides the configured ensemble defaults for one request. Models supplies an exact candidate list; CandidateCount controls automatic candidate selection when Models is omitted. ChainAgents is kept for compatibility with existing chain requests.

type Error

type Error struct {
	Kind    error
	Message string
	Cause   error
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type FailureCategory

type FailureCategory int

FailureCategory classifies a provider boundary failure for retry and fallback decisions at the application layer.

const (
	// FailureTransient is retryable on the same model: network failures,
	// request timeouts while the caller context is still active, HTTP 408,
	// HTTP 429, and HTTP 5xx.
	FailureTransient FailureCategory = iota
	// FailureUnavailable means the selected model cannot be used; proceed
	// to fallback without retrying that same model (for example, a
	// model-specific HTTP 404).
	FailureUnavailable
	// FailurePermanent is neither retryable nor fallback-eligible.
	FailurePermanent
)

func (FailureCategory) String

func (c FailureCategory) String() string

type FallbackOverride

type FallbackOverride struct {
	Enabled           *bool    `json:"enabled,omitempty"`
	MaxRetries        *int     `json:"max_retries,omitempty"`
	MaxFallbackModels *int     `json:"max_fallback_models,omitempty"`
	Models            []string `json:"models,omitempty"`
}

FallbackOverride is a per-request fallback policy merge. Omitted pointer fields inherit the global policy; an explicitly empty Models list clears every fallback candidate.

type FallbackPolicy

type FallbackPolicy struct {
	Enabled           bool
	MaxRetries        int
	MaxFallbackModels int
	Models            map[string][]string
}

FallbackPolicy is the validated runtime fallback policy. Models maps a routed model ID to an ordered list of fallback model IDs.

type Message

type Message struct {
	Role       string      `json:"role"`
	Content    string      `json:"content"`
	Name       string      `json:"name,omitempty"`
	ToolCallID string      `json:"tool_call_id,omitempty"`
	ToolCalls  interface{} `json:"tool_calls,omitempty"`
}

type ModelCandidate

type ModelCandidate struct {
	Model        string   `json:"model"`
	Provider     string   `json:"provider"`
	Description  string   `json:"description"`
	Capabilities []string `json:"capabilities,omitempty"`
}

type ModelDescriptor

type ModelDescriptor struct {
	Description  string
	Capabilities []string
}

type ModelInfo

type ModelInfo struct {
	ID         string                 `json:"id"`
	Object     string                 `json:"object"`
	Created    int64                  `json:"created"`
	OwnedBy    string                 `json:"owned_by"`
	Permission []interface{}          `json:"permission"`
	Root       string                 `json:"root"`
	Parent     *string                `json:"parent"`
	Meta       map[string]interface{} `json:"meta,omitempty"`
}

type ProgressEvent

type ProgressEvent struct {
	Stage    string
	Message  string
	Model    string
	Provider string
	Status   string
}

type Provider

type Provider interface {
	ChatCompletion(ctx context.Context, messages []Message, model string) (*ChatCompletionResponse, error)
	ChatCompletionStream(ctx context.Context, messages []Message, model string, callback func(chunk string)) error
	GetInfo() ProviderInfo
	SupportsModel(model string) bool
}

type ProviderFailure

type ProviderFailure struct {
	Category FailureCategory
	Status   int // upstream HTTP status; 0 for network failures
	Provider string
	Model    string
	Cause    error
}

ProviderFailure carries the failure category and the upstream HTTP status only. It never carries the response body or any other provider content.

func NewProviderFailure

func NewProviderFailure(category FailureCategory, provider, model string, status int, cause error) *ProviderFailure

NewProviderFailure builds a typed failure with a stable category and the upstream status. status must be 0 when there is no HTTP response.

func (*ProviderFailure) Error

func (e *ProviderFailure) Error() string

func (*ProviderFailure) Unwrap

func (e *ProviderFailure) Unwrap() error

Unwrap surfaces ErrUpstream and the original cause so existing classification (contextOrUpstreamError) and errors.Is/As keep working.

type ProviderInfo

type ProviderInfo struct {
	Name               string   `json:"name"`
	Label              string   `json:"label"`
	URL                string   `json:"url"`
	Working            bool     `json:"working"`
	Alive              bool     `json:"alive"`
	SupportedModels    []string `json:"supported_models"`
	DefaultModel       string   `json:"default_model"`
	SupportsStream     bool     `json:"supports_stream"`
	NeedsAuth          bool     `json:"needs_auth"`
	Description        string   `json:"description"`
	ReverseEngineering bool     `json:"reverse_engineering"`
}

type Registry

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

func NewRegistry

func NewRegistry() *Registry

func (*Registry) Get

func (r *Registry) Get(name string) Provider

func (*Registry) GetAll

func (r *Registry) GetAll() map[string]Provider

func (*Registry) GetForModel

func (r *Registry) GetForModel(model string) Provider

func (*Registry) GetProviderNames

func (r *Registry) GetProviderNames() []string

func (*Registry) Register

func (r *Registry) Register(name string, provider Provider)

type RouteDecision

type RouteDecision struct {
	Task     string    `json:"task"`
	Model    string    `json:"model,omitempty"`
	Models   []string  `json:"models,omitempty"`
	Reason   string    `json:"reason"`
	Attempts []Attempt `json:"-"`
}

type RoutedModel

type RoutedModel struct {
	Model          string `json:"model"`
	Provider       string `json:"provider"`
	Status         string `json:"status"`
	DurationMillis int64  `json:"duration_ms,omitempty"`
}

type RoutingInfo

type RoutingInfo struct {
	Strategy       Strategy      `json:"strategy"`
	Task           string        `json:"task,omitempty"`
	EnsembleMode   EnsembleMode  `json:"ensemble_mode,omitempty"`
	Agents         int           `json:"agents,omitempty"`
	Turns          int           `json:"turns,omitempty"`
	SynthesisModel string        `json:"synthesis_model,omitempty"`
	Models         []RoutedModel `json:"models,omitempty"`
	Attempts       []Attempt     `json:"attempts,omitempty"`
}

type RoutingPolicy

type RoutingPolicy struct {
	Models         map[string]ModelDescriptor
	Profiles       map[string]TaskRule
	Tasks          map[string]TaskRule // legacy alias for Profiles
	DefaultProfile string
	Ensemble       EnsemblePolicy
}

type SelectionMode added in v0.1.3

type SelectionMode string
const (
	SelectionLocal  SelectionMode = "local"
	SelectionRouter SelectionMode = "router"
)

type Service

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

func NewService

func NewService(registry *Registry, options ServiceOptions) (*Service, error)

func (*Service) Complete

func (s *Service) Complete(ctx context.Context, request CompletionRequest) (*ChatCompletionResponse, error)

func (*Service) CompleteStream

func (s *Service) CompleteStream(ctx context.Context, request CompletionRequest, callback func(string)) error

func (*Service) CompleteStreamWithInfo

func (s *Service) CompleteStreamWithInfo(ctx context.Context, request CompletionRequest, callback func(string, *RoutingInfo)) error

CompleteStreamWithInfo emits the route decision with each chunk so transports can include it in their initial streaming event.

func (*Service) CreateConversation

func (s *Service) CreateConversation(ctx context.Context) (Conversation, error)

func (*Service) DeleteConversation

func (s *Service) DeleteConversation(ctx context.Context, id string) error

func (*Service) FallbackPolicy

func (s *Service) FallbackPolicy() FallbackPolicy

FallbackPolicy returns a copy of the resolved fallback policy. A nil configured policy resolves to the documented defaults.

func (*Service) GetConversation

func (s *Service) GetConversation(ctx context.Context, id string) (Conversation, error)

func (*Service) ListConversations

func (s *Service) ListConversations(ctx context.Context) ([]ConversationSummary, error)

func (*Service) ListModels

func (s *Service) ListModels() []ModelInfo

func (*Service) ListProviderMetadata

func (s *Service) ListProviderMetadata() []ProviderInfo

ListProviderMetadata returns the catalogue without probing external URLs.

func (*Service) ListProviders

func (s *Service) ListProviders(ctx context.Context) ([]ProviderInfo, error)

func (*Service) RoutingProfiles added in v0.1.3

func (s *Service) RoutingProfiles() []string

RoutingProfiles returns the configured profile names together with legacy built-in task names for CLI completions and clients.

type ServiceOptions

type ServiceOptions struct {
	DefaultProvider string
	RouterModel     string
	SynthesisModel  string
	RoutingPolicy   RoutingPolicy
	Fallback        *FallbackPolicy
	Conversations   ConversationStore
	Timeout         time.Duration
	HealthProbe     func(context.Context, string) bool
	HealthClient    *http.Client
	HealthTimeout   time.Duration
}

type Strategy

type Strategy string
const (
	StrategyClassic  Strategy = "classic"
	StrategyAuto     Strategy = "auto"
	StrategyEnsemble Strategy = "ensemble"
)

type StreamChoice added in v0.0.8

type StreamChoice struct {
	Delta        *Delta  `json:"delta,omitempty"`
	FinishReason *string `json:"finish_reason"`
	Index        int     `json:"index"`
}

StreamChoice is the OpenAI streaming choice shape. It deliberately has no message field: a chat.completion.chunk carries only delta, finish_reason and index, while a non-streaming chat.completion carries message.

type StreamChunk

type StreamChunk struct {
	ID             string         `json:"id"`
	Object         string         `json:"object"`
	Created        int64          `json:"created"`
	Model          string         `json:"model"`
	ConversationID string         `json:"conversation_id,omitempty"`
	Routing        *RoutingInfo   `json:"routing,omitempty"`
	Choices        []StreamChoice `json:"choices"`
}

type TaskRule

type TaskRule struct {
	RequiredCapabilities []string
	PreferredModels      []string
	Selection            SelectionMode
}

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

Jump to

Keyboard shortcuts

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