cactus

package module
v0.0.0-...-0930456 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 32 Imported by: 1 module, 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.

README

cactus-go

cactus-go is a community-maintained Go library for running Cactus on-device models: Needle tool calling, Whistle speech and Mirage vision.

It provides:

  • CGO-free native engine loading
  • Needle 2 and Needle 3, with Needle 3 as the default
  • automatic, checksum-verified engine and base-weight downloads
  • high-level and manual completion loops
  • typed Go tool handlers
  • structured response extraction
  • Needle 3 text embeddings
  • opt-in Whistle speech transcription, live streaming and audio tool calling
  • opt-in Mirage image description, text recognition and form extraction

This project is in early development and its API may change.

Install

Requires Go 1.25 or newer.

go get github.com/zbiljic/cactus-go

Engine builds are available for macOS, Linux (glibc and musl), and Windows on amd64 and arm64.

Quick Start

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/zbiljic/cactus-go"
)

type weatherArguments struct {
	City string `json:"city" jsonschema:"description=City whose weather should be returned."`
}

func main() {
	ctx := context.Background()
	weather := cactus.NewTool(
		"get_weather",
		"Get the current weather for a city.",
		func(_ context.Context, arguments weatherArguments) (string, error) {
			return "Clear in " + arguments.City, nil
		},
	)

	agent, err := cactus.New(ctx, cactus.Config{Tools: []cactus.Tool{weather}})
	if err != nil {
		log.Fatal(err)
	}
	response, err := agent.Run(
		ctx,
		"What is the weather in Lagos?",
		cactus.DefaultMaxSteps,
		cactus.DefaultMaxNewTokens,
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(response.Results)
}

By default, cactus.New downloads and caches the pinned Cactus engine (4.1.4) and the needle3.cact base weights (~35 MB) from the Needle 3 model repository. Subsequent runs use the cached files. No Python installation is required.

Tool triggers

Opt into regex routing by assigning triggers after NewTool, using the weather tool above:

weather.Schema.Triggers = []string{`\bweather\b`, `\bforecast\b`}

The native engine interprets the patterns and matches them case-insensitively. Matching triggers can bypass the engine's confidence floor; application confidence policies and response validation still apply.

Independent requests

Agents retain conversation context by default. Set Stateless: true for independent requests:

agent, err := cactus.New(ctx, cactus.Config{Tools: tools, Stateless: true})

Each Complete or Run starts with a fresh conversation; Run retains context between its tool rounds. Keep the default stateful mode for manual tool loops that feed results back through Complete, and call Reset between independent queries.

System facts

Config.System carries environment state as facts, not instructions, such as date, locale, device, battery, network, location, user and assistant. The engine resolves relative dates such as "tomorrow" or "March 4th" only against a date: fact; without one, such requests return no call. DateFact writes it in the expected form:

agent, err := cactus.New(ctx, cactus.Config{
	Tools:  tools,
	System: cactus.DateFact(time.Now()) + "; locale: en-US",
})

Facts are fixed when the agent is created.

Validation

Run rejects a turn the engine flags as negated or ungrounded before executing any of its calls. The engine can flag a number the user did write, such as 25.5 for "$25.50", so a flagged number is accepted when it appears in the query or the system facts, other than in the date fact. For manual loops, pass the input text to ValidateResponse as a source:

if err := cactus.ValidateResponse(response, query); err != nil {
	log.Fatal(err)
}

Complete also flags a date or date-time argument whose year is not written in the conversation, such as 2026 when the user wrote "5th September 2031". Without any written year nothing is checked. The date: fact's year counts only when the input names a relative day: today, tonight, tomorrow, yesterday, next, this, coming, now, a weekday, or "in 3 days" and the like. A date without a year, such as "March 4th", is not one, so once the conversation has a year it is flagged unless its year was written. Run checks the dates of its first turn; a manual loop through Complete checks every turn, reading a tool result as the input. Reset, stateless requests and switching agents forget the years.

Repeated calls

The model emits the calls of a multi-step request together, and can call a tool again after seeing its result, often with altered arguments such as a different year. It does so less when a handler's result states the outcome, such as {"status": "created", "title": "Dentist"}, than when it is nil, "ok" or empty.

Run executes each tool in one turn at most, counting failed calls: it stops before a turn that calls a tool an earlier turn executed and returns that response, after validation, without an error. Its calls repeat completed work, so do not execute them. A manual loop with Complete needs its own guard.

Closing

Close releases an agent's response buffer and native binding; later calls return ErrClosed. The engine and loaded weights stay in the process for other agents. Whistle and Mirage have the same Close.

Threads

The Cactus engine picks a CPU thread count automatically. SetThreads sets a process-wide count for the Needle 3, Whistle and Mirage weights loaded after the call; zero restores the automatic count. The engine reads it when it loads weights, and loaded weights keep the count they were loaded with, so call it before the first New, NewWhistle or NewMirage:

if err := cactus.SetThreads(2); err != nil {
	log.Fatal(err)
}

The Needle 2 engine ignores it. cactusz takes the same setting as --threads.

Text embeddings

Needle 3 agents expose text features as []float32:

vector, err := agent.Embed(ctx, "turn on the kitchen lights")

Embed does not reset the conversation, including in stateless mode. Switching agents still follows the conversation rules below. Needle 2 agents return ErrEmbeddingUnsupported.

The base model uses confidence-head probe features rather than a trained contrastive retrieval head. Evaluate similarity on your own data; this API does not enable automatic tool retrieval. See the cosine-ranking example and upstream embedding notes.

To check finite, repeatable vectors and a tool-result continuation with an embedding between turns against the real engine:

CACTUS_TEST_NATIVE=1 go test -run '^TestNativeEmbeddings$' -v .

Speech

NewWhistle adds optional speech transcription, live streaming transcription, audio tool calling and speech encoder features on the Cactus engine. It accepts 16 kHz mono []float32 PCM of any length. Speech weights are downloaded only when requested.

See the speech guide for the API, supported languages and offline setup, or try the PCM example.

Vision

NewMirage adds optional image understanding on the Cactus engine:

  • Describe returns the scene, the objects with boxes, masks and attributes, the recognized text lines and the relations between objects.
  • Extract fills an ordered form of choice, count and text fields.

It accepts any image.Image, or packed RGB through *RGBImage. Vision weights are downloaded only when requested, and loading them keeps the loaded text and speech models.

vision, err := cactus.NewMirage(ctx, cactus.MirageConfig{})
if err != nil {
	log.Fatal(err)
}
description, err := vision.Describe(ctx, img, cactus.DescribeOptions{})

DecodeImage reads PNG, JPEG and GIF with the standard library and rotates JPEG and PNG photos upright by their EXIF orientation, as upstream does. See the vision guide for options, forms, coordinates and offline setup, or try the image example.

Model generations

Use Generation: 2 for the embedded Needle 2 model (engine 2.0.4):

agent, err := cactus.New(ctx, cactus.Config{
	Generation: 2,
	Tools:      tools,
})

Generation: 0 and Generation: 3 select Needle 3, which runs on the Cactus engine. A custom WeightsPath selects the compatible engine from the .cact header, taking precedence over Generation. Custom Needle 3 archives retain the engine's confidence scores when their metadata carries a recognized confidence head, including platform fine-tunes and the published base archive supplied through WeightsPath. Custom Needle 2 weights and recognized text archives without a valid confidence head report Confidence == nil. Unrecognized model-kind metadata is rejected before loading. Automatically loaded base weights retain the engine's confidence scores.

Both generations can run in the same process, with separate native runtimes. Within one generation, switching agents reinitializes the active conversation. After loading custom Needle 2 weights, returning to its embedded base model requires a separate process. Needle 3 can reload its base archive.

Use LibraryPath for an existing, trusted engine matching the selected generation. When LibraryPath is empty, the environment overrides are CACTUS_LIB_PATH for generation 3, and NEEDLE2_LIB_PATH, then NEEDLE_LIB_PATH, for Needle 2 (LibraryPathEnv lists them). A Needle 3 library override still downloads missing base weights unless WeightsPath is supplied.

Each generation binds one native ABI: needle_* from the Needle 2 engine and cactus_* from the Cactus engine. A library missing any function of that ABI is rejected with ErrUnsupportedABI before inference. Cactus engine failures include the engine's detailed native message.

FetchEngine prepares the library and required base weights for offline use. FetchOptions.Generation selects the generation. By default, engines are cached under ~/.cache/cactus/<engine-version>/<platform>/ and model weights under ~/.cache/cactus/models/<checksum-prefix>/, so an engine upgrade reuses unchanged weights. CacheDir selects one exact directory for both. Needle 2 uses libneedle.* and the Cactus engine uses libcactus.*, so the generations can share a custom cache directory for the same platform. For offline use, fetch for the target platform and generation, preserve the .sha256 marker files, and use the same cache directory at runtime. Markers contain the downloaded artifact hash and installed file hash; cached downloads verify both. CachedEngine checks only for the library and trusts the caller's file.

Errors

Errors wrap sentinels for errors.Is: ErrValidation (also wrapped by Run), ErrUnsupportedGeneration, ErrEmbeddingUnsupported, ErrUnsupportedABI, ErrUnsupportedPlatform, ErrEngineNotFound, ErrStreamActive and ErrClosed. A failed engine call is a *NativeError with the operation, the native code and any engine diagnostic, for errors.As.

Native engine diagnostics

The optional cactusz command can fetch the engine and verify that it loads:

go run github.com/zbiljic/cactus-go/cmd/cactusz@latest fetch
go run github.com/zbiljic/cactus-go/cmd/cactusz@latest doctor --smoke
go run github.com/zbiljic/cactus-go/cmd/cactusz@latest test
go run github.com/zbiljic/cactus-go/cmd/cactusz@latest describe photo.png

To run the checks against Needle 2 from a repository checkout:

go run ./cmd/cactusz fetch --generation 2
go run ./cmd/cactusz doctor --generation 2 --smoke
go run ./cmd/cactusz test --generation 2

cactusz eval scores a tool set against JSONL cases. Six ready suites, smart home, media player, productivity, wearable, kitchen appliance and data capture, are in cmd/cactusz/testdata/environments with their failing cases on the pinned engine. Each still fails a critical case there, so the command exits with status 1:

go run ./cmd/cactusz eval \
  --tools cmd/cactusz/testdata/environments/smart_home/tools.json \
  --system-file cmd/cactusz/testdata/environments/smart_home/system.txt \
  --cases cmd/cactusz/testdata/environments/smart_home/cases.jsonl

Responses preserve suppressed_calls for inspection. Run executes only function_calls; it never executes suppressed calls automatically.

Examples

License

Licensed under the MIT License.

Documentation

Overview

Package cactus provides Go access to the Cactus on-device models: Needle tool calling, Whistle speech and Mirage vision.

Index

Constants

View Source
const (
	// DefaultGeneration is used when no generation or custom weights are selected.
	DefaultGeneration = 3
	// DefaultMaxSteps is the default maximum number of tool-calling rounds.
	DefaultMaxSteps = 8
	// DefaultMaxNewTokens is the default generation limit for each completion.
	DefaultMaxNewTokens = 512
	// DefaultBufferSize is the default native response buffer size.
	DefaultBufferSize = 64 * 1024
)
View Source
const (
	// SpeechSampleRate is the required rate for mono float32 PCM.
	SpeechSampleRate = 16000
	// DefaultSpeechBufferSize accommodates transcripts with word timestamps for
	// clips up to about a minute; longer clips grow the buffer.
	DefaultSpeechBufferSize = 1 << 18
)
View Source
const DefaultVisionBufferSize = 16 << 20

DefaultVisionBufferSize holds descriptions with polygon or bitmap masks for many objects, as upstream does.

View Source
const (
	// EngineVersion is the Cactus engine version, which runs Needle 3 (the
	// default generation), Whistle and Mirage. Needle 2 keeps its own engine; see
	// EngineVersionFor.
	EngineVersion = "4.1.4"
)

Variables

View Source
var (
	// ErrUnsupportedPlatform indicates that no shared-library backend or engine
	// build exists for the target.
	ErrUnsupportedPlatform = errors.New("cactus: unsupported platform")
	// ErrEngineNotFound indicates that a cached engine library is unavailable.
	ErrEngineNotFound = errors.New("cactus: engine library not found")
	// ErrUnsupportedGeneration indicates a generation other than 2 or 3, or a
	// feature the selected generation lacks.
	ErrUnsupportedGeneration = errors.New("cactus: unsupported generation")
	// ErrUnsupportedABI indicates a native library that does not export the
	// complete ABI of the selected generation.
	ErrUnsupportedABI = errors.New("cactus: unsupported native ABI")
	// ErrEmbeddingUnsupported indicates that the generation has no embeddings.
	ErrEmbeddingUnsupported = errors.New("cactus: embeddings unavailable")
	// ErrValidation is wrapped by ValidateResponse, and by Run, when the engine
	// flags a response.
	ErrValidation = errors.New("cactus: response validation")
	// ErrStreamActive indicates that a live transcription is open on the
	// engine, so other speech calls must wait for its Stop.
	ErrStreamActive = errors.New("cactus: a live transcription is in progress")
	// ErrClosed is returned by an Agent or Whistle after Close.
	ErrClosed = errors.New("cactus: closed")
)

Sentinel errors for errors.Is. Returned errors wrap them with detail.

Functions

func CachedEngine

func CachedEngine(options FetchOptions) (string, error)

CachedEngine returns the expected cached library path without downloading anything. It accepts libraries installed by cactus-go or another client.

func DateFact

func DateFact(t time.Time) string

DateFact returns the date system fact for t, such as "date: 2026-07-21 Tue 14:30". The engine resolves relative dates, such as "tomorrow" or "March 4th", only against this fact; without it such requests return no call. Facts are fixed when the agent is created.

func DecodeImage

func DecodeImage(r io.Reader) (image.Image, error)

DecodeImage decodes a PNG, JPEG, GIF (first frame) or any other format registered with the image package. A JPEG or PNG with an EXIF orientation other than 1 is rotated or flipped upright, as upstream does, and returned as an *RGBImage without alpha. It reads r to EOF.

func EngineVersionFor

func EngineVersionFor(generation int) (string, error)

EngineVersionFor returns the pinned engine version for a generation (zero means 3).

func Extract

func Extract[T any](response Response) (T, error)

Extract decodes a structured response containing exactly one function call into a value of type T. It does not validate engine warnings; callers that act on the value should call ValidateResponse with the input text first.

func FetchEngine

func FetchEngine(ctx context.Context, options FetchOptions) (string, error)

FetchEngine downloads, verifies, and caches the shared library and required base weights for one desktop platform. It returns the library path.

func FetchMirage

func FetchMirage(ctx context.Context, options FetchOptions) (string, error)

FetchMirage caches the Cactus engine and Mirage vision weights for offline use. It returns the library path and does not download text or speech weights. Generation must be zero or 3; Platform and CacheDir follow FetchEngine.

func FetchWhistle

func FetchWhistle(ctx context.Context, options FetchOptions) (string, error)

FetchWhistle caches the Cactus engine and Whistle speech weights for offline use. It returns the library path and does not download text weights. Generation must be zero or 3; Platform and CacheDir follow FetchEngine.

func LibraryPathEnv

func LibraryPathEnv(generation int) ([]string, error)

LibraryPathEnv returns the environment variables that override engine discovery for a generation (zero means 3), in lookup order. The first non-empty variable selects the library.

func SetThreads

func SetThreads(threads int) error

SetThreads sets the number of CPU threads the Cactus engine uses for Needle 3, Whistle and Mirage weights loaded after the call, or zero for the engine's automatic count. The engine reads the count when it loads weights, and loaded weights keep the count they were loaded with, so call SetThreads before the first New, NewWhistle or NewMirage. The setting is process-wide and holds for an engine loaded later. The Needle 2 engine ignores it.

func ValidateResponse

func ValidateResponse(response Response, sources ...string) error

ValidateResponse checks only the response's validation warnings, the engine's and the dates Complete flags, accepting absent metadata. It rejects negation and ungrounded field paths.

Sources are the texts the request was built from, usually the user's input and the system facts. The engine can flag a number the user did write, such as 25.5 for "$25.50", so an ungrounded number is accepted when every call of that tool carries, at that path, a value written in a source. Thousands separators are ignored, so "1,234" grounds 1234 but not 1.234. Date facts in a source ground nothing. Without sources every warning is rejected. Unflagged output still needs application validation.

func WeightsGeneration

func WeightsGeneration(path string) (int, error)

WeightsGeneration reads a .cact header and returns its model generation. It does not validate the rest of the archive.

Types

type Agent

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

Agent is a Needle conversation bound to a process-global native runtime. Create one with New. Methods are safe for concurrent use; native calls for one generation are serialized.

func New

func New(ctx context.Context, config Config) (*Agent, error)

New initializes an Agent, downloading the selected engine and any required base weights when they are not cached. Generation 3 is the default.

func (*Agent) Close

func (a *Agent) Close() error

Close releases the agent's native binding and response buffer. Later calls return ErrClosed. Close is idempotent and does not unload the engine or its weights, which remain available to other agents in the process.

func (*Agent) Complete

func (a *Agent) Complete(ctx context.Context, text string, maxNewTokens int) (Response, error)

Complete performs raw inference without applying response validation. It adds to Validation.Ungrounded each date or date-time argument whose year is not written in the conversation, nor, when text names a relative day such as "tomorrow" or a weekday, in the system facts. Without any written year it adds nothing.

func (*Agent) Embed

func (a *Agent) Embed(ctx context.Context, text string) ([]float32, error)

Embed returns text features from Needle 3 without resetting the conversation. Needle 2 agents return ErrEmbeddingUnsupported.

func (*Agent) Reset

func (a *Agent) Reset(ctx context.Context) error

Reset rewinds the conversation.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, query string, maxSteps, maxNewTokens int) (Response, error)

