Documentation
¶
Overview ¶
Package sp4rk is the entry point for the sp4rk Agent SDK — a standalone Go framework for building AI agent systems with Plan & Execute orchestration, tool integration, and multi-provider LLM support.
Quick start:
fw, _ := sp4rk.New(sp4rk.Config{
LLM: sp4rk.LLMConfig{
Providers: []llm.ProviderEntry{{
Name: "anthropic", ProviderType: "anthropic",
APIKey: os.Getenv("ANTHROPIC_API_KEY"), Models: []string{"claude-sonnet-4-5"},
}},
},
})
defer fw.Shutdown()
result, _ := fw.Execute(ctx, mySystemPrompt, myEvents, "Write a hello world in Go")
Fluent API ¶
The same framework is reachable through a concise method-chain (fluent) API. The fluent entry points carry an "F" postfix to distinguish them from the classic methods on the shared Framework type; once inside a builder, methods keep their natural names so the chain reads fluently:
fw, _ := sp4rk.NewF().
Anthropic(os.Getenv("ANTHROPIC_API_KEY"), "claude-sonnet-4-5").
FileTools().
AutoApprove().
Build()
defer fw.Shutdown()
// fw.RunF — single ReAct loop (fluent counterpart of Execute).
result, _ := fw.RunF(ctx).
System("You are a helpful assistant.").
Ask("Write a hello world in Go")
// fw.TaskF — Plan → Execute → Reflect orchestration.
result, _ = fw.TaskF(ctx, task).
System("You are a task execution agent.").
Plan().Reflect().Execute()
NewF returns a FrameworkBuilder; Framework.RunF and Framework.TaskF start the single-loop and orchestration builders. The classic and fluent APIs are fully interoperable — both produce and operate on the same *Framework. For the layer map, before/after comparisons, and when to reach for classic escapes, see the Fluent API guide at docs/fluent-api.md.
Index ¶
- func AllBuiltinTools() []tools.Tool
- func Anthropic(apiKey string, models ...string) llm.ProviderEntry
- func CodeTools() []tools.Tool
- func DefaultPromptSet() planner.PromptSet
- func DefaultReflectorPrompt() string
- func FileTools() []tools.Tool
- func FinishTool() []tools.Tool
- func MCPHTTP(name, url string) (string, mcp.ServerEntry)
- func MCPStdio(name, command string, args ...string) (string, mcp.ServerEntry)
- func MemoryTools() []tools.Tool
- func OpenAI(apiKey string, models ...string) llm.ProviderEntry
- func OpenAICompatible(name, baseURL, apiKey string, models ...string) llm.ProviderEntry
- func Tools(ts ...tools.Tool) []tools.Tool
- type CompactionConfig
- type Config
- type ExecutionConfig
- type Framework
- func (fw *Framework) ContextFactory() orchestration.ContextManagerFactory
- func (fw *Framework) Execute(ctx context.Context, systemPrompt orchestration.SystemPromptFactory, ...) (*orchestration.ExecutionResult, error)
- func (fw *Framework) LLMRouter() *llm.Router
- func (fw *Framework) NewConductor(systemPrompt orchestration.SystemPromptFactory) (*orchestration.Conductor, error)
- func (fw *Framework) RestoreBlackboard(ctx context.Context, id string) (*orchestration.CheckpointedBlackboard, error)
- func (fw *Framework) RunF(ctx context.Context) *RunBuilder
- func (fw *Framework) Shutdown() error
- func (fw *Framework) TaskF(ctx context.Context, task string) *TaskBuilder
- func (fw *Framework) ToolRegistry() *tools.ToolRegistry
- type FrameworkBuilder
- func (b *FrameworkBuilder) AllBuiltinTools() *FrameworkBuilder
- func (b *FrameworkBuilder) Anthropic(apiKey string, models ...string) *FrameworkBuilder
- func (b *FrameworkBuilder) AutoApprove() *FrameworkBuilder
- func (b *FrameworkBuilder) Build() (*Framework, error)
- func (b *FrameworkBuilder) CodeTools() *FrameworkBuilder
- func (b *FrameworkBuilder) Config(cfg Config) *FrameworkBuilder
- func (b *FrameworkBuilder) ConfirmFunc(fn tools.ConfirmFunc) *FrameworkBuilder
- func (b *FrameworkBuilder) DefaultModel(model string) *FrameworkBuilder
- func (b *FrameworkBuilder) FileTools() *FrameworkBuilder
- func (b *FrameworkBuilder) HITL(h agent.HITLHandler) *FrameworkBuilder
- func (b *FrameworkBuilder) Logger(l *slog.Logger) *FrameworkBuilder
- func (b *FrameworkBuilder) MCPHTTP(name, url string) *FrameworkBuilder
- func (b *FrameworkBuilder) MCPServer(name string, entry mcp.ServerEntry) *FrameworkBuilder
- func (b *FrameworkBuilder) MCPStdio(name, command string, args ...string) *FrameworkBuilder
- func (b *FrameworkBuilder) MCPWorkDir(dir string) *FrameworkBuilder
- func (b *FrameworkBuilder) MaxSteps(n int) *FrameworkBuilder
- func (b *FrameworkBuilder) MemoryTools() *FrameworkBuilder
- func (b *FrameworkBuilder) NoAutoFinish() *FrameworkBuilder
- func (b *FrameworkBuilder) OpenAI(apiKey string, models ...string) *FrameworkBuilder
- func (b *FrameworkBuilder) OpenAICompatible(name, baseURL, apiKey string, models ...string) *FrameworkBuilder
- func (b *FrameworkBuilder) Options(opts ...Option) *FrameworkBuilder
- func (b *FrameworkBuilder) Provider(p llm.ProviderEntry) *FrameworkBuilder
- func (b *FrameworkBuilder) Providers(ps ...llm.ProviderEntry) *FrameworkBuilder
- func (b *FrameworkBuilder) Run(ctx context.Context) *RunBuilder
- func (b *FrameworkBuilder) Task(ctx context.Context, task string) *TaskBuilder
- func (b *FrameworkBuilder) Tools(ts ...tools.Tool) *FrameworkBuilder
- type LLMConfig
- type MCPConfig
- type Option
- func WithAutoApprove() Option
- func WithConfig(cfg Config) Option
- func WithConfirmFunc(fn tools.ConfirmFunc) Option
- func WithDefaultModel(model string) Option
- func WithHITL(h agent.HITLHandler) Option
- func WithLogger(l *slog.Logger) Option
- func WithMCPServer(name string, entry mcp.ServerEntry) Option
- func WithMCPWorkDir(dir string) Option
- func WithMaxSteps(n int) Option
- func WithProvider(p llm.ProviderEntry) Option
- func WithProviders(ps ...llm.ProviderEntry) Option
- func WithTools(ts ...tools.Tool) Option
- func WithoutAutoFinish() Option
- type RunBuilder
- type TaskBuilder
- func (b *TaskBuilder) Compaction(strategy string) *TaskBuilder
- func (b *TaskBuilder) Events(e orchestration.Events) *TaskBuilder
- func (b *TaskBuilder) Execute() (*orchestration.ExecutionResult, error)
- func (b *TaskBuilder) MaxRetries(n int) *TaskBuilder
- func (b *TaskBuilder) Models(planModel, execModel string) *TaskBuilder
- func (b *TaskBuilder) Plan() *TaskBuilder
- func (b *TaskBuilder) Planner(p *planner.Planner) *TaskBuilder
- func (b *TaskBuilder) Reflect() *TaskBuilder
- func (b *TaskBuilder) Reflector(r *reflector.Reflector) *TaskBuilder
- func (b *TaskBuilder) Skills(s []skills.SkillDescriptor) *TaskBuilder
- func (b *TaskBuilder) System(prompt string) *TaskBuilder
- func (b *TaskBuilder) SystemFactory(fn orchestration.SystemPromptFactory) *TaskBuilder
- func (b *TaskBuilder) Workspace(dir string) *TaskBuilder
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AllBuiltinTools ¶
AllBuiltinTools returns every zero-configuration built-in tool (file, search, memory, and orchestration-readiness tools). Parameterized tools (bash_exec, vector_search, web_fetch) are excluded — construct those individually when needed.
func Anthropic ¶
func Anthropic(apiKey string, models ...string) llm.ProviderEntry
Anthropic returns a llm.ProviderEntry for the Anthropic API with the given API key and enabled models.
sp4rk.Anthropic(os.Getenv("ANTHROPIC_API_KEY"), "claude-sonnet-4-5", "claude-haiku-3-5")
The returned entry is exactly what LLMConfig expects — pass it to the FrameworkBuilder via FrameworkBuilder.Provider/FrameworkBuilder.Anthropic or use it directly in a classic Config.
func CodeTools ¶
CodeTools returns FileTools plus ripgrep, delete_file, and delete_directory — a complete code-editing bundle for agents that search and modify a codebase.
func DefaultPromptSet ¶
DefaultPromptSet returns a general-purpose planner.PromptSet suitable for a zero-config planner. The prompts are domain-agnostic (they do not assume a specific workspace, language, or framework) so they work for any sp4rk consumer. Override individual fields after calling it to customize.
cfg := planner.DefaultConfig() cfg.Prompts = sp4rk.DefaultPromptSet() cfg.Model = "claude-sonnet-4-5"
func DefaultReflectorPrompt ¶
func DefaultReflectorPrompt() string
DefaultReflectorPrompt returns a general-purpose system prompt for a reflector.Reflector. It instructs the model to analyze a failed execution trajectory and return structured self-correction guidance (retry, replan, or abort).
func FileTools ¶
FileTools returns the built-in workspace file tools: read_file, write_file, edit_file, list_directory, glob, and create_directory. These cover the common file-manipulation surface most agents need.
func FinishTool ¶
FinishTool returns the agent.FinishTool, which signals task completion. NewF auto-registers it by default; this helper is exposed for callers that build a Config directly (classic API) or disable auto-registration.
func MCPHTTP ¶
func MCPHTTP(name, url string) (string, mcp.ServerEntry)
MCPHTTP returns an mcp.ServerEntry for an HTTP-based MCP server reachable at url. Pass the result to WithMCPServer.
name, entry := sp4rk.MCPHTTP("remote", "https://mcp.example.com/sse")
fw, _ := sp4rk.NewF(sp4rk.WithMCPServer(name, entry), ...)
func MCPStdio ¶
func MCPStdio(name, command string, args ...string) (string, mcp.ServerEntry)
MCPStdio returns an mcp.ServerEntry for a stdio-based MCP server (a local process launched via command + args). Pass the result to WithMCPServer.
name, entry := sp4rk.MCPStdio("filesystem", "npx", "-y", "@modelcontextprotocol/server-filesystem", workDir)
func MemoryTools ¶
MemoryTools returns the blackboard fact-memory tools: store_fact and search_facts. Use these when steps need to share findings with later steps.
func OpenAI ¶
func OpenAI(apiKey string, models ...string) llm.ProviderEntry
OpenAI returns a llm.ProviderEntry for the OpenAI API with the given API key and enabled models.
sp4rk.OpenAI(os.Getenv("OPENAI_API_KEY"), "gpt-4o", "gpt-4o-mini")
func OpenAICompatible ¶
func OpenAICompatible(name, baseURL, apiKey string, models ...string) llm.ProviderEntry
OpenAICompatible returns a llm.ProviderEntry for an OpenAI-compatible API (e.g. Together, Groq, a local vLLM/Ollama endpoint) reachable at baseURL.
The logical name distinguishes this provider from a built-in OpenAI entry when several providers are configured simultaneously.
sp4rk.OpenAICompatible("groq", "https://api.groq.com/openai/v1", key, "llama-3.3-70b-versatile")
Types ¶
type CompactionConfig ¶
type CompactionConfig struct {
// Strategy is the compaction algorithm: "sliding_window", "summarization",
// or "hierarchical". Empty means "sliding_window". Unrecognised values fall
// back to sliding window (see memory.NewCompactionStrategy).
Strategy string
// PredictivePercent triggers predictive compaction at this context fill %.
// 0 means use the default (85).
PredictivePercent int
// WarningPercent triggers warning-level compaction at this context fill %.
// 0 means use the default (92).
WarningPercent int
// EmergencyPercent triggers emergency compaction at this context fill %.
// 0 means use the default (98).
EmergencyPercent int
}
CompactionConfig configures context window compaction.
type Config ¶
type Config struct {
// LLM configures the LLM providers and default model.
LLM LLMConfig
// MCP optionally configures Model Context Protocol servers.
// Nil means no MCP integration.
MCP *MCPConfig
// Execution configures agent execution parameters.
Execution ExecutionConfig
// Compaction configures context window management.
Compaction CompactionConfig
// HITL optionally provides human-in-the-loop hooks.
// Nil means defaults (allow all tool calls, deny step extensions).
HITL agent.HITLHandler
// ConfirmFunc is the confirmation callback the tool registry consults
// before executing tools whose effective policy is PolicyUserConfirm
// (e.g. write_file, bash_exec). The registry is FAIL-CLOSED: when no
// ConfirmFunc is configured, such tools are denied instead of executing
// silently. To run without interactive confirmation, either provide a
// ConfirmFunc that auto-approves, or relax individual tools via
// ToolRegistry().SetPolicyOverride(name, tools.PolicyAlwaysAllow).
//
// Note: this is a separate, lower-level gate than HITL.OnToolCall.
// HITL intercepts tool calls at the executor level for every tool;
// ConfirmFunc is consulted by the registry only for confirm-policy tools.
ConfirmFunc tools.ConfirmFunc
// Checkpointer optionally provides state persistence.
Checkpointer orchestration.Checkpointer
// OnBlackboardChanged is an optional callback invoked after every successful
// blackboard write (plan, step_result, fact, reflection). The changeType argument
// describes what changed. Nil means no notifications.
OnBlackboardChanged func(changeType string)
// Logger is an optional structured logger. Uses slog.Default() if nil.
Logger *slog.Logger
}
Config holds all configuration for the Framework. Zero-value fields are replaced with sensible defaults during New().
type ExecutionConfig ¶
type ExecutionConfig struct {
// MaxSteps is the maximum number of ReAct loop iterations per step.
// 0 means use the default (50); negative means explicitly 0 (no loop
// iterations — effectively disabled).
MaxSteps int
// MaxRetries is the maximum number of retry attempts per plan step.
// 0 means use the default (2); negative means explicitly 0 (no retries).
MaxRetries int
// ToolResultBudget configures tool result truncation.
// Zero value means use the default.
ToolResultBudget agent.ToolResultBudget
// CircuitBreaker configures circuit breaker thresholds.
// Zero value means use the default.
CircuitBreaker agent.CircuitBreakerConfig
// SafetyMarginPercent reserves a percentage of the context window as safety margin.
// 0 means use the default (5).
SafetyMarginPercent int
// PreWarningPercent triggers the pre-compaction store_fact nudge at this context fill %.
// When fill reaches this threshold (but below the compaction trigger), a warning listing
// vulnerable tool outputs is appended to the observation. 0 means disabled.
PreWarningPercent int
// ToolCacheTTLSeconds controls the TTL for cached tool results. The cache enables
// tool_result_read fragmentation reads for truncated outputs.
// 0 means use the default (300s); negative means disabled.
ToolCacheTTLSeconds int
// MaxDependencyContextChars limits the context size for step dependency summaries.
// When provided to the LLM as context for a dependent step. 0 means use the default (8000).
MaxDependencyContextChars int
}
ExecutionConfig configures agent execution.
type Framework ¶
type Framework struct {
// contains filtered or unexported fields
}
Framework is the top-level entry point for building agent systems with sp4rk. It owns shared infrastructure (LLM router, tool registry, MCP gateway, tool cache) and creates per-session conductors via NewConductor().
func New ¶
New creates a new Framework from the given configuration. It builds the LLM router, tool registry, and optionally starts MCP servers. Call Shutdown() when done to release resources.
func (*Framework) ContextFactory ¶
func (fw *Framework) ContextFactory() orchestration.ContextManagerFactory
ContextFactory returns a ContextManagerFactory wired with the Framework's compaction, safety margin, and pruning configuration. Use it to give the Planner (or any other component that needs a ContextManager) the same context-window behaviour as the Framework-built Conductors.
The returned factory accepts a system prompt, model metadata, compaction strategy name, and optional pruning overrides — matching the orchestration.ContextManagerFactory signature.
func (*Framework) Execute ¶
func (fw *Framework) Execute(ctx context.Context, systemPrompt orchestration.SystemPromptFactory, events agent.Events, userMessage string) (*orchestration.ExecutionResult, error)
Execute is a convenience method that creates a Conductor and executes a single user message. Returns the execution result. For repeated use, call NewConductor() once and reuse it.
When Config.Checkpointer is set, the blackboard is a CheckpointedBlackboard (persisted through the checkpointer, keyed by a unique per-execution ID) and Config.OnBlackboardChanged (if set) receives change notifications. Without a Checkpointer the blackboard is in-memory only and OnBlackboardChanged is not invoked.
func (*Framework) LLMRouter ¶
LLMRouter returns the shared LLM router for model switching at runtime.
func (*Framework) NewConductor ¶
func (fw *Framework) NewConductor(systemPrompt orchestration.SystemPromptFactory) (*orchestration.Conductor, error)
NewConductor creates a new per-session Conductor wired with the Framework's shared infrastructure (LLM router, tool registry, MCP tools).
systemPrompt is a factory that creates the Conductor's system prompt. Lifecycle events are supplied per-run via Conductor.Run (nil = no-op emitter).
The Conductor is a single ReAct loop that owns a task end-to-end. The caller is responsible for injecting any Conductor-specific tools (delegate, declare_plan, reflect) into the context before calling Run, if desired. The sp4rk Conductor primitive itself does not provide those tools; they are an application-layer concern.
func (*Framework) RestoreBlackboard ¶
func (fw *Framework) RestoreBlackboard(ctx context.Context, id string) (*orchestration.CheckpointedBlackboard, error)
RestoreBlackboard loads a previously persisted blackboard state from the configured Checkpointer. Returns nil, nil if no checkpoint exists for the given ID. The returned CheckpointedBlackboard must be shut down by the caller after use.
func (*Framework) RunF ¶
func (fw *Framework) RunF(ctx context.Context) *RunBuilder
RunF starts a fluent single-task execution over fw. The chain is terminated by RunBuilder.Ask, which delegates to Framework.Execute and returns the original *orchestration.ExecutionResult.
result, err := fw.RunF(ctx).
System("You are a helpful assistant.").
Ask("What is the capital of France?")
RunF is the fluent counterpart of Framework.Execute: both run a single ReAct loop, but RunF returns a RunBuilder for declarative configuration.
func (*Framework) Shutdown ¶
Shutdown releases all resources held by the Framework (MCP connections, etc.). Safe to call multiple times, including concurrently: sync.Once guarantees the underlying shutdown runs exactly once.
func (*Framework) TaskF ¶
func (fw *Framework) TaskF(ctx context.Context, task string) *TaskBuilder
TaskF starts a fluent orchestrated execution over fw for the given task. The chain is terminated by TaskBuilder.Execute, which returns the original *orchestration.ExecutionResult.
TaskF is the fluent counterpart of a hand-rolled Plan→Execute→Reflect loop: without TaskBuilder.Plan it runs a single ReAct loop, with TaskBuilder.Plan it builds a DAG with retry and (optionally) reflection.
func (*Framework) ToolRegistry ¶
func (fw *Framework) ToolRegistry() *tools.ToolRegistry
ToolRegistry returns the shared tool registry for direct tool registration.
type FrameworkBuilder ¶
type FrameworkBuilder struct {
// contains filtered or unexported fields
}
FrameworkBuilder is a method-chain builder for assembling a Framework. Create one with NewF; every provider, tool, MCP server, and policy is a method returning the same builder, so the whole configuration reads as a single unbroken chain terminated by FrameworkBuilder.Build:
fw, err := sp4rk.NewF().
Anthropic(os.Getenv("ANTHROPIC_API_KEY"), "claude-sonnet-4-5").
FileTools().
MaxSteps(15).
AutoApprove().
Build()
Errors accumulated along the chain surface once, at FrameworkBuilder.Build.
This is the fluent entry point of sp4rk. The "F" postfix on the entry functions (NewF, Framework.RunF, Framework.TaskF) distinguishes the fluent API from the classic one (New, Framework.Execute) while sharing the same Framework type. Inside a builder, methods keep their natural names (no "F" postfix) — that is what makes the chain read fluently.
func NewF ¶
func NewF() *FrameworkBuilder
NewF returns a FrameworkBuilder — the entry point of the fluent API. The returned builder is configured entirely by chaining methods; terminate the chain with FrameworkBuilder.Build to obtain a *Framework.
Conventions applied at build time:
- The finish tool (agent.NewFinishTool) is auto-registered so the agent can signal task completion. Disable with FrameworkBuilder.NoAutoFinish.
- The build delegates to New; the result is a real *Framework, the same type returned by the classic New constructor.
At least one provider is required (via FrameworkBuilder.Anthropic, FrameworkBuilder.OpenAI, FrameworkBuilder.Providers, …) or via a FrameworkBuilder.Config base that already contains providers.
fw, err := sp4rk.NewF().
Anthropic(os.Getenv("ANTHROPIC_API_KEY"), "claude-sonnet-4-5").
FileTools().
AutoApprove().
Build()
func (*FrameworkBuilder) AllBuiltinTools ¶
func (b *FrameworkBuilder) AllBuiltinTools() *FrameworkBuilder
AllBuiltinTools registers every zero-configuration built-in tool (file, search, memory, and orchestration-readiness tools).
func (*FrameworkBuilder) Anthropic ¶
func (b *FrameworkBuilder) Anthropic(apiKey string, models ...string) *FrameworkBuilder
Anthropic appends an Anthropic provider entry. Repeatable to register multiple providers. Equivalent to FrameworkBuilder.Provider(Anthropic).
func (*FrameworkBuilder) AutoApprove ¶
func (b *FrameworkBuilder) AutoApprove() *FrameworkBuilder
AutoApprove installs a confirmation callback that auto-approves every PolicyUserConfirm tool call. Convenient for throwaway/sandboxed workspaces where the fail-closed default would otherwise deny writes.
func (*FrameworkBuilder) Build ¶
func (b *FrameworkBuilder) Build() (*Framework, error)
Build terminates the builder chain and constructs the *Framework, applying all accumulated configuration. It is the terminal call of NewF.
Returns the first error accumulated along the chain, or any error from the underlying New.
func (*FrameworkBuilder) CodeTools ¶
func (b *FrameworkBuilder) CodeTools() *FrameworkBuilder
CodeTools registers FileTools plus ripgrep and delete helpers — a complete code-editing bundle for agents that search and modify a codebase.
func (*FrameworkBuilder) Config ¶
func (b *FrameworkBuilder) Config(cfg Config) *FrameworkBuilder
Config supplies a full Config as the base; other builder methods are then applied on top of it. Use this when you need classic-API fields not yet surfaced as dedicated builder methods.
func (*FrameworkBuilder) ConfirmFunc ¶
func (b *FrameworkBuilder) ConfirmFunc(fn tools.ConfirmFunc) *FrameworkBuilder
ConfirmFunc sets the confirmation callback consulted before executing tools whose policy is PolicyUserConfirm (write_file, bash_exec, MCP tools). Without it, such tools are denied by the fail-closed registry.
func (*FrameworkBuilder) DefaultModel ¶
func (b *FrameworkBuilder) DefaultModel(model string) *FrameworkBuilder
DefaultModel overrides the auto-selected default model. Accepts a bare name ("claude-sonnet-4-5") or composite ID ("anthropic/claude-sonnet-4-5").
func (*FrameworkBuilder) FileTools ¶
func (b *FrameworkBuilder) FileTools() *FrameworkBuilder
FileTools registers the built-in workspace file tools bundle (read, write, edit, list, glob, mkdir).
func (*FrameworkBuilder) HITL ¶
func (b *FrameworkBuilder) HITL(h agent.HITLHandler) *FrameworkBuilder
HITL sets the human-in-the-loop handler for tool-call interception and step-limit decisions.
func (*FrameworkBuilder) Logger ¶
func (b *FrameworkBuilder) Logger(l *slog.Logger) *FrameworkBuilder
Logger sets the structured logger used by the Framework. Defaults to slog.Default() when unset.
func (*FrameworkBuilder) MCPHTTP ¶
func (b *FrameworkBuilder) MCPHTTP(name, url string) *FrameworkBuilder
MCPHTTP registers an HTTP-based MCP server reachable at url, in a single chained call.
func (*FrameworkBuilder) MCPServer ¶
func (b *FrameworkBuilder) MCPServer(name string, entry mcp.ServerEntry) *FrameworkBuilder
MCPServer registers a pre-built mcp.ServerEntry under the given name. Use this when you construct the entry by hand.
func (*FrameworkBuilder) MCPStdio ¶
func (b *FrameworkBuilder) MCPStdio(name, command string, args ...string) *FrameworkBuilder
MCPStdio registers a stdio-based MCP server (a local process launched via command + args) under the given name, in a single chained call.
func (*FrameworkBuilder) MCPWorkDir ¶
func (b *FrameworkBuilder) MCPWorkDir(dir string) *FrameworkBuilder
MCPWorkDir sets the fallback working directory for stdio-based MCP servers.
func (*FrameworkBuilder) MaxSteps ¶
func (b *FrameworkBuilder) MaxSteps(n int) *FrameworkBuilder
MaxSteps sets the maximum ReAct loop iterations per step. 0 keeps the sp4rk default (50); a negative value disables the loop.
func (*FrameworkBuilder) MemoryTools ¶
func (b *FrameworkBuilder) MemoryTools() *FrameworkBuilder
MemoryTools registers the blackboard fact-memory tools bundle (store_fact, search_facts).
func (*FrameworkBuilder) NoAutoFinish ¶
func (b *FrameworkBuilder) NoAutoFinish() *FrameworkBuilder
NoAutoFinish prevents the framework from auto-registering the finish tool. By default the finish tool is registered so the agent can signal completion.
func (*FrameworkBuilder) OpenAI ¶
func (b *FrameworkBuilder) OpenAI(apiKey string, models ...string) *FrameworkBuilder
OpenAI appends an OpenAI provider entry. Repeatable.
func (*FrameworkBuilder) OpenAICompatible ¶
func (b *FrameworkBuilder) OpenAICompatible(name, baseURL, apiKey string, models ...string) *FrameworkBuilder
OpenAICompatible appends an OpenAI-compatible provider (e.g. Together, Groq, a local vLLM/Ollama endpoint) reachable at baseURL.
func (*FrameworkBuilder) Options ¶
func (b *FrameworkBuilder) Options(opts ...Option) *FrameworkBuilder
Options applies functional options (Option values such as WithProvider or WithTools) onto the builder. This is the bridge for callers who already have option values — the dedicated method form (FrameworkBuilder.Anthropic, FrameworkBuilder.FileTools, …) is preferred for new code because it keeps the chain unbroken and free of the package prefix.
func (*FrameworkBuilder) Provider ¶
func (b *FrameworkBuilder) Provider(p llm.ProviderEntry) *FrameworkBuilder
Provider appends a single pre-built llm.ProviderEntry. Use this for custom provider types not covered by the dedicated methods.
func (*FrameworkBuilder) Providers ¶
func (b *FrameworkBuilder) Providers(ps ...llm.ProviderEntry) *FrameworkBuilder
Providers appends a set of provider entries at once. Useful when providers are assembled conditionally before the chain.
func (*FrameworkBuilder) Run ¶
func (b *FrameworkBuilder) Run(ctx context.Context) *RunBuilder
Run is a pipeline transition on FrameworkBuilder: it builds the framework from the accumulated configuration and starts a RunBuilder in one step.
Use this for single-use scripts that don't need to retain the *Framework handle (there is no defer Shutdown). If the build fails, the error is surfaced by RunBuilder.Ask instead of panicking.
sp4rk.NewF().Anthropic(key, model).
FileTools().Run(ctx).
System("You are helpful.").
Ask("What is the capital of France?")
func (*FrameworkBuilder) Task ¶
func (b *FrameworkBuilder) Task(ctx context.Context, task string) *TaskBuilder
Task is a pipeline transition on FrameworkBuilder: it builds the framework from the accumulated configuration and starts a TaskBuilder in one step.
Use this for single-use scripts that don't need to retain the *Framework handle (there is no defer Shutdown). If the build fails, the error is surfaced by TaskBuilder.Execute instead of panicking.
sp4rk.NewF().Anthropic(key, model).
FileTools().Task(ctx, task).
System("...").Plan().Reflect().Execute()
func (*FrameworkBuilder) Tools ¶
func (b *FrameworkBuilder) Tools(ts ...tools.Tool) *FrameworkBuilder
Tools appends arbitrary tools to the auto-registration set. Use this to add custom tools or a pre-assembled slice alongside the bundles above.
type LLMConfig ¶
type LLMConfig struct {
// Providers lists all enabled LLM providers. At least one is required.
Providers []llm.ProviderEntry
// DefaultModel optionally overrides the auto-selected default model.
// When empty, the Router auto-selects the first provider's first model.
// When set, it must be a bare model name ("claude-sonnet-4-5") or a
// composite identifier ("anthropic/claude-sonnet-4-5") that exists in
// some provider's Models list.
DefaultModel string
// MaxRetries sets the number of retry attempts for transient errors.
// 0 means use the default (3); negative means explicitly 0 (no retries).
MaxRetries int
// InitialBackoff is the starting backoff duration for retries.
// Empty string means use the default (1s); a negative duration (e.g.
// "-1s") means explicitly 0 (no initial backoff).
InitialBackoff string
// MaxBackoff is the maximum backoff duration for retries.
// Empty string means use the default (30s); a negative duration means
// explicitly 0 (no backoff cap).
MaxBackoff string
// OutputTokenReserve reserves context window space for model output.
// This affects context-window validation. 0 means use the default (4096).
OutputTokenReserve int
}
LLMConfig configures LLM providers.
type MCPConfig ¶
type MCPConfig struct {
// Servers maps server names to their configuration entries.
Servers map[string]mcp.ServerEntry
// DefaultWorkDir is the fallback working directory for stdio-based servers.
DefaultWorkDir string
}
MCPConfig configures Model Context Protocol server integration.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures how NewF builds the Framework.
Option uses the interface-based functional-options pattern: only this package can produce values implementing Option (the apply method is unexported), so options from other packages cannot be accidentally applied.
func WithAutoApprove ¶
func WithAutoApprove() Option
WithAutoApprove installs a confirmation callback that auto-approves every PolicyUserConfirm tool call. Convenient for throwaway/sandboxed workspaces where the fail-closed default would otherwise deny writes.
func WithConfig ¶
WithConfig supplies a full Config as the base; other options are then applied on top of it. Use this when you need classic-API fields not yet surfaced as dedicated options, while still benefiting from the fluent conveniences (provider/tool/MCP helpers, auto-finish).
func WithConfirmFunc ¶
func WithConfirmFunc(fn tools.ConfirmFunc) Option
WithConfirmFunc sets the confirmation callback consulted before executing tools whose policy is PolicyUserConfirm (write_file, bash_exec, MCP tools). Without it, such tools are denied by the fail-closed registry.
func WithDefaultModel ¶
WithDefaultModel overrides the auto-selected default model. Accepts a bare name ("claude-sonnet-4-5") or composite ID ("anthropic/claude-sonnet-4-5").
func WithHITL ¶
func WithHITL(h agent.HITLHandler) Option
WithHITL sets the human-in-the-loop handler for tool-call interception and step-limit decisions.
func WithLogger ¶
WithLogger sets the structured logger used by the Framework. Defaults to slog.Default() when unset.
func WithMCPServer ¶
func WithMCPServer(name string, entry mcp.ServerEntry) Option
WithMCPServer registers an MCP server. Pair with MCPStdio or MCPHTTP:
name, entry := sp4rk.MCPStdio("filesystem", "npx", "-y", "@modelcontextprotocol/server-filesystem", dir)
sp4rk.NewF(sp4rk.WithMCPServer(name, entry), ...)
func WithMCPWorkDir ¶
WithMCPWorkDir sets the fallback working directory for stdio-based MCP servers.
func WithMaxSteps ¶
WithMaxSteps sets the maximum ReAct loop iterations per step. 0 keeps the sp4rk default (50); a negative value disables the loop.
func WithProvider ¶
func WithProvider(p llm.ProviderEntry) Option
WithProvider adds a single LLM provider to the configuration. Repeatable to register multiple providers:
sp4rk.NewF(
sp4rk.WithProvider(sp4rk.Anthropic(...)),
sp4rk.WithProvider(sp4rk.OpenAI(...)),
)
func WithProviders ¶
func WithProviders(ps ...llm.ProviderEntry) Option
WithProviders sets the complete provider list in one call (replaces any previously added providers).
func WithTools ¶
WithTools adds tools that NewF registers automatically after building the Framework. Spread a bundle to register it:
sp4rk.WithTools(sp4rk.FileTools()...)
func WithoutAutoFinish ¶
func WithoutAutoFinish() Option
WithoutAutoFinish prevents NewF from auto-registering the finish tool. By default the finish tool is registered so the agent can signal completion.
type RunBuilder ¶
type RunBuilder struct {
// contains filtered or unexported fields
}
RunBuilder is a fluent builder for executing a single ReAct loop via Framework.Execute. Create one with Framework.RunF; terminate the chain with RunBuilder.Ask.
Conventions (all overridable):
- Events defaults to agent.NoopEvents; override with RunBuilder.Events.
- System prompt defaults to none; a static prompt is the common case (RunBuilder.System); a factory gives full control (RunBuilder.SystemFactory).
func (*RunBuilder) Ask ¶
func (b *RunBuilder) Ask(message string) (*orchestration.ExecutionResult, error)
Ask executes a single ReAct loop for the given user message and returns the original *orchestration.ExecutionResult. It is the terminal call of the RunBuilder chain.
An error is returned if no system prompt was configured.
func (*RunBuilder) Events ¶
func (b *RunBuilder) Events(e agent.Events) *RunBuilder
Events sets the lifecycle event sink. When omitted, agent.NoopEvents is used.
func (*RunBuilder) System ¶
func (b *RunBuilder) System(prompt string) *RunBuilder
System sets a static system prompt. This is the common case; the string is wrapped in a orchestration.SystemPromptFactory that ignores its arguments.
func (*RunBuilder) SystemFactory ¶
func (b *RunBuilder) SystemFactory(fn orchestration.SystemPromptFactory) *RunBuilder
SystemFactory sets a orchestration.SystemPromptFactory, giving full control (the factory receives the context, step description, and model metadata so it can adapt the prompt per model). Use this for dynamic prompts.
type TaskBuilder ¶
type TaskBuilder struct {
// contains filtered or unexported fields
}
TaskBuilder is a fluent builder for orchestrated task execution (the Plan→Execute→Reflect loop). Create one with Framework.TaskF; terminate the chain with TaskBuilder.Execute.
Without TaskBuilder.Plan, Execute runs a single ReAct loop (like [Run] but returning an orchestrated result). With TaskBuilder.Plan, Execute builds a DAG and runs it with retry and (optionally) reflection.
func (*TaskBuilder) Compaction ¶
func (b *TaskBuilder) Compaction(strategy string) *TaskBuilder
Compaction sets the context compaction strategy passed to the conductor (default "sliding_window").
func (*TaskBuilder) Events ¶
func (b *TaskBuilder) Events(e orchestration.Events) *TaskBuilder
Events sets the orchestration lifecycle event sink. Defaults to orchestration.NoopEvents.
func (*TaskBuilder) Execute ¶
func (b *TaskBuilder) Execute() (*orchestration.ExecutionResult, error)
Execute runs the task and returns the original *orchestration.ExecutionResult.
Without TaskBuilder.Plan: a single ReAct loop. With TaskBuilder.Plan: a DAG executed with retry and (if enabled) reflection, exactly as the full Plan→Execute→Reflect loop in the classic API.
func (*TaskBuilder) MaxRetries ¶
func (b *TaskBuilder) MaxRetries(n int) *TaskBuilder
MaxRetries sets the per-step retry budget (default 2). 0 disables retries.
func (*TaskBuilder) Models ¶
func (b *TaskBuilder) Models(planModel, execModel string) *TaskBuilder
Models configures runtime model switching: planModel for planning/reflection, execModel for step execution. The router is restored to planModel after execution. Use when you want a strong-reasoning model for planning and a faster/cheaper one for execution.
func (*TaskBuilder) Plan ¶
func (b *TaskBuilder) Plan() *TaskBuilder
Plan enables the planner, configured with DefaultPromptSet and the framework's active model. For a custom planner, use TaskBuilder.Planner.
func (*TaskBuilder) Planner ¶
func (b *TaskBuilder) Planner(p *planner.Planner) *TaskBuilder
Planner injects a custom planner.Planner (implies TaskBuilder.Plan).
func (*TaskBuilder) Reflect ¶
func (b *TaskBuilder) Reflect() *TaskBuilder
Reflect enables the reflector, configured with DefaultReflectorPrompt. For a custom reflector, use TaskBuilder.Reflector.
func (*TaskBuilder) Reflector ¶
func (b *TaskBuilder) Reflector(r *reflector.Reflector) *TaskBuilder
Reflector injects a custom reflector.Reflector (implies TaskBuilder.Reflect).
func (*TaskBuilder) Skills ¶
func (b *TaskBuilder) Skills(s []skills.SkillDescriptor) *TaskBuilder
Skills sets the skill descriptors available to the planner.
func (*TaskBuilder) System ¶
func (b *TaskBuilder) System(prompt string) *TaskBuilder
System sets a static system prompt for step execution.
func (*TaskBuilder) SystemFactory ¶
func (b *TaskBuilder) SystemFactory(fn orchestration.SystemPromptFactory) *TaskBuilder
SystemFactory sets a orchestration.SystemPromptFactory for dynamic prompts.
func (*TaskBuilder) Workspace ¶
func (b *TaskBuilder) Workspace(dir string) *TaskBuilder
Workspace attaches the workspace path to the execution context (via tools.WithWorkspacePath) so tools resolve relative paths correctly.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agent provides the ReAct executor loop, tool result caching, finish-tool handling, sub-agent parallelism, and context propagation for LLM-driven agent sessions.
|
Package agent provides the ReAct executor loop, tool result caching, finish-tool handling, sub-agent parallelism, and context propagation for LLM-driven agent sessions. |
|
reflector
Package reflector analyzes execution trajectories to produce structured self-correction insights (retry, replan, or abort recommendations).
|
Package reflector analyzes execution trajectories to produce structured self-correction insights (retry, replan, or abort recommendations). |
|
router
Package router classifies user requests by domain and complexity to drive execution strategy selection (direct execution vs.
|
Package router classifies user requests by domain and complexity to drive execution strategy selection (direct execution vs. |
|
Package agents provides discovery, parsing, and management of Subagent Profiles — AGENT.md files that declare specialized subagent personas and tool budgets.
|
Package agents provides discovery, parsing, and management of Subagent Profiles — AGENT.md files that declare specialized subagent personas and tool budgets. |
|
Package embedding provides file chunking and embedding utilities for local vector search.
|
Package embedding provides file chunking and embedding utilities for local vector search. |
|
Package ignore is a multi-root ignore resolver that loads .gitignore and .aiignore files (at the root and in every nested directory) for each root and answers whether an arbitrary path is ignored by the patterns of the root that contains it.
|
Package ignore is a multi-root ignore resolver that loads .gitignore and .aiignore files (at the root and in every nested directory) for each root and answers whether an arbitrary path is ignored by the patterns of the root that contains it. |
|
Package llm provides LLM provider abstractions, model registry, and routing for multi-provider inference.
|
Package llm provides LLM provider abstractions, model registry, and routing for multi-provider inference. |
|
Package memory provides working memory management, compaction strategies, and procedural memory for agent sessions.
|
Package memory provides working memory management, compaction strategies, and procedural memory for agent sessions. |
|
Package orchestration defines interfaces for multi-step task orchestration including planning, evaluation, routing, and verification of agent work.
|
Package orchestration defines interfaces for multi-step task orchestration including planning, evaluation, routing, and verification of agent work. |
|
Package pathutil provides reusable filesystem-path algorithms with no knowledge of any application's directory layout.
|
Package pathutil provides reusable filesystem-path algorithms with no knowledge of any application's directory layout. |
|
Package planner generates DAG execution plans for complex tasks, breaking them into ordered steps with dependency tracking.
|
Package planner generates DAG execution plans for complex tasks, breaking them into ordered steps with dependency tracking. |
|
Package prompt provides builders for constructing LLM system prompts with cache-break support and family-aware sampling defaults.
|
Package prompt provides builders for constructing LLM system prompts with cache-break support and family-aware sampling defaults. |
|
Package security provides utilities for defending against indirect prompt injection attacks by delimiting untrusted content with XML boundary tags.
|
Package security provides utilities for defending against indirect prompt injection attacks by delimiting untrusted content with XML boundary tags. |
|
Package skills provides discovery, parsing, and management of Agent Skills following the open agentskills.io specification.
|
Package skills provides discovery, parsing, and management of Agent Skills following the open agentskills.io specification. |
|
Package strutil provides string utilities such as UTF-8-safe truncation.
|
Package strutil provides string utilities such as UTF-8-safe truncation. |
|
Package sysproc configures process-creation attributes for child processes spawned by host applications and the SDK's own helper processes.
|
Package sysproc configures process-creation attributes for child processes spawned by host applications and the SDK's own helper processes. |
|
Package tools provides the tool abstraction, registry, and core types for agent tool execution.
|
Package tools provides the tool abstraction, registry, and core types for agent tool execution. |
|
builtins
Package builtins provides built-in tool implementations for the agent, including file operations, glob, ripgrep, and workspace utilities.
|
Package builtins provides built-in tool implementations for the agent, including file operations, glob, ripgrep, and workspace utilities. |
|
builtins/websearch
Package websearch provides a web search tool implementation that integrates external search APIs for information retrieval by agents.
|
Package websearch provides a web search tool implementation that integrates external search APIs for information retrieval by agents. |
|
internal/judge_prompts
Package judge_prompts provides embedded prompt templates for the tool safety judge.
|
Package judge_prompts provides embedded prompt templates for the tool safety judge. |
|
mcp
Package mcp provides MCP (Model Context Protocol) integration for the agent.
|
Package mcp provides MCP (Model Context Protocol) integration for the agent. |