proxy

package
v0.0.0-...-10138ad Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 41 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 ChatCompletionStatsEventID = 0x02
View Source
const ConfigFileChangedEventID = 0x03
View Source
const LogDataEventID = 0x04
View Source
const ModelPreloadedEventID = 0x06
View Source
const ProcessStateChangeEventID = 0x01
View Source
const TokenMetricsEventID = 0x05

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.

Types

type BenchyJob

type BenchyJob struct {
	ID                  string     `json:"id"`
	Model               string     `json:"model"`
	QueueModels         []string   `json:"queueModels,omitempty"`
	QueueCurrentIndex   int        `json:"queueCurrentIndex,omitempty"`
	QueueCurrentModel   string     `json:"queueCurrentModel,omitempty"`
	QueueCompletedCount int        `json:"queueCompletedCount,omitempty"`
	Tokenizer           string     `json:"tokenizer"`
	ScheduledAt         *time.Time `json:"scheduledAt,omitempty"`
	BaseURL             string     `json:"baseUrl"`
	PP                  []int      `json:"pp"`
	TG                  []int      `json:"tg"`
	Depth               []int      `json:"depth,omitempty"`
	Concurrency         []int      `json:"concurrency,omitempty"`
	Runs                int        `json:"runs"`
	LatencyMode         string     `json:"latencyMode,omitempty"`
	NoCache             bool       `json:"noCache,omitempty"`
	NoWarmup            bool       `json:"noWarmup,omitempty"`
	AdaptPrompt         *bool      `json:"adaptPrompt,omitempty"`
	EnablePrefixCaching bool       `json:"enablePrefixCaching,omitempty"`
	EnableIntelligence  bool       `json:"enableIntelligence,omitempty"`
	IntelligencePlugins []string   `json:"intelligencePlugins,omitempty"`
	AllowCodeExec       bool       `json:"allowCodeExec,omitempty"`
	DatasetCacheDir     string     `json:"datasetCacheDir,omitempty"`
	OutputDir           string     `json:"outputDir,omitempty"`
	MaxConcurrent       *int       `json:"maxConcurrent,omitempty"`
	// TrustRemoteCode controls whether we auto-accept the HuggingFace "custom code" prompt for some tokenizers.
	// This only affects local tokenizer loading, not the remote server.
	TrustRemoteCode bool `json:"trustRemoteCode,omitempty"`

	Status     BenchyJobStatus `json:"status"`
	StartedAt  time.Time       `json:"startedAt"`
	FinishedAt *time.Time      `json:"finishedAt,omitempty"`
	ExitCode   *int            `json:"exitCode,omitempty"`

	Stdout string `json:"stdout,omitempty"`
	Stderr string `json:"stderr,omitempty"`
	Error  string `json:"error,omitempty"`
}

type BenchyJobStatus

type BenchyJobStatus string

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 LogDataEvent

type LogDataEvent struct {
	Data []byte
}

func (LogDataEvent) Type

func (e LogDataEvent) Type() uint32

type LogLevel

type LogLevel int
const (
	LevelDebug LogLevel = iota
	LevelInfo
	LevelWarn
	LevelError

	LogBufferSize = 100 * 1024
)

func (LogLevel) String

func (l LogLevel) String() string

type LogMonitor

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

func NewLogMonitor

func NewLogMonitor() *LogMonitor

func NewLogMonitorWriter

func NewLogMonitorWriter(stdout io.Writer) *LogMonitor

func (*LogMonitor) Clear

func (w *LogMonitor) Clear()

Clear releases the buffer memory, making it eligible for GC. The buffer will be lazily re-allocated on the next Write.

func (*LogMonitor) Debug

func (w *LogMonitor) Debug(msg string)

func (*LogMonitor) Debugf

func (w *LogMonitor) Debugf(format string, args ...interface{})

func (*LogMonitor) Error

func (w *LogMonitor) Error(msg string)

func (*LogMonitor) Errorf

func (w *LogMonitor) Errorf(format string, args ...interface{})

func (*LogMonitor) GetHistory

func (w *LogMonitor) GetHistory() []byte

func (*LogMonitor) Info

func (w *LogMonitor) Info(msg string)

func (*LogMonitor) Infof

func (w *LogMonitor) Infof(format string, args ...interface{})

func (*LogMonitor) OnLogData

func (w *LogMonitor) OnLogData(callback func(data []byte)) context.CancelFunc

func (*LogMonitor) SetLogLevel

func (w *LogMonitor) SetLogLevel(level LogLevel)

func (*LogMonitor) SetLogTimeFormat

func (w *LogMonitor) SetLogTimeFormat(timeFormat string)

func (*LogMonitor) SetPrefix

func (w *LogMonitor) SetPrefix(prefix string)

func (*LogMonitor) Warn

func (w *LogMonitor) Warn(msg string)

func (*LogMonitor) Warnf

func (w *LogMonitor) Warnf(format string, args ...interface{})

func (*LogMonitor) Write