Run completes a query, rejects engine validation warnings, and executes accepted tool calls until the model returns a final response. It uses ValidateResponse, with the query and system facts as sources, to reject an entire flagged turn before executing any tool calls, without retrying, and returns the raw flagged response together with results from earlier completed rounds.

The model emits the calls of a multi-step request together, and can call a tool again after seeing its result, often with altered arguments. It does so less when the result states the outcome, such as {"status":"created"}, than when it is nil, "ok" or empty. Run executes each tool in one turn at most, counting failed calls: it stops before a turn that calls a tool an earlier turn executed and returns that response, after validation, without an error. Its calls repeat completed work; do not execute them. A manual loop with Complete needs its own guard.

type AudioOptions

type AudioOptions struct {
	// Language is empty for detection or one of Whistle.Languages: en, de,
	// fr, es, it, nl or pl for the published model.
	Language       string
	Keywords       []string
	WordTimestamps bool
}

AudioOptions controls language detection, keyword biasing and word timestamps.

type Config

type Config struct {
	Tools  []Tool
	System string
	// Stateless resets the conversation before each Complete or Run request.
	// Run preserves context between tool rounds. The default is stateful; use
	// stateful mode for manual tool loops that continue through Complete.
	Stateless bool
	// Generation selects 2 or 3. Zero defaults to 3; WeightsPath takes precedence.
	Generation int
	// WeightsPath selects custom .cact weights and determines the generation.
	// Custom Needle 3 weights retain confidence when their archive carries a
	// recognized confidence head; other custom weights report nil. The header
	// and model-kind metadata are checked before loading. Remaining model bytes
	// and engine revision compatibility are validated by the native loader.
	WeightsPath   string
	ToolIndexPath string
	BufferSize    int

	// LibraryPath selects a trusted shared library for the selected generation.
	// When empty, New checks the variables named by LibraryPathEnv
	// (CACTUS_LIB_PATH for generation 3; NEEDLE2_LIB_PATH, then
	// NEEDLE_LIB_PATH for generation 2), then fetches the engine.
	LibraryPath string
	// CacheDir overrides the engine and base-weight download directory.
	CacheDir string
}

