Documentation
¶
Overview ¶
llama_server.go wraps the llama-server binary as a subprocess
Ollama uses two chat paths with llama-server. Models with explicit Ollama renderers/parsers, Harmony handling, MLX, or an enabled Go TEMPLATE layer still render prompts in Go and call /completion. Other GGUF chat models use llama-server's chat_template handling through /v1/chat/completions.
For structured output, JSON schemas are passed directly to llama-server via its json_schema field (avoiding the CGO SchemaToGrammar dependency). Raw BNF grammars are passed via the grammar field.
llama-server auto-detects GPU layers (-ngl), thread count (-t), and flash attention (--flash-attn).
Index ¶
- Constants
- Variables
- func AudioFormat(data []byte) (string, bool)
- func DefaultEmbeddingNumBatchForContext(numCtx int) int
- func FindLlamaCppBinary(name string) (string, error)
- func FindLlamaServer() (string, error)
- func IsOutOfMemory(err error) bool
- func IsOutOfMemoryMessage(msg string) bool
- func LlamaServerFlashAttention(gpus []ml.DeviceInfo) ml.FlashAttentionType
- func LoadModel(model string, maxArraySize int) (*ggml.GGML, error)
- func PredictServerVRAM(modelPath string, f *ggml.GGML, numCtx int) uint64
- func SetupLlamaServerCommandEnv(cmd *exec.Cmd, exe string, gpuLibs []string, extraEnvs map[string]string)
- func ShouldRetryWithMetalTensorDisabled(err error, status *StatusWriter) bool
- func WithDefaultEmbeddingNumBatch(opts api.Options) api.Options
- type ChatRequest
- type ChatResponse
- type CompletionRequest
- type CompletionResponse
- type DoneReason
- type ExitStatus
- type LlamaServer
- type LlamaServerConfig
- type Logprob
- type MediaData
- type MediaKind
- type Message
- type ServerStatus
- type ServerStatusResponse
- type StatusWriter
- type TokenLogprob
Constants ¶
const (
DefaultEmbeddingNumBatch = 2048
)
DefaultEmbeddingNumBatch is the default NumBatch used for embedding models when neither the model nor the request specifies num_batch.
Variables ¶
var ErrLoadRequiredFull = errors.New("unable to load full model on GPU")
var LlamaServerSysProcAttr = &syscall.SysProcAttr{}
Functions ¶
func AudioFormat ¶ added in v0.30.0
func DefaultEmbeddingNumBatchForContext ¶ added in v0.30.0
DefaultEmbeddingNumBatchForContext caps the embedding batch default to the active context length before it is passed to llama-server.
func FindLlamaCppBinary ¶ added in v0.30.0
FindLlamaCppBinary locates a llama.cpp helper binary in installed and local development layouts.
func FindLlamaServer ¶ added in v0.30.0
FindLlamaServer locates the llama-server binary in lib/ollama/. There is a single binary that dynamically loads GPU backends at runtime.
func IsOutOfMemory ¶ added in v0.30.0
func IsOutOfMemoryMessage ¶ added in v0.30.0
func LlamaServerFlashAttention ¶ added in v0.30.0
func LlamaServerFlashAttention(gpus []ml.DeviceInfo) ml.FlashAttentionType
LlamaServerFlashAttention resolves the flash-attention mode passed to llama-server.
func LoadModel ¶ added in v0.1.33
LoadModel will load a model from disk. The model must be in the GGML format.
It collects array values for arrays with a size less than or equal to maxArraySize. If maxArraySize is 0, the default value of 1024 is used. If the maxArraySize is negative, all arrays are collected.
func PredictServerVRAM ¶ added in v0.30.0
PredictServerVRAM estimates VRAM usage for a model without spawning llama-server. Uses model file size as a proxy for weights plus a rough KV cache estimate. This is intentionally conservative — it overestimates to avoid VRAM contention.
func SetupLlamaServerCommandEnv ¶ added in v0.30.0
func SetupLlamaServerCommandEnv(cmd *exec.Cmd, exe string, gpuLibs []string, extraEnvs map[string]string)
SetupLlamaServerCommandEnv configures the environment for a llama-server subprocess so discovery and real model runners use the same library search paths and GPU backend selection.
func ShouldRetryWithMetalTensorDisabled ¶ added in v0.23.0
func ShouldRetryWithMetalTensorDisabled(err error, status *StatusWriter) bool
ShouldRetryWithMetalTensorDisabled detects Metal tensor API initialization failures where ggml's probe can pass but real kernel compilation or context creation fails. Retrying with GGML_METAL_TENSOR_DISABLE=1 keeps discovery and later runner launches on the conservative Metal path.
Types ¶
type ChatRequest ¶ added in v0.30.0
type ChatResponse ¶ added in v0.30.0
type ChatResponse struct {
Message api.Message `json:"message"`
DoneReason DoneReason `json:"done_reason"`
Done bool `json:"done"`
PromptEvalCount int `json:"prompt_eval_count"`
PromptEvalDuration time.Duration `json:"prompt_eval_duration"`
EvalCount int `json:"eval_count"`
EvalDuration time.Duration `json:"eval_duration"`
Logprobs []Logprob `json:"logprobs,omitempty"`
}
type CompletionRequest ¶ added in v0.1.32
type CompletionRequest struct {
Prompt string
Format json.RawMessage
Media []MediaData
Options *api.Options
Grammar string // set before sending the request to the subprocess
Shift bool
Truncate bool
PreservedTokens []string // parser tokens to render as text; ignored by non-llama-server runners
ToolCallTag string // raw generic tool parser tag, if any
LeadingBOS string // textual BOS emitted by Go rendering, if any
// Logprobs specifies whether to include log probabilities in the response
Logprobs bool
// TopLogprobs specifies the number of most likely alternative tokens to return (0-20)
TopLogprobs int
// Image generation fields
Width int32 `json:"width,omitempty"`
Height int32 `json:"height,omitempty"`
Steps int32 `json:"steps,omitempty"`
Seed int64 `json:"seed,omitempty"`
}
type CompletionResponse ¶ added in v0.1.32
type CompletionResponse struct {
Content string `json:"content"`
DoneReason DoneReason `json:"done_reason"`
Done bool `json:"done"`
PromptEvalCount int `json:"prompt_eval_count"`
PromptEvalDuration time.Duration `json:"prompt_eval_duration"`
EvalCount int `json:"eval_count"`
EvalDuration time.Duration `json:"eval_duration"`
// Logprobs contains log probability information if requested
Logprobs []Logprob `json:"logprobs,omitempty"`
// Image contains base64-encoded image data for image generation
Image string `json:"image,omitempty"`
// Step is the current step in image generation
Step int `json:"step,omitempty"`
// TotalSteps is the total number of steps for image generation
TotalSteps int `json:"total_steps,omitempty"`
}
type DoneReason ¶ added in v0.6.5
type DoneReason int
DoneReason represents the reason why a completion response is done
const ( DoneReasonStop DoneReason = iota DoneReasonLength DoneReasonConnectionClosed )
func (DoneReason) String ¶ added in v0.6.5
func (d DoneReason) String() string
type ExitStatus ¶ added in v0.30.0
type ExitStatus int
func ExitStatusFromError ¶ added in v0.30.0
func ExitStatusFromError(err error) ExitStatus
func (ExitStatus) Known ¶ added in v0.30.0
func (s ExitStatus) Known() bool
func (ExitStatus) LogValue ¶ added in v0.30.0
func (s ExitStatus) LogValue() slog.Value
func (ExitStatus) String ¶ added in v0.30.0
func (s ExitStatus) String() string
type LlamaServer ¶ added in v0.1.32
type LlamaServer interface {
ModelPath() string
Load(ctx context.Context, systemInfo ml.SystemInfo, gpus []ml.DeviceInfo, requireFull bool) ([]ml.DeviceID, error)
Ping(ctx context.Context) error
WaitUntilRunning(ctx context.Context) error
Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error
Chat(ctx context.Context, req ChatRequest, fn func(ChatResponse)) error
ApplyChatTemplate(ctx context.Context, req ChatRequest) (string, error)
Embedding(ctx context.Context, input string) ([]float32, int, error)
Tokenize(ctx context.Context, content string) ([]int, error)
Detokenize(ctx context.Context, tokens []int) (string, error)
Close() error
MemorySize() (total, vram uint64)
VRAMByGPU(id ml.DeviceID) uint64
Pid() int
GetPort() int
GetDeviceInfos(ctx context.Context) []ml.DeviceInfo
HasExited() bool
ContextLength() int
}
func NewLlamaServer ¶ added in v0.1.32
func NewLlamaServer(systemInfo ml.SystemInfo, gpus []ml.DeviceInfo, modelPath string, f *ggml.GGML, adapters, projectors []string, opts api.Options, numParallel int, config LlamaServerConfig) (LlamaServer, error)
NewLlamaServer creates a new llama-server runner for the given model. All GGML models are served via the upstream llama-server subprocess.
func NewLlamaServerRunner ¶ added in v0.30.0
func NewLlamaServerRunner( gpus []ml.DeviceInfo, modelPath string, f *ggml.GGML, adapters, projectors []string, opts api.Options, numParallel int, kvCacheType string, config LlamaServerConfig, ) (LlamaServer, error)
NewLlamaServerRunner creates a new llama-server runner that wraps the upstream llama-server binary.
type LlamaServerConfig ¶ added in v0.30.0
type Logprob ¶ added in v0.12.11
type Logprob struct {
TokenLogprob
TopLogprobs []TokenLogprob `json:"top_logprobs,omitempty"`
}
Logprob contains log probability information for a generated token.
type MediaData ¶ added in v0.30.0
func NewMediaData ¶ added in v0.30.0
type Message ¶ added in v0.30.0
type Message struct {
Role string
Content string
Thinking string
Media []MediaData
ToolCalls []api.ToolCall
ToolName string
ToolCallID string
}
func MessageFromAPI ¶ added in v0.30.0
type ServerStatus ¶ added in v0.1.32
type ServerStatus int
const ( ServerStatusReady ServerStatus = iota ServerStatusNoSlotsAvailable ServerStatusLaunched ServerStatusLoadingModel ServerStatusNotResponding ServerStatusError )
func (ServerStatus) String ¶ added in v0.6.2
func (s ServerStatus) String() string
type ServerStatusResponse ¶ added in v0.6.2
type ServerStatusResponse struct {
Status ServerStatus `json:"status"`
Progress float32 `json:"progress"`
}
type StatusWriter ¶ added in v0.1.32
type StatusWriter struct {
// contains filtered or unexported fields
}
StatusWriter is a writer that captures error messages from the llama runner process
func NewStatusWriter ¶ added in v0.1.32
func NewStatusWriter(out io.Writer) *StatusWriter
func (*StatusWriter) AppendError ¶ added in v0.23.0
func (w *StatusWriter) AppendError(msg string)
func (*StatusWriter) LastError ¶ added in v0.23.0
func (w *StatusWriter) LastError() string
func (*StatusWriter) SetLastError ¶ added in v0.23.0
func (w *StatusWriter) SetLastError(msg string)
type TokenLogprob ¶ added in v0.12.11
TokenLogprob represents log probability information for a single token alternative.