inferd

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 14 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 inferd is a client for the inferd inference daemon's IPC wire protocol (v2, inferd ADR 0021), speaking the wire directly as the protocol document defines it.

Borrowed from thlibo's internal/inferd at commit 0860bc8 (MIT, Copyright (c) 2026 3rg0n, the same author), as issue #10 scoped. Changed here (ADR 0044):

  • the embedding client is left out, since nothing here embeds;
  • a message can put its images before its text, the order Google's Gemma examples use and the one the word-reading spike measured;
  • the admin socket's capability frames are read (admin.go), to tell whether a warm model sees images before anything is sent;
  • the timeout's variable is PDFSPEC_INFERD_TIMEOUT, and its default suits a vision call.

Readiness is passive: each Post dials afresh, and a connect failure is inferd's "not ready", returned as ErrBackendNotReady so the caller goes on without the model. The daemon streams its response; Post drains it to the terminal frame and returns the text.

Index

Constants

View Source
const DefaultTimeout = 60 * time.Second

DefaultTimeout bounds a single Post round-trip.

The model is optional, so a daemon that accepts the connection and never answers — mid model load, or wedged — must cost a bounded wait, not the run. The bound lives here so that no caller can forget it. One call reads one crop or one image: the spike's slowest strip took 33 s at the default image budget, and a word crop takes under a second.

View Source
const MaxFrameBytes = 64 << 20

MaxFrameBytes is the 64 MiB per-frame payload cap (inferd THREAT_MODEL F-5). Enforced on the decoded length prefix before any payload is allocated.

View Source
const TimeoutEnv = "PDFSPEC_INFERD_TIMEOUT"

TimeoutEnv is the environment variable that overrides DefaultTimeout. Value is a Go duration ("30s", "2m") or bare seconds ("30"). A value of "0" disables the deadline entirely, for an operator debugging a slow local model.

View Source
const WireVersion uint32 = 1

WireVersion is the wire-format version this client speaks (inferd ADR 0021). Stamped on every request; the daemon rejects a mismatch with a wire_version_unsupported error frame and closes the connection.

Variables

View Source
var ErrBackendNotReady = errors.New("inferd: backend not ready")

ErrBackendNotReady is returned by Post when the inferd generation socket isn't bound (daemon down, restarting, draining, or still loading the model). Callers treat it as "no model": the conversion goes on without it.

Functions

func DefaultAdminAddress

func DefaultAdminAddress() string

DefaultAdminAddress returns inferd's admin socket. Not used by the generation path; admin.go reads it for capabilities. Admin keeps its name across versions (protocol-v2.md §1).

func DefaultGenerationAddress

func DefaultGenerationAddress() string

DefaultGenerationAddress returns the inferd generation endpoint dialled by default (protocol-v2.md §1, inferd ADR 0021). v0.4 unified generation onto a single neutral socket:

Linux/other   $XDG_RUNTIME_DIR/inferd/inferd.sock
              -> $HOME/.inferd/run/inferd.sock
              -> /tmp/inferd/inferd.sock
macOS         $TMPDIR/inferd/inferd.sock
Windows       \\.\pipe\inferd

(The pre-v0.4 paths inferd-infer / infer.sock are removed; a daemon no longer binds them.)

Types

type Attachment

type Attachment struct {
	ID     string
	Width  uint32
	Height uint32
	RGB    []byte // width*height*3, no alpha
}

Attachment is one binary payload referenced by a Message image block. Per inferd ADR 0016 the consumer decodes media to raw bytes before sending; the daemon links no image codec. RGB is width*height*3 interleaved octets (no alpha). The bytes do NOT travel in the request JSON — they ride in a 0x02 BLOB frame keyed by ID (protocol-v2.md §3.5/§3.7).

type Capability

type Capability struct {
	Backend string `json:"backend"`
	V2      bool   `json:"v2"`
	Vision  bool   `json:"vision"`
	Embed   bool   `json:"embed"`
}

Capability is one backend's advertisement on the admin socket: the "capabilities" frame (protocol-v2.md §1). An absent key means not supported, never unknown.

type Client

type Client struct {
	// Address is the inferd generation endpoint. Empty -> platform default.
	Address string

	// Timeout bounds one Post round-trip. Zero resolves to
	// $PDFSPEC_INFERD_TIMEOUT, else DefaultTimeout. Negative disables the
	// deadline (unbounded — only for operators debugging a slow model).
	Timeout time.Duration
	// contains filtered or unexported fields
}

Client dials the inferd generation socket once per Post. Address is a Unix socket path (Unix) or a named-pipe path (Windows); empty resolves to the platform default via DefaultGenerationAddress. inferd binds no inbound network listener as of v0.5 (inferd ADR 0022) — there is no TCP transport.

func (*Client) Post

func (c *Client) Post(ctx context.Context, req Request) (res Result, err error)