Config configures an Agent.

type DescribeOptions

type DescribeOptions struct {
	// Sections limits the response to these sections; nil returns all.
	Sections []VisionSection
	// Fields selects per-item details; nil returns all, and an empty
	// non-nil slice returns only IDs, names and text strings.
	Fields []VisionField
	// Confidence is the object score threshold in (0, 1] ("conf").
	Confidence float64
	// TextConfidence is the text line score threshold in (0, 1] ("text_conf").
	TextConfidence float64
	MaxObjects     int
	MaxTextLines   int
	// MaxTokens bounds the generated description.
	MaxTokens  int
	MaskFormat MaskFormat
	// NMS turns the engine's non-maximum suppression of overlapping
	// detections on or off; nil keeps the engine default.
	NMS *bool
	// Language selects the language of names and descriptions: empty for
	// English, or de, fr, es, it, nl or pl. The engine rejects languages it
	// does not support.
	Language string
	// Keywords are words and phrases to favor.
	Keywords []string
	// Extra holds other cactus_describe options, such as keyword_bias,
	// mask_threshold or mask_tolerance. It cannot repeat an option that has
	// a field above, form, language or keywords.
	Extra map[string]any
}

DescribeOptions controls a Mirage request. Zero values select the engine defaults. The engine validates names and ranges and reports invalid options as a *NativeError.

