media

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 28 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

Overview

Package media adapts "OpenAI-style media servers" to the runtime.Runtime interface: runtimes that are a server process answering POST /v1/audio/speech with an audio file or POST /v1/images/generations with an image (proto design note 2026-11-30-media-output).

The adapter does everything such runtimes have in common: it fetches and verifies the family's pinned build, starts the server on a loopback port with the model, waits for it to be healthy, restarts it when it crashes, translates requests, turns the answer into a media stream (data in pieces, progress while there is none, usage) and stops a request at the runtime when it is cancelled. What differs between runtimes is a Descriptor: a few facts and small functions per family.

Index

Constants

View Source
const (
	RoleVoices = "voices" // speech: the voice pack
	RoleVAE    = "vae"    // image: the VAE
	RoleLLM    = "llm"    // image: an LLM used as text encoder (Qwen, Mistral)
	RoleClipL  = "clip_l" // image: the CLIP-L text encoder
	RoleClipG  = "clip_g" // image: the CLIP-G text encoder
	RoleT5XXL  = "t5xxl"  // image: the T5-XXL text encoder
)

File roles (ModelSpec.files[].role), as the catalog and the proto spell them. The main artifact has no role: it is ModelSpec.Path. The image roles are the runtime's own names for the slots a split model fills.

Variables

This section is empty.

Functions

func Families

func Families() []string

Families lists the known family names, sorted.

func Register

func Register(d Descriptor)

Register makes a descriptor known under its family name.

Types

type Adapter

type Adapter struct {
	Desc Descriptor
	// Fetcher resolves the family's server binary: the configured local
	// one, or the pinned build from the family's manifest, fetched and
	// verified the first time a model of the family is loaded.
	Fetcher *llamacpp.Fetcher
	// Accels is the accelerator preference chain (hardware.AccelPreference).
	Accels []string
	Log    *slog.Logger
	// KeyDir is where the per-load API key files are kept: a directory
	// only this user can enter (the daemon's data dir). "" = the system's
	// temporary directory, for tests.
	KeyDir string
	// ProgressInterval is how often a request with nothing to send yet
	// reports progress; 0 = rt.MediaProgressInterval.
	ProgressInterval time.Duration
}

Adapter implements runtime.Runtime for one media runtime family.

func (*Adapter) Load

func (a *Adapter) Load(ctx context.Context, m rt.ModelSpec, res rt.ResourceBudget) (rt.Instance, error)

Load fetches and verifies the family's build if this is the first model of the family, starts the server on a loopback port with the model's files, waits for it to be healthy and returns the serving instance.

func (*Adapter) PrepareRuntime

func (a *Adapter) PrepareRuntime(ctx context.Context, m rt.ModelSpec) error

PrepareRuntime implements runtime.RuntimePreparer: the family's build is fetched and verified here, ahead of Load, which then finds it cached.

func (*Adapter) Resolve

func (a *Adapter) Resolve(ctx context.Context) (buildID string, err error)

Resolve reports the build of the family this node would run, without downloading it: what the daemon advertises in CapabilityProfile.runtimes. An error means the node cannot run the family (no build for this platform, a manifest it cannot trust).

func (*Adapter) SupportsModel

func (a *Adapter) SupportsModel(ctx context.Context, m rt.ModelSpec) error

SupportsModel implements runtime.ModelSupporter: before anything is downloaded for a model, the family must serve its kind and have a build for this machine. The build itself is not fetched here.

type CancelMode

type CancelMode int

CancelMode is how a request is stopped at the runtime.

const (
	// CancelDisconnect closes the HTTP request: the runtime sees its
	// client go away and stops the work. The default, and what a server
	// that checks for a dropped connection needs.
	CancelDisconnect CancelMode = iota
	// CancelRestart is for a runtime that finishes a generation whoever
	// is still listening: the request is closed and the server process is
	// killed, and the supervisor starts a fresh one. Costly (the model
	// loads again), but the GPU stops working for a request nobody waits
	// for, which is what cancelling promises the operator.
	CancelRestart
)

type Descriptor

type Descriptor struct {
	// Family is the runtime family name: ModelSpec.runtime in the catalog,
	// CapabilityProfile.runtimes on the wire, runtime.families.<name> in
	// the config, and the directory of the family's build manifest.
	Family string
	// Binary is the server executable's base name, without ".exe".
	Binary string
	// Sidecars are base-name patterns of files the family's tarball
	// carries beside the binary and cannot run without (shared libraries).
	Sidecars []string
	// Kinds are the request kinds the family serves: rt.KindSpeech,
	// rt.KindImage, or both.
	Kinds []rt.Kind
	// Provisional marks a descriptor whose facts have not been checked
	// against the real runtime. The daemon says so when one is enabled.
	Provisional bool

	// Args is the server's command line for a model: how the main
	// artifact and the files by role become arguments, and where to
	// listen. An error means the model cannot be served (a file with a
	// role the runtime needs is missing).
	Args func(l Launch) ([]string, error)
	// Env is added to the server's environment. May be nil.
	Env func(l Launch) []string

	// HealthPath is polled with GET until the server is ready; "" is
	// "/health".
	HealthPath string
	// Healthy decides whether a health answer means ready; nil = 200.
	Healthy func(status int, body []byte) bool
	// StartTimeout is how long loading a model may take before the load
	// fails; 0 = 120 s.
	StartTimeout time.Duration

	// Cancel is how a cancelled request is stopped at the runtime, for a
	// request made as one synchronous call. A family with an image job
	// API (ImageQuirks.Jobs) cancels the job instead.
	Cancel CancelMode
	// Vet looks at the model's files before anything is started and
	// refuses what the runtime must not be given. May be nil.
	Vet func(rt.ModelSpec) error
	// BearerAuth: the server is started with Launch.APIKey as its API key
	// and every request, the health probe included, carries it as a
	// bearer token. It is how the adapter knows it is talking to its own
	// child: a runtime that fails to bind its port can exit quietly, or
	// share the port, while another process answers there, and that one
	// answers 401. HealthPath must then be a route that asks for the key.
	BearerAuth bool
	// MaxConcurrent is how many requests the server takes at once; more
	// wait in the adapter, never in the runtime. 0 = no limit here.
	MaxConcurrent int
	// WarmUp returns a small image request to run once, right after the
	// server is listening, for a runtime that only reads the weights on
	// its first request: the load then ends when the model is in memory,
	// not when the port is open, and the first customer does not pay for
	// it. nil = listening is loaded.
	WarmUp func(m rt.ModelSpec) *rt.ImageRequest

	// Speech and Image are the request and response quirks per kind.
	Speech SpeechQuirks
	Image  ImageQuirks

	// InvalidInput decides whether a non-200 answer is the runtime
	// refusing the input itself (a voice it does not have, a size it
	// cannot produce, text it cannot speak) rather than failing: such a
	// request fails the same way on every node, so it is not retried and
	// the node is not blamed. nil = status 400 or 422.
	InvalidInput func(status int, body []byte) bool
	// ErrorMessage extracts the runtime's reason from an error body; nil
	// reads the usual JSON shapes ({"error":{"message"}}, {"error"},
	// {"detail"}, {"message"}) and falls back to the body itself.
	ErrorMessage func(body []byte) string
}