func (w *LogMonitor) Write(p []byte) (n int, err error)

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"`
	ContainerImage string `json:"containerImage,omitempty"`
	RecipeRef      string `json:"recipeRef,omitempty"`
	Mode           string `json:"mode,omitempty"`
	TensorParallel int    `json:"tensorParallel,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 *LogMonitor) (*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 *LogMonitor, proxyLogger *LogMonitor) *Process

func (*Process) CurrentState

func (p *Process) CurrentState() ProcessState

func (*Process) LogMonitor

func (p *Process) LogMonitor() *LogMonitor

LogMonitor returns the log monitor associated with the process.

func (*Process) Logger

func (p *Process) Logger() *LogMonitor

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 *LogMonitor, upstreamLogger *LogMonitor) *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. In swap mode we serialize switching and proxying with swapRequestMu while keeping pg.Lock short-lived.

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 NewWithConfigPath

func NewWithConfigPath(proxyConfig config.Config, configPath string) *ProxyManager

func (*ProxyManager) ServeHTTP

func (pm *ProxyManager) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler interface

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 RecipeBackendActionInfo

type RecipeBackendActionInfo struct {
	Action      string `json:"action"`
	Label       string `json:"label"`
	CommandHint string `json:"commandHint,omitempty"`
}

type RecipeBackendLLAMACPPImage

type RecipeBackendLLAMACPPImage struct {
	Selected  string   `json:"selected"`
	Default   string   `json:"default"`
	Available []string `json:"available,omitempty"`
	Warning   string   `json:"warning,omitempty"`
}

type RecipeBackendNVIDIAImage

type RecipeBackendNVIDIAImage struct {
	Selected        string   `json:"selected"`
	Default         string   `json:"default"`
	Latest          string   `json:"latest,omitempty"`
	UpdateAvailable bool     `json:"updateAvailable,omitempty"`
	Available       []string `json:"available,omitempty"`
	Warning         string   `json:"warning,omitempty"`
}

type RecipeBackendState

type RecipeBackendState struct {
	BackendDir         string                      `json:"backendDir"`
	BackendSource      string                      `json:"backendSource"`
	Options            []string                    `json:"options"`
	BackendKind        string                      `json:"backendKind"`
	BackendVendor      string                      `json:"backendVendor,omitempty"`
	DeploymentGuideURL string                      `json:"deploymentGuideUrl,omitempty"`
	RepoURL            string                      `json:"repoUrl,omitempty"`
	Actions            []RecipeBackendActionInfo   `json:"actions"`
	TRTLLMImage        *RecipeBackendTRTLLMImage   `json:"trtllmImage,omitempty"`
	NVIDIAImage        *RecipeBackendNVIDIAImage   `json:"nvidiaImage,omitempty"`
	LLAMACPPImage      *RecipeBackendLLAMACPPImage `json:"llamacppImage,omitempty"`
}

type RecipeBackendTRTLLMImage

type RecipeBackendTRTLLMImage struct {
	Selected        string   `json:"selected"`
	Default         string   `json:"default"`
	Latest          string   `json:"latest,omitempty"`
	UpdateAvailable bool     `json:"updateAvailable,omitempty"`
	Available       []string `json:"available,omitempty"`
	Warning         string   `json:"warning,omitempty"`
}

type RecipeCatalogItem

type RecipeCatalogItem struct {
	ID                    string `json:"id"`
	Ref                   string `json:"ref"`
	Path                  string `json:"path"`
	BackendDir            string `json:"backendDir,omitempty"`
	BackendKind           string `json:"backendKind,omitempty"`
	Name                  string `json:"name"`
	Description           string `json:"description"`
	Model                 string `json:"model"`
	SoloOnly              bool   `json:"soloOnly"`
	ClusterOnly           bool   `json:"clusterOnly"`
	DefaultTensorParallel int    `json:"defaultTensorParallel"`
	DefaultExtraArgs      string `json:"defaultExtraArgs,omitempty"`
	ContainerImage        string `json:"containerImage,omitempty"`
}

type RecipeManagedModel

type RecipeManagedModel struct {
	ModelID               string   `json:"modelId"`
	RecipeRef             string   `json:"recipeRef"`
	Name                  string   `json:"name"`
	Description           string   `json:"description"`
	Aliases               []string `json:"aliases"`
	UseModelName          string   `json:"useModelName"`
	Mode                  string   `json:"mode"` // solo|cluster
	TensorParallel        int      `json:"tensorParallel"`
	Nodes                 string   `json:"nodes,omitempty"`
	ExtraArgs             string   `json:"extraArgs,omitempty"`
	ContainerImage        string   `json:"containerImage,omitempty"`
	Group                 string   `json:"group"`
	Unlisted              bool     `json:"unlisted,omitempty"`
	Managed               bool     `json:"managed"`
	BenchyTrustRemoteCode *bool    `json:"benchyTrustRemoteCode,omitempty"`
	NonPrivileged         bool     `json:"nonPrivileged,omitempty"`
	MemLimitGb            int      `json:"memLimitGb,omitempty"`
	MemSwapLimitGb        int      `json:"memSwapLimitGb,omitempty"`
	PidsLimit             int      `json:"pidsLimit,omitempty"`
	ShmSizeGb             int      `json:"shmSizeGb,omitempty"`
}

type RecipeUIState

type RecipeUIState struct {
	ConfigPath  string               `json:"configPath"`
	BackendDir  string               `json:"backendDir"`
	BackendKind string               `json:"backendKind,omitempty"`
	Recipes     []RecipeCatalogItem  `json:"recipes"`
	Models      []RecipeManagedModel `json:"models"`
	Groups      []string             `json:"groups"`
}

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"`
}

func (*ReqRespCapture) Size

func (c *ReqRespCapture) Size() int

Size returns the approximate memory usage of this capture in bytes

type StopStrategy

type StopStrategy int
const (
	StopImmediately StopStrategy = iota
	StopWaitForInflightRequest
)

type TokenMetrics

type TokenMetrics struct {
	ID              int       `json:"id"`
	Timestamp       time.Time `json:"timestamp"`
	Model           string    `json:"model"`
	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"`
	DurationMs      int       `json:"duration_ms"`
	HasCapture      bool      `json:"has_capture"`
}

TokenMetrics represents parsed token statistics from llama-server logs

type TokenMetricsEvent

type TokenMetricsEvent struct {
	Metrics TokenMetrics
}

TokenMetricsEvent represents a token metrics event

func (TokenMetricsEvent) Type

func (e TokenMetricsEvent) Type() uint32

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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