type Description

type Description struct {
	Scene     map[string]string `json:"scene,omitempty"`
	Objects   []VisionObject    `json:"objects,omitempty"`
	Regions   []json.RawMessage `json:"regions,omitempty"`
	Text      []TextLine        `json:"text,omitempty"`
	Relations []Relation        `json:"relations,omitempty"`
	Events    []json.RawMessage `json:"events,omitempty"`
	Reasoning string            `json:"reasoning,omitempty"`
	// Raw is the engine's JSON, including any part this type does not model.
	Raw json.RawMessage `json:"-"`
}

Description is a Mirage response. Sections not requested are empty.

type FetchOptions

type FetchOptions struct {
	// Generation selects 2 or 3; zero defaults to 3.
	Generation int
	Platform   Platform
	CacheDir   string
	Client     *http.Client
}

FetchOptions configures an engine download. An empty Platform selects the current process platform. CacheDir is the exact destination directory.

type Form

type Form []FormField

Form is an ordered list of fields; the engine fills them in order.

func (Form) MarshalJSON

func (f Form) MarshalJSON() ([]byte, error)

MarshalJSON writes the form as a JSON object in field order.

func (*Form) UnmarshalJSON

func (f *Form) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a JSON object of field schemas, keeping field order.

type FormField

type FormField struct {
	Name   string
	Schema map[string]any
}

