Documentation
¶
Overview ¶
Package sdk provides a Go framework for building AI-powered agents with tool use.
The SDK supports multiple LLM providers (Gemini, Anthropic, Ollama) through a unified Client interface, and provides a tool system for extending agent capabilities.
Basic usage:
client, _ := gemini.New(ctx, os.Getenv("GEMINI_API_KEY"), "gemini-2.0-flash")
registry := sdk.NewRegistry()
registry.Register(tools.NewBash("/workspace"))
agent, _ := sdk.NewAgent("assistant", client, registry,
sdk.WithSystemPrompt("You are a helpful coding assistant."),
)
result, _ := agent.Run(ctx, "Find all Go files")
Index ¶
- Constants
- Variables
- func CalculateBackoff(config RetryConfig, attempt int) time.Duration
- func CanTransitionTo(from, to PlanLifecycleState) bool
- func CleanupOldCheckpoints(dir string, maxKeep int) error
- func CollectText(ctx context.Context, sr *StreamResponse) (string, error)
- func DeserializeHistory(serialized []SerializedContent) ([]*genai.Content, error)
- func GetBool(args map[string]any, key string) (bool, bool)
- func GetBoolDefault(args map[string]any, key string, defaultVal bool) bool
- func GetEmptyResultMessage(toolName string) string
- func GetInt(args map[string]any, key string) (int, bool)
- func GetIntDefault(args map[string]any, key string, defaultVal int) int
- func GetString(args map[string]any, key string) (string, bool)
- func GetStringDefault(args map[string]any, key, defaultVal string) string
- func GetToolResponseHint(toolName string) string
- func IsRateLimitError(err error) bool
- func IsRetryableError(err error) bool
- func IsTerminal(state PlanLifecycleState) bool
- func ListCheckpoints(dir string) ([]string, error)
- func ParseToolCallsFromText(text string) []*genai.FunctionCall
- func RestoreFromAgentCheckpoint(cp *AgentCheckpoint) ([]*genai.Content, error)
- func SanitizeFilename(name string) string
- func SaveCheckpoint(cp *Checkpoint, path string) error
- func SaveState(state *AgentState, path string) error
- func ShouldRetry(config RetryConfig, attempt int, err error) bool
- func ToolCallFallbackPrompt(toolDeclarations []*genai.FunctionDeclaration) string
- type APIError
- type ActionType
- type Agent
- type AgentCheckpoint
- type AgentConfig
- type AgentOption
- func WithAgentTimeout(d time.Duration) AgentOption
- func WithDelegation(ds *DelegationStrategy, runner *Runner) AgentOption
- func WithMaxTurns(n int) AgentOption
- func WithMemory(mem *SharedMemory) AgentOption
- func WithOnText(fn func(string)) AgentOption
- func WithOnToolCall(fn func(string, map[string]any)) AgentOption
- func WithPinnedContext(ctx string) AgentOption
- func WithPlanApprovalCallback(fn func(string)) AgentOption
- func WithPlanner(p *Planner) AgentOption
- func WithProgressCallback(fn func(AgentProgress)) AgentOption
- func WithReflector(r *Reflector) AgentOption
- func WithScratchpad(initial string) AgentOption
- func WithSystemPrompt(prompt string) AgentOption
- func WithToolTimeout(d time.Duration) AgentOption
- type AgentProgress
- type AgentResult
- type AgentState
- type AgentStatus
- type AgentTask
- type AgentType
- type ChangeEvent
- type Checkpoint
- type CheckpointConfig
- type CircuitBreaker
- type CircuitState
- type Client
- type ClientPool
- type ContextSnapshot
- func (cs *ContextSnapshot) AddCriticalResult(toolName, summary, details string)
- func (cs *ContextSnapshot) AddDecision(decision string)
- func (cs *ContextSnapshot) AddDiscovery(discovery string)
- func (cs *ContextSnapshot) AddErrorPattern(pattern, solution string)
- func (cs *ContextSnapshot) AddKeyFile(path, summary string)
- func (cs *ContextSnapshot) AddRequirement(requirement string)
- type CoordinatedTask
- type Coordinator
- func (c *Coordinator) AddTask(id, prompt string, agentType AgentType, priority TaskPriority, deps []string)
- func (c *Coordinator) CancelTask(id string) error
- func (c *Coordinator) GetStatus() CoordinatorStatus
- func (c *Coordinator) GetTask(id string) (*CoordinatedTask, bool)
- func (c *Coordinator) RunAll(ctx context.Context) (map[string]*AgentResult, error)
- func (c *Coordinator) RunParallel(ctx context.Context, tasks []AgentTask) ([]*AgentResult, error)
- func (c *Coordinator) RunSequential(ctx context.Context, tasks []AgentTask) ([]*AgentResult, error)
- func (c *Coordinator) SetOnTaskComplete(fn func(taskID string, task *CoordinatedTask))
- func (c *Coordinator) SetOnTaskStart(fn func(taskID string, task *CoordinatedTask))
- type CoordinatorStatus
- type CriticalResult
- type DefaultStatusCallback
- func (d *DefaultStatusCallback) OnError(err error, recoverable bool)
- func (d *DefaultStatusCallback) OnRateLimit(waitTime time.Duration)
- func (d *DefaultStatusCallback) OnRetry(attempt, maxAttempts int, delay time.Duration, reason string)
- func (d *DefaultStatusCallback) OnStreamIdle(elapsed time.Duration)
- func (d *DefaultStatusCallback) OnStreamResume()
- type DelegationContext
- type DelegationDecision
- type DelegationMetrics
- func (dm *DelegationMetrics) Clear() error
- func (dm *DelegationMetrics) GetBestTarget(fromAgent, contextType string, candidates []string) string
- func (dm *DelegationMetrics) GetRecentTrend(fromAgent, toAgent, contextType string) float64
- func (dm *DelegationMetrics) GetRuleWeight(fromAgent, toAgent, contextType string) float64
- func (dm *DelegationMetrics) GetStats() map[string]any
- func (dm *DelegationMetrics) GetSuccessRate(fromAgent, toAgent, contextType string) float64
- func (dm *DelegationMetrics) RecordExecution(fromAgent, toAgent, contextType string, success bool, duration time.Duration, ...)
- func (dm *DelegationMetrics) ShouldUseDelegation(fromAgent, toAgent, contextType string) bool
- type DelegationResult
- type DelegationRule
- type DelegationStrategy
- func (ds *DelegationStrategy) AddRule(rule DelegationRule)
- func (ds *DelegationStrategy) Evaluate(ctx DelegationContext) DelegationDecision
- func (ds *DelegationStrategy) Execute(ctx context.Context, runner *Runner, decision DelegationDecision) (*AgentResult, error)
- func (ds *DelegationStrategy) RecordOutcome(fromType, toType AgentType, ruleName string, success bool, ...)
- func (ds *DelegationStrategy) SetMetrics(metrics *DelegationMetrics)
- type ErrorPattern
- type ExecutionStrategy
- type ExecutionSummary
- type Executor
- type ExecutorOption
- type FallbackClient
- func (f *FallbackClient) Clone() Client
- func (f *FallbackClient) Close() error
- func (f *FallbackClient) GetModel() string
- func (f *FallbackClient) SendFunctionResponse(ctx context.Context, history []*genai.Content, ...) (*StreamResponse, error)
- func (f *FallbackClient) SendMessage(ctx context.Context, message string) (*StreamResponse, error)
- func (f *FallbackClient) SendMessageWithHistory(ctx context.Context, history []*genai.Content, message string) (*StreamResponse, error)
- func (f *FallbackClient) SetSystemInstruction(instruction string)
- func (f *FallbackClient) SetTools(tools []*genai.Tool)
- type FilePredictor
- type LRUCache
- func (c *LRUCache[K, V]) Cleanup() int
- func (c *LRUCache[K, V]) Clear()
- func (c *LRUCache[K, V]) Close()
- func (c *LRUCache[K, V]) Delete(key K)
- func (c *LRUCache[K, V]) Get(key K) (V, bool)
- func (c *LRUCache[K, V]) Keys() []K
- func (c *LRUCache[K, V]) Len() int
- func (c *LRUCache[K, V]) Set(key K, value V)
- type Middleware
- func ChainMiddleware(middlewares ...Middleware) Middleware
- func LoggingMiddleware(logger func(string)) Middleware
- func RetryMiddleware(config RetryConfig) Middleware
- func TimingMiddleware(onDuration func(name string, d time.Duration)) Middleware
- func ValidationMiddleware(validators map[string]func(args map[string]any) error) Middleware
- type MultimodalPart
- type NodeScore
- type PathStats
- type PathValidator
- type PlanChecker
- type PlanGoal
- type PlanLifecycle
- type PlanLifecycleState
- type PlanNode
- type PlanNodeStatus
- type PlanResult
- type PlanTree
- type PlannedAction
- type Planner
- func (p *Planner) BuildPlan(ctx context.Context, goal PlanGoal) (*PlanTree, error)
- func (p *Planner) ExpandNode(ctx context.Context, tree *PlanTree, nodeID string, context string) error
- func (p *Planner) GetReadyNodes(tree *PlanTree) []*PlanNode
- func (p *Planner) RecordResult(tree *PlanTree, nodeID string, result *PlanResult)
- func (p *Planner) ScoreNode(node *PlanNode, goal PlanGoal) NodeScore
- func (p *Planner) Search(ctx context.Context, tree *PlanTree, goal PlanGoal) ([]*PlanNode, error)
- func (p *Planner) Summary(tree *PlanTree) string
- func (p *Planner) WithPlannerConfig(config PlannerConfig) *Planner
- func (p *Planner) WithSearchStrategy(strategy SearchStrategy) *Planner
- type PlannerConfig
- type PredictedFile
- type PromptOptimizer
- func (po *PromptOptimizer) Clear() error
- func (po *PromptOptimizer) GetBestVariant(promptKey string) (*PromptVariant, bool)
- func (po *PromptOptimizer) GetVariants(promptKey string) []*PromptVariant
- func (po *PromptOptimizer) RecordOutcome(promptKey, variant string, success bool, tokens int, duration time.Duration)
- type PromptVariant
- type ReflectionResult
- type Reflector
- func (r *Reflector) AddPattern(pattern *regexp.Regexp, category, suggestion string, shouldRetry bool, ...)
- func (r *Reflector) Analyze(ctx context.Context, toolName string, args map[string]any, errorMsg string) *ReflectionResult
- func (r *Reflector) BuildIntervention(toolName string, args map[string]any, result *ReflectionResult, ...) string
- func (r *Reflector) LearnFromError(errorType, pattern, solution string, tags []string) error
- func (r *Reflector) SetPredictor(predictor FilePredictor)
- type Registry
- type Response
- type ResponseChunk
- type RetryConfig
- type RouteDecision
- type Router
- func (r *Router) Analyze(message string) *TaskComplexity
- func (r *Router) GetConversationMode() string
- func (r *Router) GetErrorRate() float64
- func (r *Router) GetStrategySuccessRate(strategy ExecutionStrategy) float64
- func (r *Router) RecordOutcome(message string, analysis *TaskComplexity, success bool)
- func (r *Router) RecordTypedOutcome(message string, taskType TaskType, strategy ExecutionStrategy, success bool)
- func (r *Router) Route(message string) *RouteDecision
- func (r *Router) SetPlanChecker(pc PlanChecker)
- func (r *Router) TrackOperation(toolName string, success bool)
- type RouterOption
- type Runner
- func (r *Runner) Cancel(agentID string) error
- func (r *Runner) GetResult(agentID string) (*AgentResult, bool)
- func (r *Runner) ListRunning() []string
- func (r *Runner) Memory() *SharedMemory
- func (r *Runner) Spawn(ctx context.Context, task AgentTask) (string, *AgentResult, error)
- func (r *Runner) SpawnAsync(ctx context.Context, task AgentTask) (string, error)
- func (r *Runner) Wait(ctx context.Context, agentID string) (*AgentResult, error)
- func (r *Runner) WaitAll(ctx context.Context) map[string]*AgentResult
- type RunnerConfig
- type RunnerOption
- func WithMaxAgents(n int) RunnerOption
- func WithOnAgentComplete(fn func(agentID string, result *AgentResult)) RunnerOption
- func WithOnAgentProgress(fn func(agentID string, text string)) RunnerOption
- func WithOnAgentStart(fn func(agentID string, task AgentTask)) RunnerOption
- func WithRunnerDelegation(ds *DelegationStrategy) RunnerOption
- func WithRunnerMaxTurns(n int) RunnerOption
- func WithRunnerReflector(ref *Reflector) RunnerOption
- func WithRunnerSystemPrompt(prompt string) RunnerOption
- func WithRunnerTimeout(d time.Duration) RunnerOption
- func WithSharedMemory(mem *SharedMemory) RunnerOption
- type SafetyLevel
- type ScoringWeights
- type SearchStrategy
- type SerializedAgentState
- type SerializedContent
- type SerializedFunc
- type SerializedPart
- type Session
- func (s *Session) AddContent(content *genai.Content)
- func (s *Session) AddModelResponse(content *genai.Content)
- func (s *Session) AddUserMessage(msg string)
- func (s *Session) Clear()
- func (s *Session) CreatedAt() time.Time
- func (s *Session) GetHistory() []*genai.Content
- func (s *Session) GetVersion() int64
- func (s *Session) ID() string
- func (s *Session) Len() int
- func (s *Session) ReplaceWithSummary(summary *genai.Content, recentMessages []*genai.Content)
- func (s *Session) SetMaxMessages(n int)
- func (s *Session) SetOnChange(fn func(ChangeEvent))
- func (s *Session) Summary() string
- type SessionStore
- type SharedEntry
- type SharedEntryType
- type SharedMemory
- func (sm *SharedMemory) CleanupExpired() int
- func (sm *SharedMemory) Clear()
- func (sm *SharedMemory) Delete(key string)
- func (sm *SharedMemory) Get(key string) (any, bool)
- func (sm *SharedMemory) GetContextSnapshot() *ContextSnapshot
- func (sm *SharedMemory) GetContextSnapshotForPrompt() string
- func (sm *SharedMemory) GetForContext(agentID string, maxEntries int) string
- func (sm *SharedMemory) Keys() []string
- func (sm *SharedMemory) ReadAll() []*SharedEntry
- func (sm *SharedMemory) ReadByType(entryType SharedEntryType) []*SharedEntry
- func (sm *SharedMemory) ReadEntry(key string) (*SharedEntry, bool)
- func (sm *SharedMemory) SaveContextSnapshot(snapshot *ContextSnapshot, sourceAgent string)
- func (sm *SharedMemory) Set(key string, value any, ttl time.Duration)
- func (sm *SharedMemory) Stats() SharedMemoryStats
- func (sm *SharedMemory) Subscribe(agentID string) <-chan *SharedEntry
- func (sm *SharedMemory) Unsubscribe(agentID string)
- func (sm *SharedMemory) Write(key string, value any, entryType SharedEntryType, sourceAgent string)
- func (sm *SharedMemory) WriteWithTTL(key string, value any, entryType SharedEntryType, sourceAgent string, ...)
- type SharedMemoryStats
- type SmartRouter
- type StatusCallback
- type StrategyMetrics
- type StrategyOptimizer
- type StreamHandler
- type StreamHandlerOption
- type StreamResponse
- type TaskComplexity
- type TaskPriority
- type TaskStatus
- type TaskType
- type Tool
- type ToolCallFromText
- type ToolDependencyClassifier
- func (c *ToolDependencyClassifier) AddWriteTool(name string)
- func (c *ToolDependencyClassifier) ClassifyDependencies(calls []*genai.FunctionCall) []ToolGroup
- func (c *ToolDependencyClassifier) IsWriteTool(name string) bool
- func (c *ToolDependencyClassifier) OptimizeForParallelism(calls []*genai.FunctionCall) []*genai.FunctionCall
- type ToolExecuteFunc
- type ToolGroup
- type ToolResult
- type ToolUsageGuide
- type ValidatingTool
- type ValidationError
Constants ¶
const ( // MaxRecentResults limits the number of recent results to track per path. MaxRecentResults = 20 // MinSamplesForConfidence is the minimum samples needed for confident decisions. MinSamplesForConfidence = 5 // MaxDelegationPaths is the maximum number of delegation paths to track. MaxDelegationPaths = 200 )
const ( // MaxFunctionCallsPerResponse limits the number of function calls processed per response. MaxFunctionCallsPerResponse = 10 // MaxConcurrentToolExecutions limits parallel goroutines for tool execution. MaxConcurrentToolExecutions = 5 )
const Version = "0.8.1"
Version is the current SDK version.
Variables ¶
var ErrCircuitOpen = errors.New("circuit breaker is open")
ErrCircuitOpen is returned when the circuit breaker is in the open state.
var ToolChainPatterns = map[string]string{
"explore_code": `To explore code:
1. glob - Find relevant files
2. read - Read key files
3. Analyze and summarize`,
"find_usage": `To find where something is used:
1. grep - Search for pattern
2. read - Read context around matches
3. Explain usage patterns`,
"understand_architecture": `To understand architecture:
1. glob - Find all source files
2. read - Read main.go and key files
3. tree - See directory structure
4. Summarize architecture`,
"debug_error": `To debug an error:
1. read - Read file with error
2. grep - Find related code
3. read - Read dependencies
4. Explain root cause and fix`,
"implement_feature": `To implement a feature:
1. glob + read - Understand existing code
2. Plan the changes
3. edit/write - Make changes
4. bash - Run tests
5. Summarize what was done`,
}
ToolChainPatterns provides recommended patterns for common tasks.
var ToolUsageGuides = map[string]ToolUsageGuide{
"read": {
Description: "Reads file contents with line numbers. Supports text files, PDFs, images, and Jupyter notebooks.",
WhenToUse: `Use when you need to:
- Understand what a file contains
- Find specific code in a known file
- Analyze code structure
- Check configuration files`,
HowToRespond: `After reading a file, ALWAYS explain:
1. What the file contains (purpose, main functions/classes)
2. Key code sections with line numbers
3. Patterns or issues you noticed
4. How it relates to the user's question`,
CommonMistakes: `DON'T:
- Read file and say nothing
- Just quote the entire file
- Give vague summaries like "it's a config file"`,
Examples: `GOOD: "I read main.go (245 lines). It's the entry point that:
- Lines 12-45: Sets up CLI with Cobra
- Lines 50-80: Initializes database
- Lines 85-120: Starts HTTP server
Key observation: Error handling at line 92 could miss connection timeouts."`,
},
"grep": {
Description: "Searches for regex patterns in files. Returns matching lines with file paths and line numbers.",
WhenToUse: `Use when you need to:
- Find where a function/variable is used
- Search for patterns across codebase
- Find all occurrences of a string
- Locate error messages or TODOs`,
HowToRespond: `After searching, ALWAYS explain:
1. How many matches found and in how many files
2. Group results by category/purpose
3. Highlight the most relevant matches
4. If no results, explain why and suggest alternatives`,
CommonMistakes: `DON'T:
- Just list raw grep output
- Say "no matches" without explanation
- Search without analyzing results`,
Examples: `GOOD: "Found 'handleError' in 12 locations across 5 files:
**Error Handlers (3 files):**
- handler/errors.go:25 - Main error handler
- middleware/recovery.go:12 - Panic recovery
**Usage (2 files):**
- api/users.go:45, 67, 89 - User endpoint errors
- api/orders.go:34 - Order validation errors
Pattern: All errors are wrapped with stack traces before returning."`,
},
"glob": {
Description: "Finds files matching a glob pattern. Supports ** for recursive matching.",
WhenToUse: `Use when you need to:
- Find files by extension (*.go, *.ts)
- Explore project structure
- Find files in specific directories
- Identify configuration files`,
HowToRespond: `After finding files, ALWAYS:
1. Summarize what types of files were found
2. Highlight important/relevant files
3. Suggest which files to read next
4. If no results, suggest alternative patterns`,
CommonMistakes: `DON'T:
- Just list file names without context
- Say "found X files" without explaining relevance
- Ignore the file structure implications`,
Examples: `GOOD: "Found 23 Go files in the project:
**Entry Points (cmd/):**
- cmd/api/main.go - API server
- cmd/worker/main.go - Background worker
**Core Logic (internal/):**
- internal/service/*.go (8 files) - Business logic
- internal/repo/*.go (5 files) - Data access
**Tests:**
- 7 test files (*_test.go) - Good coverage
Suggest reading: cmd/api/main.go first to understand the startup flow."`,
},
"bash": {
Description: "Executes shell commands. Default timeout is 30 seconds. Can run commands in background.",
WhenToUse: `Use when you need to:
- Run build commands (go build, npm install)
- Execute tests (go test, pytest)
- Run git commands
- Check system state (env, which, etc.)`,
HowToRespond: `After running a command, ALWAYS:
1. Summarize what the command did
2. Explain the output (don't just show it)
3. Highlight errors or warnings
4. Suggest next steps based on results`,
CommonMistakes: `DON'T:
- Run dangerous commands (rm -rf, etc.)
- Just show raw output without explanation
- Forget to explain what the command does
- Run long-running commands without background mode`,
Examples: `GOOD: "Ran 'go test ./...' - here's the summary:
**Results:** 45 passed, 2 failed, 3.2s total
**Failed Tests:**
1. TestUserCreate (user_test.go:34)
- Missing 'email' field in test fixture
2. TestDBConnection (db_test.go:12)
- Database connection timeout
**Fix suggestions:**
- Add email to test fixture at line 30
- Ensure test DB is running: docker-compose up -d"`,
},
"write": {
Description: "Creates or overwrites files with new content.",
WhenToUse: `Use when you need to:
- Create new files
- Replace entire file contents
- Create configuration files`,
HowToRespond: `After writing a file, ALWAYS:
1. Confirm what file was created/updated
2. Summarize what the file contains
3. Explain any important sections
4. Suggest verification steps`,
CommonMistakes: `DON'T:
- Overwrite files without reading first
- Create files without explaining what's in them
- Forget to suggest how to verify the change`,
Examples: `GOOD: "Created config.yaml with:
- Database settings (lines 1-10)
- API configuration (lines 12-25)
- Logging setup (lines 27-35)
To verify: Run 'go run cmd/api/main.go' and check logs."`,
},
"edit": {
Description: "Performs search and replace operations in files.",
WhenToUse: `Use when you need to:
- Modify specific parts of a file
- Fix bugs in code
- Update function signatures
- Refactor code`,
HowToRespond: `After editing, ALWAYS:
1. Explain what was changed
2. Show the before/after (briefly)
3. Explain why the change was made
4. Suggest verification steps`,
CommonMistakes: `DON'T:
- Edit without reading the file first
- Make changes without explaining them
- Say "fixed" without showing what changed`,
Examples: `GOOD: "Updated handler.go line 45-48:
**Before:** 'return user.Name' (nil pointer risk)
**After:** Added nil check before accessing Name
This prevents the panic when user is not authenticated.
To verify: Run 'go test ./internal/handler/...'."`,
},
"todo": {
Description: "Tracks tasks and progress for multi-step operations.",
WhenToUse: `Use when you need to:
- Break down complex tasks
- Track progress on multi-file changes
- Remember what's been done
- Show user the plan`,
HowToRespond: `When using todos:
1. Create clear, specific task items
2. Update status as you complete work
3. Reference todo items in responses`,
CommonMistakes: `DON'T:
- Create vague tasks like "fix stuff"
- Forget to update task status
- Create too many small tasks`,
Examples: `GOOD: "Here's the implementation plan:
1. [ ] Update User model with email field
2. [ ] Add validation in handler
3. [ ] Update tests
4. [ ] Update API documentation"`,
},
"tree": {
Description: "Displays directory structure in a tree format.",
WhenToUse: `Use when you need to:
- Understand project layout
- Find where files are organized
- Explain project structure to user`,
HowToRespond: `After showing tree, ALWAYS:
1. Explain the directory structure
2. Identify key directories
3. Point out patterns (cmd/, internal/, etc.)`,
CommonMistakes: `DON'T:
- Just show the tree without explanation
- Show entire tree for large projects`,
Examples: `GOOD: "Project follows standard Go layout:
- cmd/ - Application entry points
- internal/ - Private packages (can't be imported)
- pkg/ - Public packages (can be imported)
- config/ - Configuration files"`,
},
"diff": {
Description: "Shows differences between files or versions.",
WhenToUse: `Use when you need to:
- Compare two files
- Show what changed
- Review modifications`,
HowToRespond: `After showing diff, ALWAYS:
1. Summarize the changes
2. Explain why they matter
3. Highlight important modifications`,
CommonMistakes: `DON'T:
- Just show raw diff output
- Forget to explain significance of changes`,
Examples: `GOOD: "Key changes between versions:
- Added error handling (+15 lines)
- Removed deprecated function (-8 lines)
- Updated import paths"`,
},
}
ToolUsageGuides contains guidance for each tool to help the model use them correctly.
Functions ¶
func CalculateBackoff ¶
func CalculateBackoff(config RetryConfig, attempt int) time.Duration
CalculateBackoff returns the delay for the given attempt using exponential backoff with jitter. Attempt is 0-indexed (0 = first retry).
func CanTransitionTo ¶
func CanTransitionTo(from, to PlanLifecycleState) bool
CanTransitionTo checks if a state transition is valid.
func CleanupOldCheckpoints ¶
CleanupOldCheckpoints removes old checkpoints keeping only the most recent maxKeep.
func CollectText ¶
func CollectText(ctx context.Context, sr *StreamResponse) (string, error)
CollectText is a convenience function that collects only text from a stream.
func DeserializeHistory ¶
func DeserializeHistory(serialized []SerializedContent) ([]*genai.Content, error)
DeserializeHistory converts serialized history back to genai.Content.
func GetBoolDefault ¶
GetBoolDefault extracts a boolean argument with a default value.
func GetEmptyResultMessage ¶
GetEmptyResultMessage returns an appropriate message when a tool returns empty results.
func GetIntDefault ¶
GetIntDefault extracts an integer argument with a default value.
func GetStringDefault ¶
GetStringDefault extracts a string argument with a default value.
func GetToolResponseHint ¶
GetToolResponseHint returns a brief hint about how to respond after using a tool.
func IsRateLimitError ¶
IsRateLimitError checks if an error is specifically a rate limit error.
func IsRetryableError ¶
IsRetryableError checks if an error is retryable (rate limits, transient failures).
func IsTerminal ¶
func IsTerminal(state PlanLifecycleState) bool
IsTerminal checks if a state is terminal (no further transitions allowed).
func ListCheckpoints ¶
ListCheckpoints lists all checkpoint files in a directory.
func ParseToolCallsFromText ¶
func ParseToolCallsFromText(text string) []*genai.FunctionCall
ParseToolCallsFromText attempts to extract tool calls from model text output. This is used as a fallback when models don't support native function calling (e.g., Ollama models). Supports multiple formats:
- {"tool": "name", "args": {...}}
- {"name": "tool_name", "args": {...}}
- ```json\n{"tool": "name", "args": {...}}\n```
- Multiple tool calls in sequence
func RestoreFromAgentCheckpoint ¶
func RestoreFromAgentCheckpoint(cp *AgentCheckpoint) ([]*genai.Content, error)
RestoreFromAgentCheckpoint restores agent state from a checkpoint.
func SanitizeFilename ¶
SanitizeFilename removes dangerous characters from a filename.
func SaveCheckpoint ¶
func SaveCheckpoint(cp *Checkpoint, path string) error
SaveCheckpoint saves a checkpoint to a file.
func SaveState ¶
func SaveState(state *AgentState, path string) error
SaveState saves the agent state to a file.
func ShouldRetry ¶
func ShouldRetry(config RetryConfig, attempt int, err error) bool
ShouldRetry returns true if the error is retryable and we haven't exceeded max retries.
func ToolCallFallbackPrompt ¶
func ToolCallFallbackPrompt(toolDeclarations []*genai.FunctionDeclaration) string
ToolCallFallbackPrompt returns a system prompt addition that instructs models to output tool calls in a parseable JSON format. Use this for models that don't support native function calling.
Types ¶
type APIError ¶
APIError represents an error from an LLM provider API.
func NewAPIError ¶
NewAPIError creates a new APIError.
type ActionType ¶
type ActionType string
ActionType represents the type of a planned action.
const ( ActionToolCall ActionType = "tool_call" ActionDelegate ActionType = "delegate" ActionDecompose ActionType = "decompose" ActionVerify ActionType = "verify" )
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent represents an AI agent that can use tools to accomplish tasks.
func (*Agent) GetProgress ¶
func (a *Agent) GetProgress() AgentProgress
GetProgress returns the current agent progress (thread-safe).
func (*Agent) GetScratchpad ¶
GetScratchpad returns the agent's scratchpad contents.
func (*Agent) SetScratchpad ¶
SetScratchpad updates the agent's scratchpad.
type AgentCheckpoint ¶
type AgentCheckpoint struct {
ID string `json:"id"`
AgentState *SerializedAgentState `json:"agent_state"`
PlanState *PlanTree `json:"plan_state,omitempty"`
Timestamp time.Time `json:"timestamp"`
TriggerReason string `json:"trigger_reason"`
TurnNumber int `json:"turn_number"`
}
AgentCheckpoint captures a full snapshot of agent state for save/restore.
func LoadAgentCheckpoint ¶
func LoadAgentCheckpoint(path string) (*AgentCheckpoint, error)
LoadAgentCheckpoint loads a checkpoint from disk.
func SaveAgentCheckpoint ¶
func SaveAgentCheckpoint( agentName string, history []*genai.Content, turnCount int, maxTurns int, toolsUsed []string, scratchpad string, memory *SharedMemory, planTree *PlanTree, reason string, dir string, ) (*AgentCheckpoint, error)
SaveAgentCheckpoint creates a checkpoint from the current agent state.
type AgentConfig ¶
type AgentConfig struct {
SystemPrompt string
MaxTurns int
Timeout time.Duration
OnText func(text string)
OnToolCall func(name string, args map[string]any)
Memory *SharedMemory
}
AgentConfig holds the agent's configuration.
type AgentOption ¶
type AgentOption func(*Agent)
AgentOption configures an Agent.
func WithAgentTimeout ¶
func WithAgentTimeout(d time.Duration) AgentOption
WithAgentTimeout sets the overall timeout for the agent's Run() execution.
func WithDelegation ¶
func WithDelegation(ds *DelegationStrategy, runner *Runner) AgentOption
WithDelegation attaches a delegation strategy and runner for auto-delegation when stuck.
func WithMaxTurns ¶
func WithMaxTurns(n int) AgentOption
WithMaxTurns sets the maximum number of turns (LLM round-trips) the agent can take.
func WithMemory ¶
func WithMemory(mem *SharedMemory) AgentOption
WithMemory attaches a SharedMemory instance to the agent for inter-agent communication.
func WithOnText ¶
func WithOnText(fn func(string)) AgentOption
WithOnText sets a callback that is called when the agent produces text output.
func WithOnToolCall ¶
func WithOnToolCall(fn func(string, map[string]any)) AgentOption
WithOnToolCall sets a callback that is called when the agent invokes a tool.
func WithPinnedContext ¶
func WithPinnedContext(ctx string) AgentOption
WithPinnedContext injects additional context into the agent's system prompt.
func WithPlanApprovalCallback ¶
func WithPlanApprovalCallback(fn func(string)) AgentOption
WithPlanApprovalCallback sets a callback for plan approval notifications.
func WithPlanner ¶
func WithPlanner(p *Planner) AgentOption
WithPlanner attaches a planner for plan-driven execution.
func WithProgressCallback ¶
func WithProgressCallback(fn func(AgentProgress)) AgentOption
WithProgressCallback sets a callback invoked on each turn with progress updates.
func WithReflector ¶
func WithReflector(r *Reflector) AgentOption
WithReflector attaches an error reflector for automatic error analysis and recovery.
func WithScratchpad ¶
func WithScratchpad(initial string) AgentOption
WithScratchpad sets initial scratchpad content for the agent.
func WithSystemPrompt ¶
func WithSystemPrompt(prompt string) AgentOption
WithSystemPrompt sets the system prompt for the agent.
func WithToolTimeout ¶
func WithToolTimeout(d time.Duration) AgentOption
WithToolTimeout sets the per-tool execution timeout.
type AgentProgress ¶
type AgentProgress struct {
AgentID string
AgentType AgentType
CurrentStep int
TotalSteps int
CurrentAction string
StartTime time.Time
Elapsed time.Duration
EstimatedRemaining time.Duration
ToolsUsed []string
Status AgentStatus
}
AgentProgress tracks agent execution progress.
type AgentResult ¶
AgentResult represents the result of an agent's execution.
type AgentState ¶
type AgentState struct {
Name string `json:"name"`
Model string `json:"model,omitempty"`
History []SerializedContent `json:"history"`
StartTime time.Time `json:"start_time"`
TurnCount int `json:"turn_count"`
Metadata map[string]any `json:"metadata,omitempty"`
}
AgentState represents the serializable state of an agent for checkpointing.
func LoadState ¶
func LoadState(path string) (*AgentState, error)
LoadState loads an agent state from a file.
type AgentStatus ¶
type AgentStatus string
AgentStatus represents the current status of an agent.
const ( AgentStatusPending AgentStatus = "pending" AgentStatusRunning AgentStatus = "running" AgentStatusCompleted AgentStatus = "completed" AgentStatusFailed AgentStatus = "failed" AgentStatusCancelled AgentStatus = "cancelled" )
type AgentTask ¶
type AgentTask struct {
// Prompt is the task instruction.
Prompt string
// Type determines which tools are available.
Type AgentType
// Background indicates the task should run asynchronously.
Background bool
// Description is a short human-readable description.
Description string
// MaxTurns overrides the default max turns (0 = use default).
MaxTurns int
}
AgentTask describes a task to be executed by an agent.
type AgentType ¶
type AgentType string
AgentType defines the type of agent, which determines available tools.
const ( // AgentTypeGeneral has access to all tools. AgentTypeGeneral AgentType = "general" // AgentTypeExplore has access to read-only exploration tools. AgentTypeExplore AgentType = "explore" // AgentTypeBash has access to bash and basic file tools. AgentTypeBash AgentType = "bash" // AgentTypePlan has access to exploration and planning tools. AgentTypePlan AgentType = "plan" )
func ParseAgentType ¶
ParseAgentType parses a string into an AgentType.
func (AgentType) AllowedTools ¶
AllowedTools returns the tool names this agent type can use. Returns nil for general type, meaning all tools are allowed.
type ChangeEvent ¶
ChangeEvent describes a change to the session history.
type Checkpoint ¶
type Checkpoint struct {
State *AgentState `json:"state"`
CheckpointID string `json:"checkpoint_id"`
Reason string `json:"reason"`
Timestamp time.Time `json:"timestamp"`
}
Checkpoint wraps an AgentState with checkpoint metadata.
func LoadCheckpoint ¶
func LoadCheckpoint(path string) (*Checkpoint, error)
LoadCheckpoint loads a checkpoint from a file.
type CheckpointConfig ¶
type CheckpointConfig struct {
// Enabled controls whether auto-checkpointing is active.
Enabled bool
// Interval is the number of turns between auto-checkpoints.
Interval int
// Directory is where checkpoint files are saved.
Directory string
// MaxCheckpoints limits the number of retained checkpoints per agent.
MaxCheckpoints int
}
CheckpointConfig configures automatic checkpointing behavior.
func DefaultCheckpointConfig ¶
func DefaultCheckpointConfig() CheckpointConfig
DefaultCheckpointConfig returns sensible defaults for checkpointing.
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker implements the circuit breaker pattern for client calls.
func NewCircuitBreaker ¶
func NewCircuitBreaker(threshold int, resetTimeout time.Duration) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker. threshold is the number of consecutive failures before opening. resetTimeout is how long to wait before transitioning from open to half-open.
func (*CircuitBreaker) Execute ¶
func (cb *CircuitBreaker) Execute(ctx context.Context, fn func() error) error
Execute runs fn if the circuit allows it, recording success or failure.
func (*CircuitBreaker) Failures ¶
func (cb *CircuitBreaker) Failures() int
Failures returns the current failure count.
func (*CircuitBreaker) Reset ¶
func (cb *CircuitBreaker) Reset()
Reset resets the circuit breaker to the closed state.
func (*CircuitBreaker) State ¶
func (cb *CircuitBreaker) State() CircuitState
State returns the current circuit breaker state.
type CircuitState ¶
type CircuitState int
CircuitState represents the state of a circuit breaker.
const ( // CircuitClosed allows all requests through. CircuitClosed CircuitState = iota // CircuitHalfOpen allows a single test request through. CircuitHalfOpen // CircuitOpen rejects all requests. CircuitOpen )
func (CircuitState) String ¶
func (s CircuitState) String() string
String returns the string representation of the circuit state.
type Client ¶
type Client interface {
// SendMessage sends a message and returns a streaming response.
SendMessage(ctx context.Context, message string) (*StreamResponse, error)
// SendMessageWithHistory sends a message with conversation history.
SendMessageWithHistory(ctx context.Context, history []*genai.Content, message string) (*StreamResponse, error)
// SendFunctionResponse sends function call results back to the model.
SendFunctionResponse(ctx context.Context, history []*genai.Content, results []*genai.FunctionResponse) (*StreamResponse, error)
// SetTools sets the tools available for the model to use.
SetTools(tools []*genai.Tool)
// SetSystemInstruction sets the system-level instruction for the model.
SetSystemInstruction(instruction string)
// GetModel returns the model name.
GetModel() string
// Close closes the client connection.
Close() error
// Clone returns an independent copy of the client that shares the
// underlying HTTP/gRPC connection but has its own tools and system
// instruction state. This is required for concurrent agent usage.
Clone() Client
}
Client defines the interface for AI model interactions. Provider implementations (Gemini, Anthropic, Ollama) implement this interface.
func NewFallbackClient ¶
NewFallbackClient creates a Client that tries each provided client in order on failure. At least one client is required.
type ClientPool ¶
type ClientPool struct {
// contains filtered or unexported fields
}
ClientPool manages a pool of Client connections keyed by provider:model.
func NewClientPool ¶
func NewClientPool(maxSize int) *ClientPool
NewClientPool creates a new client pool with the given maximum size.
func (*ClientPool) Cleanup ¶
func (p *ClientPool) Cleanup(maxIdle time.Duration) int
Cleanup removes clients that have been idle for longer than the given duration.
func (*ClientPool) Get ¶
func (p *ClientPool) Get(provider, model string) Client
Get retrieves a client from the pool. Returns nil if not found.
func (*ClientPool) Put ¶
func (p *ClientPool) Put(provider, model string, client Client)
Put stores a client in the pool. Evicts the least recently used client if full.
func (*ClientPool) Size ¶
func (p *ClientPool) Size() int
Size returns the number of clients in the pool.
type ContextSnapshot ¶
type ContextSnapshot struct {
KeyFiles map[string]string `json:"key_files"`
Discoveries []string `json:"discoveries"`
ErrorPatterns map[string]string `json:"error_patterns"`
CriticalResults []CriticalResult `json:"critical_results"`
Requirements []string `json:"requirements"`
Decisions []string `json:"decisions"`
CreatedAt time.Time `json:"created_at"`
Source string `json:"source"`
}
ContextSnapshot captures key information for plan-to-execute transitions. This preserves critical context that would otherwise be lost during context compaction.
func NewContextSnapshot ¶
func NewContextSnapshot() *ContextSnapshot
NewContextSnapshot creates a new empty context snapshot.
func (*ContextSnapshot) AddCriticalResult ¶
func (cs *ContextSnapshot) AddCriticalResult(toolName, summary, details string)
AddCriticalResult adds a critical tool result to the snapshot.
func (*ContextSnapshot) AddDecision ¶
func (cs *ContextSnapshot) AddDecision(decision string)
AddDecision adds an architectural decision to the snapshot.
func (*ContextSnapshot) AddDiscovery ¶
func (cs *ContextSnapshot) AddDiscovery(discovery string)
AddDiscovery adds a discovery to the snapshot.
func (*ContextSnapshot) AddErrorPattern ¶
func (cs *ContextSnapshot) AddErrorPattern(pattern, solution string)
AddErrorPattern adds an error pattern and its solution.
func (*ContextSnapshot) AddKeyFile ¶
func (cs *ContextSnapshot) AddKeyFile(path, summary string)
AddKeyFile adds a key file with its summary to the snapshot.
func (*ContextSnapshot) AddRequirement ¶
func (cs *ContextSnapshot) AddRequirement(requirement string)
AddRequirement adds a requirement to the snapshot.
type CoordinatedTask ¶
type CoordinatedTask struct {
ID string
Prompt string
AgentType AgentType
Priority TaskPriority
Dependencies []string // task IDs that must complete first
Status TaskStatus
Result *AgentResult
}
CoordinatedTask is a task managed by the Coordinator.
type Coordinator ¶
type Coordinator struct {
// contains filtered or unexported fields
}
Coordinator manages parallel and sequential task execution with dependencies.
func NewCoordinator ¶
func NewCoordinator(runner *Runner, maxParallel int) *Coordinator
NewCoordinator creates a new task coordinator.
func (*Coordinator) AddTask ¶
func (c *Coordinator) AddTask(id, prompt string, agentType AgentType, priority TaskPriority, deps []string)
AddTask adds a new task to the coordinator.
func (*Coordinator) CancelTask ¶
func (c *Coordinator) CancelTask(id string) error
CancelTask cancels a task and its dependents.
func (*Coordinator) GetStatus ¶
func (c *Coordinator) GetStatus() CoordinatorStatus
GetStatus returns a summary of all task statuses.
func (*Coordinator) GetTask ¶
func (c *Coordinator) GetTask(id string) (*CoordinatedTask, bool)
GetTask returns a task by ID.
func (*Coordinator) RunAll ¶
func (c *Coordinator) RunAll(ctx context.Context) (map[string]*AgentResult, error)
RunAll executes all tasks respecting dependencies and parallelism limits.
func (*Coordinator) RunParallel ¶
func (c *Coordinator) RunParallel(ctx context.Context, tasks []AgentTask) ([]*AgentResult, error)
RunParallel runs a list of independent tasks in parallel (no dependencies).
func (*Coordinator) RunSequential ¶
func (c *Coordinator) RunSequential(ctx context.Context, tasks []AgentTask) ([]*AgentResult, error)
RunSequential runs tasks one after another.
func (*Coordinator) SetOnTaskComplete ¶
func (c *Coordinator) SetOnTaskComplete(fn func(taskID string, task *CoordinatedTask))
SetOnTaskComplete sets a callback invoked when a task completes.
func (*Coordinator) SetOnTaskStart ¶
func (c *Coordinator) SetOnTaskStart(fn func(taskID string, task *CoordinatedTask))
SetOnTaskStart sets a callback invoked when a task starts.
type CoordinatorStatus ¶
type CoordinatorStatus struct {
Total int
Pending int
Blocked int
Ready int
Running int
Completed int
Failed int
}
CoordinatorStatus summarizes the state of all coordinated tasks.
type CriticalResult ¶
type CriticalResult struct {
ToolName string `json:"tool_name"`
Summary string `json:"summary"`
Details string `json:"details"`
}
CriticalResult represents a tool result that should be preserved.
type DefaultStatusCallback ¶
type DefaultStatusCallback struct{}
DefaultStatusCallback is a no-op implementation of StatusCallback. Use this when you don't need status notifications.
func (*DefaultStatusCallback) OnError ¶
func (d *DefaultStatusCallback) OnError(err error, recoverable bool)
func (*DefaultStatusCallback) OnRateLimit ¶
func (d *DefaultStatusCallback) OnRateLimit(waitTime time.Duration)
func (*DefaultStatusCallback) OnRetry ¶
func (d *DefaultStatusCallback) OnRetry(attempt, maxAttempts int, delay time.Duration, reason string)
func (*DefaultStatusCallback) OnStreamIdle ¶
func (d *DefaultStatusCallback) OnStreamIdle(elapsed time.Duration)
func (*DefaultStatusCallback) OnStreamResume ¶
func (d *DefaultStatusCallback) OnStreamResume()
type DelegationContext ¶
type DelegationContext struct {
// AgentType is the current agent's type.
AgentType AgentType
// CurrentTurn is how many turns the agent has taken.
CurrentTurn int
// LastToolName is the most recently used tool.
LastToolName string
// LastToolError is the error from the most recent tool call, if any.
LastToolError string
// StuckCount is how many turns without progress.
StuckCount int
// DelegationDepth is the current delegation nesting level.
DelegationDepth int
}
DelegationContext provides information about the current agent state for evaluation.
type DelegationDecision ¶
type DelegationDecision struct {
// ShouldDelegate indicates if delegation is recommended.
ShouldDelegate bool
// TargetType is the recommended agent type to delegate to.
TargetType AgentType
// Reason explains why delegation was recommended.
Reason string
// Query is the suggested prompt for the delegated agent.
Query string
}
DelegationDecision represents the result of evaluating whether to delegate.
type DelegationMetrics ¶
type DelegationMetrics struct {
// PathMetrics tracks statistics by delegation path: "from_agent:to_agent:context_type"
PathMetrics map[string]*PathStats `json:"path_metrics"`
// RuleWeights are adjusted based on historical performance.
RuleWeights map[string]float64 `json:"rule_weights"`
// UpdatedAt is the last update timestamp.
UpdatedAt time.Time `json:"updated_at"`
// contains filtered or unexported fields
}
DelegationMetrics tracks success/failure rates for delegation decisions.
func NewDelegationMetrics ¶
func NewDelegationMetrics(configDir string) *DelegationMetrics
NewDelegationMetrics creates a new delegation metrics tracker. configDir is the directory where metrics will be persisted (e.g., ~/.config/gokin/). Pass "" to disable persistence.
func (*DelegationMetrics) Clear ¶
func (dm *DelegationMetrics) Clear() error
Clear removes all metrics.
func (*DelegationMetrics) GetBestTarget ¶
func (dm *DelegationMetrics) GetBestTarget(fromAgent, contextType string, candidates []string) string
GetBestTarget returns the best delegation target based on historical data.
func (*DelegationMetrics) GetRecentTrend ¶
func (dm *DelegationMetrics) GetRecentTrend(fromAgent, toAgent, contextType string) float64
GetRecentTrend analyzes recent executions to determine performance trend. Returns -1.0 (declining) to 1.0 (improving).
func (*DelegationMetrics) GetRuleWeight ¶
func (dm *DelegationMetrics) GetRuleWeight(fromAgent, toAgent, contextType string) float64
GetRuleWeight returns the weight for a delegation rule.
func (*DelegationMetrics) GetStats ¶
func (dm *DelegationMetrics) GetStats() map[string]any
GetStats returns overall statistics.
func (*DelegationMetrics) GetSuccessRate ¶
func (dm *DelegationMetrics) GetSuccessRate(fromAgent, toAgent, contextType string) float64
GetSuccessRate returns the success rate for a delegation path.
func (*DelegationMetrics) RecordExecution ¶
func (dm *DelegationMetrics) RecordExecution(fromAgent, toAgent, contextType string, success bool, duration time.Duration, errorType string)
RecordExecution records the outcome of a delegation.
func (*DelegationMetrics) ShouldUseDelegation ¶
func (dm *DelegationMetrics) ShouldUseDelegation(fromAgent, toAgent, contextType string) bool
ShouldUseDelegation returns whether delegation should be used based on historical performance.
type DelegationResult ¶
type DelegationResult struct {
Success bool `json:"success"`
Duration time.Duration `json:"duration"`
Timestamp time.Time `json:"timestamp"`
ErrorType string `json:"error_type,omitempty"`
}
DelegationResult represents a single delegation execution result.
type DelegationRule ¶
type DelegationRule struct {
// Name identifies this rule.
Name string
// FromType restricts to a specific agent type ("" = any).
FromType AgentType
// Condition returns true if this rule should fire.
Condition func(ctx DelegationContext) bool
// TargetType is the agent type to delegate to.
TargetType AgentType
// BuildQuery constructs the delegation prompt.
BuildQuery func(ctx DelegationContext) string
// Reason explains why this rule triggers.
Reason string
}
DelegationRule defines a rule for when delegation should occur.
type DelegationStrategy ¶
type DelegationStrategy struct {
// contains filtered or unexported fields
}
DelegationStrategy evaluates delegation rules and decides when to delegate.
func NewDelegationStrategy ¶
func NewDelegationStrategy() *DelegationStrategy
NewDelegationStrategy creates a new delegation strategy with default rules.
func (*DelegationStrategy) AddRule ¶
func (ds *DelegationStrategy) AddRule(rule DelegationRule)
AddRule adds a custom delegation rule.
func (*DelegationStrategy) Evaluate ¶
func (ds *DelegationStrategy) Evaluate(ctx DelegationContext) DelegationDecision
Evaluate checks all rules and returns a delegation decision.
func (*DelegationStrategy) Execute ¶
func (ds *DelegationStrategy) Execute(ctx context.Context, runner *Runner, decision DelegationDecision) (*AgentResult, error)
Execute runs delegation using the provided runner.
func (*DelegationStrategy) RecordOutcome ¶
func (ds *DelegationStrategy) RecordOutcome(fromType, toType AgentType, ruleName string, success bool, duration time.Duration, errorType string)
RecordOutcome records the result of a delegation for future optimization.
func (*DelegationStrategy) SetMetrics ¶
func (ds *DelegationStrategy) SetMetrics(metrics *DelegationMetrics)
SetMetrics sets the delegation metrics for data-driven decisions.
type ErrorPattern ¶
type ErrorPattern struct {
Pattern *regexp.Regexp
Category string
Suggestion string
ShouldRetry bool
Alternative string
ShouldRetryWithFix bool
SuggestedFix string
}
ErrorPattern defines a pattern-based error classification rule.
type ExecutionStrategy ¶
type ExecutionStrategy string
ExecutionStrategy determines how to execute the task.
const ( StrategyDirect ExecutionStrategy = "direct" StrategySingleTool ExecutionStrategy = "single_tool" StrategyExecutor ExecutionStrategy = "executor" StrategySubAgent ExecutionStrategy = "sub_agent" )
type ExecutionSummary ¶
type ExecutionSummary struct {
ToolName string `json:"tool_name"`
DisplayName string `json:"display_name"`
Action string `json:"action"`
Target string `json:"target"`
ExpectedTime time.Duration `json:"expected_time"`
RiskLevel SafetyLevel `json:"risk_level"`
UserVisible bool `json:"user_visible"`
RequiresApproval bool `json:"requires_approval"`
}
ExecutionSummary provides metadata about a tool execution for logging and approval flows.
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
Executor handles parallel execution of tool calls.
func NewExecutor ¶
func NewExecutor(registry *Registry, opts ...ExecutorOption) *Executor
NewExecutor creates a new tool executor.
func (*Executor) Execute ¶
func (e *Executor) Execute(ctx context.Context, calls []*genai.FunctionCall) ([]*genai.FunctionResponse, error)
Execute processes a list of function calls and returns function responses.
type ExecutorOption ¶
type ExecutorOption func(*Executor)
ExecutorOption configures the Executor.
func WithOnToolEnd ¶
func WithOnToolEnd(fn func(name string, result *ToolResult)) ExecutorOption
WithOnToolEnd sets a callback invoked when a tool finishes executing.
func WithOnToolStart ¶
func WithOnToolStart(fn func(name string, args map[string]any)) ExecutorOption
WithOnToolStart sets a callback invoked when a tool starts executing.
func WithTimeout ¶
func WithTimeout(d time.Duration) ExecutorOption
WithTimeout sets the per-tool execution timeout.
type FallbackClient ¶
type FallbackClient struct {
// contains filtered or unexported fields
}
FallbackClient wraps multiple Clients and automatically fails over to the next one on error.
func (*FallbackClient) Clone ¶
func (f *FallbackClient) Clone() Client
func (*FallbackClient) Close ¶
func (f *FallbackClient) Close() error
func (*FallbackClient) GetModel ¶
func (f *FallbackClient) GetModel() string
func (*FallbackClient) SendFunctionResponse ¶
func (f *FallbackClient) SendFunctionResponse(ctx context.Context, history []*genai.Content, results []*genai.FunctionResponse) (*StreamResponse, error)
func (*FallbackClient) SendMessage ¶
func (f *FallbackClient) SendMessage(ctx context.Context, message string) (*StreamResponse, error)
func (*FallbackClient) SendMessageWithHistory ¶
func (f *FallbackClient) SendMessageWithHistory(ctx context.Context, history []*genai.Content, message string) (*StreamResponse, error)
func (*FallbackClient) SetSystemInstruction ¶
func (f *FallbackClient) SetSystemInstruction(instruction string)
func (*FallbackClient) SetTools ¶
func (f *FallbackClient) SetTools(tools []*genai.Tool)
type FilePredictor ¶
type FilePredictor interface {
PredictFiles(currentFile string, limit int) []PredictedFile
}
FilePredictor predicts related files based on access patterns.
type LRUCache ¶
type LRUCache[K comparable, V any] struct { // contains filtered or unexported fields }
LRUCache is a generic LRU cache with TTL support and background cleanup.
func NewLRUCache ¶
NewLRUCache creates a new LRU cache with the given capacity and TTL. A background goroutine periodically removes expired entries. Call Close() to stop the background cleanup goroutine.
func (*LRUCache[K, V]) Clear ¶
func (c *LRUCache[K, V]) Clear()
Clear removes all entries from the cache.
func (*LRUCache[K, V]) Close ¶
func (c *LRUCache[K, V]) Close()
Close stops the background cleanup goroutine and releases resources.
func (*LRUCache[K, V]) Delete ¶
func (c *LRUCache[K, V]) Delete(key K)
Delete removes a key from the cache.
func (*LRUCache[K, V]) Get ¶
Get retrieves a value from the cache. Returns the value and true if found and not expired, zero value and false otherwise.
func (*LRUCache[K, V]) Keys ¶
func (c *LRUCache[K, V]) Keys() []K
Keys returns all non-expired keys in the cache.
type Middleware ¶
type Middleware func(next ToolExecuteFunc) ToolExecuteFunc
Middleware wraps a ToolExecuteFunc with additional behavior.
func ChainMiddleware ¶
func ChainMiddleware(middlewares ...Middleware) Middleware
ChainMiddleware composes multiple middleware into a single middleware. Middleware is applied in order: first middleware is outermost.
func LoggingMiddleware ¶
func LoggingMiddleware(logger func(string)) Middleware
LoggingMiddleware logs tool calls and their results.
func RetryMiddleware ¶
func RetryMiddleware(config RetryConfig) Middleware
RetryMiddleware retries failed tool calls.
func TimingMiddleware ¶
func TimingMiddleware(onDuration func(name string, d time.Duration)) Middleware
TimingMiddleware measures tool execution duration.
func ValidationMiddleware ¶
func ValidationMiddleware(validators map[string]func(args map[string]any) error) Middleware
ValidationMiddleware validates tool arguments before execution.
type MultimodalPart ¶
MultimodalPart represents a non-text part of a tool result (e.g., image, binary).
type NodeScore ¶
type NodeScore struct {
// SuccessProb is the estimated probability of success (0.0 - 1.0).
SuccessProb float64
// CostEstimate is the estimated cost (tokens/time) normalized to 0.0 - 1.0.
CostEstimate float64
// GoalProgress is how much progress this node represents toward the goal (0.0 - 1.0).
GoalProgress float64
// Composite is the weighted sum of all components.
Composite float64
}
NodeScore represents a multi-component score for a plan node.
type PathStats ¶
type PathStats struct {
FromAgent string `json:"from_agent"`
ToAgent string `json:"to_agent"`
ContextType string `json:"context_type"`
SuccessCount int `json:"success_count"`
FailureCount int `json:"failure_count"`
TotalTime time.Duration `json:"total_time"`
// RecentResults stores recent executions for trend analysis.
RecentResults []DelegationResult `json:"recent_results"`
LastUsed time.Time `json:"last_used"`
}
PathStats tracks statistics for a specific delegation path.
type PathValidator ¶
type PathValidator struct {
// contains filtered or unexported fields
}
PathValidator validates file paths to prevent directory traversal attacks.
func NewPathValidator ¶
func NewPathValidator(allowedDirs []string) *PathValidator
NewPathValidator creates a new path validator with the given allowed directories.
func NewPathValidatorWithSymlinks ¶
func NewPathValidatorWithSymlinks(allowedDirs []string) *PathValidator
NewPathValidatorWithSymlinks creates a path validator that allows symlinks.
func (*PathValidator) IsWithinAllowed ¶
func (v *PathValidator) IsWithinAllowed(absPath string) bool
IsWithinAllowed checks if the path is within any of the allowed directories.
type PlanChecker ¶
type PlanChecker interface {
IsActive() bool
}
PlanChecker allows the router to check if a plan is actively executing.
type PlanGoal ¶
type PlanGoal struct {
Description string `json:"description"`
SuccessCriteria []string `json:"success_criteria"`
MaxDepth int `json:"max_depth"`
}
PlanGoal defines the objective for planning.
type PlanLifecycle ¶
type PlanLifecycle struct {
PlanID string `json:"plan_id"`
State PlanLifecycleState `json:"state"`
Tree *PlanTree `json:"tree"`
Version int `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Replan tracking
ReplanCount int `json:"replan_count"`
ReplanReason string `json:"replan_reason,omitempty"`
// contains filtered or unexported fields
}
PlanLifecycle manages the lifecycle of a plan from draft to completion.
func NewPlanLifecycle ¶
func NewPlanLifecycle(planID string, tree *PlanTree) *PlanLifecycle
NewPlanLifecycle creates a new plan lifecycle in draft state.
func (*PlanLifecycle) GetState ¶
func (lc *PlanLifecycle) GetState() PlanLifecycleState
GetState returns the current state (thread-safe).
func (*PlanLifecycle) IsActive ¶
func (lc *PlanLifecycle) IsActive() bool
IsActive returns true if the plan is in an active (non-terminal) state.
func (*PlanLifecycle) RequestReplan ¶
func (lc *PlanLifecycle) RequestReplan(reason string) error
RequestReplan marks the plan for replanning by transitioning to draft.
func (*PlanLifecycle) Summary ¶
func (lc *PlanLifecycle) Summary() string
Summary returns a brief summary of the plan lifecycle.
func (*PlanLifecycle) TransitionTo ¶
func (lc *PlanLifecycle) TransitionTo(state PlanLifecycleState) error
TransitionTo moves the plan to a new lifecycle state.
type PlanLifecycleState ¶
type PlanLifecycleState string
PlanLifecycleState represents the state of a plan lifecycle.
const ( PlanStateDraft PlanLifecycleState = "draft" PlanStateApproved PlanLifecycleState = "approved" PlanStateExecuting PlanLifecycleState = "executing" PlanStateCompleted PlanLifecycleState = "completed" PlanStateFailed PlanLifecycleState = "failed" PlanStatePaused PlanLifecycleState = "paused" )
type PlanNode ¶
type PlanNode struct {
ID string `json:"id"`
ParentID string `json:"parent_id,omitempty"`
Action *PlannedAction `json:"action"`
Status PlanNodeStatus `json:"status"`
Score float64 `json:"score"`
Children []*PlanNode `json:"children,omitempty"`
Result *PlanResult `json:"result,omitempty"`
// MCTS statistics
Visits int `json:"visits"`
TotalReward float64 `json:"total_reward"`
}
PlanNode represents a node in the plan tree.
type PlanNodeStatus ¶
type PlanNodeStatus string
PlanNodeStatus represents the status of a plan node.
const ( PlanNodePending PlanNodeStatus = "pending" PlanNodeRunning PlanNodeStatus = "running" PlanNodeCompleted PlanNodeStatus = "completed" PlanNodeFailed PlanNodeStatus = "failed" PlanNodeSkipped PlanNodeStatus = "skipped" )
type PlanResult ¶
type PlanResult struct {
Output string `json:"output"`
Error string `json:"error,omitempty"`
Success bool `json:"success"`
}
PlanResult captures the output of executing a plan node.
type PlanTree ¶
type PlanTree struct {
Root *PlanNode `json:"root"`
BestPath []*PlanNode `json:"-"`
TotalNodes int `json:"total_nodes"`
// contains filtered or unexported fields
}
PlanTree is the tree of plan nodes.
type PlannedAction ¶
type PlannedAction struct {
Type ActionType `json:"type"`
AgentType AgentType `json:"agent_type,omitempty"`
Prompt string `json:"prompt"`
ToolName string `json:"tool_name,omitempty"`
ToolArgs map[string]any `json:"tool_args,omitempty"`
NodeID string `json:"node_id"`
Prerequisites []string `json:"prerequisites,omitempty"`
}
PlannedAction describes what a plan step should do.
type Planner ¶
type Planner struct {
// contains filtered or unexported fields
}
Planner builds and manages plan trees using LLM-based action generation.
func NewPlanner ¶
func NewPlanner(client Client, optimizer *StrategyOptimizer) *Planner
NewPlanner creates a new planner.
func (*Planner) BuildPlan ¶
BuildPlan generates a plan tree for the given goal and optionally applies search.
func (*Planner) ExpandNode ¶
func (p *Planner) ExpandNode(ctx context.Context, tree *PlanTree, nodeID string, context string) error
ExpandNode generates child actions for a node.
func (*Planner) GetReadyNodes ¶
GetReadyNodes returns nodes that are ready to execute. A node is ready if it's pending, its parent is completed (or it's root), and all its prerequisites are completed.
func (*Planner) RecordResult ¶
func (p *Planner) RecordResult(tree *PlanTree, nodeID string, result *PlanResult)
RecordResult records the outcome of executing a plan node.
func (*Planner) Search ¶
Search dispatches to the configured search algorithm and returns the best path.
func (*Planner) WithPlannerConfig ¶
func (p *Planner) WithPlannerConfig(config PlannerConfig) *Planner
WithPlannerConfig sets the planner configuration.
func (*Planner) WithSearchStrategy ¶
func (p *Planner) WithSearchStrategy(strategy SearchStrategy) *Planner
WithSearchStrategy sets the search strategy.
type PlannerConfig ¶
type PlannerConfig struct {
// MCTSIterations is the number of MCTS simulation iterations.
MCTSIterations int
// ExplorationC is the UCB1 exploration constant (default: 1.414).
ExplorationC float64
// MaxTreeDepth limits the depth of the plan tree.
MaxTreeDepth int
// MaxTreeNodes limits the total number of nodes in the plan tree.
MaxTreeNodes int
// Weights for multi-component scoring.
Weights ScoringWeights
}
PlannerConfig holds configuration for the planner.
func DefaultPlannerConfig ¶
func DefaultPlannerConfig() PlannerConfig
DefaultPlannerConfig returns sensible defaults for the planner.
type PredictedFile ¶
PredictedFile represents a file predicted by the file predictor.
type PromptOptimizer ¶
type PromptOptimizer struct {
// contains filtered or unexported fields
}
PromptOptimizer A/B tests prompt variants and tracks performance.
func NewPromptOptimizer ¶
func NewPromptOptimizer(storePath string) *PromptOptimizer
NewPromptOptimizer creates a new prompt optimizer.
func (*PromptOptimizer) Clear ¶
func (po *PromptOptimizer) Clear() error
Clear removes all variants.
func (*PromptOptimizer) GetBestVariant ¶
func (po *PromptOptimizer) GetBestVariant(promptKey string) (*PromptVariant, bool)
GetBestVariant returns the best performing variant for a prompt key.
func (*PromptOptimizer) GetVariants ¶
func (po *PromptOptimizer) GetVariants(promptKey string) []*PromptVariant
GetVariants returns all variants for a prompt key, sorted by score.
func (*PromptOptimizer) RecordOutcome ¶
func (po *PromptOptimizer) RecordOutcome(promptKey, variant string, success bool, tokens int, duration time.Duration)
RecordOutcome records the outcome of a prompt execution.
type PromptVariant ¶
type PromptVariant struct {
ID string `json:"id"`
BasePrompt string `json:"base_prompt"`
Variation string `json:"variation"`
SuccessRate float64 `json:"success_rate"`
AvgTokens int `json:"avg_tokens"`
AvgDuration time.Duration `json:"avg_duration"`
UseCount int `json:"use_count"`
SuccessCount int `json:"success_count"`
FailureCount int `json:"failure_count"`
LastUsed time.Time `json:"last_used"`
Created time.Time `json:"created"`
}
PromptVariant represents a variation of a prompt with performance metrics.
func (*PromptVariant) Score ¶
func (pv *PromptVariant) Score() float64
Score calculates a combined score for ranking variants.
type ReflectionResult ¶
type ReflectionResult struct {
Category string
Suggestion string
RootCause string
ShouldRetry bool
PredictedFiles []string
Alternative string
Matched bool
}
ReflectionResult contains the analysis of an error.
type Reflector ¶
type Reflector struct {
// contains filtered or unexported fields
}
Reflector analyzes errors with regex patterns and optional LLM semantic fallback.
func NewReflector ¶
func NewReflector(client Client, errorStore *memory.ErrorStore) *Reflector
NewReflector creates a new error reflector. client is optional — if nil, semantic analysis is disabled. errorStore is optional — if nil, learning is disabled.
func (*Reflector) AddPattern ¶
func (r *Reflector) AddPattern(pattern *regexp.Regexp, category, suggestion string, shouldRetry bool, alternative string)
AddPattern adds a custom error pattern.
func (*Reflector) Analyze ¶
func (r *Reflector) Analyze(ctx context.Context, toolName string, args map[string]any, errorMsg string) *ReflectionResult
Analyze classifies an error and returns suggestions. Order: 1) learned errors, 2) pattern matching, 3) semantic analysis (+ learning), 4) fallback.
func (*Reflector) BuildIntervention ¶
func (r *Reflector) BuildIntervention(toolName string, args map[string]any, result *ReflectionResult, errorMsg string) string
BuildIntervention creates a formatted intervention message.
func (*Reflector) LearnFromError ¶
LearnFromError records an error pattern in the error store.
func (*Reflector) SetPredictor ¶
func (r *Reflector) SetPredictor(predictor FilePredictor)
SetPredictor sets the file predictor for file_not_found suggestions.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages the collection of available tools.
func (*Registry) GeminiTools ¶
GeminiTools returns the tools in Gemini format.
func (*Registry) MustRegister ¶
MustRegister adds a tool to the registry and panics on error.
type Response ¶
type Response struct {
// Text is the accumulated text response.
Text string
// FunctionCalls contains all function calls from the response.
FunctionCalls []*genai.FunctionCall
// Parts contains all original parts from the response.
Parts []*genai.Part
// FinishReason indicates why the response finished.
FinishReason genai.FinishReason
// InputTokens from API usage metadata.
InputTokens int
// OutputTokens from API usage metadata.
OutputTokens int
}
Response represents a complete response from the model.
func ProcessStream ¶
func ProcessStream(ctx context.Context, sr *StreamResponse, handler *StreamHandler) (*Response, error)
ProcessStream processes a streaming response with the given handler, accumulating results into a Response.
type ResponseChunk ¶
type ResponseChunk struct {
// Text contains any text content in this chunk.
Text string
// FunctionCalls contains any function calls in this chunk.
FunctionCalls []*genai.FunctionCall
// Parts contains the original parts from the response.
Parts []*genai.Part
// Error contains any error that occurred.
Error error
// Done indicates if this is the final chunk.
Done bool
// FinishReason indicates why the response finished.
FinishReason genai.FinishReason
// InputTokens from API usage metadata (if available).
InputTokens int
// OutputTokens from API usage metadata (if available).
OutputTokens int
}
ResponseChunk represents a single chunk in a streaming response.
type RetryConfig ¶
type RetryConfig struct {
// MaxRetries is the maximum number of retry attempts.
MaxRetries int
// InitialDelay is the base delay before the first retry.
InitialDelay time.Duration
// MaxDelay caps the maximum delay between retries.
MaxDelay time.Duration
// Multiplier is the exponential backoff multiplier (default: 2.0).
Multiplier float64
}
RetryConfig configures retry behavior with exponential backoff.
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns a sensible default retry configuration.
type RouteDecision ¶
type RouteDecision struct {
Analysis *TaskComplexity `json:"analysis"`
Message string `json:"message"`
Handler string `json:"handler"` // "direct", "executor", "sub_agent"
SubAgentType string `json:"sub_agent_type,omitempty"`
Background bool `json:"background"`
Reasoning string `json:"reasoning"`
SuggestedModel string `json:"suggested_model,omitempty"`
ThinkingBudget int32 `json:"thinking_budget,omitempty"`
}
RouteDecision represents the routing decision for a task.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router determines the optimal execution strategy for incoming tasks and routes them to the appropriate handler.
func (*Router) Analyze ¶
func (r *Router) Analyze(message string) *TaskComplexity
Analyze returns the task analysis without executing.
func (*Router) GetConversationMode ¶
GetConversationMode returns the current inferred conversation mode.
func (*Router) GetErrorRate ¶
GetErrorRate returns the recent error rate.
func (*Router) GetStrategySuccessRate ¶
func (r *Router) GetStrategySuccessRate(strategy ExecutionStrategy) float64
GetStrategySuccessRate returns the historical success rate for a strategy (exported).
func (*Router) RecordOutcome ¶
func (r *Router) RecordOutcome(message string, analysis *TaskComplexity, success bool)
RecordOutcome records whether a routing decision was successful.
func (*Router) RecordTypedOutcome ¶
func (r *Router) RecordTypedOutcome(message string, taskType TaskType, strategy ExecutionStrategy, success bool)
RecordTypedOutcome records an outcome with explicit task type and strategy.
func (*Router) Route ¶
func (r *Router) Route(message string) *RouteDecision
Route determines the best execution strategy for a message.
func (*Router) SetPlanChecker ¶
func (r *Router) SetPlanChecker(pc PlanChecker)
SetPlanChecker sets a plan checker for plan-aware routing.
func (*Router) TrackOperation ¶
TrackOperation records an operation outcome for context awareness.
type RouterOption ¶
type RouterOption func(*Router)
RouterOption configures the Router.
func WithDecomposeThreshold ¶
func WithDecomposeThreshold(threshold int) RouterOption
WithDecomposeThreshold sets the complexity score at which tasks are decomposed.
func WithFastModel ¶
func WithFastModel(model string) RouterOption
WithFastModel sets the model name to use for simple tasks.
func WithParallelThreshold ¶
func WithParallelThreshold(threshold int) RouterOption
WithParallelThreshold sets the complexity score at which parallel execution is used.
func WithRouterEnabled ¶
func WithRouterEnabled(enabled bool) RouterOption
WithRouterEnabled enables or disables routing.
func WithRouterOptimizer ¶
func WithRouterOptimizer(optimizer *StrategyOptimizer) RouterOption
WithRouterOptimizer sets the strategy optimizer for learning-based routing.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner manages multiple agents and their lifecycle.
func NewRunner ¶
func NewRunner(client Client, registry *Registry, opts ...RunnerOption) *Runner
NewRunner creates a new multi-agent runner.
func (*Runner) GetResult ¶
func (r *Runner) GetResult(agentID string) (*AgentResult, bool)
GetResult returns the result for a specific agent.
func (*Runner) ListRunning ¶
ListRunning returns IDs of currently running agents.
func (*Runner) Memory ¶
func (r *Runner) Memory() *SharedMemory
Memory returns the shared memory instance.
func (*Runner) SpawnAsync ¶
SpawnAsync starts a new agent asynchronously and returns its ID.
type RunnerConfig ¶
type RunnerConfig struct {
// OnAgentStart is called when an agent begins executing.
OnAgentStart func(agentID string, task AgentTask)
// OnAgentComplete is called when an agent finishes.
OnAgentComplete func(agentID string, result *AgentResult)
// OnAgentProgress is called with text output from agents.
OnAgentProgress func(agentID string, text string)
// DefaultMaxTurns is the default max turns for spawned agents.
DefaultMaxTurns int
// DefaultTimeout is the default timeout for spawned agents.
DefaultTimeout time.Duration
// SystemPrompt is the default system prompt for spawned agents.
SystemPrompt string
// MaxAgents limits concurrent running agents (0 = unlimited).
MaxAgents int
}
RunnerConfig configures the Runner.
type RunnerOption ¶
type RunnerOption func(*Runner)
RunnerOption configures a Runner.
func WithMaxAgents ¶
func WithMaxAgents(n int) RunnerOption
WithMaxAgents sets the maximum number of concurrent agents.
func WithOnAgentComplete ¶
func WithOnAgentComplete(fn func(agentID string, result *AgentResult)) RunnerOption
WithOnAgentComplete sets a callback invoked when an agent completes.
func WithOnAgentProgress ¶
func WithOnAgentProgress(fn func(agentID string, text string)) RunnerOption
WithOnAgentProgress sets a callback invoked for agent text output.
func WithOnAgentStart ¶
func WithOnAgentStart(fn func(agentID string, task AgentTask)) RunnerOption
WithOnAgentStart sets a callback invoked when an agent starts.
func WithRunnerDelegation ¶
func WithRunnerDelegation(ds *DelegationStrategy) RunnerOption
WithRunnerDelegation sets a delegation strategy to propagate to spawned agents.
func WithRunnerMaxTurns ¶
func WithRunnerMaxTurns(n int) RunnerOption
WithRunnerMaxTurns sets the default max turns for spawned agents.
func WithRunnerReflector ¶
func WithRunnerReflector(ref *Reflector) RunnerOption
WithRunnerReflector sets a reflector to propagate to spawned agents.
func WithRunnerSystemPrompt ¶
func WithRunnerSystemPrompt(prompt string) RunnerOption
WithRunnerSystemPrompt sets the default system prompt for spawned agents.
func WithRunnerTimeout ¶
func WithRunnerTimeout(d time.Duration) RunnerOption
WithRunnerTimeout sets the default timeout for spawned agents.
func WithSharedMemory ¶
func WithSharedMemory(mem *SharedMemory) RunnerOption
WithSharedMemory sets a custom SharedMemory instance for the runner.
type SafetyLevel ¶
type SafetyLevel string
SafetyLevel indicates the risk level of a tool operation.
const ( SafetyLevelSafe SafetyLevel = "safe" SafetyLevelCaution SafetyLevel = "caution" SafetyLevelDangerous SafetyLevel = "dangerous" SafetyLevelCritical SafetyLevel = "critical" )
type ScoringWeights ¶
ScoringWeights configures the relative importance of scoring components.
func DefaultScoringWeights ¶
func DefaultScoringWeights() ScoringWeights
DefaultScoringWeights returns the default scoring weights.
type SearchStrategy ¶
type SearchStrategy string
SearchStrategy defines how the planner explores the plan tree.
const ( SearchBeam SearchStrategy = "beam" SearchMCTS SearchStrategy = "mcts" SearchAStar SearchStrategy = "astar" )
type SerializedAgentState ¶
type SerializedAgentState struct {
History []SerializedContent `json:"history"`
MaxTurns int `json:"max_turns"`
TurnCount int `json:"turn_count"`
ToolsUsed []string `json:"tools_used,omitempty"`
Scratchpad string `json:"scratchpad,omitempty"`
}
SerializedAgentState holds the serializable parts of agent execution state.
type SerializedContent ¶
type SerializedContent struct {
Role string `json:"role"`
Parts []SerializedPart `json:"parts"`
}
SerializedContent represents a serializable conversation content.
func SerializeHistory ¶
func SerializeHistory(history []*genai.Content) []SerializedContent
SerializeHistory converts genai.Content history to serializable form.
type SerializedFunc ¶
type SerializedFunc struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Args map[string]any `json:"args,omitempty"`
Response map[string]any `json:"response,omitempty"`
}
SerializedFunc represents a serializable function call or response.
type SerializedPart ¶
type SerializedPart struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
FunctionCall *SerializedFunc `json:"function_call,omitempty"`
FunctionResp *SerializedFunc `json:"function_response,omitempty"`
}
SerializedPart represents a serializable content part.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session provides thread-safe conversation history management.
func NewSession ¶
NewSession creates a new session with the given ID.
func (*Session) AddContent ¶
AddContent appends any content to the history.
func (*Session) AddModelResponse ¶
AddModelResponse appends a model response to the history.
func (*Session) AddUserMessage ¶
AddUserMessage appends a user message to the history.
func (*Session) GetHistory ¶
GetHistory returns a copy of the conversation history.
func (*Session) GetVersion ¶
GetVersion returns the current version number.
func (*Session) ReplaceWithSummary ¶
ReplaceWithSummary replaces the history with a summary plus recent messages.
func (*Session) SetMaxMessages ¶
SetMaxMessages sets the maximum number of messages before trimming.
func (*Session) SetOnChange ¶
func (s *Session) SetOnChange(fn func(ChangeEvent))
SetOnChange sets a callback invoked when the history changes.
type SessionStore ¶
type SessionStore struct {
// contains filtered or unexported fields
}
SessionStore provides file-based persistence for sessions.
func NewSessionStore ¶
func NewSessionStore(dir string) *SessionStore
NewSessionStore creates a new store that saves sessions in the given directory.
func (*SessionStore) Delete ¶
func (ss *SessionStore) Delete(id string) error
Delete removes a session from disk.
func (*SessionStore) List ¶
func (ss *SessionStore) List() ([]string, error)
List returns all saved session IDs.
func (*SessionStore) Load ¶
func (ss *SessionStore) Load(id string) (*Session, error)
Load reads a session from disk.
func (*SessionStore) Save ¶
func (ss *SessionStore) Save(session *Session) error
Save persists a session to disk.
type SharedEntry ¶
type SharedEntry struct {
}
SharedEntry represents a typed entry in shared memory.
func (*SharedEntry) IsExpired ¶
func (e *SharedEntry) IsExpired() bool
IsExpired returns true if the entry has expired.
type SharedEntryType ¶
type SharedEntryType string
SharedEntryType represents the type of shared memory entry.
const ( MaxSharedEntries = 500 )
type SharedMemory ¶
type SharedMemory struct {
// contains filtered or unexported fields
}
SharedMemory provides a shared memory space for inter-agent communication. It supports both simple key-value storage (Set/Get) and typed entries with pub/sub notifications (Write/Read/Subscribe).
func NewSharedMemory ¶
func NewSharedMemory() *SharedMemory
NewSharedMemory creates a new shared memory instance.
func (*SharedMemory) CleanupExpired ¶
func (sm *SharedMemory) CleanupExpired() int
CleanupExpired removes all expired entries.
func (*SharedMemory) Clear ¶
func (sm *SharedMemory) Clear()
Clear removes all entries from shared memory.
func (*SharedMemory) Delete ¶
func (sm *SharedMemory) Delete(key string)
Delete removes an entry from shared memory.
func (*SharedMemory) Get ¶
func (sm *SharedMemory) Get(key string) (any, bool)
Get retrieves a value from shared memory. Returns the value and true if found and not expired, nil and false otherwise.
func (*SharedMemory) GetContextSnapshot ¶
func (sm *SharedMemory) GetContextSnapshot() *ContextSnapshot
GetContextSnapshot retrieves the latest context snapshot.
func (*SharedMemory) GetContextSnapshotForPrompt ¶
func (sm *SharedMemory) GetContextSnapshotForPrompt() string
GetContextSnapshotForPrompt returns a formatted context snapshot for injection into prompts.
func (*SharedMemory) GetForContext ¶
func (sm *SharedMemory) GetForContext(agentID string, maxEntries int) string
GetForContext returns a formatted string of relevant entries for injection into prompts.
func (*SharedMemory) Keys ¶
func (sm *SharedMemory) Keys() []string
Keys returns all non-expired keys.
func (*SharedMemory) ReadAll ¶
func (sm *SharedMemory) ReadAll() []*SharedEntry
ReadAll returns all non-expired entries.
func (*SharedMemory) ReadByType ¶
func (sm *SharedMemory) ReadByType(entryType SharedEntryType) []*SharedEntry
ReadByType returns all entries of a specific type.
func (*SharedMemory) ReadEntry ¶
func (sm *SharedMemory) ReadEntry(key string) (*SharedEntry, bool)
ReadEntry reads a typed entry from shared memory.
func (*SharedMemory) SaveContextSnapshot ¶
func (sm *SharedMemory) SaveContextSnapshot(snapshot *ContextSnapshot, sourceAgent string)
SaveContextSnapshot saves a context snapshot for plan-to-execute transition.
func (*SharedMemory) Set ¶
func (sm *SharedMemory) Set(key string, value any, ttl time.Duration)
Set stores a value with an optional TTL. Pass 0 for no expiration. This is a convenience method compatible with simple key-value usage.
func (*SharedMemory) Stats ¶
func (sm *SharedMemory) Stats() SharedMemoryStats
Stats returns statistics about the shared memory.
func (*SharedMemory) Subscribe ¶
func (sm *SharedMemory) Subscribe(agentID string) <-chan *SharedEntry
Subscribe creates a subscription channel for an agent.
func (*SharedMemory) Unsubscribe ¶
func (sm *SharedMemory) Unsubscribe(agentID string)
Unsubscribe removes a subscription.
func (*SharedMemory) Write ¶
func (sm *SharedMemory) Write(key string, value any, entryType SharedEntryType, sourceAgent string)
Write writes a typed value to shared memory and notifies subscribers.
func (*SharedMemory) WriteWithTTL ¶
func (sm *SharedMemory) WriteWithTTL(key string, value any, entryType SharedEntryType, sourceAgent string, ttl time.Duration)
WriteWithTTL writes a typed value with a time-to-live.
type SharedMemoryStats ¶
type SharedMemoryStats struct {
}
SharedMemoryStats contains statistics about shared memory usage.
type SmartRouter ¶
type SmartRouter struct {
Router
// contains filtered or unexported fields
}
SmartRouter extends Router with strategy optimizer-based learning.
func NewSmartRouter ¶
func NewSmartRouter(optimizer *StrategyOptimizer, opts ...RouterOption) *SmartRouter
NewSmartRouter creates a router with built-in learning via StrategyOptimizer.
func (*SmartRouter) GetAdaptiveStats ¶
func (sr *SmartRouter) GetAdaptiveStats() map[string]*StrategyMetrics
GetAdaptiveStats returns debug information about the optimizer's learned strategies.
func (*SmartRouter) Route ¶
func (sr *SmartRouter) Route(message string) *RouteDecision
Route overrides Router.Route with optimizer-informed strategy selection.
type StatusCallback ¶
type StatusCallback interface {
// OnRetry is called when the client is retrying a failed request.
// attempt is the current retry number (1-based), maxAttempts is the total allowed.
// delay is the time before the retry will be attempted.
// reason describes why the retry is happening (e.g., "connection reset", "429 rate limit").
OnRetry(attempt, maxAttempts int, delay time.Duration, reason string)
// OnRateLimit is called when the client is waiting due to rate limiting.
// waitTime is the duration the client will wait before retrying.
OnRateLimit(waitTime time.Duration)
// OnStreamIdle is called when the streaming response has been idle for a while.
// elapsed is the time since the last data was received.
OnStreamIdle(elapsed time.Duration)
// OnStreamResume is called when the stream resumes after being idle.
OnStreamResume()
// OnError is called when an error occurs.
// recoverable indicates whether the client will attempt to recover from the error.
OnError(err error, recoverable bool)
}
StatusCallback provides notifications about client operation status. Implement this interface to receive feedback during retry operations, rate limiting, stream idle states, and recoverable errors.
type StrategyMetrics ¶
type StrategyMetrics struct {
StrategyName string `json:"strategy_name"`
SuccessCount int `json:"success_count"`
FailureCount int `json:"failure_count"`
TotalTime time.Duration `json:"total_time"`
AvgDuration time.Duration `json:"avg_duration"`
LastUsed time.Time `json:"last_used"`
TaskTypes map[string]int `json:"task_types"`
}
StrategyMetrics tracks performance metrics for a strategy.
func (*StrategyMetrics) SuccessRate ¶
func (sm *StrategyMetrics) SuccessRate() float64
SuccessRate returns the success rate as a float64.
type StrategyOptimizer ¶
type StrategyOptimizer struct {
// contains filtered or unexported fields
}
StrategyOptimizer tracks and optimizes strategy choices with composite scoring.
func NewStrategyOptimizer ¶
func NewStrategyOptimizer(storePath string) *StrategyOptimizer
NewStrategyOptimizer creates a new strategy optimizer. storePath is the JSON file used for persistence.
func (*StrategyOptimizer) Clear ¶
func (so *StrategyOptimizer) Clear() error
Clear removes all metrics.
func (*StrategyOptimizer) GetBestStrategy ¶
func (so *StrategyOptimizer) GetBestStrategy(taskType string) string
GetBestStrategy returns the best strategy for a task type using composite scoring. Score = success_rate + experience_boost - recency_penalty.
func (*StrategyOptimizer) GetStrategies ¶
func (so *StrategyOptimizer) GetStrategies() map[string]*StrategyMetrics
GetStrategies returns all strategy metrics.
func (*StrategyOptimizer) RecordOutcome ¶
func (so *StrategyOptimizer) RecordOutcome(taskType, strategy string, success bool, duration time.Duration)
RecordOutcome records the outcome of a strategy execution.
type StreamHandler ¶
type StreamHandler struct {
// OnText is called for each text chunk received.
OnText func(text string)
// OnToolCall is called for each function call received.
OnToolCall func(fc *genai.FunctionCall)
// OnToolResult is not called during stream processing itself,
// but can be set for use in higher-level orchestration.
OnToolResult func(name string, result string)
// OnError is called when an error occurs during streaming.
OnError func(err error)
// OnDone is called when the response is complete.
OnDone func(response *Response)
}
StreamHandler provides callbacks for processing streaming responses.
func NewStreamHandler ¶
func NewStreamHandler(opts ...StreamHandlerOption) *StreamHandler
NewStreamHandler creates a stream handler with the given callbacks. Nil callbacks are safely ignored during processing.
type StreamHandlerOption ¶
type StreamHandlerOption func(*StreamHandler)
StreamHandlerOption configures a StreamHandler.
func WithStreamOnDone ¶
func WithStreamOnDone(fn func(*Response)) StreamHandlerOption
WithStreamOnDone sets the OnDone callback.
func WithStreamOnError ¶
func WithStreamOnError(fn func(error)) StreamHandlerOption
WithStreamOnError sets the OnError callback.
func WithStreamOnText ¶
func WithStreamOnText(fn func(string)) StreamHandlerOption
WithStreamOnText sets the OnText callback.
func WithStreamOnToolCall ¶
func WithStreamOnToolCall(fn func(*genai.FunctionCall)) StreamHandlerOption
WithStreamOnToolCall sets the OnToolCall callback.
type StreamResponse ¶
type StreamResponse struct {
// Chunks is a channel that receives response chunks.
Chunks <-chan ResponseChunk
// Done is closed when the response is complete.
Done <-chan struct{}
}
StreamResponse represents a streaming response from the model.
type TaskComplexity ¶
type TaskComplexity struct {
Score int `json:"score"`
Type TaskType `json:"type"`
Strategy ExecutionStrategy `json:"strategy"`
Reasoning string `json:"reasoning"`
}
TaskComplexity represents the complexity analysis of a task.
type TaskPriority ¶
type TaskPriority int
TaskPriority defines the priority of a coordinated task.
const ( TaskPriorityLow TaskPriority = 0 TaskPriorityNormal TaskPriority = 1 TaskPriorityHigh TaskPriority = 2 )
type TaskStatus ¶
type TaskStatus string
TaskStatus represents the status of a coordinated task.
const ( TaskStatusPending TaskStatus = "pending" TaskStatusBlocked TaskStatus = "blocked" TaskStatusReady TaskStatus = "ready" TaskStatusRunning TaskStatus = "running" TaskStatusCompleted TaskStatus = "completed" TaskStatusFailed TaskStatus = "failed" )
type TaskType ¶
type TaskType string
TaskType represents the type of task.
const ( TaskTypeQuestion TaskType = "question" TaskTypeSingleTool TaskType = "single_tool" TaskTypeMultiTool TaskType = "multi_tool" TaskTypeExploration TaskType = "exploration" TaskTypeRefactoring TaskType = "refactoring" TaskTypeComplex TaskType = "complex" TaskTypeBackground TaskType = "background" )
type Tool ¶
type Tool interface {
// Name returns the unique name of the tool.
Name() string
// Description returns a human-readable description.
Description() string
// Declaration returns the Gemini function declaration for this tool.
Declaration() *genai.FunctionDeclaration
// Execute runs the tool with the given arguments.
Execute(ctx context.Context, args map[string]any) (*ToolResult, error)
}
Tool defines the interface for all tools.
type ToolCallFromText ¶
type ToolCallFromText struct {
Tool string `json:"tool"`
Name string `json:"name"` // alias for "tool"
Args map[string]any `json:"args"`
}
ToolCallFromText represents a tool call parsed from text output.
type ToolDependencyClassifier ¶
type ToolDependencyClassifier struct {
// contains filtered or unexported fields
}
ToolDependencyClassifier determines which tools can run in parallel.
func NewToolDependencyClassifier ¶
func NewToolDependencyClassifier() *ToolDependencyClassifier
NewToolDependencyClassifier creates a new classifier with default write tool list.
func (*ToolDependencyClassifier) AddWriteTool ¶
func (c *ToolDependencyClassifier) AddWriteTool(name string)
AddWriteTool registers a tool as a write tool.
func (*ToolDependencyClassifier) ClassifyDependencies ¶
func (c *ToolDependencyClassifier) ClassifyDependencies(calls []*genai.FunctionCall) []ToolGroup
ClassifyDependencies groups tool calls by dependency. Returns groups that should be executed sequentially, where each group's internal calls can be executed in parallel (if Parallel is true).
func (*ToolDependencyClassifier) IsWriteTool ¶
func (c *ToolDependencyClassifier) IsWriteTool(name string) bool
IsWriteTool returns true if the tool modifies state.
func (*ToolDependencyClassifier) OptimizeForParallelism ¶
func (c *ToolDependencyClassifier) OptimizeForParallelism(calls []*genai.FunctionCall) []*genai.FunctionCall
OptimizeForParallelism reorders calls to maximize parallel execution. Moves all read-only calls to the front, then write calls.
type ToolExecuteFunc ¶
type ToolExecuteFunc func(ctx context.Context, name string, args map[string]any) (*ToolResult, error)
ToolExecuteFunc is the function signature for tool execution.
type ToolGroup ¶
type ToolGroup struct {
Calls []*genai.FunctionCall
Parallel bool // If true, calls in this group can run in parallel
}
ToolGroup represents a group of tool calls that can be executed together.
type ToolResult ¶
type ToolResult struct {
// Content is the main result content (usually text).
Content string
// Data holds structured data (e.g., parsed JSON, typed objects).
Data any
// Error contains an error message if the tool failed.
Error string
// Success indicates if the tool executed successfully.
Success bool
// ExecutionSummary provides metadata about the execution.
ExecutionSummary *ExecutionSummary
// SafetyLevel indicates the risk level of the operation performed.
SafetyLevel SafetyLevel
// Duration records how long the tool execution took.
Duration string
// MultimodalParts holds non-text result parts (images, binary data).
MultimodalParts []*MultimodalPart
}
ToolResult represents the result of a tool execution.
func NewErrorResult ¶
func NewErrorResult(errMsg string) *ToolResult
NewErrorResult creates a failed tool result.
func NewSuccessResult ¶
func NewSuccessResult(content string) *ToolResult
NewSuccessResult creates a successful tool result.
func (*ToolResult) ToMap ¶
func (r *ToolResult) ToMap() map[string]any
ToMap converts the result to a map for Gemini function response.
type ToolUsageGuide ¶
type ToolUsageGuide struct {
Description string // What the tool does
WhenToUse string // When this tool is appropriate
HowToRespond string // How to respond after using this tool
CommonMistakes string // What NOT to do
Examples string // Example usage patterns
}
ToolUsageGuide provides detailed instructions for how to use each tool effectively.
func GetToolGuide ¶
func GetToolGuide(toolName string) (ToolUsageGuide, bool)
GetToolGuide returns the usage guide for a specific tool.
type ValidatingTool ¶
ValidatingTool is an optional interface that tools can implement to validate arguments before execution.
type ValidationError ¶
ValidationError represents a validation failure for a specific field.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Source Files
¶
- agent.go
- agent_options.go
- agent_state.go
- agent_type.go
- cache.go
- checkpoint.go
- circuit_breaker.go
- client.go
- coordinator.go
- delegation.go
- delegation_metrics.go
- errors.go
- executor.go
- fallback.go
- middleware.go
- path_validator.go
- plan_lifecycle.go
- plan_scoring.go
- plan_search.go
- planner.go
- pool.go
- prompt_optimizer.go
- reflection.go
- retry.go
- router.go
- router_options.go
- runner.go
- runner_options.go
- sdk.go
- session.go
- session_store.go
- shared_memory.go
- smart_router.go
- status_callback.go
- strategy_optimizer.go
- streaming_handler.go
- tool.go
- tool_classifier.go
- tool_parser.go
- tool_prompts.go
- types.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package context provides context management for SDK agents including token counting, conversation summarization, and context optimization.
|
Package context provides context management for SDK agents including token counting, conversation summarization, and context optimization. |
|
examples
|
|
|
anthropic
command
Package main demonstrates using the Anthropic provider.
|
Package main demonstrates using the Anthropic provider. |
|
mcp
command
Package main demonstrates MCP server integration.
|
Package main demonstrates MCP server integration. |
|
multi_agent
command
Package main demonstrates multi-agent task execution with the Runner and Coordinator.
|
Package main demonstrates multi-agent task execution with the Runner and Coordinator. |
|
openai
command
Package main demonstrates using the OpenAI provider.
|
Package main demonstrates using the OpenAI provider. |
|
planner
command
Package main demonstrates plan-driven agent execution with the Planner.
|
Package main demonstrates plan-driven agent execution with the Planner. |
|
reflector
command
Package main demonstrates the Reflector for automatic error analysis and recovery.
|
Package main demonstrates the Reflector for automatic error analysis and recovery. |
|
session
command
Package main demonstrates session persistence.
|
Package main demonstrates session persistence. |
|
simple
command
Package main provides a simple example of using the gokin-sdk.
|
Package main provides a simple example of using the gokin-sdk. |
|
smart_router
command
Package main demonstrates the SmartRouter for adaptive task routing.
|
Package main demonstrates the SmartRouter for adaptive task routing. |
|
Package highlight provides syntax highlighting for code blocks using Chroma.
|
Package highlight provides syntax highlighting for code blocks using Chroma. |
|
Package logging provides structured logging utilities for the SDK.
|
Package logging provides structured logging utilities for the SDK. |
|
Package mcp provides Model Context Protocol (MCP) client support for integrating external tool servers with the SDK.
|
Package mcp provides Model Context Protocol (MCP) client support for integrating external tool servers with the SDK. |
|
Package memory provides persistent memory storage for agent learning and context.
|
Package memory provides persistent memory storage for agent learning and context. |
|
provider
|
|
|
anthropic
Package anthropic provides an Anthropic-compatible client implementation for the SDK.
|
Package anthropic provides an Anthropic-compatible client implementation for the SDK. |
|
gemini
Package gemini provides a Gemini client implementation for the SDK.
|
Package gemini provides a Gemini client implementation for the SDK. |
|
ollama
Package ollama provides an Ollama client implementation for the SDK.
|
Package ollama provides an Ollama client implementation for the SDK. |
|
openai
Package openai provides an OpenAI-compatible client implementation for the SDK.
|
Package openai provides an OpenAI-compatible client implementation for the SDK. |
|
Package tools provides built-in tool implementations for the SDK.
|
Package tools provides built-in tool implementations for the SDK. |