Documentation
¶
Overview ¶
Package agent provides the core agent framework for AgentFlow.
Package agent provides the core agent framework for AgentFlow.
Package agent provides the core agent framework for AgentFlow.
Overview ¶
The agent package implements a flexible, extensible agent architecture that supports various AI agent patterns including ReAct, Chain-of-Thought, and custom workflows. It provides a unified interface for building intelligent agents that can reason, plan, and execute tasks using Large Language Models (LLMs).
Architecture ¶
The agent framework follows a layered architecture:
┌─────────────────────────────────────────────────────────────┐ │ Agent Interface │ │ (ID, Name, Type, State, Init, Teardown, Plan, Execute) │ ├─────────────────────────────────────────────────────────────┤ │ BaseAgent │ │ (Common functionality, lifecycle management, hooks) │ ├─────────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │ │ Memory │ │ Tools │ │ Guardrails │ │ │ │ Manager │ │ Manager │ │ (Validators) │ │ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ LLM Provider │ └─────────────────────────────────────────────────────────────┘
Core Components ¶
Agent Interface: Defines the contract for all agent implementations.
type Agent interface {
ID() string
Name() string
Type() AgentType
State() State
Init(ctx context.Context) error
Teardown(ctx context.Context) error
Plan(ctx context.Context, input *Input) (*PlanResult, error)
Execute(ctx context.Context, input *Input) (*Output, error)
Observe(ctx context.Context, feedback *Feedback) error
}
BaseAgent: Provides common functionality for all agent types including:
- Lifecycle management (Init, Teardown)
- State machine (Idle → Running → Completed/Failed)
- Hook system (BeforeExecute, AfterExecute, OnError)
- Checkpoint/recovery support
MemoryManager: Manages agent memory across multiple layers:
- Working Memory: Short-term context storage
- Episodic Memory: Event-based experiences
- Semantic Memory: Factual knowledge
- Procedural Memory: How-to knowledge
ToolManager: Handles tool registration, selection, and execution.
Usage ¶
Basic agent creation using the builder pattern:
agent, err := agent.NewAgentBuilder(agent.Config{
Name: "my-agent",
Type: agent.TypeReAct,
MaxIterations: 10,
}).
WithProvider(llmProvider).
WithMemory(memoryManager).
WithTools(toolManager).
Build()
if err != nil {
log.Fatal(err)
}
// Execute a task
output, err := agent.Execute(ctx, &agent.Input{
Query: "What is the weather in Beijing?",
})
Agent Types ¶
The framework supports multiple agent types:
- TypeReAct: Reasoning and Acting pattern
- TypeCoT: Chain-of-Thought reasoning
- TypePlanAndExecute: Planning then execution
- TypeReflection: Self-reflection and improvement
- TypeCustom: User-defined agent logic
State Machine ¶
Agents follow a well-defined state machine:
Idle → Running → Completed
↓
Failed
State transitions are validated to ensure correct agent behavior.
Checkpointing ¶
The framework supports checkpointing for long-running tasks:
// Enable checkpointing agent.EnableCheckpointing(checkpointManager) // Recover from checkpoint agent.RecoverFromCheckpoint(ctx, checkpointID)
Error Handling ¶
The package defines structured errors with error codes:
var (
ErrProviderNotSet = NewError(ErrCodeProviderNotSet, "LLM provider not configured")
ErrAgentNotReady = NewError(ErrCodeNotReady, "agent not in ready state")
ErrAgentBusy = NewError(ErrCodeBusy, "agent is busy executing another task")
)
Thread Safety ¶
All agent implementations are designed to be thread-safe. The BaseAgent uses appropriate synchronization primitives to protect shared state.
Extensibility ¶
The framework is designed for extensibility:
- Custom agent types via AgentFactory registration
- Custom validators via Validator interface
- Custom memory stores via MemoryStore interface
- Custom tools via Tool interface
See the subpackages for additional functionality:
- agent/guardrails: Input/output validation and security
- agent/memory: Memory management systems
- agent/evaluation: Agent evaluation and A/B testing
- agent/structured: Structured output parsing
- agent/protocol/a2a: Agent-to-Agent communication
Package agent provides the core agent framework for AgentFlow.
Index ¶
- Constants
- Variables
- func CanTransition(from, to State) bool
- func InitGlobalRegistry(logger *zap.Logger)
- func IsRetryable(err error) bool
- func RegisterAgentType(agentType AgentType, factory AgentFactory)
- func WithRuntimeStreamEmitter(ctx context.Context, emit RuntimeStreamEmitter) context.Context
- type Action
- type Agent
- type AgentBuilder
- func (b *AgentBuilder) Build() (*BaseAgent, error)
- func (b *AgentBuilder) Validate() error
- func (b *AgentBuilder) WithDefaultEnhancedMemory(config *memory.EnhancedMemoryConfig) *AgentBuilder
- func (b *AgentBuilder) WithDefaultMCPServer(name, version string) *AgentBuilder
- func (b *AgentBuilder) WithDefaultSkills(directory string, config *skills.SkillManagerConfig) *AgentBuilder
- func (b *AgentBuilder) WithEnhancedMemory(config interface{}) *AgentBuilder
- func (b *AgentBuilder) WithEventBus(bus EventBus) *AgentBuilder
- func (b *AgentBuilder) WithLogger(logger *zap.Logger) *AgentBuilder
- func (b *AgentBuilder) WithMCP(config interface{}) *AgentBuilder
- func (b *AgentBuilder) WithMemory(memory MemoryManager) *AgentBuilder
- func (b *AgentBuilder) WithObservability(config interface{}) *AgentBuilder
- func (b *AgentBuilder) WithPromptEnhancer(config *PromptEnhancerConfig) *AgentBuilder
- func (b *AgentBuilder) WithProvider(provider llm.Provider) *AgentBuilder
- func (b *AgentBuilder) WithReflection(config *ReflectionExecutorConfig) *AgentBuilder
- func (b *AgentBuilder) WithSkills(config interface{}) *AgentBuilder
- func (b *AgentBuilder) WithToolManager(toolManager ToolManager) *AgentBuilder
- func (b *AgentBuilder) WithToolSelection(config *ToolSelectionConfig) *AgentBuilder
- type AgentFactory
- type AgentFactoryFunc
- type AgentIdentity
- type AgentRegistry
- func (r *AgentRegistry) Create(config Config, provider llm.Provider, memory MemoryManager, ...) (Agent, error)
- func (r *AgentRegistry) IsRegistered(agentType AgentType) bool
- func (r *AgentRegistry) ListTypes() []AgentType
- func (r *AgentRegistry) Register(agentType AgentType, factory AgentFactory)
- func (r *AgentRegistry) Unregister(agentType AgentType)
- type AgentType
- type ApprovalPolicy
- type ApprovalRequest
- type ApprovalRequestedEvent
- type ApprovalRespondedEvent
- type ApprovalResponse
- type ApprovalStatus
- type ApprovalStore
- type ApprovalType
- type AsyncExecution
- type AsyncExecutor
- type BaseAgent
- func (b *BaseAgent) AddInputValidator(v guardrails.Validator)
- func (b *BaseAgent) AddOutputFilter(f guardrails.Filter)
- func (b *BaseAgent) AddOutputValidator(v guardrails.Validator)
- func (b *BaseAgent) ChatCompletion(ctx context.Context, messages []llm.Message) (*llm.ChatResponse, error)
- func (b *BaseAgent) Config() Config
- func (b *BaseAgent) ContextEngineEnabled() bool
- func (b *BaseAgent) EnableEnhancedMemory(memorySystem interface{})
- func (b *BaseAgent) EnableMCP(server interface{})
- func (b *BaseAgent) EnableObservability(obsSystem interface{})
- func (b *BaseAgent) EnablePromptEnhancer(enhancer interface{})
- func (b *BaseAgent) EnableReflection(executor interface{})
- func (b *BaseAgent) EnableSkills(manager interface{})
- func (b *BaseAgent) EnableToolSelection(selector interface{})
- func (b *BaseAgent) EnsureReady() error
- func (b *BaseAgent) Execute(ctx context.Context, input *Input) (*Output, error)
- func (b *BaseAgent) ExecuteEnhanced(ctx context.Context, input *Input, options EnhancedExecutionOptions) (*Output, error)
- func (b *BaseAgent) ExportConfiguration() map[string]interface{}
- func (b *BaseAgent) GetFeatureMetrics() map[string]interface{}
- func (b *BaseAgent) GetFeatureStatus() map[string]bool
- func (b *BaseAgent) GuardrailsEnabled() bool
- func (b *BaseAgent) ID() string
- func (b *BaseAgent) Init(ctx context.Context) error
- func (b *BaseAgent) Logger() *zap.Logger
- func (b *BaseAgent) Memory() MemoryManager
- func (b *BaseAgent) Name() string
- func (b *BaseAgent) Observe(ctx context.Context, feedback *Feedback) error
- func (b *BaseAgent) Plan(ctx context.Context, input *Input) (*PlanResult, error)
- func (b *BaseAgent) PrintFeatureStatus()
- func (b *BaseAgent) Provider() llm.Provider
- func (b *BaseAgent) QuickSetup(ctx context.Context, options QuickSetupOptions) error
- func (b *BaseAgent) RecallMemory(ctx context.Context, query string, topK int) ([]MemoryRecord, error)
- func (b *BaseAgent) SaveMemory(ctx context.Context, content string, kind MemoryKind, metadata map[string]any) error
- func (b *BaseAgent) SetContextManager(cm ContextManager)
- func (b *BaseAgent) SetGuardrails(cfg *guardrails.GuardrailsConfig)
- func (b *BaseAgent) State() State
- func (b *BaseAgent) StreamCompletion(ctx context.Context, messages []llm.Message) (<-chan llm.StreamChunk, error)
- func (b *BaseAgent) Teardown(ctx context.Context) error
- func (b *BaseAgent) Tools() ToolManager
- func (b *BaseAgent) Transition(ctx context.Context, to State) error
- func (b *BaseAgent) TryLockExec() bool
- func (b *BaseAgent) Type() AgentType
- func (b *BaseAgent) UnlockExec()
- func (b *BaseAgent) ValidateConfiguration() error
- type Checkpoint
- type CheckpointDiff
- type CheckpointManager
- func (m *CheckpointManager) CompareVersions(ctx context.Context, threadID string, version1, version2 int) (*CheckpointDiff, error)
- func (m *CheckpointManager) CreateCheckpoint(ctx context.Context, agent Agent, threadID string) error
- func (m *CheckpointManager) DisableAutoSave()
- func (m *CheckpointManager) EnableAutoSave(ctx context.Context, agent Agent, threadID string, interval time.Duration) error
- func (m *CheckpointManager) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)
- func (m *CheckpointManager) LoadCheckpoint(ctx context.Context, checkpointID string) (*Checkpoint, error)
- func (m *CheckpointManager) LoadLatestCheckpoint(ctx context.Context, threadID string) (*Checkpoint, error)
- func (m *CheckpointManager) ResumeFromCheckpoint(ctx context.Context, agent Agent, checkpointID string) error
- func (m *CheckpointManager) RollbackToVersion(ctx context.Context, agent Agent, threadID string, version int) error
- func (m *CheckpointManager) SaveCheckpoint(ctx context.Context, checkpoint *Checkpoint) error
- type CheckpointMessage
- type CheckpointStore
- type CheckpointToolCall
- type CheckpointVersion
- type Config
- type Container
- func (c *Container) CreateBaseAgent(config Config) (*BaseAgent, error)
- func (c *Container) CreateModularAgent(config ModularAgentConfig) (*ModularAgent, error)
- func (c *Container) EventBus() EventBus
- func (c *Container) Logger() *zap.Logger
- func (c *Container) Memory() MemoryManager
- func (c *Container) Provider() llm.Provider
- func (c *Container) ToolManager() ToolManager
- func (c *Container) WithEventBus(bus EventBus) *Container
- func (c *Container) WithGuardrailsFactory(factory func() interface{}) *Container
- func (c *Container) WithLogger(logger *zap.Logger) *Container
- func (c *Container) WithMemory(memory MemoryManager) *Container
- func (c *Container) WithProvider(provider llm.Provider) *Container
- func (c *Container) WithReflectionFactory(factory func() interface{}) *Container
- func (c *Container) WithToolManager(toolManager ToolManager) *Container
- func (c *Container) WithToolSelectionFactory(factory func() interface{}) *Container
- type ContextManager
- type Critique
- type DefaultApprovalPolicy
- type DefensivePromptConfig
- type DefensivePromptEnhancer
- type DynamicToolSelector
- func (s *DynamicToolSelector) ScoreTools(ctx context.Context, task string, tools []llm.ToolSchema) ([]ToolScore, error)
- func (s *DynamicToolSelector) SelectTools(ctx context.Context, task string, availableTools []llm.ToolSchema) ([]llm.ToolSchema, error)
- func (s *DynamicToolSelector) UpdateToolStats(toolName string, success bool, latency time.Duration, cost float64)
- type EnhancedExecutionOptions
- type ErrInvalidTransition
- type Error
- func (e *Error) Error() string
- func (e *Error) ToTypesError() *types.Error
- func (e *Error) Unwrap() error
- func (e *Error) WithAgent(id string, agentType AgentType) *Error
- func (e *Error) WithCause(cause error) *Error
- func (e *Error) WithMetadata(key string, value interface{}) *Error
- func (e *Error) WithRetryable(retryable bool) *Error
- type ErrorCode
- type Event
- type EventBus
- type EventHandler
- type EventType
- type Example
- type ExecutionContext
- type ExecutionStatus
- type ExtensionManager
- func (em *ExtensionManager) EnhancedMemory() types.EnhancedMemoryExtension
- func (em *ExtensionManager) Guardrails() types.GuardrailsExtension
- func (em *ExtensionManager) HasGuardrails() bool
- func (em *ExtensionManager) HasObservability() bool
- func (em *ExtensionManager) HasReflection() bool
- func (em *ExtensionManager) HasToolSelection() bool
- func (em *ExtensionManager) MCP() types.MCPExtension
- func (em *ExtensionManager) Observability() types.ObservabilityExtension
- func (em *ExtensionManager) PromptEnhancer() types.PromptEnhancerExtension
- func (em *ExtensionManager) Reflection() types.ReflectionExtension
- func (em *ExtensionManager) SetEnhancedMemory(ext types.EnhancedMemoryExtension)
- func (em *ExtensionManager) SetGuardrails(ext types.GuardrailsExtension)
- func (em *ExtensionManager) SetMCP(ext types.MCPExtension)
- func (em *ExtensionManager) SetObservability(ext types.ObservabilityExtension)
- func (em *ExtensionManager) SetPromptEnhancer(ext types.PromptEnhancerExtension)
- func (em *ExtensionManager) SetReflection(ext types.ReflectionExtension)
- func (em *ExtensionManager) SetSkills(ext types.SkillsExtension)
- func (em *ExtensionManager) SetToolSelection(ext types.ToolSelectionExtension)
- func (em *ExtensionManager) Skills() types.SkillsExtension
- func (em *ExtensionManager) ToolSelection() types.ToolSelectionExtension
- type FailureMode
- type Feedback
- type FeedbackEvent
- type FileCheckpointStore
- func (s *FileCheckpointStore) Delete(ctx context.Context, checkpointID string) error
- func (s *FileCheckpointStore) DeleteThread(ctx context.Context, threadID string) error
- func (s *FileCheckpointStore) List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error)
- func (s *FileCheckpointStore) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)
- func (s *FileCheckpointStore) Load(ctx context.Context, checkpointID string) (*Checkpoint, error)
- func (s *FileCheckpointStore) LoadLatest(ctx context.Context, threadID string) (*Checkpoint, error)
- func (s *FileCheckpointStore) LoadVersion(ctx context.Context, threadID string, version int) (*Checkpoint, error)
- func (s *FileCheckpointStore) Rollback(ctx context.Context, threadID string, version int) error
- func (s *FileCheckpointStore) Save(ctx context.Context, checkpoint *Checkpoint) error
- type GuardRail
- type GuardrailsError
- type GuardrailsErrorType
- type HealthStatus
- type HumanInLoopManager
- func (m *HumanInLoopManager) CancelApproval(ctx context.Context, requestID string) error
- func (m *HumanInLoopManager) GetPendingRequests(agentID string) []*ApprovalRequest
- func (m *HumanInLoopManager) RequestApproval(ctx context.Context, agentID string, approvalType ApprovalType, content string, ...) (*ApprovalResponse, error)
- func (m *HumanInLoopManager) RespondToApproval(ctx context.Context, requestID string, response *ApprovalResponse) error
- type InMemoryApprovalStore
- func (s *InMemoryApprovalStore) List(ctx context.Context, agentID string, status ApprovalStatus, limit int) ([]*ApprovalRequest, error)
- func (s *InMemoryApprovalStore) Load(ctx context.Context, requestID string) (*ApprovalRequest, error)
- func (s *InMemoryApprovalStore) Save(ctx context.Context, request *ApprovalRequest) error
- func (s *InMemoryApprovalStore) Update(ctx context.Context, request *ApprovalRequest) error
- type InjectionDefenseConfig
- type Input
- type LLMExecutor
- func (e *LLMExecutor) Complete(ctx context.Context, messages []llm.Message) (*llm.ChatResponse, error)
- func (e *LLMExecutor) Provider() llm.Provider
- func (e *LLMExecutor) SetContextManager(cm ContextManager)
- func (e *LLMExecutor) Stream(ctx context.Context, messages []llm.Message) (<-chan llm.StreamChunk, error)
- type LLMExecutorConfig
- type LifecycleManager
- type MCPServerOptions
- type MemoryConfig
- type MemoryKind
- type MemoryManager
- type MemoryReader
- type MemoryRecord
- type MemoryWriter
- type MiddlewarePlugin
- type ModularAgent
- func (a *ModularAgent) Execute(ctx context.Context, input *Input) (*Output, error)
- func (a *ModularAgent) Extensions() *ExtensionManager
- func (a *ModularAgent) ID() string
- func (a *ModularAgent) Init(ctx context.Context) error
- func (a *ModularAgent) LLM() *LLMExecutor
- func (a *ModularAgent) Memory() MemoryManager
- func (a *ModularAgent) Name() string
- func (a *ModularAgent) Observe(ctx context.Context, feedback *Feedback) error
- func (a *ModularAgent) Plan(ctx context.Context, input *Input) (*PlanResult, error)
- func (a *ModularAgent) State() State
- func (a *ModularAgent) Teardown(ctx context.Context) error
- func (a *ModularAgent) Tools() ToolManager
- func (a *ModularAgent) Type() AgentType
- type ModularAgentConfig
- type Output
- type OutputSchema
- type PlanConfig
- type PlanResult
- type Plugin
- type PluginEnabledAgent
- func (a *PluginEnabledAgent) Execute(ctx context.Context, input *Input) (*Output, error)
- func (a *PluginEnabledAgent) ID() string
- func (a *PluginEnabledAgent) Init(ctx context.Context) error
- func (a *PluginEnabledAgent) Name() string
- func (a *PluginEnabledAgent) Observe(ctx context.Context, feedback *Feedback) error
- func (a *PluginEnabledAgent) Plan(ctx context.Context, input *Input) (*PlanResult, error)
- func (a *PluginEnabledAgent) Registry() *PluginRegistry
- func (a *PluginEnabledAgent) State() State
- func (a *PluginEnabledAgent) Teardown(ctx context.Context) error
- func (a *PluginEnabledAgent) Type() AgentType
- func (a *PluginEnabledAgent) UnderlyingAgent() Agent
- type PluginRegistry
- func (r *PluginRegistry) Close(ctx context.Context) error
- func (r *PluginRegistry) Get(name string) (Plugin, bool)
- func (r *PluginRegistry) Init(ctx context.Context) error
- func (r *PluginRegistry) List() []Plugin
- func (r *PluginRegistry) MiddlewarePlugins() []MiddlewarePlugin
- func (r *PluginRegistry) PostProcessPlugins() []PostProcessPlugin
- func (r *PluginRegistry) PreProcessPlugins() []PreProcessPlugin
- func (r *PluginRegistry) Register(plugin Plugin) error
- func (r *PluginRegistry) Unregister(name string) error
- type PluginType
- type PostProcessPlugin
- type PostgreSQLCheckpointStore
- func (s *PostgreSQLCheckpointStore) Delete(ctx context.Context, checkpointID string) error
- func (s *PostgreSQLCheckpointStore) DeleteThread(ctx context.Context, threadID string) error
- func (s *PostgreSQLCheckpointStore) List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error)
- func (s *PostgreSQLCheckpointStore) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)
- func (s *PostgreSQLCheckpointStore) Load(ctx context.Context, checkpointID string) (*Checkpoint, error)
- func (s *PostgreSQLCheckpointStore) LoadLatest(ctx context.Context, threadID string) (*Checkpoint, error)
- func (s *PostgreSQLCheckpointStore) LoadVersion(ctx context.Context, threadID string, version int) (*Checkpoint, error)
- func (s *PostgreSQLCheckpointStore) Rollback(ctx context.Context, threadID string, version int) error
- func (s *PostgreSQLCheckpointStore) Save(ctx context.Context, checkpoint *Checkpoint) error
- type PostgreSQLClient
- type PreProcessPlugin
- type PromptBundle
- func (b *PromptBundle) AppendExamples(examples ...Example)
- func (b PromptBundle) EffectiveVersion(defaultVersion string) string
- func (b PromptBundle) ExtractVariables() []string
- func (b PromptBundle) HasExamples() bool
- func (b PromptBundle) IsZero() bool
- func (b PromptBundle) RenderExamplesAsMessages() []llm.Message
- func (b PromptBundle) RenderExamplesAsMessagesWithVars(vars map[string]string) []llm.Message
- func (b PromptBundle) RenderSystemPrompt() string
- func (b PromptBundle) RenderSystemPromptWithVars(vars map[string]string) string
- func (b PromptBundle) RenderWithVars(vars map[string]string) PromptBundle
- type PromptEngineeringConfig
- type PromptEnhancer
- type PromptEnhancerConfig
- type PromptOptimizer
- type PromptTemplate
- type PromptTemplateLibrary
- func (l *PromptTemplateLibrary) GetTemplate(name string) (PromptTemplate, bool)
- func (l *PromptTemplateLibrary) ListTemplates() []string
- func (l *PromptTemplateLibrary) RegisterTemplate(template PromptTemplate)
- func (l *PromptTemplateLibrary) RenderTemplate(name string, vars map[string]string) (string, error)
- type QuickSetupOptions
- type RealtimeCoordinator
- type RedisCheckpointStore
- func (s *RedisCheckpointStore) Delete(ctx context.Context, checkpointID string) error
- func (s *RedisCheckpointStore) DeleteThread(ctx context.Context, threadID string) error
- func (s *RedisCheckpointStore) List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error)
- func (s *RedisCheckpointStore) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)
- func (s *RedisCheckpointStore) Load(ctx context.Context, checkpointID string) (*Checkpoint, error)
- func (s *RedisCheckpointStore) LoadLatest(ctx context.Context, threadID string) (*Checkpoint, error)
- func (s *RedisCheckpointStore) LoadVersion(ctx context.Context, threadID string, version int) (*Checkpoint, error)
- func (s *RedisCheckpointStore) Rollback(ctx context.Context, threadID string, version int) error
- func (s *RedisCheckpointStore) Save(ctx context.Context, checkpoint *Checkpoint) error
- type RedisClient
- type ReflectionConfig
- type ReflectionExecutor
- type ReflectionExecutorConfig
- type ReflectionResult
- type Row
- type Rows
- type RuntimeStreamEmitter
- type RuntimeStreamEvent
- type RuntimeStreamEventType
- type RuntimeToolCall
- type RuntimeToolResult
- type ServiceLocator
- func (sl *ServiceLocator) Get(name string) (interface{}, bool)
- func (sl *ServiceLocator) GetEventBus() (EventBus, bool)
- func (sl *ServiceLocator) GetLogger() (*zap.Logger, bool)
- func (sl *ServiceLocator) GetMemory() (MemoryManager, bool)
- func (sl *ServiceLocator) GetProvider() (llm.Provider, bool)
- func (sl *ServiceLocator) GetToolManager() (ToolManager, bool)
- func (sl *ServiceLocator) MustGet(name string) interface{}
- func (sl *ServiceLocator) Register(name string, service interface{})
- type SimpleEventBus
- type SkillsOptions
- type State
- type StateChangeEvent
- type StateManager
- type SubagentCompletedEvent
- type SubagentManager
- func (m *SubagentManager) CleanupCompleted(olderThan time.Duration) int
- func (m *SubagentManager) GetExecution(executionID string) (*AsyncExecution, error)
- func (m *SubagentManager) ListExecutions() []*AsyncExecution
- func (m *SubagentManager) SpawnSubagent(ctx context.Context, subagent Agent, input *Input) (*AsyncExecution, error)
- type SystemPrompt
- type ToolCallEvent
- type ToolManager
- type ToolScore
- type ToolSelectionConfig
- type ToolSelector
- type ToolStats
Constants ¶
const ( ServiceProvider = "provider" ServiceMemory = "memory" ServiceToolManager = "tool_manager" ServiceEventBus = "event_bus" ServiceLogger = "logger" )
Well-known service names
const ( MemoryShortTerm = types.MemoryWorking // 短期记忆 -> Working MemoryWorking = types.MemoryWorking // 工作记忆 MemoryLongTerm = types.MemorySemantic // 长期记忆 -> Semantic MemoryEpisodic = types.MemoryEpisodic // 情节记忆 MemorySemantic = types.MemorySemantic // 语义记忆 (新增) MemoryProcedural = types.MemoryProcedural // 程序记忆 (新增) )
Memory kind constants - mapped to unified types.MemoryCategory Deprecated: Use types.MemoryWorking, types.MemoryEpisodic, etc.
Variables ¶
var ( ErrProviderNotSet = NewError(ErrCodeProviderNotSet, "LLM provider not configured") ErrAgentNotReady = NewError(ErrCodeNotReady, "agent not in ready state") ErrAgentBusy = NewError(ErrCodeBusy, "agent is busy executing another task") )
预定义错误(向后兼容)
Functions ¶
func InitGlobalRegistry ¶
InitGlobalRegistry initializes the global agent registry
func IsRetryable ¶
IsRetryable checks if an agent error is retryable
func RegisterAgentType ¶
func RegisterAgentType(agentType AgentType, factory AgentFactory)
RegisterAgentType registers an agent type in the global registry
func WithRuntimeStreamEmitter ¶
func WithRuntimeStreamEmitter(ctx context.Context, emit RuntimeStreamEmitter) context.Context
Types ¶
type Action ¶
type Action struct {
Type string `json:"type"`
Content string `json:"content"`
Metadata map[string]interface{} `json:"metadata"`
}
Action 需要审批的动作
type Agent ¶
type Agent interface {
// 身份标识
ID() string
Name() string
Type() AgentType
// 生命周期
State() State
Init(ctx context.Context) error
Teardown(ctx context.Context) error
// 核心执行
Plan(ctx context.Context, input *Input) (*PlanResult, error)
Execute(ctx context.Context, input *Input) (*Output, error)
Observe(ctx context.Context, feedback *Feedback) error
}
Agent 定义核心行为接口
func CreateAgent ¶
func CreateAgent( config Config, provider llm.Provider, memory MemoryManager, toolManager ToolManager, bus EventBus, logger *zap.Logger, ) (Agent, error)
CreateAgent creates an agent using the global registry
type AgentBuilder ¶
type AgentBuilder struct {
// contains filtered or unexported fields
}
AgentBuilder 提供流式构建 Agent 的能力 支持链式调用,简化 Agent 创建过程
func NewAgentBuilder ¶
func NewAgentBuilder(config Config) *AgentBuilder
NewAgentBuilder 创建 Agent 构建器
func (*AgentBuilder) WithDefaultEnhancedMemory ¶
func (b *AgentBuilder) WithDefaultEnhancedMemory(config *memory.EnhancedMemoryConfig) *AgentBuilder
WithDefaultEnhancedMemory enables the built-in enhanced memory system with in-memory stores.
func (*AgentBuilder) WithDefaultMCPServer ¶
func (b *AgentBuilder) WithDefaultMCPServer(name, version string) *AgentBuilder
WithDefaultMCPServer enables the built-in MCP server with a default name/version.
func (*AgentBuilder) WithDefaultSkills ¶
func (b *AgentBuilder) WithDefaultSkills(directory string, config *skills.SkillManagerConfig) *AgentBuilder
WithDefaultSkills enables the built-in skills manager and optionally scans a directory.
func (*AgentBuilder) WithEnhancedMemory ¶
func (b *AgentBuilder) WithEnhancedMemory(config interface{}) *AgentBuilder
WithEnhancedMemory 启用增强记忆系统
func (*AgentBuilder) WithEventBus ¶
func (b *AgentBuilder) WithEventBus(bus EventBus) *AgentBuilder
WithEventBus 设置事件总线
func (*AgentBuilder) WithLogger ¶
func (b *AgentBuilder) WithLogger(logger *zap.Logger) *AgentBuilder
WithLogger 设置日志器
func (*AgentBuilder) WithMCP ¶
func (b *AgentBuilder) WithMCP(config interface{}) *AgentBuilder
WithMCP 启用 MCP 集成
func (*AgentBuilder) WithMemory ¶
func (b *AgentBuilder) WithMemory(memory MemoryManager) *AgentBuilder
WithMemory 设置记忆管理器
func (*AgentBuilder) WithObservability ¶
func (b *AgentBuilder) WithObservability(config interface{}) *AgentBuilder
WithObservability 启用可观测性系统
func (*AgentBuilder) WithPromptEnhancer ¶
func (b *AgentBuilder) WithPromptEnhancer(config *PromptEnhancerConfig) *AgentBuilder
WithPromptEnhancer 启用提示词增强
func (*AgentBuilder) WithProvider ¶
func (b *AgentBuilder) WithProvider(provider llm.Provider) *AgentBuilder
WithProvider 设置 LLM Provider
func (*AgentBuilder) WithReflection ¶
func (b *AgentBuilder) WithReflection(config *ReflectionExecutorConfig) *AgentBuilder
WithReflection 启用 Reflection 机制
func (*AgentBuilder) WithSkills ¶
func (b *AgentBuilder) WithSkills(config interface{}) *AgentBuilder
WithSkills 启用 Skills 系统
func (*AgentBuilder) WithToolManager ¶
func (b *AgentBuilder) WithToolManager(toolManager ToolManager) *AgentBuilder
WithToolManager 设置工具管理器
func (*AgentBuilder) WithToolSelection ¶
func (b *AgentBuilder) WithToolSelection(config *ToolSelectionConfig) *AgentBuilder
WithToolSelection 启用动态工具选择
type AgentFactory ¶
type AgentFactory func( config Config, provider llm.Provider, memory MemoryManager, toolManager ToolManager, bus EventBus, logger *zap.Logger, ) (Agent, error)
AgentFactory is a function that creates an Agent instance
type AgentFactoryFunc ¶
type AgentFactoryFunc struct {
// contains filtered or unexported fields
}
AgentFactoryFunc creates agents with pre-configured dependencies.
func NewAgentFactoryFunc ¶
func NewAgentFactoryFunc(container *Container) *AgentFactoryFunc
NewAgentFactoryFunc creates a new agent factory.
func (*AgentFactoryFunc) CreateAgent ¶
func (f *AgentFactoryFunc) CreateAgent(config Config) (Agent, error)
CreateAgent creates an agent based on the provided configuration.
func (*AgentFactoryFunc) CreateModular ¶
func (f *AgentFactoryFunc) CreateModular(config ModularAgentConfig) (*ModularAgent, error)
CreateModular creates a modular agent.
type AgentIdentity ¶
type AgentIdentity struct {
// contains filtered or unexported fields
}
AgentIdentity manages agent identity information.
func NewAgentIdentity ¶
func NewAgentIdentity(id, name string, agentType AgentType) *AgentIdentity
NewAgentIdentity creates a new AgentIdentity.
func (*AgentIdentity) Description ¶
func (i *AgentIdentity) Description() string
Description returns the agent's description.
func (*AgentIdentity) ID ¶
func (i *AgentIdentity) ID() string
ID returns the agent's unique identifier.
func (*AgentIdentity) SetDescription ¶
func (i *AgentIdentity) SetDescription(desc string)
SetDescription sets the agent's description.
func (*AgentIdentity) Type ¶
func (i *AgentIdentity) Type() AgentType
Type returns the agent's type.
type AgentRegistry ¶
type AgentRegistry struct {
// contains filtered or unexported fields
}
AgentRegistry manages agent type registration and creation It provides a centralized way to register and instantiate different agent types
var GlobalRegistry *AgentRegistry
GlobalRegistry is the default agent registry instance
func NewAgentRegistry ¶
func NewAgentRegistry(logger *zap.Logger) *AgentRegistry
NewAgentRegistry creates a new agent registry
func (*AgentRegistry) Create ¶
func (r *AgentRegistry) Create( config Config, provider llm.Provider, memory MemoryManager, toolManager ToolManager, bus EventBus, logger *zap.Logger, ) (Agent, error)
Create creates a new agent instance of the specified type
func (*AgentRegistry) IsRegistered ¶
func (r *AgentRegistry) IsRegistered(agentType AgentType) bool
IsRegistered checks if an agent type is registered
func (*AgentRegistry) ListTypes ¶
func (r *AgentRegistry) ListTypes() []AgentType
ListTypes returns all registered agent types
func (*AgentRegistry) Register ¶
func (r *AgentRegistry) Register(agentType AgentType, factory AgentFactory)
Register registers a new agent type with its factory function
func (*AgentRegistry) Unregister ¶
func (r *AgentRegistry) Unregister(agentType AgentType)
Unregister removes an agent type from the registry
type ApprovalPolicy ¶
type ApprovalPolicy interface {
RequiresApproval(ctx context.Context, agentID string, action Action) bool
}
ApprovalPolicy 审批策略
type ApprovalRequest ¶
type ApprovalRequest struct {
ID string `json:"id"`
AgentID string `json:"agent_id"`
Type ApprovalType `json:"type"`
Content string `json:"content"`
Context map[string]interface{} `json:"context"`
Status ApprovalStatus `json:"status"`
RequestedAt time.Time `json:"requested_at"`
RespondedAt time.Time `json:"responded_at,omitempty"`
Response *ApprovalResponse `json:"response,omitempty"`
Timeout time.Duration `json:"timeout"`
// contains filtered or unexported fields
}
ApprovalRequest 审批请求
type ApprovalRequestedEvent ¶
type ApprovalRequestedEvent struct {
RequestID string
AgentID string
ApprovalType ApprovalType
Content string
Timestamp_ time.Time
}
ApprovalRequestedEvent 审批请求事件
func (*ApprovalRequestedEvent) Timestamp ¶
func (e *ApprovalRequestedEvent) Timestamp() time.Time
func (*ApprovalRequestedEvent) Type ¶
func (e *ApprovalRequestedEvent) Type() EventType
type ApprovalRespondedEvent ¶
type ApprovalRespondedEvent struct {
RequestID string
Approved bool
Reason string
Timestamp_ time.Time
}
ApprovalRespondedEvent 审批响应事件
func (*ApprovalRespondedEvent) Timestamp ¶
func (e *ApprovalRespondedEvent) Timestamp() time.Time
func (*ApprovalRespondedEvent) Type ¶
func (e *ApprovalRespondedEvent) Type() EventType
type ApprovalResponse ¶
type ApprovalResponse struct {
Approved bool `json:"approved"`
Reason string `json:"reason,omitempty"`
Feedback string `json:"feedback,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ApprovalResponse 审批响应
type ApprovalStatus ¶
type ApprovalStatus string
ApprovalStatus 审批状态
const ( ApprovalStatusPending ApprovalStatus = "pending" ApprovalStatusApproved ApprovalStatus = "approved" ApprovalStatusRejected ApprovalStatus = "rejected" ApprovalStatusTimeout ApprovalStatus = "timeout" )
type ApprovalStore ¶
type ApprovalStore interface {
Save(ctx context.Context, request *ApprovalRequest) error
Load(ctx context.Context, requestID string) (*ApprovalRequest, error)
List(ctx context.Context, agentID string, status ApprovalStatus, limit int) ([]*ApprovalRequest, error)
Update(ctx context.Context, request *ApprovalRequest) error
}
ApprovalStore 审批存储接口
type ApprovalType ¶
type ApprovalType string
ApprovalType 审批类型
const ( ApprovalTypeToolCall ApprovalType = "tool_call" // 工具调用审批 ApprovalTypeOutput ApprovalType = "output" // 输出审批 ApprovalTypeStateChange ApprovalType = "state_change" // 状态变更审批 ApprovalTypeDataAccess ApprovalType = "data_access" // 数据访问审批 ApprovalTypeCustom ApprovalType = "custom" // 自定义审批 )
type AsyncExecution ¶
type AsyncExecution struct {
ID string
AgentID string
Input *Input
Output *Output
Status ExecutionStatus
Error string
StartTime time.Time
EndTime time.Time
// contains filtered or unexported fields
}
AsyncExecution 异步执行状态
type AsyncExecutor ¶
type AsyncExecutor struct {
// contains filtered or unexported fields
}
AsyncExecutor 异步 Agent 执行器(基于 Anthropic 2026 标准) 支持异步 Subagent 创建和实时协调
func NewAsyncExecutor ¶
func NewAsyncExecutor(agent Agent, logger *zap.Logger) *AsyncExecutor
NewAsyncExecutor 创建异步执行器
func (*AsyncExecutor) ExecuteAsync ¶
func (e *AsyncExecutor) ExecuteAsync(ctx context.Context, input *Input) (*AsyncExecution, error)
ExecuteAsync 异步执行任务
func (*AsyncExecutor) ExecuteWithSubagents ¶
func (e *AsyncExecutor) ExecuteWithSubagents(ctx context.Context, input *Input, subagents []Agent) (*Output, error)
ExecuteWithSubagents 使用 Subagents 并行执行
type BaseAgent ¶
type BaseAgent struct {
// contains filtered or unexported fields
}
BaseAgent 提供可复用的状态管理、记忆、工具与 LLM 能力
func NewBaseAgent ¶
func NewBaseAgent( cfg Config, provider llm.Provider, memory MemoryManager, toolManager ToolManager, bus EventBus, logger *zap.Logger, ) *BaseAgent
NewBaseAgent 创建基础 Agent
func (*BaseAgent) AddInputValidator ¶
func (b *BaseAgent) AddInputValidator(v guardrails.Validator)
AddInputValidator adds a custom input validator Requirements 1.7: Support custom validation rule registration and extension
func (*BaseAgent) AddOutputFilter ¶
func (b *BaseAgent) AddOutputFilter(f guardrails.Filter)
AddOutputFilter adds a custom output filter
func (*BaseAgent) AddOutputValidator ¶
func (b *BaseAgent) AddOutputValidator(v guardrails.Validator)
AddOutputValidator adds a custom output validator Requirements 1.7: Support custom validation rule registration and extension
func (*BaseAgent) ChatCompletion ¶
func (b *BaseAgent) ChatCompletion(ctx context.Context, messages []llm.Message) (*llm.ChatResponse, error)
ChatCompletion 调用 LLM 完成对话
func (*BaseAgent) ContextEngineEnabled ¶
ContextEngineEnabled 返回上下文工程是否启用
func (*BaseAgent) EnableEnhancedMemory ¶
func (b *BaseAgent) EnableEnhancedMemory(memorySystem interface{})
EnableEnhancedMemory 启用增强记忆系统
func (*BaseAgent) EnableObservability ¶
func (b *BaseAgent) EnableObservability(obsSystem interface{})
EnableObservability 启用可观测性系统
func (*BaseAgent) EnablePromptEnhancer ¶
func (b *BaseAgent) EnablePromptEnhancer(enhancer interface{})
EnablePromptEnhancer 启用提示词增强
func (*BaseAgent) EnableReflection ¶
func (b *BaseAgent) EnableReflection(executor interface{})
EnableReflection 启用 Reflection 机制
func (*BaseAgent) EnableSkills ¶
func (b *BaseAgent) EnableSkills(manager interface{})
EnableSkills 启用 Skills 系统
func (*BaseAgent) EnableToolSelection ¶
func (b *BaseAgent) EnableToolSelection(selector interface{})
EnableToolSelection 启用动态工具选择
func (*BaseAgent) Execute ¶
Execute 执行任务(完整的 ReAct 循环) 这是 Agent 的核心执行方法,包含完整的推理-行动循环 Requirements 1.7: 集成输入验证 Requirements 2.4: 输出验证失败时支持重试
func (*BaseAgent) ExecuteEnhanced ¶
func (b *BaseAgent) ExecuteEnhanced(ctx context.Context, input *Input, options EnhancedExecutionOptions) (*Output, error)
ExecuteEnhanced 增强执行(集成所有功能)
func (*BaseAgent) ExportConfiguration ¶
ExportConfiguration 导出配置(用于持久化或分享)
func (*BaseAgent) GetFeatureMetrics ¶
GetFeatureMetrics 获取功能使用指标
func (*BaseAgent) GetFeatureStatus ¶
GetFeatureStatus 获取功能启用状态
func (*BaseAgent) GuardrailsEnabled ¶
GuardrailsEnabled returns whether guardrails are enabled
func (*BaseAgent) PrintFeatureStatus ¶
func (b *BaseAgent) PrintFeatureStatus()
PrintFeatureStatus 打印功能状态
func (*BaseAgent) QuickSetup ¶
func (b *BaseAgent) QuickSetup(ctx context.Context, options QuickSetupOptions) error
QuickSetup 快速设置(启用推荐功能) 注意:这个方法需要在实际项目中根据具体的类型进行实现 这里提供一个框架示例
func (*BaseAgent) RecallMemory ¶
func (b *BaseAgent) RecallMemory(ctx context.Context, query string, topK int) ([]MemoryRecord, error)
RecallMemory 检索记忆
func (*BaseAgent) SaveMemory ¶
func (b *BaseAgent) SaveMemory(ctx context.Context, content string, kind MemoryKind, metadata map[string]any) error
SaveMemory 保存记忆
func (*BaseAgent) SetContextManager ¶
func (b *BaseAgent) SetContextManager(cm ContextManager)
SetContextManager 设置上下文管理器
func (*BaseAgent) SetGuardrails ¶
func (b *BaseAgent) SetGuardrails(cfg *guardrails.GuardrailsConfig)
SetGuardrails configures guardrails for the agent Requirements 1.7: Support custom validation rule registration and extension
func (*BaseAgent) StreamCompletion ¶
func (b *BaseAgent) StreamCompletion(ctx context.Context, messages []llm.Message) (<-chan llm.StreamChunk, error)
StreamCompletion 流式调用 LLM
func (*BaseAgent) Transition ¶
Transition 状态转换(带校验)
func (*BaseAgent) ValidateConfiguration ¶
ValidateConfiguration 验证配置
type Checkpoint ¶
type Checkpoint struct {
ID string `json:"id"`
ThreadID string `json:"thread_id"` // 会话线程 ID
AgentID string `json:"agent_id"`
Version int `json:"version"` // 版本号(线程内递增)
State State `json:"state"`
Messages []CheckpointMessage `json:"messages"`
Metadata map[string]interface{} `json:"metadata"`
CreatedAt time.Time `json:"created_at"`
ParentID string `json:"parent_id,omitempty"` // 父检查点 ID
// ExecutionContext 工作流执行上下文
ExecutionContext *ExecutionContext `json:"execution_context,omitempty"`
}
Checkpoint Agent 执行检查点(基于 LangGraph 2026 标准)
type CheckpointDiff ¶
type CheckpointDiff struct {
ThreadID string `json:"thread_id"`
Version1 int `json:"version1"`
Version2 int `json:"version2"`
StateChanged bool `json:"state_changed"`
OldState State `json:"old_state"`
NewState State `json:"new_state"`
MessagesDiff string `json:"messages_diff"`
MetadataDiff string `json:"metadata_diff"`
TimeDiff time.Duration `json:"time_diff"`
}
CheckpointDiff represents the differences between two checkpoint versions
type CheckpointManager ¶
type CheckpointManager struct {
// contains filtered or unexported fields
}
CheckpointManager 检查点管理器
func NewCheckpointManager ¶
func NewCheckpointManager(store CheckpointStore, logger *zap.Logger) *CheckpointManager
NewCheckpointManager 创建检查点管理器
func (*CheckpointManager) CompareVersions ¶
func (m *CheckpointManager) CompareVersions(ctx context.Context, threadID string, version1, version2 int) (*CheckpointDiff, error)
CompareVersions compares two checkpoint versions and returns the differences
func (*CheckpointManager) CreateCheckpoint ¶
func (m *CheckpointManager) CreateCheckpoint(ctx context.Context, agent Agent, threadID string) error
CreateCheckpoint captures the current agent state and saves it as a checkpoint
func (*CheckpointManager) DisableAutoSave ¶
func (m *CheckpointManager) DisableAutoSave()
DisableAutoSave stops automatic checkpoint saving
func (*CheckpointManager) EnableAutoSave ¶
func (m *CheckpointManager) EnableAutoSave(ctx context.Context, agent Agent, threadID string, interval time.Duration) error
EnableAutoSave enables automatic checkpoint saving with the specified interval
func (*CheckpointManager) ListVersions ¶
func (m *CheckpointManager) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)
ListVersions lists all checkpoint versions for a thread
func (*CheckpointManager) LoadCheckpoint ¶
func (m *CheckpointManager) LoadCheckpoint(ctx context.Context, checkpointID string) (*Checkpoint, error)
LoadCheckpoint 加载检查点
func (*CheckpointManager) LoadLatestCheckpoint ¶
func (m *CheckpointManager) LoadLatestCheckpoint(ctx context.Context, threadID string) (*Checkpoint, error)
LoadLatestCheckpoint 加载最新检查点
func (*CheckpointManager) ResumeFromCheckpoint ¶
func (m *CheckpointManager) ResumeFromCheckpoint(ctx context.Context, agent Agent, checkpointID string) error
ResumeFromCheckpoint 从检查点恢复执行
func (*CheckpointManager) RollbackToVersion ¶
func (m *CheckpointManager) RollbackToVersion(ctx context.Context, agent Agent, threadID string, version int) error
RollbackToVersion rolls back the agent to a specific checkpoint version
func (*CheckpointManager) SaveCheckpoint ¶
func (m *CheckpointManager) SaveCheckpoint(ctx context.Context, checkpoint *Checkpoint) error
SaveCheckpoint 保存检查点
type CheckpointMessage ¶
type CheckpointMessage struct {
Role string `json:"role"`
Content string `json:"content"`
ToolCalls []CheckpointToolCall `json:"tool_calls,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
CheckpointMessage 检查点消息
type CheckpointStore ¶
type CheckpointStore interface {
// Save 保存检查点
Save(ctx context.Context, checkpoint *Checkpoint) error
// Load 加载检查点
Load(ctx context.Context, checkpointID string) (*Checkpoint, error)
// LoadLatest 加载线程最新检查点
LoadLatest(ctx context.Context, threadID string) (*Checkpoint, error)
// List 列出线程的所有检查点
List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error)
// Delete 删除检查点
Delete(ctx context.Context, checkpointID string) error
// DeleteThread 删除整个线程
DeleteThread(ctx context.Context, threadID string) error
// LoadVersion 加载指定版本的检查点
LoadVersion(ctx context.Context, threadID string, version int) (*Checkpoint, error)
// ListVersions 列出线程的所有版本
ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)
// Rollback 回滚到指定版本
Rollback(ctx context.Context, threadID string, version int) error
}
CheckpointStore 检查点存储接口
type CheckpointToolCall ¶
type CheckpointToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
Result json.RawMessage `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
CheckpointToolCall 工具调用记录
type CheckpointVersion ¶
type CheckpointVersion struct {
Version int `json:"version"`
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
State State `json:"state"`
Summary string `json:"summary"`
}
CheckpointVersion 检查点版本元数据
type Config ¶
type Config struct {
ID string `json:"id"`
Name string `json:"name"`
Type AgentType `json:"type"`
Description string `json:"description,omitempty"`
Model string `json:"model"` // LLM 模型
Provider string `json:"provider,omitempty"` // LLM Provider
MaxTokens int `json:"max_tokens,omitempty"` // 最大 token
Temperature float32 `json:"temperature,omitempty"` // 温度
PromptBundle PromptBundle `json:"prompt_bundle,omitempty"` // 模块化提示词包
Tools []string `json:"tools,omitempty"` // 可用工具列表
Metadata map[string]string `json:"metadata,omitempty"`
// 2025 新增配置(可选)
EnableReflection bool `json:"enable_reflection,omitempty"`
EnableToolSelection bool `json:"enable_tool_selection,omitempty"`
EnablePromptEnhancer bool `json:"enable_prompt_enhancer,omitempty"`
EnableSkills bool `json:"enable_skills,omitempty"`
EnableMCP bool `json:"enable_mcp,omitempty"`
EnableEnhancedMemory bool `json:"enable_enhanced_memory,omitempty"`
EnableObservability bool `json:"enable_observability,omitempty"`
// 2026 Guardrails 配置
// Requirements 1.7: 支持自定义验证规则的注册和扩展
Guardrails *guardrails.GuardrailsConfig `json:"guardrails,omitempty"`
}
Config Agent 配置
type Container ¶
type Container struct {
// contains filtered or unexported fields
}
Container holds all dependencies for agent creation.
func (*Container) CreateBaseAgent ¶
CreateBaseAgent creates a BaseAgent using container dependencies.
func (*Container) CreateModularAgent ¶
func (c *Container) CreateModularAgent(config ModularAgentConfig) (*ModularAgent, error)
CreateModularAgent creates a ModularAgent using container dependencies.
func (*Container) Memory ¶
func (c *Container) Memory() MemoryManager
Memory returns the memory manager.
func (*Container) ToolManager ¶
func (c *Container) ToolManager() ToolManager
ToolManager returns the tool manager.
func (*Container) WithEventBus ¶
WithEventBus sets the event bus.
func (*Container) WithGuardrailsFactory ¶
WithGuardrailsFactory sets the guardrails extension factory.
func (*Container) WithLogger ¶
WithLogger sets the logger.
func (*Container) WithMemory ¶
func (c *Container) WithMemory(memory MemoryManager) *Container
WithMemory sets the memory manager.
func (*Container) WithProvider ¶
WithProvider sets the LLM provider.
func (*Container) WithReflectionFactory ¶
WithReflectionFactory sets the reflection extension factory.
func (*Container) WithToolManager ¶
func (c *Container) WithToolManager(toolManager ToolManager) *Container
WithToolManager sets the tool manager.
func (*Container) WithToolSelectionFactory ¶
WithToolSelectionFactory sets the tool selection extension factory.
type ContextManager ¶
type ContextManager interface {
PrepareMessages(ctx context.Context, messages []llm.Message, currentQuery string) ([]llm.Message, error)
GetStatus(messages []llm.Message) interface{}
EstimateTokens(messages []llm.Message) int
}
ContextManager 上下文管理器接口 使用 pkg/context.AgentContextManager 作为标准实现
type Critique ¶
type Critique struct {
Score float64 `json:"score"` // 0-1 分数
IsGood bool `json:"is_good"` // 是否达标
Issues []string `json:"issues"` // 问题列表
Suggestions []string `json:"suggestions"` // 改进建议
RawFeedback string `json:"raw_feedback"` // 原始反馈
}
Critique 评审结果
type DefaultApprovalPolicy ¶
type DefaultApprovalPolicy struct {
// 需要审批的工具列表
RequireApprovalTools []string
// 需要审批的状态变更
RequireApprovalStates []State
// 总是需要审批
AlwaysRequireApproval bool
}
DefaultApprovalPolicy 默认审批策略
func (*DefaultApprovalPolicy) RequiresApproval ¶
func (p *DefaultApprovalPolicy) RequiresApproval(ctx context.Context, agentID string, action Action) bool
RequiresApproval 检查是否需要审批
type DefensivePromptConfig ¶
type DefensivePromptConfig struct {
// 失败处理模式
FailureModes []FailureMode `json:"failure_modes"`
// 输出 Schema 强制
OutputSchema *OutputSchema `json:"output_schema,omitempty"`
// 护栏规则
GuardRails []GuardRail `json:"guard_rails"`
// 提示注入防护
InjectionDefense *InjectionDefenseConfig `json:"injection_defense,omitempty"`
}
DefensivePromptConfig 防御性提示配置(基于 2025 年生产最佳实践)
func DefaultDefensivePromptConfig ¶
func DefaultDefensivePromptConfig() DefensivePromptConfig
DefaultDefensivePromptConfig 返回默认防御性提示配置
type DefensivePromptEnhancer ¶
type DefensivePromptEnhancer struct {
// contains filtered or unexported fields
}
DefensivePromptEnhancer 防御性提示增强器
func NewDefensivePromptEnhancer ¶
func NewDefensivePromptEnhancer(config DefensivePromptConfig) *DefensivePromptEnhancer
NewDefensivePromptEnhancer 创建防御性提示增强器
func (*DefensivePromptEnhancer) EnhancePromptBundle ¶
func (e *DefensivePromptEnhancer) EnhancePromptBundle(bundle PromptBundle) PromptBundle
EnhancePromptBundle 增强提示词包(添加防御性规则)
func (*DefensivePromptEnhancer) SanitizeUserInput ¶
func (e *DefensivePromptEnhancer) SanitizeUserInput(input string) (string, bool)
SanitizeUserInput 清理用户输入(防止提示注入)
func (*DefensivePromptEnhancer) ValidateOutput ¶
func (e *DefensivePromptEnhancer) ValidateOutput(output string) error
ValidateOutput 验证输出是否符合 Schema
type DynamicToolSelector ¶
type DynamicToolSelector struct {
// contains filtered or unexported fields
}
DynamicToolSelector 动态工具选择器
func NewDynamicToolSelector ¶
func NewDynamicToolSelector(agent *BaseAgent, config ToolSelectionConfig) *DynamicToolSelector
NewDynamicToolSelector 创建动态工具选择器
func (*DynamicToolSelector) ScoreTools ¶
func (s *DynamicToolSelector) ScoreTools(ctx context.Context, task string, tools []llm.ToolSchema) ([]ToolScore, error)
ScoreTools 对工具进行评分
func (*DynamicToolSelector) SelectTools ¶
func (s *DynamicToolSelector) SelectTools(ctx context.Context, task string, availableTools []llm.ToolSchema) ([]llm.ToolSchema, error)
SelectTools 选择最佳工具
func (*DynamicToolSelector) UpdateToolStats ¶
func (s *DynamicToolSelector) UpdateToolStats(toolName string, success bool, latency time.Duration, cost float64)
UpdateToolStats 更新工具统计信息
type EnhancedExecutionOptions ¶
type EnhancedExecutionOptions struct {
// Reflection 选项
UseReflection bool
ReflectionConfig interface{} // ReflectionConfig
// 工具选择选项
UseToolSelection bool
ToolSelectionConfig interface{} // ToolSelectionConfig
// 提示词增强选项
UsePromptEnhancer bool
PromptEngineeringConfig interface{} // PromptEngineeringConfig
// Skills 选项
UseSkills bool
SkillsQuery string
// 记忆选项
UseEnhancedMemory bool
LoadWorkingMemory bool
LoadShortTermMemory bool
SaveToMemory bool
// 可观测性选项
UseObservability bool
RecordMetrics bool
RecordTrace bool
}
EnhancedExecutionOptions 增强执行选项
func DefaultEnhancedExecutionOptions ¶
func DefaultEnhancedExecutionOptions() EnhancedExecutionOptions
DefaultEnhancedExecutionOptions 默认增强执行选项
type ErrInvalidTransition ¶
ErrInvalidTransition 状态转换错误
func (ErrInvalidTransition) Error ¶
func (e ErrInvalidTransition) Error() string
func (ErrInvalidTransition) ToAgentError ¶
func (e ErrInvalidTransition) ToAgentError() *Error
ToAgentError 将 ErrInvalidTransition 转换为 Agent.Error
type Error ¶
type Error struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
AgentID string `json:"agent_id,omitempty"`
AgentType AgentType `json:"agent_type,omitempty"`
Retryable bool `json:"retryable"`
Timestamp time.Time `json:"timestamp"`
Cause error `json:"-"` // 原始错误
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Error Agent 统一错误类型 Extends types.Error with Agent-specific fields.
func FromTypesError ¶
FromTypesError converts a types.Error to an agent.Error
func NewErrorWithCause ¶
NewErrorWithCause 创建带原因的错误
func (*Error) ToTypesError ¶
ToTypesError converts an agent.Error to a types.Error
func (*Error) WithMetadata ¶
WithMetadata 添加元数据
func (*Error) WithRetryable ¶
WithRetryable 设置是否可重试
type ErrorCode ¶
ErrorCode 定义 Agent 错误码 Uses types.ErrorCode as the underlying type for consistency with the framework.
const ( // 状态相关错误 ErrCodeInvalidTransition ErrorCode = "AGENT_INVALID_TRANSITION" ErrCodeNotReady ErrorCode = "AGENT_NOT_READY" ErrCodeBusy ErrorCode = "AGENT_BUSY" ErrCodeNotFound ErrorCode = "AGENT_NOT_FOUND" // 配置相关错误 ErrCodeProviderNotSet ErrorCode = "AGENT_PROVIDER_NOT_SET" ErrCodeInvalidConfig ErrorCode = "AGENT_INVALID_CONFIG" // 执行相关错误 ErrCodeExecutionFailed ErrorCode = "AGENT_EXECUTION_FAILED" ErrCodePlanningFailed ErrorCode = "AGENT_PLANNING_FAILED" ErrCodeTimeout ErrorCode = "AGENT_TIMEOUT" // 工具相关错误 ErrCodeToolNotFound ErrorCode = "AGENT_TOOL_NOT_FOUND" ErrCodeToolNotAllowed ErrorCode = "AGENT_TOOL_NOT_ALLOWED" ErrCodeToolExecFailed ErrorCode = "AGENT_TOOL_EXEC_FAILED" ErrCodeToolValidation ErrorCode = "AGENT_TOOL_VALIDATION" // 记忆相关错误 ErrCodeMemoryNotSet ErrorCode = "AGENT_MEMORY_NOT_SET" ErrCodeMemorySaveFailed ErrorCode = "AGENT_MEMORY_SAVE_FAILED" ErrCodeMemoryLoadFailed ErrorCode = "AGENT_MEMORY_LOAD_FAILED" // Reflection 相关错误 ErrCodeReflectionFailed ErrorCode = "AGENT_REFLECTION_FAILED" ErrCodeCritiqueFailed ErrorCode = "AGENT_CRITIQUE_FAILED" // 上下文相关错误 ErrCodeContextOptimizationFailed ErrorCode = "AGENT_CONTEXT_OPTIMIZATION_FAILED" // Guardrails 相关错误 ErrCodeGuardrailsViolated ErrorCode = "AGENT_GUARDRAILS_VIOLATED" )
Agent-specific error codes These extend the base error codes defined in types/error.go
func GetErrorCode ¶
GetErrorCode extracts the error code from an error
type EventBus ¶
type EventBus interface {
Publish(event Event)
Subscribe(eventType EventType, handler EventHandler) string
Unsubscribe(subscriptionID string)
}
EventBus 定义事件总线接口
type ExecutionContext ¶
type ExecutionContext struct {
WorkflowID string `json:"workflow_id,omitempty"`
CurrentNode string `json:"current_node,omitempty"`
NodeResults map[string]interface{} `json:"node_results,omitempty"`
Variables map[string]interface{} `json:"variables,omitempty"`
}
ExecutionContext 工作流执行上下文
type ExecutionStatus ¶
type ExecutionStatus string
ExecutionStatus 执行状态
const ( ExecutionStatusPending ExecutionStatus = "pending" ExecutionStatusRunning ExecutionStatus = "running" ExecutionStatusCompleted ExecutionStatus = "completed" ExecutionStatusFailed ExecutionStatus = "failed" ExecutionStatusCancelled ExecutionStatus = "cancelled" )
type ExtensionManager ¶
type ExtensionManager struct {
// contains filtered or unexported fields
}
ExtensionManager manages optional agent extensions.
func NewExtensionManager ¶
func NewExtensionManager(logger *zap.Logger) *ExtensionManager
NewExtensionManager creates a new ExtensionManager.
func (*ExtensionManager) EnhancedMemory ¶
func (em *ExtensionManager) EnhancedMemory() types.EnhancedMemoryExtension
EnhancedMemory returns the enhanced memory extension.
func (*ExtensionManager) Guardrails ¶
func (em *ExtensionManager) Guardrails() types.GuardrailsExtension
Guardrails returns the guardrails extension.
func (*ExtensionManager) HasGuardrails ¶
func (em *ExtensionManager) HasGuardrails() bool
HasGuardrails checks if guardrails are available.
func (*ExtensionManager) HasObservability ¶
func (em *ExtensionManager) HasObservability() bool
HasObservability checks if observability is available.
func (*ExtensionManager) HasReflection ¶
func (em *ExtensionManager) HasReflection() bool
HasReflection checks if reflection is available.
func (*ExtensionManager) HasToolSelection ¶
func (em *ExtensionManager) HasToolSelection() bool
HasToolSelection checks if tool selection is available.
func (*ExtensionManager) MCP ¶
func (em *ExtensionManager) MCP() types.MCPExtension
MCP returns the MCP extension.
func (*ExtensionManager) Observability ¶
func (em *ExtensionManager) Observability() types.ObservabilityExtension
Observability returns the observability extension.
func (*ExtensionManager) PromptEnhancer ¶
func (em *ExtensionManager) PromptEnhancer() types.PromptEnhancerExtension
PromptEnhancer returns the prompt enhancer extension.
func (*ExtensionManager) Reflection ¶
func (em *ExtensionManager) Reflection() types.ReflectionExtension
Reflection returns the reflection extension.
func (*ExtensionManager) SetEnhancedMemory ¶
func (em *ExtensionManager) SetEnhancedMemory(ext types.EnhancedMemoryExtension)
SetEnhancedMemory sets the enhanced memory extension.
func (*ExtensionManager) SetGuardrails ¶
func (em *ExtensionManager) SetGuardrails(ext types.GuardrailsExtension)
SetGuardrails sets the guardrails extension.
func (*ExtensionManager) SetMCP ¶
func (em *ExtensionManager) SetMCP(ext types.MCPExtension)
SetMCP sets the MCP extension.
func (*ExtensionManager) SetObservability ¶
func (em *ExtensionManager) SetObservability(ext types.ObservabilityExtension)
SetObservability sets the observability extension.
func (*ExtensionManager) SetPromptEnhancer ¶
func (em *ExtensionManager) SetPromptEnhancer(ext types.PromptEnhancerExtension)
SetPromptEnhancer sets the prompt enhancer extension.
func (*ExtensionManager) SetReflection ¶
func (em *ExtensionManager) SetReflection(ext types.ReflectionExtension)
SetReflection sets the reflection extension.
func (*ExtensionManager) SetSkills ¶
func (em *ExtensionManager) SetSkills(ext types.SkillsExtension)
SetSkills sets the skills extension.
func (*ExtensionManager) SetToolSelection ¶
func (em *ExtensionManager) SetToolSelection(ext types.ToolSelectionExtension)
SetToolSelection sets the tool selection extension.
func (*ExtensionManager) Skills ¶
func (em *ExtensionManager) Skills() types.SkillsExtension
Skills returns the skills extension.
func (*ExtensionManager) ToolSelection ¶
func (em *ExtensionManager) ToolSelection() types.ToolSelectionExtension
ToolSelection returns the tool selection extension.
type FailureMode ¶
type FailureMode struct {
Condition string `json:"condition"` // "missing_data", "ambiguous_input", "conflicting_requirements", "tool_unavailable"
Action string `json:"action"` // "return_error", "request_clarification", "use_default", "escalate_to_human"
Template string `json:"template"` // 错误消息模板
Example string `json:"example,omitempty"`
}
FailureMode 失败模式定义
type Feedback ¶
type Feedback struct {
Type string `json:"type"` // approval/rejection/correction
Content string `json:"content,omitempty"`
Data map[string]any `json:"data,omitempty"`
}
Feedback 反馈信息
type FeedbackEvent ¶
type FeedbackEvent struct {
AgentID_ string
FeedbackType string
Content string
Data map[string]any
Timestamp_ time.Time
}
FeedbackEvent 反馈事件
func (*FeedbackEvent) Timestamp ¶
func (e *FeedbackEvent) Timestamp() time.Time
func (*FeedbackEvent) Type ¶
func (e *FeedbackEvent) Type() EventType
type FileCheckpointStore ¶
type FileCheckpointStore struct {
// contains filtered or unexported fields
}
FileCheckpointStore 文件检查点存储(用于本地开发和测试)
func NewFileCheckpointStore ¶
func NewFileCheckpointStore(basePath string, logger *zap.Logger) (*FileCheckpointStore, error)
NewFileCheckpointStore 创建文件检查点存储
func (*FileCheckpointStore) Delete ¶
func (s *FileCheckpointStore) Delete(ctx context.Context, checkpointID string) error
Delete 删除检查点
func (*FileCheckpointStore) DeleteThread ¶
func (s *FileCheckpointStore) DeleteThread(ctx context.Context, threadID string) error
DeleteThread 删除线程
func (*FileCheckpointStore) List ¶
func (s *FileCheckpointStore) List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error)
List 列出检查点
func (*FileCheckpointStore) ListVersions ¶
func (s *FileCheckpointStore) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)
ListVersions 列出线程的所有版本
func (*FileCheckpointStore) Load ¶
func (s *FileCheckpointStore) Load(ctx context.Context, checkpointID string) (*Checkpoint, error)
Load 加载检查点
func (*FileCheckpointStore) LoadLatest ¶
func (s *FileCheckpointStore) LoadLatest(ctx context.Context, threadID string) (*Checkpoint, error)
LoadLatest 加载最新检查点
func (*FileCheckpointStore) LoadVersion ¶
func (s *FileCheckpointStore) LoadVersion(ctx context.Context, threadID string, version int) (*Checkpoint, error)
LoadVersion 加载指定版本的检查点
func (*FileCheckpointStore) Save ¶
func (s *FileCheckpointStore) Save(ctx context.Context, checkpoint *Checkpoint) error
Save 保存检查点
type GuardRail ¶
type GuardRail struct {
Type string `json:"type"` // "never", "always", "boundary", "constraint"
Category string `json:"category"` // "data_safety", "action_limit", "disclosure", "ethical"
Description string `json:"description"`
Examples []string `json:"examples,omitempty"`
Severity string `json:"severity"` // "critical", "high", "medium", "low"
}
GuardRail 护栏规则(负面指令)
type GuardrailsError ¶
type GuardrailsError struct {
Type GuardrailsErrorType `json:"type"`
Message string `json:"message"`
Errors []guardrails.ValidationError `json:"errors"`
}
GuardrailsError represents a guardrails validation error Requirements 1.6: Return detailed error information with failure reasons
func (*GuardrailsError) Error ¶
func (e *GuardrailsError) Error() string
Error implements the error interface
type GuardrailsErrorType ¶
type GuardrailsErrorType string
GuardrailsErrorType defines the type of guardrails error
const ( // GuardrailsErrorTypeInput indicates input validation failure GuardrailsErrorTypeInput GuardrailsErrorType = "input" // GuardrailsErrorTypeOutput indicates output validation failure GuardrailsErrorTypeOutput GuardrailsErrorType = "output" )
type HealthStatus ¶
type HealthStatus struct {
Healthy bool `json:"healthy"`
State State `json:"state"`
LastCheck time.Time `json:"last_check"`
Message string `json:"message,omitempty"`
}
HealthStatus 健康状态
type HumanInLoopManager ¶
type HumanInLoopManager struct {
// contains filtered or unexported fields
}
HumanInLoopManager Human-in-the-Loop 管理器(生产级) 支持人工审批、反馈和干预
func NewHumanInLoopManager ¶
func NewHumanInLoopManager(store ApprovalStore, eventBus EventBus, logger *zap.Logger) *HumanInLoopManager
NewHumanInLoopManager 创建 Human-in-the-Loop 管理器
func (*HumanInLoopManager) CancelApproval ¶
func (m *HumanInLoopManager) CancelApproval(ctx context.Context, requestID string) error
CancelApproval 取消审批请求
func (*HumanInLoopManager) GetPendingRequests ¶
func (m *HumanInLoopManager) GetPendingRequests(agentID string) []*ApprovalRequest
GetPendingRequests 获取待审批请求
func (*HumanInLoopManager) RequestApproval ¶
func (m *HumanInLoopManager) RequestApproval(ctx context.Context, agentID string, approvalType ApprovalType, content string, timeout time.Duration) (*ApprovalResponse, error)
RequestApproval 请求人工审批
func (*HumanInLoopManager) RespondToApproval ¶
func (m *HumanInLoopManager) RespondToApproval(ctx context.Context, requestID string, response *ApprovalResponse) error
RespondToApproval 响应审批请求
type InMemoryApprovalStore ¶
type InMemoryApprovalStore struct {
// contains filtered or unexported fields
}
InMemoryApprovalStore 内存审批存储
func NewInMemoryApprovalStore ¶
func NewInMemoryApprovalStore() *InMemoryApprovalStore
NewInMemoryApprovalStore 创建内存审批存储
func (*InMemoryApprovalStore) List ¶
func (s *InMemoryApprovalStore) List(ctx context.Context, agentID string, status ApprovalStatus, limit int) ([]*ApprovalRequest, error)
func (*InMemoryApprovalStore) Load ¶
func (s *InMemoryApprovalStore) Load(ctx context.Context, requestID string) (*ApprovalRequest, error)
func (*InMemoryApprovalStore) Save ¶
func (s *InMemoryApprovalStore) Save(ctx context.Context, request *ApprovalRequest) error
func (*InMemoryApprovalStore) Update ¶
func (s *InMemoryApprovalStore) Update(ctx context.Context, request *ApprovalRequest) error
type InjectionDefenseConfig ¶
type InjectionDefenseConfig struct {
Enabled bool `json:"enabled"`
DetectionPatterns []string `json:"detection_patterns"`
UseDelimiters bool `json:"use_delimiters"`
SanitizeInput bool `json:"sanitize_input"`
RoleIsolation bool `json:"role_isolation"` // 分离用户输入和系统指令
}
InjectionDefenseConfig 提示注入防护配置
type Input ¶
type Input struct {
TraceID string `json:"trace_id"`
TenantID string `json:"tenant_id,omitempty"`
UserID string `json:"user_id,omitempty"`
ChannelID string `json:"channel_id,omitempty"`
Content string `json:"content"`
Context map[string]any `json:"context,omitempty"` // 额外上下文
Variables map[string]string `json:"variables,omitempty"` // 变量替换
}
Input Agent 输入
type LLMExecutor ¶
type LLMExecutor struct {
// contains filtered or unexported fields
}
LLMExecutor handles LLM interactions.
func NewLLMExecutor ¶
func NewLLMExecutor(provider llm.Provider, config LLMExecutorConfig, logger *zap.Logger) *LLMExecutor
NewLLMExecutor creates a new LLMExecutor.
func (*LLMExecutor) Complete ¶
func (e *LLMExecutor) Complete(ctx context.Context, messages []llm.Message) (*llm.ChatResponse, error)
Complete sends a completion request to the LLM.
func (*LLMExecutor) Provider ¶
func (e *LLMExecutor) Provider() llm.Provider
Provider returns the underlying LLM provider.
func (*LLMExecutor) SetContextManager ¶
func (e *LLMExecutor) SetContextManager(cm ContextManager)
SetContextManager sets the context manager for message optimization.
func (*LLMExecutor) Stream ¶
func (e *LLMExecutor) Stream(ctx context.Context, messages []llm.Message) (<-chan llm.StreamChunk, error)
Stream sends a streaming request to the LLM.
type LLMExecutorConfig ¶
LLMExecutorConfig configures the LLM executor.
type LifecycleManager ¶
type LifecycleManager struct {
// contains filtered or unexported fields
}
LifecycleManager 管理 Agent 的生命周期 提供启动、停止、健康检查等功能
func NewLifecycleManager ¶
func NewLifecycleManager(agent Agent, logger *zap.Logger) *LifecycleManager
NewLifecycleManager 创建生命周期管理器
func (*LifecycleManager) GetHealthStatus ¶
func (lm *LifecycleManager) GetHealthStatus() HealthStatus
GetHealthStatus 获取健康状态
func (*LifecycleManager) IsRunning ¶
func (lm *LifecycleManager) IsRunning() bool
IsRunning 检查是否正在运行
func (*LifecycleManager) Restart ¶
func (lm *LifecycleManager) Restart(ctx context.Context) error
Restart 重启 Agent
type MCPServerOptions ¶
MCPServerOptions configures how the builder creates a default MCP server.
type MemoryConfig ¶
type MemoryConfig struct {
Enabled bool `json:"enabled,omitempty"`
}
type MemoryKind ¶
type MemoryKind = types.MemoryCategory
MemoryKind 记忆类型 Deprecated: Use types.MemoryCategory instead for new code. This alias is kept for backward compatibility.
type MemoryManager ¶
type MemoryManager interface {
MemoryWriter
MemoryReader
}
MemoryManager 组合读写接口
type MemoryReader ¶
type MemoryReader interface {
// LoadRecent 加载最近的记忆(按时间倒序)
LoadRecent(ctx context.Context, agentID string, kind MemoryKind, limit int) ([]MemoryRecord, error)
// Search 语义检索(长期记忆)
Search(ctx context.Context, agentID string, query string, topK int) ([]MemoryRecord, error)
// Get 获取单条记忆
Get(ctx context.Context, id string) (*MemoryRecord, error)
}
MemoryReader 记忆读取接口
type MemoryRecord ¶
type MemoryRecord struct {
ID string `json:"id"`
AgentID string `json:"agent_id"`
Kind types.MemoryCategory `json:"kind"`
Content string `json:"content"`
Metadata map[string]any `json:"metadata,omitempty"`
VectorID string `json:"vector_id,omitempty"` // Qdrant 向量 ID
CreatedAt time.Time `json:"created_at"`
ExpiresAt *time.Time `json:"expires_at,omitempty"` // 短期记忆过期时间
}
MemoryRecord 统一记忆结构 Uses types.MemoryCategory for the Kind field to ensure consistency.
type MemoryWriter ¶
type MemoryWriter interface {
// Save 保存记忆
Save(ctx context.Context, rec MemoryRecord) error
// Delete 删除记忆
Delete(ctx context.Context, id string) error
// Clear 清空 Agent 的所有记忆
Clear(ctx context.Context, agentID string, kind MemoryKind) error
}
MemoryWriter 记忆写入接口
type MiddlewarePlugin ¶
type MiddlewarePlugin interface {
Plugin
// Wrap wraps the execution function.
Wrap(next func(ctx context.Context, input *Input) (*Output, error)) func(ctx context.Context, input *Input) (*Output, error)
}
MiddlewarePlugin wraps agent execution.
type ModularAgent ¶
type ModularAgent struct {
// contains filtered or unexported fields
}
ModularAgent is a refactored agent using composition over inheritance. It delegates responsibilities to specialized components.
func NewModularAgent ¶
func NewModularAgent( config ModularAgentConfig, provider llm.Provider, memory MemoryManager, tools ToolManager, bus EventBus, logger *zap.Logger, ) *ModularAgent
NewModularAgent creates a new ModularAgent.
func (*ModularAgent) Extensions ¶
func (a *ModularAgent) Extensions() *ExtensionManager
Extensions returns the extension manager.
func (*ModularAgent) Init ¶
func (a *ModularAgent) Init(ctx context.Context) error
Init initializes the agent.
func (*ModularAgent) Memory ¶
func (a *ModularAgent) Memory() MemoryManager
Memory returns the memory manager.
func (*ModularAgent) Observe ¶
func (a *ModularAgent) Observe(ctx context.Context, feedback *Feedback) error
Observe processes feedback.
func (*ModularAgent) Plan ¶
func (a *ModularAgent) Plan(ctx context.Context, input *Input) (*PlanResult, error)
Plan generates an execution plan.
func (*ModularAgent) Teardown ¶
func (a *ModularAgent) Teardown(ctx context.Context) error
Teardown cleans up the agent.
func (*ModularAgent) Tools ¶
func (a *ModularAgent) Tools() ToolManager
Tools returns the tool manager.
type ModularAgentConfig ¶
type ModularAgentConfig struct {
ID string
Name string
Type AgentType
Description string
LLM LLMExecutorConfig
}
ModularAgentConfig configures a ModularAgent.
type Output ¶
type Output struct {
TraceID string `json:"trace_id"`
Content string `json:"content"`
Metadata map[string]any `json:"metadata,omitempty"`
TokensUsed int `json:"tokens_used,omitempty"`
Cost float64 `json:"cost,omitempty"`
Duration time.Duration `json:"duration"`
FinishReason string `json:"finish_reason,omitempty"`
}
Output Agent 输出
type OutputSchema ¶
type OutputSchema struct {
Type string `json:"type"` // "json", "markdown", "structured_text"
Schema map[string]interface{} `json:"schema,omitempty"` // JSON Schema
Required []string `json:"required,omitempty"`
Example string `json:"example,omitempty"`
Validation string `json:"validation,omitempty"` // 验证规则描述
}
OutputSchema 输出格式 Schema
type PlanConfig ¶
type PlanConfig struct {
Enabled bool `json:"enabled,omitempty"`
}
type PlanResult ¶
type PlanResult struct {
Steps []string `json:"steps"` // 执行步骤
Estimate time.Duration `json:"estimate,omitempty"` // 预估耗时
Metadata map[string]any `json:"metadata,omitempty"`
}
PlanResult 规划结果
type Plugin ¶
type Plugin interface {
// Name returns the plugin name.
Name() string
// Type returns the plugin type.
Type() PluginType
// Init initializes the plugin.
Init(ctx context.Context) error
// Close cleans up the plugin.
Close(ctx context.Context) error
}
Plugin defines the interface for agent plugins.
type PluginEnabledAgent ¶
type PluginEnabledAgent struct {
// contains filtered or unexported fields
}
PluginEnabledAgent wraps an agent with plugin support.
func NewPluginEnabledAgent ¶
func NewPluginEnabledAgent(agent Agent, registry *PluginRegistry) *PluginEnabledAgent
NewPluginEnabledAgent creates a plugin-enabled agent wrapper.
func (*PluginEnabledAgent) Init ¶
func (a *PluginEnabledAgent) Init(ctx context.Context) error
Init initializes the agent and plugins.
func (*PluginEnabledAgent) Name ¶
func (a *PluginEnabledAgent) Name() string
Name returns the agent name.
func (*PluginEnabledAgent) Observe ¶
func (a *PluginEnabledAgent) Observe(ctx context.Context, feedback *Feedback) error
Observe processes feedback.
func (*PluginEnabledAgent) Plan ¶
func (a *PluginEnabledAgent) Plan(ctx context.Context, input *Input) (*PlanResult, error)
Plan generates an execution plan.
func (*PluginEnabledAgent) Registry ¶
func (a *PluginEnabledAgent) Registry() *PluginRegistry
Registry returns the plugin registry.
func (*PluginEnabledAgent) State ¶
func (a *PluginEnabledAgent) State() State
State returns the agent state.
func (*PluginEnabledAgent) Teardown ¶
func (a *PluginEnabledAgent) Teardown(ctx context.Context) error
Teardown cleans up the agent and plugins.
func (*PluginEnabledAgent) Type ¶
func (a *PluginEnabledAgent) Type() AgentType
Type returns the agent type.
func (*PluginEnabledAgent) UnderlyingAgent ¶
func (a *PluginEnabledAgent) UnderlyingAgent() Agent
UnderlyingAgent returns the wrapped agent.
type PluginRegistry ¶
type PluginRegistry struct {
// contains filtered or unexported fields
}
PluginRegistry manages plugin registration and lifecycle.
func NewPluginRegistry ¶
func NewPluginRegistry() *PluginRegistry
NewPluginRegistry creates a new plugin registry.
func (*PluginRegistry) Close ¶
func (r *PluginRegistry) Close(ctx context.Context) error
Close closes all plugins.
func (*PluginRegistry) Get ¶
func (r *PluginRegistry) Get(name string) (Plugin, bool)
Get retrieves a plugin by name.
func (*PluginRegistry) Init ¶
func (r *PluginRegistry) Init(ctx context.Context) error
Init initializes all plugins.
func (*PluginRegistry) List ¶
func (r *PluginRegistry) List() []Plugin
List returns all registered plugins.
func (*PluginRegistry) MiddlewarePlugins ¶
func (r *PluginRegistry) MiddlewarePlugins() []MiddlewarePlugin
MiddlewarePlugins returns all middleware plugins.
func (*PluginRegistry) PostProcessPlugins ¶
func (r *PluginRegistry) PostProcessPlugins() []PostProcessPlugin
PostProcessPlugins returns all post-process plugins.
func (*PluginRegistry) PreProcessPlugins ¶
func (r *PluginRegistry) PreProcessPlugins() []PreProcessPlugin
PreProcessPlugins returns all pre-process plugins.
func (*PluginRegistry) Register ¶
func (r *PluginRegistry) Register(plugin Plugin) error
Register registers a plugin.
func (*PluginRegistry) Unregister ¶
func (r *PluginRegistry) Unregister(name string) error
Unregister removes a plugin.
type PluginType ¶
type PluginType string
PluginType defines the type of plugin.
const ( PluginTypePreProcess PluginType = "pre_process" // Runs before execution PluginTypePostProcess PluginType = "post_process" // Runs after execution PluginTypeMiddleware PluginType = "middleware" // Wraps execution PluginTypeExtension PluginType = "extension" // Adds new capabilities )
type PostProcessPlugin ¶
type PostProcessPlugin interface {
Plugin
// PostProcess processes output after execution.
PostProcess(ctx context.Context, output *Output) (*Output, error)
}
PostProcessPlugin runs after agent execution.
type PostgreSQLCheckpointStore ¶
type PostgreSQLCheckpointStore struct {
// contains filtered or unexported fields
}
PostgreSQLCheckpointStore PostgreSQL 检查点存储
func NewPostgreSQLCheckpointStore ¶
func NewPostgreSQLCheckpointStore(db PostgreSQLClient, logger *zap.Logger) *PostgreSQLCheckpointStore
NewPostgreSQLCheckpointStore 创建 PostgreSQL 检查点存储
func (*PostgreSQLCheckpointStore) Delete ¶
func (s *PostgreSQLCheckpointStore) Delete(ctx context.Context, checkpointID string) error
Delete 删除检查点
func (*PostgreSQLCheckpointStore) DeleteThread ¶
func (s *PostgreSQLCheckpointStore) DeleteThread(ctx context.Context, threadID string) error
DeleteThread 删除线程
func (*PostgreSQLCheckpointStore) List ¶
func (s *PostgreSQLCheckpointStore) List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error)
List 列出检查点
func (*PostgreSQLCheckpointStore) ListVersions ¶
func (s *PostgreSQLCheckpointStore) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)
ListVersions 列出线程的所有版本
func (*PostgreSQLCheckpointStore) Load ¶
func (s *PostgreSQLCheckpointStore) Load(ctx context.Context, checkpointID string) (*Checkpoint, error)
Load 加载检查点
func (*PostgreSQLCheckpointStore) LoadLatest ¶
func (s *PostgreSQLCheckpointStore) LoadLatest(ctx context.Context, threadID string) (*Checkpoint, error)
LoadLatest 加载最新检查点
func (*PostgreSQLCheckpointStore) LoadVersion ¶
func (s *PostgreSQLCheckpointStore) LoadVersion(ctx context.Context, threadID string, version int) (*Checkpoint, error)
LoadVersion 加载指定版本的检查点
func (*PostgreSQLCheckpointStore) Rollback ¶
func (s *PostgreSQLCheckpointStore) Rollback(ctx context.Context, threadID string, version int) error
Rollback 回滚到指定版本
func (*PostgreSQLCheckpointStore) Save ¶
func (s *PostgreSQLCheckpointStore) Save(ctx context.Context, checkpoint *Checkpoint) error
Save 保存检查点
type PostgreSQLClient ¶
type PostgreSQLClient interface {
Exec(ctx context.Context, query string, args ...interface{}) error
QueryRow(ctx context.Context, query string, args ...interface{}) Row
Query(ctx context.Context, query string, args ...interface{}) (Rows, error)
}
PostgreSQLClient PostgreSQL 客户端接口
type PreProcessPlugin ¶
type PreProcessPlugin interface {
Plugin
// PreProcess processes input before execution.
PreProcess(ctx context.Context, input *Input) (*Input, error)
}
PreProcessPlugin runs before agent execution.
type PromptBundle ¶
type PromptBundle struct {
Version string `json:"version"`
System SystemPrompt `json:"system"`
Tools []llm.ToolSchema `json:"tools,omitempty"`
Examples []Example `json:"examples,omitempty"`
Memory MemoryConfig `json:"memory,omitempty"`
Plan *PlanConfig `json:"plan,omitempty"`
Reflection *ReflectionConfig `json:"reflection,omitempty"`
Constraints []string `json:"constraints,omitempty"`
}
PromptBundle 模块化提示词包(按版本管理)。
说明:当前版本主要承载 System 模块,其他模块作为扩展点保留。
func NewPromptBundleFromIdentity ¶
func NewPromptBundleFromIdentity(version, identity string) PromptBundle
func (*PromptBundle) AppendExamples ¶
func (b *PromptBundle) AppendExamples(examples ...Example)
AppendExamples 追加 Examples
func (PromptBundle) EffectiveVersion ¶
func (b PromptBundle) EffectiveVersion(defaultVersion string) string
func (PromptBundle) ExtractVariables ¶
func (b PromptBundle) ExtractVariables() []string
ExtractVariables 从 PromptBundle 中提取所有模板变量名
func (PromptBundle) HasExamples ¶
func (b PromptBundle) HasExamples() bool
HasExamples 检查是否有 Few-shot Examples
func (PromptBundle) IsZero ¶
func (b PromptBundle) IsZero() bool
func (PromptBundle) RenderExamplesAsMessages ¶
func (b PromptBundle) RenderExamplesAsMessages() []llm.Message
RenderExamplesAsMessages 将 Examples 渲染为 LLM Message 格式
func (PromptBundle) RenderExamplesAsMessagesWithVars ¶
func (b PromptBundle) RenderExamplesAsMessagesWithVars(vars map[string]string) []llm.Message
RenderExamplesAsMessagesWithVars 渲染 Examples 并替换变量
func (PromptBundle) RenderSystemPrompt ¶
func (b PromptBundle) RenderSystemPrompt() string
func (PromptBundle) RenderSystemPromptWithVars ¶
func (b PromptBundle) RenderSystemPromptWithVars(vars map[string]string) string
RenderSystemPromptWithVars 渲染系统提示词并替换模板变量
func (PromptBundle) RenderWithVars ¶
func (b PromptBundle) RenderWithVars(vars map[string]string) PromptBundle
RenderWithVars 渲染完整提示词包并替换变量(包括 Examples 中的变量)
type PromptEngineeringConfig ¶
type PromptEngineeringConfig = PromptEnhancerConfig
PromptEngineeringConfig is an alias for PromptEnhancerConfig for backward compatibility
func DefaultPromptEngineeringConfig ¶
func DefaultPromptEngineeringConfig() PromptEngineeringConfig
DefaultPromptEngineeringConfig returns default prompt engineering configuration
type PromptEnhancer ¶
type PromptEnhancer struct {
// contains filtered or unexported fields
}
PromptEnhancer 提示词增强器
func NewPromptEnhancer ¶
func NewPromptEnhancer(config PromptEngineeringConfig) *PromptEnhancer
NewPromptEnhancer 创建提示词增强器
func (*PromptEnhancer) EnhancePromptBundle ¶
func (e *PromptEnhancer) EnhancePromptBundle(bundle PromptBundle) PromptBundle
EnhancePromptBundle 增强提示词包
func (*PromptEnhancer) EnhanceUserPrompt ¶
func (e *PromptEnhancer) EnhanceUserPrompt(prompt string, outputFormat string) string
EnhanceUserPrompt 增强用户提示词
type PromptEnhancerConfig ¶
type PromptEnhancerConfig struct {
UseChainOfThought bool `json:"use_chain_of_thought"` // Use Chain of Thought (CoT)
UseSelfConsistency bool `json:"use_self_consistency"` // Use self-consistency
UseStructuredOutput bool `json:"use_structured_output"` // Use structured output
UseFewShot bool `json:"use_few_shot"` // Use few-shot learning
MaxExamples int `json:"max_examples,omitempty"` // Maximum number of examples
UseDelimiters bool `json:"use_delimiters"` // Use delimiters
}
PromptEnhancerConfig prompt engineering configuration
func DefaultPromptEnhancerConfig ¶
func DefaultPromptEnhancerConfig() *PromptEnhancerConfig
DefaultPromptEnhancerConfig returns default prompt enhancer configuration
type PromptOptimizer ¶
type PromptOptimizer struct{}
PromptOptimizer 提示词优化器(基于最佳实践)
func (*PromptOptimizer) OptimizePrompt ¶
func (o *PromptOptimizer) OptimizePrompt(prompt string) string
OptimizePrompt 优化提示词 基于 2025 年最佳实践: 1. 明确具体 2. 提供示例 3. 让模型思考 4. 使用分隔符 5. 拆分复杂任务
type PromptTemplate ¶
type PromptTemplate struct {
Name string
Description string
Template string
Variables []string
Examples []Example
}
PromptTemplate 提示词模板
type PromptTemplateLibrary ¶
type PromptTemplateLibrary struct {
// contains filtered or unexported fields
}
PromptTemplateLibrary 提示词模板库
func NewPromptTemplateLibrary ¶
func NewPromptTemplateLibrary() *PromptTemplateLibrary
NewPromptTemplateLibrary 创建提示词模板库
func (*PromptTemplateLibrary) GetTemplate ¶
func (l *PromptTemplateLibrary) GetTemplate(name string) (PromptTemplate, bool)
GetTemplate 获取模板
func (*PromptTemplateLibrary) ListTemplates ¶
func (l *PromptTemplateLibrary) ListTemplates() []string
ListTemplates 列出所有模板
func (*PromptTemplateLibrary) RegisterTemplate ¶
func (l *PromptTemplateLibrary) RegisterTemplate(template PromptTemplate)
RegisterTemplate 注册自定义模板
func (*PromptTemplateLibrary) RenderTemplate ¶
RenderTemplate 渲染模板
type QuickSetupOptions ¶
type QuickSetupOptions struct {
EnableAllFeatures bool
// 功能开关
EnableReflection bool
EnableToolSelection bool
EnablePromptEnhancer bool
EnableSkills bool
EnableMCP bool
EnableEnhancedMemory bool
EnableObservability bool
// 配置
ReflectionMaxIterations int
ToolSelectionMaxTools int
SkillsDirectory string
MCPServerName string
MemoryTTL time.Duration
}
QuickSetupOptions 快速设置选项
func DefaultQuickSetupOptions ¶
func DefaultQuickSetupOptions() QuickSetupOptions
DefaultQuickSetupOptions 默认快速设置选项
type RealtimeCoordinator ¶
type RealtimeCoordinator struct {
// contains filtered or unexported fields
}
RealtimeCoordinator 实时协调器 支持 Subagents 之间的实时通信和协调
func NewRealtimeCoordinator ¶
func NewRealtimeCoordinator(manager *SubagentManager, eventBus EventBus, logger *zap.Logger) *RealtimeCoordinator
NewRealtimeCoordinator 创建实时协调器
func (*RealtimeCoordinator) CoordinateSubagents ¶
func (c *RealtimeCoordinator) CoordinateSubagents(ctx context.Context, subagents []Agent, input *Input) (*Output, error)
CoordinateSubagents 协调多个 Subagents
type RedisCheckpointStore ¶
type RedisCheckpointStore struct {
// contains filtered or unexported fields
}
RedisCheckpointStore Redis 检查点存储
func NewRedisCheckpointStore ¶
func NewRedisCheckpointStore(client RedisClient, prefix string, ttl time.Duration, logger *zap.Logger) *RedisCheckpointStore
NewRedisCheckpointStore 创建 Redis 检查点存储
func (*RedisCheckpointStore) Delete ¶
func (s *RedisCheckpointStore) Delete(ctx context.Context, checkpointID string) error
Delete 删除检查点
func (*RedisCheckpointStore) DeleteThread ¶
func (s *RedisCheckpointStore) DeleteThread(ctx context.Context, threadID string) error
DeleteThread 删除线程
func (*RedisCheckpointStore) List ¶
func (s *RedisCheckpointStore) List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error)
List 列出检查点
func (*RedisCheckpointStore) ListVersions ¶
func (s *RedisCheckpointStore) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)
ListVersions 列出线程的所有版本
func (*RedisCheckpointStore) Load ¶
func (s *RedisCheckpointStore) Load(ctx context.Context, checkpointID string) (*Checkpoint, error)
Load 加载检查点
func (*RedisCheckpointStore) LoadLatest ¶
func (s *RedisCheckpointStore) LoadLatest(ctx context.Context, threadID string) (*Checkpoint, error)
LoadLatest 加载最新检查点
func (*RedisCheckpointStore) LoadVersion ¶
func (s *RedisCheckpointStore) LoadVersion(ctx context.Context, threadID string, version int) (*Checkpoint, error)
LoadVersion 加载指定版本的检查点
func (*RedisCheckpointStore) Save ¶
func (s *RedisCheckpointStore) Save(ctx context.Context, checkpoint *Checkpoint) error
Save 保存检查点
type RedisClient ¶
type RedisClient interface {
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
Get(ctx context.Context, key string) ([]byte, error)
Delete(ctx context.Context, key string) error
Keys(ctx context.Context, pattern string) ([]string, error)
ZAdd(ctx context.Context, key string, score float64, member string) error
ZRevRange(ctx context.Context, key string, start, stop int64) ([]string, error)
ZRemRangeByScore(ctx context.Context, key string, min, max string) error
}
RedisClient Redis 客户端接口
type ReflectionConfig ¶
type ReflectionConfig struct {
Enabled bool `json:"enabled,omitempty"`
}
type ReflectionExecutor ¶
type ReflectionExecutor struct {
// contains filtered or unexported fields
}
ReflectionExecutor Reflection 执行器
func NewReflectionExecutor ¶
func NewReflectionExecutor(agent *BaseAgent, config ReflectionExecutorConfig) *ReflectionExecutor
NewReflectionExecutor 创建 Reflection 执行器
func (*ReflectionExecutor) ExecuteWithReflection ¶
func (r *ReflectionExecutor) ExecuteWithReflection(ctx context.Context, input *Input) (*ReflectionResult, error)
ExecuteWithReflection 执行任务并进行 Reflection
type ReflectionExecutorConfig ¶
type ReflectionExecutorConfig struct {
Enabled bool `json:"enabled"`
MaxIterations int `json:"max_iterations"` // Maximum reflection iterations
MinQuality float64 `json:"min_quality"` // Minimum quality threshold (0-1)
CriticPrompt string `json:"critic_prompt"` // Critic prompt template
}
ReflectionExecutorConfig Reflection executor configuration
func DefaultReflectionConfig ¶
func DefaultReflectionConfig() *ReflectionExecutorConfig
DefaultReflectionConfig returns default reflection configuration
func DefaultReflectionExecutorConfig ¶
func DefaultReflectionExecutorConfig() ReflectionExecutorConfig
DefaultReflectionExecutorConfig returns default reflection configuration
type ReflectionResult ¶
type ReflectionResult struct {
FinalOutput *Output `json:"final_output"`
Iterations int `json:"iterations"`
Critiques []Critique `json:"critiques"`
TotalDuration time.Duration `json:"total_duration"`
ImprovedByReflection bool `json:"improved_by_reflection"`
}
ReflectionResult Reflection 执行结果
type RuntimeStreamEmitter ¶
type RuntimeStreamEmitter func(RuntimeStreamEvent)
type RuntimeStreamEvent ¶
type RuntimeStreamEvent struct {
Type RuntimeStreamEventType `json:"type"`
Timestamp time.Time `json:"timestamp"`
Token string `json:"token,omitempty"`
Delta string `json:"delta,omitempty"`
ToolCall *RuntimeToolCall `json:"tool_call,omitempty"`
ToolResult *RuntimeToolResult `json:"tool_result,omitempty"`
}
type RuntimeStreamEventType ¶
type RuntimeStreamEventType string
const ( RuntimeStreamToken RuntimeStreamEventType = "token" RuntimeStreamToolCall RuntimeStreamEventType = "tool_call" RuntimeStreamToolResult RuntimeStreamEventType = "tool_result" )
type RuntimeToolCall ¶
type RuntimeToolCall struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments,omitempty"`
}
type RuntimeToolResult ¶
type ServiceLocator ¶
type ServiceLocator struct {
// contains filtered or unexported fields
}
ServiceLocator provides a global service registry.
func NewServiceLocator ¶
func NewServiceLocator() *ServiceLocator
NewServiceLocator creates a new service locator.
func (*ServiceLocator) Get ¶
func (sl *ServiceLocator) Get(name string) (interface{}, bool)
Get retrieves a service by name.
func (*ServiceLocator) GetEventBus ¶
func (sl *ServiceLocator) GetEventBus() (EventBus, bool)
GetEventBus retrieves the event bus.
func (*ServiceLocator) GetLogger ¶
func (sl *ServiceLocator) GetLogger() (*zap.Logger, bool)
GetLogger retrieves the logger.
func (*ServiceLocator) GetMemory ¶
func (sl *ServiceLocator) GetMemory() (MemoryManager, bool)
GetMemory retrieves the memory manager.
func (*ServiceLocator) GetProvider ¶
func (sl *ServiceLocator) GetProvider() (llm.Provider, bool)
GetProvider retrieves the LLM provider.
func (*ServiceLocator) GetToolManager ¶
func (sl *ServiceLocator) GetToolManager() (ToolManager, bool)
GetToolManager retrieves the tool manager.
func (*ServiceLocator) MustGet ¶
func (sl *ServiceLocator) MustGet(name string) interface{}
MustGet retrieves a service or panics if not found.
func (*ServiceLocator) Register ¶
func (sl *ServiceLocator) Register(name string, service interface{})
Register registers a service.
type SimpleEventBus ¶
type SimpleEventBus struct {
// contains filtered or unexported fields
}
SimpleEventBus 简单的事件总线实现
func (*SimpleEventBus) Subscribe ¶
func (b *SimpleEventBus) Subscribe(eventType EventType, handler EventHandler) string
Subscribe 订阅事件
func (*SimpleEventBus) Unsubscribe ¶
func (b *SimpleEventBus) Unsubscribe(subscriptionID string)
Unsubscribe 取消订阅
type SkillsOptions ¶
type SkillsOptions struct {
Directory string
Config skills.SkillManagerConfig
}
SkillsOptions configures how the builder creates a default skills manager.
type State ¶
type State string
State 定义 Agent 生命周期状态
const ( StateInit State = "init" // Initializing StateReady State = "ready" // Ready to execute StateRunning State = "running" // Executing StatePaused State = "paused" // Paused (waiting for human/external input) StateCompleted State = "completed" // Completed StateFailed State = "failed" // Failed )
type StateChangeEvent ¶
StateChangeEvent 状态变更事件
func (*StateChangeEvent) Timestamp ¶
func (e *StateChangeEvent) Timestamp() time.Time
func (*StateChangeEvent) Type ¶
func (e *StateChangeEvent) Type() EventType
type StateManager ¶
type StateManager struct {
// contains filtered or unexported fields
}
StateManager manages agent state transitions (lightweight version).
func NewStateManager ¶
func NewStateManager(agentID string, bus EventBus, logger *zap.Logger) *StateManager
NewStateManager creates a new StateManager.
func (*StateManager) EnsureReady ¶
func (sm *StateManager) EnsureReady() error
EnsureReady checks if the agent is in ready state.
func (*StateManager) Transition ¶
func (sm *StateManager) Transition(ctx context.Context, to State) error
Transition performs a state transition with validation.
func (*StateManager) TryLockExec ¶
func (sm *StateManager) TryLockExec() bool
TryLockExec attempts to acquire the execution lock.
func (*StateManager) UnlockExec ¶
func (sm *StateManager) UnlockExec()
UnlockExec releases the execution lock.
type SubagentCompletedEvent ¶
type SubagentCompletedEvent struct {
ExecutionID string
AgentID string
Output *Output
Timestamp_ time.Time
}
SubagentCompletedEvent Subagent 完成事件
func (*SubagentCompletedEvent) Timestamp ¶
func (e *SubagentCompletedEvent) Timestamp() time.Time
func (*SubagentCompletedEvent) Type ¶
func (e *SubagentCompletedEvent) Type() EventType
type SubagentManager ¶
type SubagentManager struct {
// contains filtered or unexported fields
}
SubagentManager Subagent 管理器
func NewSubagentManager ¶
func NewSubagentManager(logger *zap.Logger) *SubagentManager
NewSubagentManager 创建 Subagent 管理器
func (*SubagentManager) CleanupCompleted ¶
func (m *SubagentManager) CleanupCompleted(olderThan time.Duration) int
CleanupCompleted 清理已完成的执行
func (*SubagentManager) GetExecution ¶
func (m *SubagentManager) GetExecution(executionID string) (*AsyncExecution, error)
GetExecution 获取执行状态
func (*SubagentManager) ListExecutions ¶
func (m *SubagentManager) ListExecutions() []*AsyncExecution
ListExecutions 列出所有执行
func (*SubagentManager) SpawnSubagent ¶
func (m *SubagentManager) SpawnSubagent(ctx context.Context, subagent Agent, input *Input) (*AsyncExecution, error)
SpawnSubagent 创建 Subagent 执行
type SystemPrompt ¶
type SystemPrompt struct {
Role string `json:"role,omitempty"`
Identity string `json:"identity,omitempty"`
Policies []string `json:"policies,omitempty"`
OutputRules []string `json:"output_rules,omitempty"`
Prohibits []string `json:"prohibits,omitempty"`
}
func (SystemPrompt) IsZero ¶
func (s SystemPrompt) IsZero() bool
func (SystemPrompt) Render ¶
func (s SystemPrompt) Render() string
type ToolCallEvent ¶
type ToolCallEvent struct {
AgentID_ string
RunID string
TraceID string
PromptBundleVersion string
ToolCallID string
ToolName string
Stage string // start/end
Error string
Timestamp_ time.Time
}
ToolCallEvent 工具调用事件
func (*ToolCallEvent) Timestamp ¶
func (e *ToolCallEvent) Timestamp() time.Time
func (*ToolCallEvent) Type ¶
func (e *ToolCallEvent) Type() EventType
type ToolManager ¶
type ToolManager interface {
GetAllowedTools(agentID string) []llm.ToolSchema
ExecuteForAgent(ctx context.Context, agentID string, calls []llm.ToolCall) []llmtools.ToolResult
}
ToolManager abstracts the "tool list + tool execution" capability for Agent runtime.
Design goals: - Avoid pkg/agent directly depending on pkg/agent/tools (eliminate import cycle) - Allow different implementations to be injected at application layer (default uses tools.ToolManager)
type ToolScore ¶
type ToolScore struct {
Tool llm.ToolSchema `json:"tool"`
SemanticSimilarity float64 `json:"semantic_similarity"` // Semantic similarity (0-1)
EstimatedCost float64 `json:"estimated_cost"` // Estimated cost
AvgLatency time.Duration `json:"avg_latency"` // Average latency
ReliabilityScore float64 `json:"reliability_score"` // Reliability (0-1)
TotalScore float64 `json:"total_score"` // Total score (0-1)
}
ToolScore 工具评分
type ToolSelectionConfig ¶
type ToolSelectionConfig struct {
Enabled bool `json:"enabled"`
// Scoring weights
SemanticWeight float64 `json:"semantic_weight"` // Semantic similarity weight
CostWeight float64 `json:"cost_weight"` // Cost weight
LatencyWeight float64 `json:"latency_weight"` // Latency weight
ReliabilityWeight float64 `json:"reliability_weight"` // Reliability weight
// Selection strategy
MaxTools int `json:"max_tools"` // Maximum number of tools to select
MinScore float64 `json:"min_score"` // Minimum score threshold
UseLLMRanking bool `json:"use_llm_ranking"` // Whether to use LLM-assisted ranking
}
ToolSelectionConfig 工具选择配置
func DefaultToolSelectionConfig ¶
func DefaultToolSelectionConfig() *ToolSelectionConfig
DefaultToolSelectionConfig returns default tool selection configuration
type ToolSelector ¶
type ToolSelector interface {
// SelectTools 基于任务选择最佳工具
SelectTools(ctx context.Context, task string, availableTools []llm.ToolSchema) ([]llm.ToolSchema, error)
// ScoreTools 对工具进行评分
ScoreTools(ctx context.Context, task string, tools []llm.ToolSchema) ([]ToolScore, error)
}
ToolSelector 工具选择器接口
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package artifacts provides artifact lifecycle management for AI agents.
|
Package artifacts provides artifact lifecycle management for AI agents. |
|
Package browser provides Agentic Browser with Vision-Action Loop.
|
Package browser provides Agentic Browser with Vision-Action Loop. |
|
Package context provides unified context management for agents.
|
Package context provides unified context management for agents. |
|
Package conversation provides conversation management with branching and rollback.
|
Package conversation provides conversation management with branching and rollback. |
|
Package crews provides role-based agent teams with autonomous negotiation.
|
Package crews provides role-based agent teams with autonomous negotiation. |
|
Package deliberation provides CrewAI-style autonomous reasoning mode.
|
Package deliberation provides CrewAI-style autonomous reasoning mode. |
|
Package deployment provides cloud deployment support for AI agents.
|
Package deployment provides cloud deployment support for AI agents. |
|
Package evaluation provides automated evaluation framework for AI agents.
|
Package evaluation provides automated evaluation framework for AI agents. |
|
package execution provides pluggable persistence backends for agent state.
|
package execution provides pluggable persistence backends for agent state. |
|
Package federation provides cross-organization agent collaboration.
|
Package federation provides cross-organization agent collaboration. |
|
Package guardrails provides input/output validation and content filtering for agents.
|
Package guardrails provides input/output validation and content filtering for agents. |
|
Package handoff provides Agent Handoff protocol for task delegation between agents.
|
Package handoff provides Agent Handoff protocol for task delegation between agents. |
|
Package hitl provides Human-in-the-Loop workflow interrupt and resume capabilities.
|
Package hitl provides Human-in-the-Loop workflow interrupt and resume capabilities. |
|
Package hosted provides hosted tool implementations like Web Search and File Search.
|
Package hosted provides hosted tool implementations like Web Search and File Search. |
|
Package k8s provides Kubernetes operator capabilities for agent management.
|
Package k8s provides Kubernetes operator capabilities for agent management. |
|
Package longrunning provides support for long-running agent tasks (days-level).
|
Package longrunning provides support for long-running agent tasks (days-level). |
|
Package memory provides layered memory systems for AI agents.
|
Package memory provides layered memory systems for AI agents. |
|
Package observability provides explainability and reasoning trace capabilities.
|
Package observability provides explainability and reasoning trace capabilities. |
|
protocol
|
|
|
a2a
Package a2a provides A2A (Agent-to-Agent) protocol support.
|
Package a2a provides A2A (Agent-to-Agent) protocol support. |
|
Package reasoning provides advanced reasoning patterns for AI agents.
|
Package reasoning provides advanced reasoning patterns for AI agents. |
|
Package skills provides standardized skill definitions and discovery.
|
Package skills provides standardized skill definitions and discovery. |
|
Package streaming provides bidirectional real-time streaming for audio/text.
|
Package streaming provides bidirectional real-time streaming for audio/text. |
|
Package structured provides structured output support with JSON Schema validation.
|
Package structured provides structured output support with JSON Schema validation. |
|
Package voice provides native multimodal audio reasoning (GPT-4o style).
|
Package voice provides native multimodal audio reasoning (GPT-4o style). |