FormField is one field of an Extract form. The engine reads Schema, which ChoiceField, CountField and TextField build for the common kinds.

func ChoiceField

func ChoiceField(name string, choices ...string) FormField

ChoiceField is a field whose value is one of choices, as {"enum": choices}.

func CountField

func CountField(name string, minimum, maximum int) FormField

CountField is a bounded integer field, as {"type": "integer", "minimum", "maximum"}.

func TextField

func TextField(name string, maxLength int) FormField

TextField is a free text field of at most maxLength characters, as {"type": "string", "maxLength": maxLength}.

type FormValue

type FormValue struct {
	// Value is a string for choice and text fields and a float64 for count
	// fields. It is nil when the model chose no value.
	Value any `json:"value"`
	// Probability is the confidence of a text value.
	Probability float64 `json:"probability,omitempty"`
	// Probabilities maps each choice or count to its probability; "-" is the
	// probability of no value.
	Probabilities map[string]float64 `json:"probabilities,omitempty"`
}

FormValue is a filled form field.

type FunctionCall

type FunctionCall struct {
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
}

FunctionCall is a tool invocation selected by the model.

type Mask

type Mask struct {
	Polygons [][]float64
	// Size is [height, width] in pixels.
	Size []int
	// Counts is an uncompressed COCO run-length encoding: alternating runs
	// of background and mask pixels in column-major order, starting with
	// background.
	Counts []int
}

Mask is an object mask. Polygon formats fill Polygons, each a flattened x0, y0, x1, y1, ... outline in the 0 to 1000 space. MaskBitmap fills Size and Counts instead.

func (Mask) Bitmap

func (m Mask) Bitmap() *image.Alpha

Bitmap decodes a MaskBitmap mask, with 0xff for mask pixels. It returns nil for polygon masks or an inconsistent encoding.