Post submits one generation request to inferd over the v0.4 length-prefixed wire, streams the response to its terminal frame, and returns the collapsed result (concatenated text deltas + any structured tool_use blocks).

On a connect failure that looks like "daemon not ready" the error wraps ErrBackendNotReady, so the caller goes on without the model.

type Message

type Message struct {
	Role        Role
	Content     string
	ImageRefs   []string // attachment IDs (see Request.Attachments)
	ImagesFirst bool
}

Message is one turn in the v2 conversation. Content is the text of the turn; ImageRefs, when non-empty, adds image content blocks referencing attachment IDs present in Request.Attachments (the bytes ride in BLOB frames, not here — protocol-v2.md §3.4/§3.5). A turn may carry text, images, or both: text first, then images, unless ImagesFirst. The daemon's Gemma 4 template renders blocks in the order sent.

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

MarshalJSON renders a Message as a protocol-v2 MessageV2 whose content is a text block (when Content != "") followed by one image block per ImageRef (protocol-v2.md §3.3/§3.4). At least one block is always emitted (content MUST be non-empty per spec); a Message with neither text nor images marshals as a single empty text block.

type Request

type Request struct {
	WireVersion    uint32          `json:"wire_version"`
	ID             string          `json:"id,omitempty"`
	Messages       []Message       `json:"messages"`
	Attachments    []Attachment    `json:"attachments,omitempty"`
	Tools          []Tool          `json:"tools,omitempty"`
	ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
	Temperature    *float64        `json:"temperature,omitempty"`
	TopP           *float64        `json:"top_p,omitempty"`
	TopK           *int            `json:"top_k,omitempty"`
	MaxTokens      *int            `json:"max_tokens,omitempty"`
	Stream         *bool           `json:"stream,omitempty"`
}

Request is a generation request (protocol-v2.md §3.2). WireVersion is set by Post; callers leave it zero. Pointer sampling fields distinguish "omitted" (daemon default) from "explicit zero".

Attachments carries image (etc.) payloads referenced by Message image blocks. Its RGB bytes are NOT serialised into the request JSON (a custom MarshalJSON emits metadata only); client.Post writes each attachment's bytes as a separate BLOB frame after the request frame.

func (Request) MarshalJSON

func (r Request) MarshalJSON() ([]byte, error)

MarshalJSON renders the request frame body. Attachments are emitted as metadata-only objects (kind/id/width/height) — the RGB bytes ride in BLOB frames (protocol-v2.md §3.5). A dedicated wire struct keeps the byte-carrying Attachment type out of the JSON.

type ResponseFormat

type ResponseFormat struct {
	Type   string          `json:"type"`
	Schema json.RawMessage `json:"schema"`
}

ResponseFormat constrains generation to a structured output (protocol-v2.md §3.2a). The daemon translates Schema to an engine constraint (GBNF for llamacpp); backends without structured-output support ignore it and return unconstrained output — no error. Type is currently always "json_schema".

func JSONSchemaFormat

func JSONSchemaFormat(schema json.RawMessage) *ResponseFormat

JSONSchemaFormat builds a ResponseFormat for a JSON Schema object.

type Result

type Result struct {
	Text      string
	ToolCalls []ToolCall
	// StopReason is the done frame's: "end_turn", or "max_tokens" for a generation the
	// token bound cut off, which is how a repetition loop ends.
	StopReason string
}

Result is the outcome of a Post. Text is the concatenated text deltas (thought-stripping is the caller's job). ToolCalls holds any structured tool_use blocks the model emitted, in arrival order.

type Role

type Role string

Role is a conversation role in a Message. Lowercase on the wire.

const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
)

type Status

type Status struct {
	Capabilities []Capability
	// State is the snapshot frame's status: "ready" when generation is served, "loading" or
	// another phase while it is not.
	State string
}

Status is what the admin socket says on connect: a capability frame per backend, then the daemon's state.

func ReadStatus

func ReadStatus(ctx context.Context, addr string) (Status, error)

ReadStatus dials the admin socket at addr, empty for the platform default, and reads the frames the daemon writes on connect. A daemon that is not running returns ErrBackendNotReady. The socket is read-only, so nothing is sent.

func (Status) Ready

func (s Status) Ready() bool

Ready reports whether the daemon is ready.

func (Status) Vision

func (s Status) Vision() (Capability, bool)

Vision returns the generation backend that takes images, and whether there is one.

type Tool

type Tool struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"input_schema"`
}

Tool is a tool definition the model may call (protocol-v2.md §3.6). InputSchema is a JSON Schema object. v2 has no GBNF grammar; the daemon does not enforce InputSchema against emitted arguments — that is the consumer's job when the tool_use result returns.

type ToolCall

type ToolCall struct {
	ID    string
	Name  string
	Input json.RawMessage
}

ToolCall is a structured tool invocation surfaced from a tool_use response block. Used by the router in place of the removed GBNF grammar + text parsing.

Jump to

Keyboard shortcuts

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