Documentation
¶
Overview ¶
Package ds4 provides Go-native conveniences for the ds4 inference engine.
The lower-level github.com/NimbleMarkets/ds4go/ds4api package is the strict purego wrapper around ds4.h. This package owns runtime policy such as default paths, friendly diagnostics, and small convenience entry points.
Index ¶
- Constants
- Variables
- func ApplyMTPDefaults(opts *EngineOptions)
- func DefaultDir() string
- func DefaultLibraryDir() string
- func DefaultLibraryPath() string
- func DefaultMTPPath() string
- func DefaultModelPath() string
- func DefaultModelsDir() string
- func DiscardLogs() error
- func EngineHolders(modelsDir string) (map[int][]string, error)
- func EnrichEngineOpenError(err error) error
- func Load(path string) (*ds4api.Library, error)
- func NewEngine(opts ds4api.EngineOptions) (*ds4api.Engine, error)
- func SetAbortFunc(fn AbortFunc) error
- func SetDefaultLibrary(lib *ds4api.Library)
- func SetStderr(f *os.File) error
- func SetStderrFd(fd int) error
- type AbortFunc
- type ArgmaxGenerateOptions
- type Backend
- type ChatMessage
- type ContextMemory
- type Engine
- type EngineOptions
- type GenerateOptions
- type GenerationDoneFunc
- type Generator
- func (g Generator) Continue(opts GenerateOptions) ([]int, error)
- func (g Generator) Generate(prompt []int, opts GenerateOptions) ([]int, error)
- func (g Generator) GenerateString(prompt string, opts GenerateOptions) (string, error)
- func (g Generator) GenerateTokens(prompt *ds4api.Tokens, opts GenerateOptions) ([]int, error)
- type Library
- type LogType
- type ProcessInfo
- type ProgressFunc
- type Session
- type SessionRewriteResult
- type StderrCapture
- type ThinkMode
- type TokenEmitFunc
- type TokenScore
- type Tokens
- type Tool
- type ToolCall
- type ToolFunc
- type ToolHandler
- type ToolLoop
- type ToolLoopOptions
- type ToolLoopResult
- type ToolRegistry
- func (r *ToolRegistry) BuildPrompt(engine *Engine, system string, history []ChatMessage, think ThinkMode) (*Tokens, error)
- func (r *ToolRegistry) ExecuteToolCalls(ctx context.Context, calls []ToolCall) ([]ChatMessage, error)
- func (r *ToolRegistry) MustRegister(handler ToolHandler)
- func (r *ToolRegistry) ParseAssistant(text string, thinking bool) (ChatMessage, error)
- func (r *ToolRegistry) Register(handler ToolHandler) error
- func (r *ToolRegistry) RegisterFunc(schema ToolSchema, fn ToolFunc) error
- func (r *ToolRegistry) RenderToolsSection() (string, error)
- func (r *ToolRegistry) ReplayStore() *dsml.ReplayStore
- func (r *ToolRegistry) Schemas() []ToolSchema
- func (r *ToolRegistry) SetReplayStore(store *dsml.ReplayStore)
- type ToolSchema
Constants ¶
const ( // DefaultTemperature is ds4's default sampling temperature. DefaultTemperature = ds4api.DefaultTemperature // DefaultTopP is ds4's default nucleus sampling probability. DefaultTopP = ds4api.DefaultTopP // DefaultMinP is ds4's default minimum relative-probability filter. DefaultMinP = ds4api.DefaultMinP // BackendMetal selects the Metal backend. BackendMetal = ds4api.BackendMetal // BackendCUDA selects the CUDA backend. BackendCUDA = ds4api.BackendCUDA // BackendCPU selects the CPU reference backend. BackendCPU = ds4api.BackendCPU // ThinkNone disables thinking markers in chat prompts. ThinkNone = ds4api.ThinkNone // ThinkHigh enables ordinary high-effort thinking. ThinkHigh = ds4api.ThinkHigh // ThinkMax requests maximum-effort thinking. ds4 may downgrade it to // ThinkHigh when the context is below ThinkMaxMinContext. ThinkMax = ds4api.ThinkMax // SessionRewriteError means the rewrite failed. SessionRewriteError = ds4api.SessionRewriteError // SessionRewriteOK means the rewrite completed in place. SessionRewriteOK = ds4api.SessionRewriteOK // SessionRewriteRebuildNeeded means the caller should restore or rebuild // the session state. SessionRewriteRebuildNeeded = ds4api.SessionRewriteRebuildNeeded // LogDefault is the default ds4 log style. LogDefault = ds4api.LogDefault // LogPrefill marks prefill messages. LogPrefill = ds4api.LogPrefill // LogGeneration marks generation messages. LogGeneration = ds4api.LogGeneration // LogKVCache marks KV-cache messages. LogKVCache = ds4api.LogKVCache // LogTool marks tool-calling messages. LogTool = ds4api.LogTool // LogWarning marks warnings. LogWarning = ds4api.LogWarning // LogTiming marks timing messages. LogTiming = ds4api.LogTiming // LogOK marks successful status messages. LogOK = ds4api.LogOK // LogError marks errors. LogError = ds4api.LogError // DefaultMTPDraftTokens is the default number of draft tokens speculative // decoding generates per step when MTP is enabled. A value of 0 disables // speculative decoding; set it explicitly to enable MTP. DefaultMTPDraftTokens = 0 // DefaultMTPMargin is the default minimum margin (in tokens) between the // draft model's accepted sequence and the full target model output. DefaultMTPMargin = 3 )
Variables ¶
var ErrContextFull = errors.New("ds4go: session context full")
ErrContextFull is returned when a session has no room left in its context window. When generation is capped by the remaining room, it is returned alongside the tokens produced before the limit was reached.
var ErrStderrUnsupportedOnWindows = errors.New("ds4: stderr redirection is not supported on Windows")
ErrStderrUnsupportedOnWindows is returned by SetStderr, SetStderrFd, and DiscardLogs on Windows. libds4's ds4_set_stderr_fd is a C-runtime function that calls _dup on a CRT file descriptor, but os.File.Fd returns a Win32 HANDLE; passing it across that boundary fails with EBADF, and there is no portable way to bridge the two from Go. In-process diagnostic redirection is therefore unavailable on Windows.
Functions ¶
func ApplyMTPDefaults ¶ added in v0.2.2
func ApplyMTPDefaults(opts *EngineOptions)
ApplyMTPDefaults populates MTPPath, MTPDraftTokens, and MTPMargin with sensible defaults when an MTP model is installed. It only fills fields that are currently empty or zero, so explicit caller settings are respected.
func DefaultDir ¶
func DefaultDir() string
DefaultDir returns the ds4go data directory.
DS4_DIR overrides the default. When DS4_DIR is unset, DefaultDir returns "$HOME/.ds4" when the user home directory can be determined, otherwise ".ds4".
func DefaultLibraryDir ¶
func DefaultLibraryDir() string
DefaultLibraryDir returns the directory where libds4 is installed by default: the "lib" subdirectory of DefaultDir.
func DefaultLibraryPath ¶
func DefaultLibraryPath() string
DefaultLibraryPath returns the preferred libds4 shared-library path.
Search order is DS4_LIB, DS4_DIR/lib, executable-local paths, and finally the platform library name for system loader lookup.
The current working directory is deliberately NOT searched: loading a shared library from the CWD would let an attacker who can write a file into a directory the user happens to run ds4go from plant a malicious libds4 and gain code execution (binary planting). Use DS4_LIB or DS4_DIR to load a library from a non-default location.
func DefaultMTPPath ¶ added in v0.2.2
func DefaultMTPPath() string
DefaultMTPPath returns the path to the installed MTP companion model, or empty string if it is not present.
func DefaultModelPath ¶
func DefaultModelPath() string
DefaultModelPath returns the path to the default model symlink.
The default model is a symlink at $DS4_DIR/models/<DefaultModelSymlink> that points to the active downloaded model. Use ds4go model set to switch it.
func DefaultModelsDir ¶ added in v0.4.0
func DefaultModelsDir() string
DefaultModelsDir returns the directory where downloaded models are stored: the "models" subdirectory of DefaultDir.
func DiscardLogs ¶ added in v0.3.0
func DiscardLogs() error
DiscardLogs redirects libds4's diagnostic output to the null device for the default library. The native stderr is restored by SetStderr(nil).
Not supported on Windows; see SetStderrFd.
func EngineHolders ¶ added in v0.4.0
EngineHolders returns a map of process PIDs to the list of model files they are currently running. If modelsDir is empty, it uses the default models directory. To ensure security, queries are restricted to paths within authorized directories (DefaultDir or executable directory).
func EnrichEngineOpenError ¶
EnrichEngineOpenError adds process names to ds4 engine-open errors that mention lock-holder PIDs.
func Load ¶
Load loads libds4 using ds4go's runtime path policy.
Passing an empty path searches DS4_LIB, DS4_DIR/lib, executable-local library locations, and finally the platform loader path. The current working directory is not searched; see DefaultLibraryPath.
func NewEngine ¶
func NewEngine(opts ds4api.EngineOptions) (*ds4api.Engine, error)
NewEngine loads the default libds4 shared library and opens a ds4 engine.
func SetAbortFunc ¶ added in v0.3.0
SetAbortFunc installs a last-chance libds4 fatal-invariant callback.
libds4 invokes the callback after logging the fatal message and immediately before native abort(). Passing nil restores the default behavior. This hook is process-global inside libds4 and is intended for crash telemetry, flushing logs, or deliberate process termination; returning from the callback does not recover the engine.
func SetDefaultLibrary ¶
SetDefaultLibrary makes lib the low-level package default library.
func SetStderr ¶ added in v0.5.0
SetStderr redirects libds4's diagnostic output to f for the default library. Passing nil restores the native stderr.
libds4 dups the descriptor internally and writes its diagnostics there unbuffered, so f may be closed once it is no longer the active target. The redirect target is process-global inside libds4; install it once at startup, before generation is active. Calling Fd on f detaches it from the Go runtime poller and puts it in blocking mode, so do not pass a file you also use for asynchronous I/O.
Not supported on Windows; see SetStderrFd.
func SetStderrFd ¶ added in v0.5.0
SetStderrFd reports that libds4 diagnostic redirection is unavailable on Windows. See ErrStderrUnsupportedOnWindows.
Types ¶
type AbortFunc ¶ added in v0.3.0
AbortFunc receives a libds4 fatal-invariant message immediately before abort.
type ArgmaxGenerateOptions ¶ added in v0.3.0
type ArgmaxGenerateOptions = ds4api.ArgmaxGenerateOptions
ArgmaxGenerateOptions controls ds4_engine_generate_argmax.
type Backend ¶
Backend selects the accelerator implementation compiled into libds4.
func DetectDefaultBackend ¶ added in v0.5.0
DetectDefaultBackend probes the environment and installation metadata to determine the preferred backend for the shared library at libPath.
Passing an empty string probes using the default library path.
type ChatMessage ¶ added in v0.3.0
type ChatMessage struct {
// Role is "system", "user", "assistant", or "tool".
Role string
// Content is the plain text content for the message.
Content string
// ReasoningContent is the assistant reasoning block when thinking mode is enabled.
ReasoningContent string
// ToolCalls is the assistant's requested tool calls for this turn.
ToolCalls []ToolCall
// ToolCallID associates a tool result message with the call it answers.
// DSML does not render this ID into <tool_result>; prompt builders expect
// tool result messages to be ordered to match the assistant's ToolCalls.
ToolCallID string
}
ChatMessage is one tool-aware chat turn.
type ContextMemory ¶ added in v0.3.0
type ContextMemory = ds4api.ContextMemory
ContextMemory is ds4_context_memory.
type EngineOptions ¶
type EngineOptions = ds4api.EngineOptions
EngineOptions configures ds4_engine_open.
type GenerateOptions ¶
type GenerateOptions struct {
// MaxTokens is the maximum number of tokens to generate.
MaxTokens int
// Temperature controls sampling. Values <= 0 use argmax.
Temperature float32
// TopK limits sampling to the best k tokens when Temperature > 0.
TopK int
// TopP applies nucleus sampling when Temperature > 0.
TopP float32
// MinP applies minimum probability sampling when Temperature > 0.
MinP float32
// Seed seeds ds4's sampler. A zero seed is valid and deterministic.
Seed uint64
// StopOnEOS stops generation when ds4 emits the engine EOS token.
StopOnEOS bool
// ExcludeToken asks argmax generation to skip a specific token id.
ExcludeToken int
// OnToken streams generated tokens. Returning normally continues generation.
OnToken ds4api.TokenEmitFunc
// Context, when non-nil, can be cancelled to stop generation gracefully
// before the next token is sampled.
Context context.Context
}
GenerateOptions controls Go-native session generation helpers.
type GenerationDoneFunc ¶ added in v0.3.0
type GenerationDoneFunc = ds4api.GenerationDoneFunc
GenerationDoneFunc is called after ds4 completes generation.
type Generator ¶
Generator binds a ds4 engine and session for Go-native generation helpers.
func (Generator) Continue ¶
func (g Generator) Continue(opts GenerateOptions) ([]int, error)
Continue generates tokens from the current session logits.
func (Generator) Generate ¶
func (g Generator) Generate(prompt []int, opts GenerateOptions) ([]int, error)
Generate synchronizes to prompt and generates tokens from the session.
func (Generator) GenerateString ¶
func (g Generator) GenerateString(prompt string, opts GenerateOptions) (string, error)
GenerateString tokenizes prompt, generates, and decodes the generated text.
func (Generator) GenerateTokens ¶
GenerateTokens synchronizes to prompt and generates tokens from the session.
type ProcessInfo ¶ added in v0.4.0
ProcessInfo represents a process holding or using a ds4 resource.
func LibraryHolders ¶ added in v0.4.0
func LibraryHolders(libPath string) ([]ProcessInfo, error)
LibraryHolders returns a list of processes currently holding onto the libds4 shared library. If libPath is empty, it uses the default library path. To ensure security, queries are restricted to paths within authorized directories (DefaultDir, executable directory, or explicit DS4_LIB).
type ProgressFunc ¶ added in v0.3.0
type ProgressFunc = ds4api.ProgressFunc
ProgressFunc receives ds4 progress events.
type SessionRewriteResult ¶ added in v0.3.0
type SessionRewriteResult = ds4api.SessionRewriteResult
SessionRewriteResult is returned by session rewrite helpers.
type StderrCapture ¶ added in v0.5.0
type StderrCapture struct {
// contains filtered or unexported fields
}
StderrCapture pumps libds4's redirected diagnostic stream into an io.Writer until Close restores the native stderr. It is created by CaptureStderr.
func CaptureStderr ¶ added in v0.5.0
func CaptureStderr(dst io.Writer) (*StderrCapture, error)
CaptureStderr redirects libds4's diagnostic output into dst and returns a handle that restores the native stderr when closed.
dst receives the raw bytes libds4 writes — line splitting and any leveling are the caller's concern. This is the io.Writer counterpart to SetStderr, implemented with an os.Pipe and a background pump; use SetStderr directly when the sink is already a file or the null device. The redirect target is process-global inside libds4, so only one capture (or SetStderr target) is active at a time; install it once during startup, before generation.
Not supported on Windows; see SetStderrFd. On failure no redirect is installed and the pipe is released.
func (*StderrCapture) Close ¶ added in v0.5.0
func (c *StderrCapture) Close() error
Close restores the native stderr and waits for the pump to drain. Diagnostics libds4 already wrote are flushed to dst before Close returns. Close is idempotent only in the sense that the underlying files tolerate a double close; call it exactly once per CaptureStderr.
type TokenEmitFunc ¶
type TokenEmitFunc = ds4api.TokenEmitFunc
TokenEmitFunc is called when ds4 emits a generated token.
type TokenScore ¶ added in v0.3.0
type TokenScore = ds4api.TokenScore
TokenScore is ds4_token_score.
type Tokens ¶
Tokens owns a ds4_tokens value allocated by libds4.
func BuildChatPrompt ¶ added in v0.3.0
func BuildChatPrompt(engine *Engine, system string, tools []dsml.Tool, history []ChatMessage, think ThinkMode) (*Tokens, error)
BuildChatPrompt renders a tool-aware chat prompt using ds4's chat helpers.
The tools section is prepended to the system message. If system is empty and tools is non-empty, BuildChatPrompt creates a system turn containing only the rendered tools section. Tool result messages are rendered as user turns containing DSML <tool_result> blocks.
type Tool ¶ added in v0.3.0
type Tool struct {
ToolSchema
Handler ToolFunc
}
Tool binds a schema to a Go function.
func (Tool) Schema ¶ added in v0.3.0
func (t Tool) Schema() ToolSchema
Schema returns the tool schema.
type ToolCall ¶ added in v0.3.0
type ToolCall struct {
// ID is the stable tool-call identifier used for exact replay.
ID string
// Name is the called tool name.
Name string
// Arguments is the JSON argument object string.
Arguments string
}
ToolCall is one tool request emitted by the assistant.
type ToolHandler ¶ added in v0.3.0
type ToolHandler interface {
// Schema returns the public tool schema shown to the model.
Schema() ToolSchema
// Invoke executes the tool with the JSON arguments requested by the model.
Invoke(ctx context.Context, args json.RawMessage) (string, error)
}
ToolHandler exposes a Go tool to the model.
type ToolLoop ¶ added in v0.3.0
type ToolLoop struct {
// Engine owns token decoding and prompt rendering.
Engine *Engine
// Session is the live ds4 session used for generation.
Session *Session
// Tools stores the tool schemas, handlers, and replay state.
Tools *ToolRegistry
// ThinkMode controls ds4's assistant prefix rendering.
ThinkMode ThinkMode
// Thinking tells ParseAssistant whether to require and extract a reasoning block.
Thinking bool
// CompleteFunc overrides the default generator-backed completion path.
// When nil, Run uses Generator.GenerateTokens and Engine.TokenText.
CompleteFunc func(prompt *Tokens, opts GenerateOptions) (string, error)
}
ToolLoop drives multi-turn tool calling on top of Generator and ToolRegistry.
func (ToolLoop) Run ¶ added in v0.3.0
func (l ToolLoop) Run(opts ToolLoopOptions) (ToolLoopResult, error)
Run executes assistant generation, dispatches requested tools, and continues until the assistant returns a plain answer or MaxRounds is reached. A cancelled GenerateOptions.Context, a tool handler error, or a call to an unregistered tool aborts the run and is returned as an error.
type ToolLoopOptions ¶ added in v0.3.0
type ToolLoopOptions struct {
// System is the system prompt content.
System string
// History is the existing chat transcript excluding the generated assistant turn.
History []ChatMessage
// Generate controls model generation for each assistant turn.
Generate GenerateOptions
// MaxRounds bounds the total number of assistant turns — tool-calling
// rounds plus the final answer. Values <= 0 default to 8.
MaxRounds int
}
ToolLoopOptions configures one tool loop run.
type ToolLoopResult ¶ added in v0.3.0
type ToolLoopResult struct {
// History is the full updated transcript, including the final assistant turn.
History []ChatMessage
// Assistant is the final assistant message with no further tool calls.
Assistant ChatMessage
// ToolRounds is the number of assistant turns that requested tools.
ToolRounds int
}
ToolLoopResult is the final result of one tool loop run.
type ToolRegistry ¶ added in v0.3.0
type ToolRegistry struct {
// contains filtered or unexported fields
}
ToolRegistry stores Go-exposed tools and exact sampled DSML replay state.
func NewToolRegistry ¶ added in v0.3.0
func NewToolRegistry() *ToolRegistry
NewToolRegistry creates an empty tool registry with exact DSML replay enabled.
func (*ToolRegistry) BuildPrompt ¶ added in v0.3.0
func (r *ToolRegistry) BuildPrompt(engine *Engine, system string, history []ChatMessage, think ThinkMode) (*Tokens, error)
BuildPrompt renders a tool-aware chat prompt using ds4's chat helpers.
func (*ToolRegistry) ExecuteToolCalls ¶ added in v0.3.0
func (r *ToolRegistry) ExecuteToolCalls(ctx context.Context, calls []ToolCall) ([]ChatMessage, error)
ExecuteToolCalls invokes the registered Go handlers for the given tool calls. It stops and returns an error if ctx is cancelled, if a call names an unregistered tool, or if a handler returns an error.
func (*ToolRegistry) MustRegister ¶ added in v0.3.0
func (r *ToolRegistry) MustRegister(handler ToolHandler)
MustRegister adds one tool handler and panics on error.
func (*ToolRegistry) ParseAssistant ¶ added in v0.3.0
func (r *ToolRegistry) ParseAssistant(text string, thinking bool) (ChatMessage, error)
ParseAssistant parses one assistant completion and assigns stable tool-call IDs.
func (*ToolRegistry) Register ¶ added in v0.3.0
func (r *ToolRegistry) Register(handler ToolHandler) error
Register adds one tool handler to the registry.
func (*ToolRegistry) RegisterFunc ¶ added in v0.3.0
func (r *ToolRegistry) RegisterFunc(schema ToolSchema, fn ToolFunc) error
RegisterFunc adds one function-backed tool to the registry.
func (*ToolRegistry) RenderToolsSection ¶ added in v0.3.0
func (r *ToolRegistry) RenderToolsSection() (string, error)
RenderToolsSection renders the DSML tools section for the registered tools.
func (*ToolRegistry) ReplayStore ¶ added in v0.3.0
func (r *ToolRegistry) ReplayStore() *dsml.ReplayStore
ReplayStore returns the exact sampled DSML replay store.
func (*ToolRegistry) Schemas ¶ added in v0.3.0
func (r *ToolRegistry) Schemas() []ToolSchema
Schemas returns the registered tool schemas in registration order.
func (*ToolRegistry) SetReplayStore ¶ added in v0.3.0
func (r *ToolRegistry) SetReplayStore(store *dsml.ReplayStore)
SetReplayStore replaces the exact sampled DSML replay store. Passing nil disables replay.
type ToolSchema ¶ added in v0.3.0
type ToolSchema struct {
// Name is the tool's callable name.
Name string
// Description explains what the tool does.
Description string
// Parameters is the JSON Schema object for the tool's arguments.
Parameters json.RawMessage
}
ToolSchema describes one Go-exposed tool.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ds4api test infrastructure: a pure-Go mock of libds4.
|
Package ds4api test infrastructure: a pure-Go mock of libds4. |
|
Package dsml encodes and decodes DeepSeek DSML tool-calling markup.
|
Package dsml encodes and decodes DeepSeek DSML tool-calling markup. |
|
examples
|
|
|
chat
command
Command chat is an interactive ds4 REPL.
|
Command chat is an interactive ds4 REPL. |
|
openai-compatible
command
Command openai-compatible serves a small OpenAI-style chat endpoint backed by the ds4 engine.
|
Command openai-compatible serves a small OpenAI-style chat endpoint backed by the ds4 engine. |
|
simple
command
Command simple loads a ds4 model and generates one response.
|
Command simple loads a ds4 model and generates one response. |
|
toolloop
command
Command toolloop demonstrates end-to-end DSML tool calling with Go handlers.
|
Command toolloop demonstrates end-to-end DSML tool calling with Go handlers. |
|
internal
|
|
|
cliopts
Package cliopts defines the command-line flag surface shared by the ds4go CLI and examples.
|
Package cliopts defines the command-line flag surface shared by the ds4go CLI and examples. |
|
install
Package install downloads prebuilt libds4 release assets for the ds4go CLI.
|
Package install downloads prebuilt libds4 release assets for the ds4go CLI. |
|
models
Package models manages ds4go's curated model catalog.
|
Package models manages ds4go's curated model catalog. |
|
Package lsp is a small client for Language Server Protocol servers, built for driving generation/self-correction loops: start one persistent server, sync in-memory documents, and query diagnostics, hover, symbols, and completion.
|
Package lsp is a small client for Language Server Protocol servers, built for driving generation/self-correction loops: start one persistent server, sync in-memory documents, and query diagnostics, hover, symbols, and completion. |
|
lsptool
Package lsptool adapts an *lsp.Client into ds4go.ToolHandler values so a model running in a ds4go.ToolLoop can query a language server.
|
Package lsptool adapts an *lsp.Client into ds4go.ToolHandler values so a model running in a ds4go.ToolLoop can query a language server. |