func (Mask) MarshalJSON

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

MarshalJSON writes a bitmap as {"size", "counts"} and polygons as a list of flattened polygons.

func (*Mask) UnmarshalJSON

func (m *Mask) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts a flat polygon, a list of polygons or a run-length encoded bitmap.

type MaskFormat

type MaskFormat string

MaskFormat selects how object masks are encoded.

const (
	// MaskLargest outlines the largest part of the mask as one polygon.
	MaskLargest MaskFormat = "largest"
	// MaskMerged outlines the whole mask as one polygon.
	MaskMerged MaskFormat = "merged"
	// MaskPolygons returns one polygon per part of the mask.
	MaskPolygons MaskFormat = "polygons"
	// MaskBitmap returns a run-length encoded pixel mask.
	MaskBitmap MaskFormat = "bitmap"
)

type Mirage

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

Mirage describes images and fills forms from them. Vision, Needle 3 text and Whistle speech models share a serialized process-global engine.

func NewMirage

func NewMirage(ctx context.Context, config MirageConfig) (*Mirage, error)

NewMirage loads vision weights without downloading or initializing text or speech weights.

func (*Mirage) Close

func (m *Mirage) Close() error

Close releases the response buffer. Later calls return ErrClosed. Loaded vision weights stay in the engine for other Mirage values.

func (*Mirage) Describe

func (m *Mirage) Describe(ctx context.Context, img image.Image, options DescribeOptions) (Description, error)

Describe describes the scene, objects, text and relations in an image. Images other than *RGBImage are converted to packed RGB first, ignoring alpha. Calls are serialized with all text and speech native work. If the engine JSON does not fit Description, the error comes with a Description holding only Raw.

func (*Mirage) Extract

func (m *Mirage) Extract(ctx context.Context, img image.Image, form Form, options DescribeOptions) (map[string]FormValue, error)

Extract fills form from an image and returns the values by field name. Fields are filled in order, so a field can depend on earlier ones. Sections and Fields are passed to the engine but have no effect on forms.

type MirageConfig

type MirageConfig struct {
	WeightsPath string
	LibraryPath string
	CacheDir    string
	BufferSize  int
}

MirageConfig selects vision weights and the Cactus engine that runs them. LibraryPath and CacheDir follow Config. Empty WeightsPath fetches Mirage. Zero BufferSize selects DefaultVisionBufferSize.

type NativeError

type NativeError struct {
	Operation string
	Code      int32
	Detail    string
}

NativeError reports a failed engine call. Detail carries the engine's diagnostic when one is available.

func (*NativeError) Error

func (e *NativeError) Error() string

type Platform

type Platform string

Platform identifies a downloadable desktop engine build.

const (
	PlatformDarwinAMD64    Platform = "darwin-amd64"
	PlatformDarwinARM64    Platform = "darwin-arm64"
	PlatformLinuxAMD64     Platform = "linux-amd64"
	PlatformLinuxARM64     Platform = "linux-arm64"
	PlatformLinuxAMD64Musl Platform = "linux-amd64-musl"
	PlatformLinuxARM64Musl Platform = "linux-arm64-musl"
	PlatformWindowsAMD64   Platform = "windows-amd64"
	PlatformWindowsARM64   Platform = "windows-arm64"
)

func CurrentPlatform

func CurrentPlatform() (Platform, error)

CurrentPlatform returns the engine build matching the running process.

func SupportedPlatforms

func SupportedPlatforms() []Platform

SupportedPlatforms returns the desktop engine builds known to this version.

type RGBImage

type RGBImage struct {
	Pix    []byte
	Width  int
	Height int
}

RGBImage is packed 8-bit RGB: Width*Height pixels in row-major order, three bytes per pixel, without row padding. Mirage passes Pix to the engine without converting it.

func (*RGBImage) At

func (p *RGBImage) At(x, y int) color.Color

At returns the opaque pixel at (x, y), or transparent black outside the image or the pixel data.

func (*RGBImage) Bounds

func (p *RGBImage) Bounds() image.Rectangle

Bounds returns the rectangle from (0, 0) to (Width, Height).

func (*RGBImage) ColorModel

func (p *RGBImage) ColorModel() color.Model

ColorModel returns color.RGBAModel.

type Relation

type Relation struct {
	Subject   int    `json:"subject"`
	Predicate string `json:"predicate"`
	Object    int    `json:"object"`
}

Relation links two entities by object ID, as in {1, "next_to", 2}.

type Response

