Documentation
¶
Overview ¶
Package cactus provides Go access to the Cactus on-device models: Needle tool calling, Whistle speech and Mirage vision.
Index ¶
- Constants
- Variables
- func CachedEngine(options FetchOptions) (string, error)
- func DateFact(t time.Time) string
- func DecodeImage(r io.Reader) (image.Image, error)
- func EngineVersionFor(generation int) (string, error)
- func Extract[T any](response Response) (T, error)
- func FetchEngine(ctx context.Context, options FetchOptions) (string, error)
- func FetchMirage(ctx context.Context, options FetchOptions) (string, error)
- func FetchWhistle(ctx context.Context, options FetchOptions) (string, error)
- func LibraryPathEnv(generation int) ([]string, error)
- func SetThreads(threads int) error
- func ValidateResponse(response Response, sources ...string) error
- func WeightsGeneration(path string) (int, error)
- type Agent
- func (a *Agent) Close() error
- func (a *Agent) Complete(ctx context.Context, text string, maxNewTokens int) (Response, error)
- func (a *Agent) Embed(ctx context.Context, text string) ([]float32, error)
- func (a *Agent) Reset(ctx context.Context) error
- func (a *Agent) Run(ctx context.Context, query string, maxSteps, maxNewTokens int) (Response, error)
- type AudioOptions
- type Config
- type DescribeOptions
- type Description
- type FetchOptions
- type Form
- type FormField
- type FormValue
- type FunctionCall
- type Mask
- type MaskFormat
- type Mirage
- type MirageConfig
- type NativeError
- type Platform
- type RGBImage
- type Relation
- type Response
- type ResponseType
- type Stream
- type StreamTranscript
- type TextLine
- type Tool
- type ToolHandler
- type ToolSchema
- type Transcript
- type Validation
- type VisionField
- type VisionObject
- type VisionSection
- type Whistle
- func (w *Whistle) Close() error
- func (w *Whistle) Complete(ctx context.Context, textAgent *Agent, pcm []float32, options AudioOptions, ...) (Response, error)
- func (w *Whistle) Embed(ctx context.Context, pcm []float32) ([]float32, error)
- func (w *Whistle) Languages() []string
- func (w *Whistle) Stream(options AudioOptions) (*Stream, error)
- func (w *Whistle) Transcribe(ctx context.Context, pcm []float32, options AudioOptions) (Transcript, error)
- type WhistleConfig
- type WordTimestamp
Constants ¶
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 )
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 )
const DefaultVisionBufferSize = 16 << 20
DefaultVisionBufferSize holds descriptions with polygon or bitmap masks for many objects, as upstream does.
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 ¶
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 ¶
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 ¶
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 ¶
EngineVersionFor returns the pinned engine version for a generation (zero means 3).
func Extract ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Embed returns text features from Needle 3 without resetting the conversation. Needle 2 agents return ErrEmbeddingUnsupported.
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 ¶
MarshalJSON writes the form as a JSON object in field order.
func (*Form) UnmarshalJSON ¶
UnmarshalJSON reads a JSON object of field schemas, keeping field order.
type FormField ¶
FormField is one field of an Extract form. The engine reads Schema, which ChoiceField, CountField and TextField build for the common kinds.
func ChoiceField ¶
ChoiceField is a field whose value is one of choices, as {"enum": choices}.
func CountField ¶
CountField is a bounded integer field, as {"type": "integer", "minimum", "maximum"}.
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 ¶
Bitmap decodes a MaskBitmap mask, with 0xff for mask pixels. It returns nil for polygon masks or an inconsistent encoding.
func (Mask) MarshalJSON ¶
MarshalJSON writes a bitmap as {"size", "counts"} and polygons as a list of flattened polygons.
func (*Mask) UnmarshalJSON ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
At returns the opaque pixel at (x, y), or transparent black outside the image or the pixel data.
func (*RGBImage) ColorModel ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
WhistleConfig selects speech weights and the Cactus engine that runs them. LibraryPath and CacheDir follow Config. Empty WeightsPath fetches Whistle.
Source Files
¶
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
|
|
|
structured-extraction
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. |