Documentation
¶
Index ¶
- Constants
- Variables
- func GetReactFS() (http.FileSystem, error)
- func GetReactIndexHTML() ([]byte, error)
- func SanitizeAccessControlRequestHeaderValues(headerValues string) string
- func ServeCompressedFile(fs http.FileSystem, w http.ResponseWriter, r *http.Request, name string)
- func SetLlamaCppBuildInfo(build, git, date, features string)
- type ActivityLogEntry
- type ActivityLogEvent
- type ChatCompletionStats
- type ConfigFileChangedEvent
- type DiscardWriter
- type InFlightRequestsEvent
- type InflightCounter
- type Matrix
- func (m *Matrix) GetProcess(modelID string) (*Process, bool)
- func (m *Matrix) HasModel(modelID string) bool
- func (m *Matrix) ProxyRequest(modelID string, w http.ResponseWriter, r *http.Request) error
- func (m *Matrix) RunningModels() []string
- func (m *Matrix) Shutdown()
- func (m *Matrix) StopProcess(modelID string, strategy StopStrategy) error
- func (m *Matrix) StopProcesses(strategy StopStrategy)
- type MatrixSolver
- type Model
- type ModelPreloadedEvent
- type PeerProxy
- type Process
- func (p *Process) CurrentState() ProcessState
- func (p *Process) InFlightAge() (time.Duration, bool)
- func (p *Process) LogMonitor() *logmon.Monitor
- func (p *Process) Logger() *logmon.Monitor
- func (p *Process) ProxyRequest(w http.ResponseWriter, r *http.Request)
- func (p *Process) Shutdown()
- func (p *Process) Stop()
- func (p *Process) StopImmediately()
- type ProcessGroup
- func (pg *ProcessGroup) GetMember(modelName string) (*Process, bool)
- func (pg *ProcessGroup) HasMember(modelName string) bool
- func (pg *ProcessGroup) ProxyRequest(modelID string, writer http.ResponseWriter, request *http.Request) error
- func (pg *ProcessGroup) Shutdown()
- func (pg *ProcessGroup) StopProcess(modelID string, strategy StopStrategy) error
- func (pg *ProcessGroup) StopProcesses(strategy StopStrategy)
- type ProcessState
- type ProcessStateChangeEvent
- type ProxyManager
- func (pm *ProxyManager) RegisterMDNS()
- func (pm *ProxyManager) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (pm *ProxyManager) SetConfigFile(path string)
- func (pm *ProxyManager) SetListenAddr(addr string)
- func (pm *ProxyManager) SetPerfMonitor(m *perf.Monitor)
- func (pm *ProxyManager) SetReloadFn(fn func())
- func (pm *ProxyManager) SetVersion(buildDate string, commit string, version string)
- func (pm *ProxyManager) Shutdown()
- func (pm *ProxyManager) StopProcesses(strategy StopStrategy)
- type ReloadingState
- type ReqRespCapture
- type Reservation
- type ReservationStore
- type SessionMetrics
- type SessionMetricsStore
- type SkeinCapabilities
- type SolveResult
- type StopStrategy
- type TokenMetrics
Constants ¶
const ActivityLogEventID = 0x05
const ChatCompletionStatsEventID = 0x02
const ConfigFileChangedEventID = 0x03
const InFlightRequestsEventID = 0x07
const ModelPreloadedEventID = 0x06
const (
PROFILE_SPLIT_CHAR = ":"
)
const ProcessStateChangeEventID = 0x01
const SkeinCapabilitiesVersion = 1
SkeinCapabilitiesVersion is the current version of the Skein companion API.
Variables ¶
var ( ErrExpectedStateMismatch = errors.New("expected state mismatch") ErrInvalidStateTransition = errors.New("invalid state transition") )
custom error types for swapping state
Functions ¶
func GetReactFS ¶
func GetReactFS() (http.FileSystem, error)
GetReactFS returns the embedded React filesystem
func GetReactIndexHTML ¶
GetReactIndexHTML returns the main index.html for the React app
func ServeCompressedFile ¶
func ServeCompressedFile(fs http.FileSystem, w http.ResponseWriter, r *http.Request, name string)
ServeCompressedFile serves a file with compression support. It checks for pre-compressed versions and serves them with proper headers.
func SetLlamaCppBuildInfo ¶
func SetLlamaCppBuildInfo(build, git, date, features string)
SetLlamaCppBuildInfo sets the llama.cpp build metadata injected via ldflags.
Types ¶
type ActivityLogEntry ¶
type ActivityLogEntry struct {
ID int `json:"id"`
Timestamp time.Time `json:"timestamp"`
Model string `json:"model"`
ReqPath string `json:"req_path"`
RespContentType string `json:"resp_content_type"`
RespStatusCode int `json:"resp_status_code"`
Tokens TokenMetrics `json:"tokens"`
DurationMs int `json:"duration_ms"`
HasCapture bool `json:"has_capture"`
// Skein companion: reservation ID from X-Skein-Reservation header (optional)
ReservationID string `json:"reservation_id,omitempty"`
}
ActivityLogEntry represents parsed token statistics from llama-server logs
type ActivityLogEvent ¶
type ActivityLogEvent struct {
Metrics ActivityLogEntry
}
ActivityLogEvent represents a token metrics event
func (ActivityLogEvent) Type ¶
func (e ActivityLogEvent) Type() uint32
type ChatCompletionStats ¶
type ChatCompletionStats struct {
TokensGenerated int
}
func (ChatCompletionStats) Type ¶
func (e ChatCompletionStats) Type() uint32
type ConfigFileChangedEvent ¶
type ConfigFileChangedEvent struct {
ReloadingState ReloadingState
}
func (ConfigFileChangedEvent) Type ¶
func (e ConfigFileChangedEvent) Type() uint32
type DiscardWriter ¶
type DiscardWriter struct {
// contains filtered or unexported fields
}
Custom discard writer that implements http.ResponseWriter but just discards everything
func (*DiscardWriter) Flush ¶
func (w *DiscardWriter) Flush()
Satisfy the http.Flusher interface for streaming responses
func (*DiscardWriter) Header ¶
func (w *DiscardWriter) Header() http.Header
func (*DiscardWriter) WriteHeader ¶
func (w *DiscardWriter) WriteHeader(code int)
type InFlightRequestsEvent ¶
type InFlightRequestsEvent struct {
Total int
}
func (InFlightRequestsEvent) Type ¶
func (e InFlightRequestsEvent) Type() uint32
type InflightCounter ¶
type InflightCounter struct {
// contains filtered or unexported fields
}
func (*InflightCounter) Current ¶
func (ic *InflightCounter) Current() int
func (*InflightCounter) Decrement ¶
func (ic *InflightCounter) Decrement() int
func (*InflightCounter) Increment ¶
func (ic *InflightCounter) Increment() int
type Matrix ¶
Matrix manages processes using solver-based swap logic.
func NewMatrix ¶
NewMatrix creates a Matrix from config. It creates a Process for every model defined in the config (any model can run alone even if not in a set).
func (*Matrix) GetProcess ¶
GetProcess returns the Process for a model.
func (*Matrix) ProxyRequest ¶
ProxyRequest handles the swap logic and proxies the request to the model.
func (*Matrix) RunningModels ¶
RunningModels returns model names currently in an active (non-stopped) state.
func (*Matrix) StopProcess ¶
func (m *Matrix) StopProcess(modelID string, strategy StopStrategy) error
StopProcess stops a single process by model ID.
func (*Matrix) StopProcesses ¶
func (m *Matrix) StopProcesses(strategy StopStrategy)
StopProcesses stops all running processes.
type MatrixSolver ¶
type MatrixSolver struct {
// contains filtered or unexported fields
}
MatrixSolver contains pure swap-decision logic with no Process dependencies. It is safe for concurrent reads after construction.
func NewMatrixSolver ¶
func NewMatrixSolver(expandedSets []config.ExpandedSet, evictCosts map[string]int) *MatrixSolver
NewMatrixSolver builds a solver from expanded sets and eviction costs.
func (*MatrixSolver) Solve ¶
func (s *MatrixSolver) Solve(requestedModel string, runningModels []string) (SolveResult, error)
Solve determines which models to evict when a model is requested.
Algorithm:
- If requestedModel is already running, no eviction needed.
- Find all sets containing requestedModel.
- If no sets found, the model runs alone; evict all running models.
- For each candidate set, compute cost = sum of evict_costs for running models NOT in that set.
- Pick lowest cost. Ties broken by definition order (index in expandedSets).
- Return models to evict and the chosen set.
type ModelPreloadedEvent ¶
func (ModelPreloadedEvent) Type ¶
func (e ModelPreloadedEvent) Type() uint32
type PeerProxy ¶
type PeerProxy struct {
// contains filtered or unexported fields
}
func NewPeerProxy ¶
func (*PeerProxy) GetPeerFilters ¶
GetPeerFilters returns the filters for a peer model, or empty filters if not found
func (*PeerProxy) HasPeerModel ¶
func (*PeerProxy) ListPeers ¶
func (p *PeerProxy) ListPeers() config.PeerDictionaryConfig
func (*PeerProxy) ProxyRequest ¶
type Process ¶
type Process struct {
ID string
// contains filtered or unexported fields
}
func NewProcess ¶
func (*Process) CurrentState ¶
func (p *Process) CurrentState() ProcessState
func (*Process) InFlightAge ¶
InFlightAge returns how long a request has been continuously in flight on this process and whether one is in flight now. Used by the GPU-stall watchdog to age a possibly-wedged request.
func (*Process) LogMonitor ¶
LogMonitor returns the log monitor associated with the process.
func (*Process) ProxyRequest ¶
func (p *Process) ProxyRequest(w http.ResponseWriter, r *http.Request)
func (*Process) Shutdown ¶
func (p *Process) Shutdown()
Shutdown is called when llama-swap is shutting down. It will give a little bit of time for any inflight requests to complete before shutting down. If the Process is in the state of starting, it will cancel it and shut it down. Once a process is in the StateShutdown state, it can not be started again.
func (*Process) Stop ¶
func (p *Process) Stop()
Stop will wait for inflight requests to complete before stopping the process.
func (*Process) StopImmediately ¶
func (p *Process) StopImmediately()
StopImmediately will transition the process to the stopping state and stop the process with a SIGTERM. If the process does not stop within the specified timeout, it will be forcefully stopped with a SIGKILL.
type ProcessGroup ¶
func NewProcessGroup ¶
func (*ProcessGroup) GetMember ¶
func (pg *ProcessGroup) GetMember(modelName string) (*Process, bool)
func (*ProcessGroup) HasMember ¶
func (pg *ProcessGroup) HasMember(modelName string) bool
func (*ProcessGroup) ProxyRequest ¶
func (pg *ProcessGroup) ProxyRequest(modelID string, writer http.ResponseWriter, request *http.Request) error
ProxyRequest proxies a request to the specified model
func (*ProcessGroup) Shutdown ¶
func (pg *ProcessGroup) Shutdown()
func (*ProcessGroup) StopProcess ¶
func (pg *ProcessGroup) StopProcess(modelID string, strategy StopStrategy) error
func (*ProcessGroup) StopProcesses ¶
func (pg *ProcessGroup) StopProcesses(strategy StopStrategy)
type ProcessState ¶
type ProcessState string
const ( StateStopped ProcessState = ProcessState("stopped") StateStarting ProcessState = ProcessState("starting") StateReady ProcessState = ProcessState("ready") StateStopping ProcessState = ProcessState("stopping") // process is shutdown and will not be restarted StateShutdown ProcessState = ProcessState("shutdown") )
type ProcessStateChangeEvent ¶
type ProcessStateChangeEvent struct {
ProcessName string
NewState ProcessState
OldState ProcessState
}
func (ProcessStateChangeEvent) Type ¶
func (e ProcessStateChangeEvent) Type() uint32
type ProxyManager ¶
func New ¶
func New(proxyConfig config.Config) *ProxyManager
func (*ProxyManager) RegisterMDNS ¶
func (pm *ProxyManager) RegisterMDNS()
RegisterMDNS advertises this llama-swap instance on the LAN via mDNS/Bonjour under the service type _llamaswap._tcp.local. The registration is automatically withdrawn when the ProxyManager shuts down.
Call SetListenAddr before RegisterMDNS so the correct port is announced.
func (*ProxyManager) ServeHTTP ¶
func (pm *ProxyManager) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler interface
func (*ProxyManager) SetConfigFile ¶
func (pm *ProxyManager) SetConfigFile(path string)
SetConfigFile stores the path to the on-disk config YAML so that the management API can write model entries back to it.
func (*ProxyManager) SetListenAddr ¶
func (pm *ProxyManager) SetListenAddr(addr string)
SetListenAddr stores the HTTP listen address (e.g. "0.0.0.0:11435") so that RegisterMDNS can advertise the correct port.
func (*ProxyManager) SetPerfMonitor ¶
func (pm *ProxyManager) SetPerfMonitor(m *perf.Monitor)
func (*ProxyManager) SetReloadFn ¶
func (pm *ProxyManager) SetReloadFn(fn func())
SetReloadFn injects the reload callback from main so that POST /api/config/reload (and auto-reload after writes) can trigger it.
func (*ProxyManager) SetVersion ¶
func (pm *ProxyManager) SetVersion(buildDate string, commit string, version string)
func (*ProxyManager) Shutdown ¶
func (pm *ProxyManager) Shutdown()
Shutdown stops all processes managed by this ProxyManager
func (*ProxyManager) StopProcesses ¶
func (pm *ProxyManager) StopProcesses(strategy StopStrategy)
StopProcesses acquires a lock and stops all running upstream processes. This is the public method safe for concurrent calls. Unlike Shutdown, this method only stops the processes but doesn't perform a complete shutdown, allowing for process replacement without full termination.
type ReloadingState ¶
type ReloadingState int
const ( ReloadingStateStart ReloadingState = iota ReloadingStateEnd )
type ReqRespCapture ¶
type Reservation ¶
type Reservation struct {
ID string `json:"reservation_id"`
Model string `json:"model"`
Role string `json:"role"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
}
Reservation represents an active model reservation that prevents llama-swap from evicting a model mid-session.
type ReservationStore ¶
type ReservationStore struct {
// contains filtered or unexported fields
}
ReservationStore holds active reservations with a cleanup goroutine.
func NewReservationStore ¶
func NewReservationStore(ctx context.Context) *ReservationStore
NewReservationStore creates a reservation store and starts the expiry cleanup goroutine.
func (*ReservationStore) Add ¶
func (s *ReservationStore) Add(model, role string, durationSecs int) *Reservation
Add creates a new reservation and returns its ID.
func (*ReservationStore) Delete ¶
func (s *ReservationStore) Delete(id string) bool
Delete removes a reservation by ID.
func (*ReservationStore) Get ¶
func (s *ReservationStore) Get(id string) *Reservation
Get returns a reservation by ID, or nil if not found/expired.
func (*ReservationStore) HasActiveFor ¶
func (s *ReservationStore) HasActiveFor(model string) bool
HasActiveFor returns true if any active reservation exists for the given model.
type SessionMetrics ¶
type SessionMetrics struct {
TokensPrompt int `json:"tokens_prompt"`
TokensCompletion int `json:"tokens_completion"`
Requests int `json:"requests"`
AvgTTFTMs float64 `json:"avg_ttft_ms"`
AvgTPS float64 `json:"avg_tps"`
Model string `json:"model"`
DurationSecs int `json:"duration_secs"`
}
SessionMetrics accumulates per-reservation performance metrics.
type SessionMetricsStore ¶
type SessionMetricsStore struct {
// contains filtered or unexported fields
}
SessionMetricsStore accumulates metrics per reservation ID. It listens to ActivityLogEvent and aggregates by the X-Skein-Reservation header.
func NewSessionMetricsStore ¶
func NewSessionMetricsStore() *SessionMetricsStore
NewSessionMetricsStore creates a new session metrics store.
func (*SessionMetricsStore) Get ¶
func (s *SessionMetricsStore) Get(reservationID string) *SessionMetrics
Get returns the accumulated metrics for a reservation ID.
func (*SessionMetricsStore) Record ¶
func (s *SessionMetricsStore) Record(reservationID string, entry ActivityLogEntry)
Record adds an activity log entry to the accumulator for the given reservation ID.
type SkeinCapabilities ¶
SkeinCapabilities represents the response from GET /api/skein/capabilities.
type SolveResult ¶
type SolveResult struct {
Evict []string // running models that must be stopped
TargetSet []string // the chosen set of models (for informational purposes)
SetName string // name of the chosen set
DSL string // original DSL expression for the chosen set
TotalCost int // total eviction cost
}
SolveResult describes what the solver decided.
type StopStrategy ¶
type StopStrategy int
const ( StopImmediately StopStrategy = iota StopWaitForInflightRequest )
type TokenMetrics ¶
type TokenMetrics struct {
CachedTokens int `json:"cache_tokens"`
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
PromptPerSecond float64 `json:"prompt_per_second"`
TokensPerSecond float64 `json:"tokens_per_second"`
}
TokenMetrics holds token usage and performance metrics
Source Files
¶
- discardWriter.go
- events.go
- matrix.go
- metrics_monitor.go
- peerproxy.go
- process.go
- process_unix.go
- processgroup.go
- proxymanager.go
- proxymanager_api.go
- proxymanager_config.go
- proxymanager_disk.go
- proxymanager_disk_unix.go
- proxymanager_loghandlers.go
- proxymanager_mdns.go
- proxymanager_metrics.go
- proxymanager_models.go
- proxymanager_ollama.go
- proxymanager_reserve.go
- proxymanager_silent.go
- proxymanager_skein.go
- proxymanager_storage_unix.go
- proxymanager_upgrade.go
- proxymanager_warmup.go
- sanitize_cors.go
- ui_compress.go
- ui_embed.go