type Response struct {
	Type          ResponseType   `json:"type"`
	Success       bool           `json:"success"`
	Error         *string        `json:"error"`
	ErrorCode     *string        `json:"error_code"`
	FunctionCalls []FunctionCall `json:"function_calls"`
	// SuppressedCalls are withheld by the engine and must not be executed automatically.
	SuppressedCalls []FunctionCall  `json:"suppressed_calls,omitempty"`
	Reasoning       string          `json:"reasoning"`
	Confidence      *float64        `json:"confidence"`
	PrefillTPS      float64         `json:"prefill_tps"`
	DecodeTPS       float64         `json:"decode_tps"`
	PeakRAMMB       float64         `json:"peak_ram_mb"`
	Results         []any           `json:"results,omitempty"`
	Validation      *Validation     `json:"validation,omitempty"`
	AudioText       *string         `json:"audio_text,omitempty"`
	AudioLanguage   *string         `json:"audio_language,omitempty"`
	AudioWords      []WordTimestamp `json:"audio_words,omitempty"`
	AudioTTFTMS     *float64        `json:"audio_ttft_ms,omitempty"`
	AudioDecodeTPS  *float64        `json:"audio_decode_tps,omitempty"`
}

Response is the structured response envelope returned by Needle.

type ResponseType

type ResponseType string

ResponseType identifies the action returned by Needle.

const (
	ResponseCall    ResponseType = "call"
	ResponseRespond ResponseType = "respond"
	ResponseRefuse  ResponseType = "refuse"
	ResponseText    ResponseType = "text"
)

type Stream

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

Stream is a live transcription started by Whistle.Stream. Feed about one second of PCM per Process call and finish with Stop, which commits the tail. The engine holds one stream per process: while a stream is open, speech calls other than its own Process and Stop return ErrStreamActive. A failed Process ends the stream. Closing the Whistle also ends it.

func (*Stream) Process

func (s *Stream) Process(ctx context.Context, pcm []float32) (StreamTranscript, error)

Process appends PCM to the stream and returns the words it committed.

func (*Stream) Stop

func (s *Stream) Stop(ctx context.Context) (StreamTranscript, error)

Stop ends the stream and returns the words committed from its tail. A stopped stream cannot be resumed; start another with Whistle.Stream.

type StreamTranscript

type StreamTranscript struct {
	Text     string          `json:"text"`
	Words    []WordTimestamp `json:"words"`
	Pending  string          `json:"pending"`
	Language string          `json:"language"`
	Received float64         `json:"received"`
	PassMS   float64         `json:"pass_ms"`
}

StreamTranscript is one step of live transcription. Text and Words are the words the step committed, with times in seconds from the start of the stream, and Pending is the unconfirmed tail. Received counts the seconds of audio so far and PassMS the time the step took. Join the texts of consecutive steps with a space.

type TextLine

type TextLine struct {
	Text  string    `json:"string"`
	BBox  []float64 `json:"bbox,omitempty"`
	Score float64   `json:"score,omitempty"`
	Point []float64 `json:"point,omitempty"`
}

TextLine is a line of recognized text, with details as in VisionObject. The text reader reads Latin script only.

type Tool

type Tool struct {
	Schema  ToolSchema
	Handler ToolHandler
}

Tool pairs a JSON schema with an optional Go implementation. A tool without a handler can be used with Complete, while Run reports it as unknown if the model selects it.

func NewTool

func NewTool[Arguments, Result any](
	name string,
	description string,
	handler func(context.Context, Arguments) (Result, error),
) Tool

NewTool builds a Tool whose parameter schema is derived from Arguments. Model-produced JSON arguments are decoded before the typed handler is called.

A nil handler produces a schema-only tool suitable for use with Complete.

type ToolHandler

type ToolHandler func(context.Context, json.RawMessage) (any, error)

ToolHandler executes a model-selected function call.

type ToolSchema

type ToolSchema struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	// Parameters is the JSON Schema object of the arguments; empty or null
	// means none. The engine receives it as written, key order included, and
	// the model reads that order. Write type, properties and required, in
	// that order; within a property, type, then enum or items, description
	// and constraints. SchemaFor writes this order.
	Parameters json.RawMessage `json:"parameters"`
	// Triggers opt into native regex routing and can bypass the confidence floor.
	Triggers []string `json:"triggers,omitempty"`
}

ToolSchema describes a function that the model may call.

func SchemaFor

func SchemaFor[T any](name, description string) ToolSchema

SchemaFor builds a tool schema whose parameters are derived from T. JSON field names and optionality follow encoding/json tags; JSON Schema annotations can be supplied with jsonschema tags. Properties keep the struct's field order, and every schema lists its keys in the order the model was trained on: type, properties and required, then enum or items, description and the constraints.

type Transcript

type Transcript struct {
	Text      string          `json:"text"`
	Language  string          `json:"language"`
	Words     []WordTimestamp `json:"words,omitempty"`
	TTFTMS    float64         `json:"ttft_ms"`
	DecodeTPS float64         `json:"decode_tps"`
}

Transcript is a Whistle response. Silence has empty Text and Language.

type Validation

type Validation struct {
	Ungrounded []string `json:"ungrounded"`
	Negation   bool     `json:"negation"`
}

Validation contains the engine's warnings and, from Complete, the date arguments whose year is not written in the conversation.

type VisionField

type VisionField string

VisionField names a per-item detail of objects and text lines. IDs, names and text strings are always present.

