proxy

package
v0.0.0-...-a86a093 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2026 License: MIT Imports: 45 Imported by: ? 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 ActivityLogEventID = 0x05
View Source
const ChatCompletionStatsEventID = 0x02
View Source
const ConfigFileChangedEventID = 0x03
View Source
const InFlightRequestsEventID = 0x07
View Source
const ModelPreloadedEventID = 0x06
View Source
const (
	PROFILE_SPLIT_CHAR = ":"
)
View Source
const ProcessStateChangeEventID = 0x01
View Source
const SkeinCapabilitiesVersion = 1

SkeinCapabilitiesVersion is the current version of the Skein companion API.

Variables

View Source
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

func GetReactIndexHTML() ([]byte, error)

GetReactIndexHTML returns the main index.html for the React app

func SanitizeAccessControlRequestHeaderValues

func SanitizeAccessControlRequestHeaderValues(headerValues string) string

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) Write

func (w *DiscardWriter) Write(data []byte) (int, error)

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

type Matrix struct {
	sync.Mutex
	// contains filtered or unexported fields
}

Matrix manages processes using solver-based swap logic.

func NewMatrix

func NewMatrix(cfg config.Config, proxyLogger, upstreamLogger *logmon.Monitor) *Matrix

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

func (m *Matrix) GetProcess(modelID string) (*Process, bool)

GetProcess returns the Process for a model.

func (*Matrix) HasModel

func (m *Matrix) HasModel(modelID string) bool

HasModel returns true if the model is managed by this matrix.

func (*Matrix) ProxyRequest

func (m *Matrix) ProxyRequest(modelID string, w http.ResponseWriter, r *http.Request) error

ProxyRequest handles the swap logic and proxies the request to the model.

func (*Matrix) RunningModels

func (m *Matrix) RunningModels() []string

RunningModels returns model names currently in an active (non-stopped) state.

func (*Matrix) Shutdown

func (m *Matrix) Shutdown()

Shutdown shuts down all processes.

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:

  1. If requestedModel is already running, no eviction needed.
  2. Find all sets containing requestedModel.
  3. If no sets found, the model runs alone; evict all running models.
  4. For each candidate set, compute cost = sum of evict_costs for running models NOT in that set.
  5. Pick lowest cost. Ties broken by definition order (index in expandedSets).
  6. Return models to evict and the chosen set.

type Model

type Model struct {
	Id          string   `json:"id"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	State       string   `json:"state"`
	Unlisted    bool     `json:"unlisted"`
	PeerID      string   `json:"peerID"`
	Aliases     []string `json:"aliases,omitempty"`
}

type ModelPreloadedEvent

type ModelPreloadedEvent struct {
	ModelName string
	Success   bool
}

func (ModelPreloadedEvent) Type

func (e ModelPreloadedEvent) Type() uint32

type PeerProxy

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

func NewPeerProxy

func NewPeerProxy(peers config.PeerDictionaryConfig, proxyLogger *logmon.Monitor) (*PeerProxy, error)

func (*PeerProxy) GetPeerFilters

func (p *PeerProxy) GetPeerFilters(modelID string) config.Filters

GetPeerFilters returns the filters for a peer model, or empty filters if not found

func (*PeerProxy) HasPeerModel

func (p *PeerProxy) HasPeerModel(modelID string) bool

func (*PeerProxy) ListPeers

func (p *PeerProxy) ListPeers() config.PeerDictionaryConfig

func (*PeerProxy) ProxyRequest

func (p *PeerProxy) ProxyRequest(model_id string, writer http.ResponseWriter, request *http.Request) error

type Process

type Process struct {
	ID string
	// contains filtered or unexported fields
}

func NewProcess

func NewProcess(ID string, healthCheckTimeout int, config config.ModelConfig, processLogger *logmon.Monitor, proxyLogger *logmon.Monitor) *Process

func (*Process) CurrentState

func (p *Process) CurrentState() ProcessState

func (*Process) InFlightAge

func (p *Process) InFlightAge() (time.Duration, bool)

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

func (p *Process) LogMonitor() *logmon.Monitor

LogMonitor returns the log monitor associated with the process.

func (*Process) Logger

func (p *Process) Logger() *logmon.Monitor

Logger returns the logger for this 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

type ProcessGroup struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewProcessGroup

func NewProcessGroup(id string, config config.Config, proxyLogger *logmon.Monitor, upstreamLogger *logmon.Monitor) *ProcessGroup

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

type ProxyManager

type ProxyManager struct {
	sync.Mutex
	// contains filtered or unexported fields
}

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 ReqRespCapture struct {
	ID          int               `json:"id"`
	ReqPath     string            `json:"req_path"`
	ReqHeaders  map[string]string `json:"req_headers"`
	ReqBody     []byte            `json:"req_body"`
	RespHeaders map[string]string `json:"resp_headers"`
	RespBody    []byte            `json:"resp_body"`
}

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

type SkeinCapabilities struct {
	Version  int      `json:"version"`
	Features []string `json:"features"`
}

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

Jump to

Keyboard shortcuts

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