Descriptor is everything the adapter needs to know about one runtime family. Only Family, Binary, Kinds and Args are required; every other field has a default that is the plain OpenAI behaviour.

func Lookup

func Lookup(family string) (Descriptor, bool)

Lookup returns the descriptor of a family.

type ImageJobs

type ImageJobs struct {
	// Submit is the request that starts a generation: POST path with a
	// JSON body. Any 2xx answer means the job exists.
	Submit func(m rt.ModelSpec, req *rt.ImageRequest) (path string, body map[string]any)
	// Started reads the job's id from the answer to Submit.
	Started func(raw []byte) (id string, err error)
	// PollPath is the GET that reports a job; CancelPath the POST that
	// cancels it.
	PollPath   func(id string) string
	CancelPath func(id string) string
	// State reads the answer to a poll.
	State func(raw []byte) (JobState, error)
	// PollInterval is how often a job is polled; 0 = one second.
	PollInterval time.Duration
}

ImageJobs is the second request style, for a runtime whose plain generation call cannot be watched or stopped: a generation is a job that is submitted, polled for progress and its result, and cancelled by a call of its own.

type ImageQuirks

type ImageQuirks struct {
	// Path is the endpoint; "" is "/v1/images/generations".
	Path string
	// Body edits the request body before it is sent. It starts as
	// OpenAI's (model, prompt, n, size, response_format, output_format)
	// plus the generation settings under the names most servers take:
	// seed, steps, guidance, negative_prompt. May be nil.
	Body func(body map[string]any, m rt.ModelSpec, req *rt.ImageRequest)
	// Progress asks the runtime how far along the generation is, 0..1000,
	// for the progress pieces sent while it works. nil (or ok false):
	// the runtime cannot say, and progress is reported as 0.
	Progress func(ctx context.Context, c *http.Client, baseURL string) (permille int, ok bool)
	// Jobs, when set, replaces the one synchronous call (Path, Body,
	// Progress) with the runtime's job API: submit, poll, cancel.
	Jobs *ImageJobs
}

ImageQuirks adjust the image translation for a family.

type JobState

type JobState struct {
	Status JobStatus
	// Permille is how far along a running job is, 0..1000.
	Permille int
	// Image is the result of a finished job: the file, base64.
	Image string
	// Error is the runtime's reason for a failed job.
	Error string
}

JobState is one poll of a job.

type JobStatus

type JobStatus int

JobStatus is where a job stands.

const (
	JobRunning   JobStatus = iota // queued or generating
	JobDone                       // JobState.Image is the result
	JobFailed                     // JobState.Error says why
	JobCancelled                  // stopped at the runtime
)

type Launch

type Launch struct {
	// Model is the model to serve: Path is its main artifact, Files the
	// further files by role (FilePath), Speech or Image what it offers.
	Model rt.ModelSpec
	// Host and Port are where the server must listen (loopback).
	Host string
	Port int
	// Accel is the accelerator lane of the build that will run ("metal",
	// "cuda12", "vulkan", "cpu-avx2", ...); "" for a configured local
	// binary, whose backend the daemon cannot know.
	Accel string
	// Budget is the operator's resource ceiling for this load.
	Budget rt.ResourceBudget
	// APIKey is a random secret made for this one model load. A family
	// with BearerAuth starts its server with it and the adapter sends it
	// with every request. APIKeyFile is a file readable by this user only
	// that holds it on one line: the way to hand it over, because a
	// command line is visible to every user of the machine.
	APIKey     string
	APIKeyFile string
}

Launch is what a family's Args turn into a command line.

type SpeechQuirks

type SpeechQuirks struct {
	// Path is the endpoint; "" is "/v1/audio/speech".
	Path string
	// Body edits the request body before it is sent. It starts as
	// OpenAI's: model, input, voice, response_format, speed. A family
	// renames, removes or adds fields here (a language field, a format
	// name the runtime spells differently). May be nil.
	Body func(body map[string]any, m rt.ModelSpec, req *rt.SpeechRequest)
}

SpeechQuirks adjust the speech translation for a family.

Jump to

Keyboard shortcuts

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