const (
	FieldBBox        VisionField = "bbox"
	FieldScore       VisionField = "score"
	FieldPoint       VisionField = "point"
	FieldMask        VisionField = "mask"
	FieldPosition    VisionField = "position"
	FieldDescription VisionField = "description"
)

type VisionObject

type VisionObject struct {
	// ID names the entity the object belongs to. Instances of one entity,
	// such as two trees, share an ID.
	ID   int    `json:"id"`
	Name string `json:"name"`
	// BBox is [x0, y0, x1, y1].
	BBox  []float64 `json:"bbox,omitempty"`
	Score float64   `json:"score,omitempty"`
	// Point is an [x, y] point on the object.
	Point []float64 `json:"point,omitempty"`
	Mask  *Mask     `json:"mask,omitempty"`
	// Position is a coarse placement, such as "left" or "top".
	Position string `json:"position,omitempty"`
	// Description holds attributes such as color and shape.
	Description map[string]string `json:"description,omitempty"`
}

VisionObject is a detected object. Coordinates are in a 0 to 1000 space over the image width and height; multiply x by width/1000 and y by height/1000 for pixels. Details not selected by Fields are empty.

type VisionSection

type VisionSection string

VisionSection names a top-level part of a Description.

const (
	SectionScene     VisionSection = "scene"
	SectionObjects   VisionSection = "objects"
	SectionRegions   VisionSection = "regions"
	SectionText      VisionSection = "text"
	SectionRelations VisionSection = "relations"
	SectionEvents    VisionSection = "events"
	SectionReasoning VisionSection = "reasoning"
)

type Whistle

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

Whistle transcribes caller-provided 16 kHz mono float32 PCM in [-1, 1]. Speech and Needle 3 text models share a serialized process-global engine.

func NewWhistle

func NewWhistle(ctx context.Context, config WhistleConfig) (*Whistle, error)

NewWhistle loads speech weights without downloading or initializing text weights.

func (*Whistle) Close

func (w *Whistle) Close() error

Close ends an open stream of this Whistle and releases the response buffer. Later calls return ErrClosed. Loaded speech weights stay in the engine for other Whistle values.

func (*Whistle) Complete

func (w *Whistle) Complete(ctx context.Context, textAgent *Agent, pcm []float32, options AudioOptions, maxNewTokens int) (Response, error)

Complete transcribes PCM and completes a raw Needle 3 turn inside the engine. It returns tool calls without executing handlers or applying ValidateResponse. Date arguments are checked against the years heard, as Agent.Complete checks them against written years. textAgent must be a Needle 3 Agent created by New that shares this engine.

func (*Whistle) Embed

func (w *Whistle) Embed(ctx context.Context, pcm []float32) ([]float32, error)

Embed returns the speech encoder output for up to 30 seconds of PCM as flattened rows, about one per 80 ms of audio; the published model's rows are 512 floats wide. Calls are serialized with all other native work and fail with ErrStreamActive while a live stream is open.

func (*Whistle) Languages

func (w *Whistle) Languages() []string

Languages returns the language codes the speech weights accept for AudioOptions.Language, read from their tokenizer.

func (*Whistle) Stream

func (w *Whistle) Stream(options AudioOptions) (*Stream, error)

Stream prepares a live transcription with the language and keywords of options; WordTimestamps is ignored because every step carries word times. Nothing reaches the engine until the first Process.

func (*Whistle) Transcribe

func (w *Whistle) Transcribe(ctx context.Context, pcm []float32, options AudioOptions) (Transcript, error)

Transcribe accepts PCM of any length: up to 30 seconds runs as one pass, and longer audio runs as consecutive 30 second windows with word times counted from the start of the clip. Empty audio and silence return an empty transcript. Calls are serialized with all text and speech native work.

type WhistleConfig

type WhistleConfig struct {
	WeightsPath string
	LibraryPath string
	CacheDir    string
	BufferSize  int
}

WhistleConfig selects speech weights and the Cactus engine that runs them. LibraryPath and CacheDir follow Config. Empty WeightsPath fetches Whistle.

type WordTimestamp

type WordTimestamp struct {
	Word        string  `json:"word"`
	Start       float64 `json:"start"`
	End         float64 `json:"end"`
	Probability float64 `json:"probability"`
}

WordTimestamp describes a recognized word, with times in seconds.

Directories

Path Synopsis
cmd
cactusz command
examples
describe-image command
Describe a PNG, JPEG or GIF with Mirage, or fill a form from it with -form, a JSON object of field schemas in the order to fill them.
Describe a PNG, JPEG or GIF with Mirage, or fill a form from it with -form, a JSON object of field schemas in the order to fill them.
embeddings command
fetch-engine command
manual-loop command
tool-call command
transcribe command
Transcribe a file of little-endian float32 mono samples recorded at 16000 Hz, in one pass or, with -stream, live in one-second chunks.
Transcribe a file of little-endian float32 mono samples recorded at 16000 Hz, in one pass or, with -stream, live in one-second chunks.

Jump to

Keyboard shortcuts

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