Documentation
¶
Overview ¶
包 agent 提供 AgentFlow 的核心智能体框架。
概述 ¶
本包面向"可编排、可扩展、可观测"的智能体开发场景,统一了 智能体生命周期管理、任务执行流程、工具调用、记忆管理与状态控制。
框架支持多种推理与执行模式,包括 ReAct、链式推理、计划后执行、 反思式迭代以及自定义策略,适合从简单任务型 Agent 到复杂多阶段 协作流程的实现。
架构分层 ¶
整体能力由以下层次组成:
- Agent 接口层:定义统一能力边界,如 Init、Plan、Execute。 - BaseAgent 基础层:提供状态机、钩子、并发保护等通用能力。 - 组件层:记忆、工具、护栏、观测、持久化等可插拔模块。 - LLM 适配层:通过 llm.Provider 抽象接入不同模型提供商。
核心接口 ¶
- Agent:智能体统一接口,提供 ID / Name / Type / Init / Plan / Execute / Observe
- ContextManager:上下文管理接口,提供 GetContext / UpdateContext
- EventBus:事件总线接口,提供 Publish / Subscribe / Unsubscribe
- ToolManager:工具管理接口,提供 GetAllowedTools / ExecuteForAgent
- ToolSelector:工具选择接口,根据上下文动态选择最优工具集
- MemoryWriter / MemoryReader / MemoryManager:记忆读写与管理接口
- Plugin:插件接口,支持 PreProcess / PostProcess / Middleware 扩展点
核心类型 ¶
- BaseAgent:Agent 基础实现,内置状态机、护栏、记忆与工具管理
- Config:Agent 配置,包含执行参数、模型绑定与能力开关
- Input / Output:执行输入与输出模型
- PlanResult:规划结果,包含步骤列表与推理过程
- Feedback:观测反馈,用于反思与学习
- Event / EventType / EventHandler:事件模型与处理器
- SimpleEventBus:默认事件总线实现
- GuardrailsError:护栏校验错误,包含错误类型与详情
异步与协作 ¶
- AsyncExecutor:异步任务执行器,支持后台执行与结果回调
- SubagentManager:子 Agent 管理器,支持动态注册与任务分发
- RealtimeCoordinator:实时协调器,基于事件总线协调多 Agent 执行
Prompt 工程 ¶
- PromptEnhancer:Prompt 增强器,自动优化与丰富提示词
- PromptBundle:Prompt 配置包,组合系统提示、示例与记忆配置
- PromptTemplateLibrary:Prompt 模板库,管理可复用模板
插件系统 ¶
- PluginRegistry:插件注册表,管理插件生命周期
- PluginEnabledAgent:插件增强 Agent,在执行流程中自动触发插件
工具集成 ¶
- AgentTool:将 Agent 封装为工具,支持 Agent 间嵌套调用
- DynamicToolSelector:动态工具选择器,基于历史统计选择最优工具
核心能力 ¶
- 生命周期管理:统一初始化、执行、收尾与状态转换流程。 - 状态机约束:保证状态流转合法,减少异常路径下的行为漂移。 - 组件注入:通过构建器按需启用记忆、工具、护栏、反思与观测能力。 - 错误语义化:通过统一错误类型与错误码提升调试与恢复效率。 - 并发安全:基础实现内置必要同步机制,保护共享状态一致性。
使用方式 ¶
推荐通过构建器创建 Agent,并按需开启增强能力:
- 使用 NewAgentBuilder 配置名称、类型与执行参数。 - 通过 WithProvider 绑定主模型,必要时通过 WithToolProvider 分离工具调用模型。 - 通过 WithMemory、WithToolManager、WithReflection 等接口启用扩展能力。 - 通过 Build 生成可执行实例,再调用 Execute 处理输入任务。
相关子包 ¶
- agent/guardrails:输入与输出约束、注入防护、安全校验。 - agent/memory:多层记忆与检索能力。 - agent/discovery:多 Agent 能力发现与匹配。 - agent/evaluation:效果评测、指标采集与实验能力。 - agent/structured:结构化输出生成与校验。 - agent/protocol/a2a:智能体间通信协议与实现。 - agent/persistence:状态持久化与任务存储。 - agent/collaboration:多 Agent 协作角色与流水线。 - agent/deliberation:深度推理与决策引擎。 - agent/voice:语音交互与实时对话。 - agent/artifacts:产物管理与存储。
Index ¶
- Constants
- Variables
- func CanTransition(from, to State) bool
- func DurationPtr(d time.Duration) *time.Duration
- func Float32Ptr(f float32) *float32
- func InitGlobalRegistry(logger *zap.Logger)
- func IntPtr(i int) *int
- func IsRetryable(err error) bool
- func RegisterAgentType(agentType AgentType, factory AgentFactory)
- func StringPtr(s string) *string
- func WithRunConfig(ctx context.Context, rc *RunConfig) context.Context
- 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) WithDefaultLSPServer(name, version string) *AgentBuilder
- func (b *AgentBuilder) WithDefaultMCPServer(name, version string) *AgentBuilder
- func (b *AgentBuilder) WithDefaultSkills(directory string, config *skills.SkillManagerConfig) *AgentBuilder
- func (b *AgentBuilder) WithEnhancedMemory(mem EnhancedMemoryRunner) *AgentBuilder
- func (b *AgentBuilder) WithEventBus(bus EventBus) *AgentBuilder
- func (b *AgentBuilder) WithLSP(client LSPClientRunner) *AgentBuilder
- func (b *AgentBuilder) WithLSPWithLifecycle(client LSPClientRunner, lifecycle LSPLifecycleOwner) *AgentBuilder
- func (b *AgentBuilder) WithLogger(logger *zap.Logger) *AgentBuilder
- func (b *AgentBuilder) WithMCP(server MCPServerRunner) *AgentBuilder
- func (b *AgentBuilder) WithMaxReActIterations(n int) *AgentBuilder
- func (b *AgentBuilder) WithMemory(memory MemoryManager) *AgentBuilder
- func (b *AgentBuilder) WithObservability(obs ObservabilityRunner) *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(discoverer SkillDiscoverer) *AgentBuilder
- func (b *AgentBuilder) WithToolManager(toolManager ToolManager) *AgentBuilder
- func (b *AgentBuilder) WithToolProvider(provider llm.Provider) *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 AgentTool
- type AgentToolConfig
- 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 EnhancedMemoryRunner)
- func (b *BaseAgent) EnableLSP(client LSPClientRunner)
- func (b *BaseAgent) EnableLSPWithLifecycle(client LSPClientRunner, lifecycle LSPLifecycleOwner)
- func (b *BaseAgent) EnableMCP(server MCPServerRunner)
- func (b *BaseAgent) EnableObservability(obsSystem ObservabilityRunner)
- func (b *BaseAgent) EnablePromptEnhancer(enhancer PromptEnhancerRunner)
- func (b *BaseAgent) EnableReflection(executor ReflectionRunner)
- func (b *BaseAgent) EnableSkills(manager SkillDiscoverer)
- func (b *BaseAgent) EnableToolSelection(selector DynamicToolSelectorRunner)
- 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]any
- func (b *BaseAgent) GetFeatureMetrics() map[string]any
- 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) SetToolProvider(p llm.Provider)
- 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) ToolProvider() llm.Provider
- 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 CachingResolver
- 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() any) *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() any) *Container
- func (c *Container) WithToolManager(toolManager ToolManager) *Container
- func (c *Container) WithToolSelectionFactory(factory func() any) *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 DynamicToolSelectorRunner
- type EnhancedExecutionOptions
- type EnhancedMemoryRunner
- type ErrInvalidTransition
- type 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 FeatureManager
- func (fm *FeatureManager) DisableAll()
- func (fm *FeatureManager) DisableEnhancedMemory()
- func (fm *FeatureManager) DisableLSP()
- func (fm *FeatureManager) DisableMCP()
- func (fm *FeatureManager) DisableObservability()
- func (fm *FeatureManager) DisablePromptEnhancer()
- func (fm *FeatureManager) DisableReflection()
- func (fm *FeatureManager) DisableSkills()
- func (fm *FeatureManager) DisableToolSelection()
- func (fm *FeatureManager) EnableEnhancedMemory(system EnhancedMemoryRunner)
- func (fm *FeatureManager) EnableLSP(client LSPClientRunner)
- func (fm *FeatureManager) EnableMCP(server MCPServerRunner)
- func (fm *FeatureManager) EnableObservability(system ObservabilityRunner)
- func (fm *FeatureManager) EnablePromptEnhancer(enhancer PromptEnhancerRunner)
- func (fm *FeatureManager) EnableReflection(executor ReflectionRunner)
- func (fm *FeatureManager) EnableSkills(manager SkillDiscoverer)
- func (fm *FeatureManager) EnableToolSelection(selector DynamicToolSelectorRunner)
- func (fm *FeatureManager) EnabledFeatures() []string
- func (fm *FeatureManager) GetEnhancedMemory() EnhancedMemoryRunner
- func (fm *FeatureManager) GetLSP() LSPClientRunner
- func (fm *FeatureManager) GetMCPServer() MCPServerRunner
- func (fm *FeatureManager) GetObservability() ObservabilityRunner
- func (fm *FeatureManager) GetPromptEnhancer() PromptEnhancerRunner
- func (fm *FeatureManager) GetReflection() ReflectionRunner
- func (fm *FeatureManager) GetSkillManager() SkillDiscoverer
- func (fm *FeatureManager) GetToolSelector() DynamicToolSelectorRunner
- func (fm *FeatureManager) IsEnhancedMemoryEnabled() bool
- func (fm *FeatureManager) IsLSPEnabled() bool
- func (fm *FeatureManager) IsMCPEnabled() bool
- func (fm *FeatureManager) IsObservabilityEnabled() bool
- func (fm *FeatureManager) IsPromptEnhancerEnabled() bool
- func (fm *FeatureManager) IsReflectionEnabled() bool
- func (fm *FeatureManager) IsSkillsEnabled() bool
- func (fm *FeatureManager) IsToolSelectionEnabled() bool
- 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 GuardrailsCoordinator
- func (gc *GuardrailsCoordinator) AddInputValidator(v guardrails.Validator)
- func (gc *GuardrailsCoordinator) AddOutputFilter(f guardrails.Filter)
- func (gc *GuardrailsCoordinator) AddOutputValidator(v guardrails.Validator)
- func (gc *GuardrailsCoordinator) BuildValidationFeedbackMessage(result *guardrails.ValidationResult) string
- func (gc *GuardrailsCoordinator) Enabled() bool
- func (gc *GuardrailsCoordinator) GetConfig() *guardrails.GuardrailsConfig
- func (gc *GuardrailsCoordinator) GetInputValidatorChain() *guardrails.ValidatorChain
- func (gc *GuardrailsCoordinator) GetOutputValidator() *guardrails.OutputValidator
- func (gc *GuardrailsCoordinator) InputValidatorCount() int
- func (gc *GuardrailsCoordinator) SetEnabled(enabled bool)
- func (gc *GuardrailsCoordinator) ValidateInput(ctx context.Context, input string) (*guardrails.ValidationResult, error)
- func (gc *GuardrailsCoordinator) ValidateOutput(ctx context.Context, output string) (string, *guardrails.ValidationResult, error)
- 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 LSPClientRunner
- type LSPLifecycleOwner
- type LifecycleManager
- type MCPServerOptions
- type MCPServerRunner
- type ManagedLSP
- type MemoryConfig
- type MemoryCoordinator
- func (mc *MemoryCoordinator) ClearRecentMemory()
- func (mc *MemoryCoordinator) GetMemoryManager() MemoryManager
- func (mc *MemoryCoordinator) GetRecentMemory() []MemoryRecord
- func (mc *MemoryCoordinator) HasMemory() bool
- func (mc *MemoryCoordinator) LoadRecent(ctx context.Context, kind MemoryKind, limit int) error
- func (mc *MemoryCoordinator) RecallRelevant(ctx context.Context, query string, topK int) ([]MemoryRecord, error)
- func (mc *MemoryCoordinator) Save(ctx context.Context, content string, kind MemoryKind, metadata map[string]any) error
- func (mc *MemoryCoordinator) SaveConversation(ctx context.Context, input, output string) error
- func (mc *MemoryCoordinator) Search(ctx context.Context, query string, topK int) ([]MemoryRecord, error)
- 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 ObservabilityRunner
- 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) 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) Shutdown(ctx context.Context) 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 PromptEnhancerRunner
- 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 ReflectionRunner
- type Row
- type Rows
- type RunConfig
- type RuntimeStreamEmitter
- type RuntimeStreamEvent
- type RuntimeStreamEventType
- type RuntimeToolCall
- type RuntimeToolResult
- type ServiceLocator
- func (sl *ServiceLocator) Get(name string) (any, 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) any
- func (sl *ServiceLocator) Register(name string, service any)
- type SimpleEventBus
- type SkillDiscoverer
- 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" )
众所周知的服务名称
const ( MemoryShortTerm = types.MemoryWorking // 短期记忆 -> Working MemoryWorking = types.MemoryWorking // 工作记忆 MemoryLongTerm = types.MemorySemantic // 长期记忆 -> Semantic MemoryEpisodic = types.MemoryEpisodic // 情节记忆 MemorySemantic = types.MemorySemantic // 语义记忆 (新增) MemoryProcedural = types.MemoryProcedural // 程序记忆 (新增) )
记忆类型常数 - 映射到统一类型. 内存类型 折旧:使用类型。 记忆工作,类型。 记忆 Essodic等.
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 DurationPtr ¶
DurationPtr returns a pointer to the given time.Duration.
func Float32Ptr ¶
Float32Ptr returns a pointer to the given float32.
func InitGlobalRegistry ¶
Init Global Registry将全球代理登记初始化。 此函数可以安全多次调用 - 只有第一个调用会初始化 。
func RegisterAgentType ¶
func RegisterAgentType(agentType AgentType, factory AgentFactory)
AgentType在全球登记册中登记一种代理类型。 如果全球登记册没有初始化,它将以nop日志初始化。
func WithRunConfig ¶
WithRunConfig stores a RunConfig in the context.
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]any `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)
Create Agent 使用全球登记册创建代理
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
通过DefaultEnhancedMemory,可以使内置增强的内存系统与内存存储相通.
func (*AgentBuilder) WithDefaultLSPServer ¶
func (b *AgentBuilder) WithDefaultLSPServer(name, version string) *AgentBuilder
WithDefaultLSPServer 启用默认名称/版本的内置 LSP 运行时。
func (*AgentBuilder) WithDefaultMCPServer ¶
func (b *AgentBuilder) WithDefaultMCPServer(name, version string) *AgentBuilder
With DefaultMCPServer 启用默认名称/版本的内置的MCP服务器.
func (*AgentBuilder) WithDefaultSkills ¶
func (b *AgentBuilder) WithDefaultSkills(directory string, config *skills.SkillManagerConfig) *AgentBuilder
With DefaultSkills 启用了内置的技能管理器,并可以选择扫描一个目录.
func (*AgentBuilder) WithEnhancedMemory ¶
func (b *AgentBuilder) WithEnhancedMemory(mem EnhancedMemoryRunner) *AgentBuilder
WithEnhancedMemory 启用增强记忆系统
func (*AgentBuilder) WithEventBus ¶
func (b *AgentBuilder) WithEventBus(bus EventBus) *AgentBuilder
WithEventBus 设置事件总线
func (*AgentBuilder) WithLSP ¶
func (b *AgentBuilder) WithLSP(client LSPClientRunner) *AgentBuilder
WithLSP 启用 LSP 集成。
func (*AgentBuilder) WithLSPWithLifecycle ¶ added in v1.0.0
func (b *AgentBuilder) WithLSPWithLifecycle(client LSPClientRunner, lifecycle LSPLifecycleOwner) *AgentBuilder
WithLSPWithLifecycle 启用 LSP 集成,并注册可选生命周期对象。
func (*AgentBuilder) WithLogger ¶
func (b *AgentBuilder) WithLogger(logger *zap.Logger) *AgentBuilder
WithLogger 设置日志器
func (*AgentBuilder) WithMCP ¶
func (b *AgentBuilder) WithMCP(server MCPServerRunner) *AgentBuilder
WithMCP 启用 MCP 集成
func (*AgentBuilder) WithMaxReActIterations ¶
func (b *AgentBuilder) WithMaxReActIterations(n int) *AgentBuilder
WithMaxReActIterations 设置 ReAct 最大迭代次数。 n <= 0 时忽略,使用默认值 10。
func (*AgentBuilder) WithMemory ¶
func (b *AgentBuilder) WithMemory(memory MemoryManager) *AgentBuilder
WithMemory 设置记忆管理器
func (*AgentBuilder) WithObservability ¶
func (b *AgentBuilder) WithObservability(obs ObservabilityRunner) *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(discoverer SkillDiscoverer) *AgentBuilder
WithSkills 启用 Skills 系统
func (*AgentBuilder) WithToolManager ¶
func (b *AgentBuilder) WithToolManager(toolManager ToolManager) *AgentBuilder
WithToolManager 设置工具管理器
func (*AgentBuilder) WithToolProvider ¶
func (b *AgentBuilder) WithToolProvider(provider llm.Provider) *AgentBuilder
WithToolProvider 设置工具调用专用的 LLM Provider。 ReAct 循环中的推理和工具调用将使用此 Provider,而最终内容生成仍使用主 Provider。 如果不设置,所有调用都使用主 Provider(向后兼容)。
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)
Agent Factory 是创建 Agent 实例的函数
type AgentFactoryFunc ¶
type AgentFactoryFunc struct {
// contains filtered or unexported fields
}
Agent FactoryFunc 创建具有预配置依赖关系的代理.
func NewAgentFactoryFunc ¶
func NewAgentFactoryFunc(container *Container) *AgentFactoryFunc
新AgentFactoryFunc创建了新的代理工厂.
func (*AgentFactoryFunc) CreateAgent ¶
func (f *AgentFactoryFunc) CreateAgent(config Config) (Agent, error)
Create Agent 根据提供的配置创建代理 。
func (*AgentFactoryFunc) CreateModular ¶
func (f *AgentFactoryFunc) CreateModular(config ModularAgentConfig) (*ModularAgent, error)
Create Modular 创建模块化代理.
type AgentIdentity ¶
type AgentIdentity struct {
// contains filtered or unexported fields
}
代理身份管理代理身份信息.
func NewAgentIdentity ¶
func NewAgentIdentity(id, name string, agentType AgentType) *AgentIdentity
新代理身份创建了新的代理身份.
func (*AgentIdentity) SetDescription ¶
func (i *AgentIdentity) SetDescription(desc string)
设置 Description 设置代理描述 。
type AgentRegistry ¶
type AgentRegistry struct {
// contains filtered or unexported fields
}
Agent Registry 管理代理类型注册和创建 它提供了一种集中的方式 注册和即时处理不同的代理类型
var (
GlobalRegistry *AgentRegistry
)
Global Registry 是默认代理注册实例
func GetGlobalRegistry ¶
func GetGlobalRegistry(logger *zap.Logger) *AgentRegistry
Get GlobalRegistry 返回全球注册,必要时初始化它. 这是访问全球登记册的建议方式。
func (*AgentRegistry) Create ¶
func (r *AgentRegistry) Create( config Config, provider llm.Provider, memory MemoryManager, toolManager ToolManager, bus EventBus, logger *zap.Logger, ) (Agent, error)
创建指定类型的新代理实例
func (*AgentRegistry) IsRegistered ¶
func (r *AgentRegistry) IsRegistered(agentType AgentType) bool
如果已注册代理类型, 正在注册检查
func (*AgentRegistry) Register ¶
func (r *AgentRegistry) Register(agentType AgentType, factory AgentFactory)
登记册登记具有工厂功能的新代理类型
func (*AgentRegistry) Unregister ¶
func (r *AgentRegistry) Unregister(agentType AgentType)
未注册从注册簿中删除代理类型
type AgentTool ¶
type AgentTool struct {
// contains filtered or unexported fields
}
AgentTool wraps an Agent instance as a callable tool, enabling lightweight agent-to-agent delegation via the standard tool-calling interface.
func NewAgentTool ¶
func NewAgentTool(agent Agent, config *AgentToolConfig) *AgentTool
NewAgentTool creates an AgentTool that wraps the given Agent. If config is nil, defaults are used.
func (*AgentTool) Schema ¶
func (at *AgentTool) Schema() types.ToolSchema
Schema returns the ToolSchema describing this agent-as-tool.
type AgentToolConfig ¶
type AgentToolConfig struct {
// Name overrides the default tool name (default: "agent_<agent.Name()>").
Name string
// Description overrides the agent's description in the tool schema.
Description string
// Timeout limits the agent execution time. Zero means no extra timeout.
Timeout time.Duration
}
AgentToolConfig configures how an Agent is exposed as a tool.
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]any `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]any `json:"metadata,omitempty"`
}
ApprovalResponse 审批响应
type ApprovalStatus ¶
type ApprovalStatus string
ApprovalStatus 审批状态
const ( ApprovalStatusPending ApprovalStatus = "pending" ApprovalStatusApproved ApprovalStatus = "approved" ApprovalStatusRejected ApprovalStatus = "rejected" ApprovalStatusTimeout ApprovalStatus = "timeout" ApprovalStatusCancelled ApprovalStatus = "cancelled" )
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
StartTime time.Time
// contains filtered or unexported fields
}
AsyncExecution 异步执行状态
func (*AsyncExecution) GetEndTime ¶
func (e *AsyncExecution) GetEndTime() time.Time
GetEndTime returns when the execution finished.
func (*AsyncExecution) GetError ¶
func (e *AsyncExecution) GetError() string
GetError returns the error message, if any.
func (*AsyncExecution) GetOutput ¶
func (e *AsyncExecution) GetOutput() *Output
GetOutput returns the execution output, if completed.
func (*AsyncExecution) GetStatus ¶
func (e *AsyncExecution) GetStatus() ExecutionStatus
GetStatus returns the current execution status.
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)
添加自定义输入验证器 1.7: 支持海关验证规则的登记和延期
func (*BaseAgent) AddOutputFilter ¶
func (b *BaseAgent) AddOutputFilter(f guardrails.Filter)
添加 OutputFilter 添加自定义输出过滤器
func (*BaseAgent) AddOutputValidator ¶
func (b *BaseAgent) AddOutputValidator(v guardrails.Validator)
添加输出变量添加自定义输出验证器 1.7: 支持海关验证规则的登记和延期
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 EnhancedMemoryRunner)
EnableEnhancedMemory 启用增强记忆系统
func (*BaseAgent) EnableLSP ¶
func (b *BaseAgent) EnableLSP(client LSPClientRunner)
EnableLSP 启用 LSP 集成。
func (*BaseAgent) EnableLSPWithLifecycle ¶
func (b *BaseAgent) EnableLSPWithLifecycle(client LSPClientRunner, lifecycle LSPLifecycleOwner)
EnableLSPWithLifecycle 启用 LSP,并注册可选生命周期对象(例如 *ManagedLSP)。
func (*BaseAgent) EnableMCP ¶
func (b *BaseAgent) EnableMCP(server MCPServerRunner)
EnableMCP 启用 MCP 集成
func (*BaseAgent) EnableObservability ¶
func (b *BaseAgent) EnableObservability(obsSystem ObservabilityRunner)
EnableObservability 启用可观测性系统
func (*BaseAgent) EnablePromptEnhancer ¶
func (b *BaseAgent) EnablePromptEnhancer(enhancer PromptEnhancerRunner)
EnablePromptEnhancer 启用提示词增强
func (*BaseAgent) EnableReflection ¶
func (b *BaseAgent) EnableReflection(executor ReflectionRunner)
EnableReflection 启用 Reflection 机制
func (*BaseAgent) EnableSkills ¶
func (b *BaseAgent) EnableSkills(manager SkillDiscoverer)
EnableSkills 启用 Skills 系统
func (*BaseAgent) EnableToolSelection ¶
func (b *BaseAgent) EnableToolSelection(selector DynamicToolSelectorRunner)
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) 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)
设置守护栏为代理设置守护栏 1.7: 支持海关验证规则的登记和延期
func (*BaseAgent) SetToolProvider ¶
SetToolProvider 设置工具调用专用的 LLM Provider
func (*BaseAgent) StreamCompletion ¶
func (b *BaseAgent) StreamCompletion(ctx context.Context, messages []llm.Message) (<-chan llm.StreamChunk, error)
StreamCompletion 流式调用 LLM
func (*BaseAgent) ToolProvider ¶
ToolProvider 返回工具调用专用的 LLM Provider(可能为 nil)
func (*BaseAgent) Transition ¶
Transition 状态转换(带校验)
func (*BaseAgent) ValidateConfiguration ¶
ValidateConfiguration 验证配置
type CachingResolver ¶ added in v1.0.0
type CachingResolver struct {
// contains filtered or unexported fields
}
CachingResolver resolves agent IDs to live Agent instances, creating them on demand via AgentRegistry and caching them for reuse. It uses singleflight to ensure concurrent requests for the same agentID only trigger one Create+Init cycle.
func NewCachingResolver ¶ added in v1.0.0
func NewCachingResolver(registry *AgentRegistry, provider llm.Provider, logger *zap.Logger) *CachingResolver
NewCachingResolver creates a CachingResolver backed by the given registry and LLM provider.
func (*CachingResolver) Resolve ¶ added in v1.0.0
Resolve returns a cached Agent for agentID, or creates and initialises one.
func (*CachingResolver) TeardownAll ¶ added in v1.0.0
func (r *CachingResolver) TeardownAll(ctx context.Context)
TeardownAll tears down all cached agent instances. Intended to be called during graceful shutdown.
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]any `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"`
}
检查站 Diff 代表两个检查站版本之间的差异
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)
比较Version 比较两个检查点版本并返回差异
func (*CheckpointManager) CreateCheckpoint ¶
func (m *CheckpointManager) CreateCheckpoint(ctx context.Context, agent Agent, threadID string) error
创建检查点来抓取当前代理状态并将其保存为检查点
func (*CheckpointManager) DisableAutoSave ¶
func (m *CheckpointManager) DisableAutoSave()
禁用自动保存停止自动检查
func (*CheckpointManager) EnableAutoSave ¶
func (m *CheckpointManager) EnableAutoSave(ctx context.Context, agent Agent, threadID string, interval time.Duration) error
启用自动保存以指定间隔自动保存检查点
func (*CheckpointManager) ListVersions ¶
func (m *CheckpointManager) ListVersions(ctx context.Context, threadID string) ([]CheckpointVersion, error)
ListVersion 列出用于线索的所有检查点版本
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
Rollback ToVersion 将代理拖回特定检查点版本
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]any `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 检查点存储接口(Agent 层)。
注意:项目中存在两个 CheckpointStore 接口,操作不同的检查点类型:
- agent.CheckpointStore(本接口) — 操作 *agent.Checkpoint,含 List/DeleteThread/Rollback
- workflow.CheckpointStore — 操作 *workflow.EnhancedCheckpoint,用于 DAG 工作流时间旅行
两者的检查点结构体字段不同(Agent 状态 vs DAG 节点结果),无法统一。
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"`
EnableLSP bool `json:"enable_lsp,omitempty"`
EnableEnhancedMemory bool `json:"enable_enhanced_memory,omitempty"`
EnableObservability bool `json:"enable_observability,omitempty"`
// ReAct 最大迭代次数,默认 10
MaxReActIterations int `json:"max_react_iterations,omitempty"`
// 2026 Guardrails 配置
// Requirements 1.7: 支持自定义验证规则的注册和扩展
Guardrails *guardrails.GuardrailsConfig `json:"guardrails,omitempty"`
}
Config Agent 配置
type Container ¶
type Container struct {
// contains filtered or unexported fields
}
集装箱拥有建立代理的所有依赖性。
func (*Container) CreateBaseAgent ¶
CreatBaseAgent 使用容器依赖性创建 BaseAgent 。
func (*Container) CreateModularAgent ¶
func (c *Container) CreateModularAgent(config ModularAgentConfig) (*ModularAgent, error)
创建 ModularAgent 使用容器依赖性创建了 ModularAgent 。
func (*Container) WithEventBus ¶
用 EventBus 设置活动总线 。
func (*Container) WithGuardrailsFactory ¶
与Guardrails Factory 设置了护栏延长工厂.
func (*Container) WithLogger ¶
由Logger设置日志 。
func (*Container) WithMemory ¶
func (c *Container) WithMemory(memory MemoryManager) *Container
与记忆设定内存管理器.
func (*Container) WithProvider ¶
由Provider设置 LLM 提供者.
func (*Container) WithReflectionFactory ¶
随着ReflectionFactory设置了反射延伸工厂.
func (*Container) WithToolManager ¶
func (c *Container) WithToolManager(toolManager ToolManager) *Container
与 ToolManager 设置工具管理器 。
func (*Container) WithToolSelectionFactory ¶
With ToolSelectFactory 设置工具选择扩展厂.
type ContextManager ¶
type ContextManager interface {
PrepareMessages(ctx context.Context, messages []llm.Message, currentQuery string) ([]llm.Message, error)
GetStatus(messages []llm.Message) any
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 DynamicToolSelectorRunner ¶ added in v1.0.0
type DynamicToolSelectorRunner interface {
SelectTools(ctx context.Context, task string, availableTools any) (any, error)
}
DynamicToolSelectorRunner dynamically selects tools relevant to a given task. This uses any for availableTools to match the integration.go call site signature. Implemented by: *DynamicToolSelector (agent/tool_selector.go) via adapter
func AsToolSelectorRunner ¶ added in v1.0.0
func AsToolSelectorRunner(selector *DynamicToolSelector) DynamicToolSelectorRunner
AsToolSelectorRunner wraps a *DynamicToolSelector as a DynamicToolSelectorRunner.
type EnhancedExecutionOptions ¶
type EnhancedExecutionOptions struct {
// Reflection 选项
UseReflection bool
// 工具选择选项
UseToolSelection bool
// 提示词增强选项
UsePromptEnhancer bool
// 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 EnhancedMemoryRunner ¶ added in v1.0.0
type EnhancedMemoryRunner interface {
LoadWorking(ctx context.Context, agentID string) ([]any, error)
LoadShortTerm(ctx context.Context, agentID string, limit int) ([]any, error)
SaveShortTerm(ctx context.Context, agentID, content string, metadata map[string]any) error
RecordEpisode(ctx context.Context, event *memory.EpisodicEvent) error
}
EnhancedMemoryRunner provides advanced memory capabilities. Implemented by: *memory.EnhancedMemorySystem (agent/memory/)
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 {
Base *types.Error `json:"base,inline"`
AgentID string `json:"agent_id,omitempty"`
AgentType AgentType `json:"agent_type,omitempty"`
Timestamp time.Time `json:"timestamp"`
Metadata map[string]any `json:"metadata,omitempty"`
}
Error Agent 统一错误类型 Uses Base *types.Error for unified error handling across the framework. Agent-specific fields (AgentID, AgentType, Timestamp, Metadata) extend the base. Access base fields via promoted-style helpers: e.Code, e.Message, e.Retryable, e.Cause.
func NewErrorWithCause ¶
NewErrorWithCause 创建带原因的错误
func (*Error) WithMetadata ¶
WithMetadata 添加元数据
func (*Error) WithRetryable ¶
WithRetryable 设置是否可重试
type ErrorCode ¶
ErrorCode 定义 Agent 错误码 用途类型。 ErrorCode作为与框架保持一致的基础类型.
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" )
特定代理错误代码 这些扩展了类型/error.go中定义的基础错误代码
type EventBus ¶
type EventBus interface {
Publish(event Event)
Subscribe(eventType EventType, handler EventHandler) string
Unsubscribe(subscriptionID string)
Stop()
}
EventBus 定义事件总线接口
type ExecutionContext ¶
type ExecutionContext struct {
WorkflowID string `json:"workflow_id,omitempty"`
CurrentNode string `json:"current_node,omitempty"`
NodeResults map[string]any `json:"node_results,omitempty"`
Variables map[string]any `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
}
扩展管理器管理可选代理扩展 。
func NewExtensionManager ¶
func NewExtensionManager(logger *zap.Logger) *ExtensionManager
NewExtensionManager创建了新的扩展管理器.
func (*ExtensionManager) EnhancedMemory ¶
func (em *ExtensionManager) EnhancedMemory() types.EnhancedMemoryExtension
增强记忆返回增强的内存扩展.
func (*ExtensionManager) Guardrails ¶
func (em *ExtensionManager) Guardrails() types.GuardrailsExtension
护卫员把护卫员的分机还给我
func (*ExtensionManager) HasGuardrails ¶
func (em *ExtensionManager) HasGuardrails() bool
如果有护栏,就检查护栏
func (*ExtensionManager) HasObservability ¶
func (em *ExtensionManager) HasObservability() bool
如果存在可观察性,则有可观察性检查。
func (*ExtensionManager) HasReflection ¶
func (em *ExtensionManager) HasReflection() bool
如果存在反射, 请进行反射检查 。
func (*ExtensionManager) HasToolSelection ¶
func (em *ExtensionManager) HasToolSelection() bool
如果可以选择工具, HasTooLSsection 检查 。
func (*ExtensionManager) Observability ¶
func (em *ExtensionManager) Observability() types.ObservabilityExtension
可观察性返回可观察性扩展.
func (*ExtensionManager) PromptEnhancer ¶
func (em *ExtensionManager) PromptEnhancer() types.PromptEnhancerExtension
PowerEnhancer 返回快速增强器扩展 。
func (*ExtensionManager) Reflection ¶
func (em *ExtensionManager) Reflection() types.ReflectionExtension
反射返回反射扩展.
func (*ExtensionManager) SetEnhancedMemory ¶
func (em *ExtensionManager) SetEnhancedMemory(ext types.EnhancedMemoryExtension)
Set Enhanced Memory 设置了增强的内存扩展名.
func (*ExtensionManager) SetGuardrails ¶
func (em *ExtensionManager) SetGuardrails(ext types.GuardrailsExtension)
SetGuardrails设置了护栏扩展.
func (*ExtensionManager) SetMCP ¶
func (em *ExtensionManager) SetMCP(ext types.MCPExtension)
SetMCP设置了MCP扩展.
func (*ExtensionManager) SetObservability ¶
func (em *ExtensionManager) SetObservability(ext types.ObservabilityExtension)
SetObservacy设置可观察扩展.
func (*ExtensionManager) SetPromptEnhancer ¶
func (em *ExtensionManager) SetPromptEnhancer(ext types.PromptEnhancerExtension)
SetPrompt Enhancer 设置了快速增强器扩展.
func (*ExtensionManager) SetReflection ¶
func (em *ExtensionManager) SetReflection(ext types.ReflectionExtension)
设定反射设置反射扩展 。
func (*ExtensionManager) SetSkills ¶
func (em *ExtensionManager) SetSkills(ext types.SkillsExtension)
SetSkills 设置技能扩展.
func (*ExtensionManager) SetToolSelection ¶
func (em *ExtensionManager) SetToolSelection(ext types.ToolSelectionExtension)
SetTools Selection 设置工具选择扩展名.
func (*ExtensionManager) Skills ¶
func (em *ExtensionManager) Skills() types.SkillsExtension
技能返回技能扩展。
func (*ExtensionManager) ToolSelection ¶
func (em *ExtensionManager) ToolSelection() types.ToolSelectionExtension
ToolSection 返回工具选择扩展名.
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 FeatureManager ¶
type FeatureManager struct {
// contains filtered or unexported fields
}
特性管理器管理可选代理特性. 它囊括了之前在BaseAgent中的特性管理逻辑.
func NewFeatureManager ¶
func NewFeatureManager(logger *zap.Logger) *FeatureManager
NewFeatureManager创建了新的功能管理器.
func (*FeatureManager) DisableEnhancedMemory ¶
func (fm *FeatureManager) DisableEnhancedMemory()
禁用增强的记忆功能 。
func (*FeatureManager) DisableLSP ¶
func (fm *FeatureManager) DisableLSP()
DisableLSP disables the LSP feature.
func (*FeatureManager) DisableObservability ¶
func (fm *FeatureManager) DisableObservability()
禁用可观察性可以禁用可观察性特性 。
func (*FeatureManager) DisablePromptEnhancer ¶
func (fm *FeatureManager) DisablePromptEnhancer()
禁用Prompt Enhancer 禁用快速增强器特性 。
func (*FeatureManager) DisableToolSelection ¶
func (fm *FeatureManager) DisableToolSelection()
禁用工具选择功能 。
func (*FeatureManager) EnableEnhancedMemory ¶
func (fm *FeatureManager) EnableEnhancedMemory(system EnhancedMemoryRunner)
启用 Enhanced Memory 启用增强的内存功能 。
func (*FeatureManager) EnableLSP ¶
func (fm *FeatureManager) EnableLSP(client LSPClientRunner)
EnableLSP enables the LSP feature.
func (*FeatureManager) EnableMCP ¶
func (fm *FeatureManager) EnableMCP(server MCPServerRunner)
启用 MCP 启用 MCP( 模式背景协议) 特性 。
func (*FeatureManager) EnableObservability ¶
func (fm *FeatureManager) EnableObservability(system ObservabilityRunner)
启用可观察性可以实现可观察性特性.
func (*FeatureManager) EnablePromptEnhancer ¶
func (fm *FeatureManager) EnablePromptEnhancer(enhancer PromptEnhancerRunner)
启用Prompt Enhancer 启用了即时增强器特性 。
func (*FeatureManager) EnableReflection ¶
func (fm *FeatureManager) EnableReflection(executor ReflectionRunner)
启用反射功能可以实现反射功能 。
func (*FeatureManager) EnableSkills ¶
func (fm *FeatureManager) EnableSkills(manager SkillDiscoverer)
启用技能可以实现技能特性 。
func (*FeatureManager) EnableToolSelection ¶
func (fm *FeatureManager) EnableToolSelection(selector DynamicToolSelectorRunner)
启用工具选择允许动态工具选择功能 。
func (*FeatureManager) EnabledFeatures ¶
func (fm *FeatureManager) EnabledFeatures() []string
启用 Features 返回已启用的特性名列表 。
func (*FeatureManager) GetEnhancedMemory ¶
func (fm *FeatureManager) GetEnhancedMemory() EnhancedMemoryRunner
Get Enhanced Memory 返回增强的内存系统.
func (*FeatureManager) GetLSP ¶
func (fm *FeatureManager) GetLSP() LSPClientRunner
GetLSP returns the LSP client.
func (*FeatureManager) GetMCPServer ¶
func (fm *FeatureManager) GetMCPServer() MCPServerRunner
GetMCPServer 返回 MCP 服务器.
func (*FeatureManager) GetObservability ¶
func (fm *FeatureManager) GetObservability() ObservabilityRunner
GetObservacy返回可观察系统.
func (*FeatureManager) GetPromptEnhancer ¶
func (fm *FeatureManager) GetPromptEnhancer() PromptEnhancerRunner
GetPrompt Enhancer 返回快速增强器 。
func (*FeatureManager) GetReflection ¶
func (fm *FeatureManager) GetReflection() ReflectionRunner
Get Reflection 返回反射执行器 。
func (*FeatureManager) GetSkillManager ¶
func (fm *FeatureManager) GetSkillManager() SkillDiscoverer
GetSkillManager返回技能管理器.
func (*FeatureManager) GetToolSelector ¶
func (fm *FeatureManager) GetToolSelector() DynamicToolSelectorRunner
GetTooSelector 返回工具选择器。
func (*FeatureManager) IsEnhancedMemoryEnabled ¶
func (fm *FeatureManager) IsEnhancedMemoryEnabled() bool
如果启用了增强内存, IsEnhanced Memory Enabled 检查。
func (*FeatureManager) IsLSPEnabled ¶
func (fm *FeatureManager) IsLSPEnabled() bool
IsLSPEnabled checks if LSP is enabled.
func (*FeatureManager) IsMCPEnabled ¶
func (fm *FeatureManager) IsMCPEnabled() bool
如果启用 MCP , IsMCP 可启用检查 。
func (*FeatureManager) IsObservabilityEnabled ¶
func (fm *FeatureManager) IsObservabilityEnabled() bool
如果启用可观察性, 则可以进行可观察性检查 。
func (*FeatureManager) IsPromptEnhancerEnabled ¶
func (fm *FeatureManager) IsPromptEnhancerEnabled() bool
IsPrompt EnhancerEnabled 检查如果启用了即时增强器。
func (*FeatureManager) IsReflectionEnabled ¶
func (fm *FeatureManager) IsReflectionEnabled() bool
是否启用了反射功能 。
func (*FeatureManager) IsSkillsEnabled ¶
func (fm *FeatureManager) IsSkillsEnabled() bool
IsSkills 启用技能后可以检查 。
func (*FeatureManager) IsToolSelectionEnabled ¶
func (fm *FeatureManager) IsToolSelectionEnabled() bool
如果启用了工具选择, IsTools Selection 可启用检查 。
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 GuardrailsCoordinator ¶
type GuardrailsCoordinator struct {
// contains filtered or unexported fields
}
护栏协调员利用护栏协调输入/输出验证。 它囊括了先前在BaseAgent中存在的护栏逻辑.
func NewGuardrailsCoordinator ¶
func NewGuardrailsCoordinator(config *guardrails.GuardrailsConfig, logger *zap.Logger) *GuardrailsCoordinator
新护卫组织协调员设立了一个新的护卫组织协调员。
func (*GuardrailsCoordinator) AddInputValidator ¶
func (gc *GuardrailsCoordinator) AddInputValidator(v guardrails.Validator)
添加InputValidator为输入链添加了验证符.
func (*GuardrailsCoordinator) AddOutputFilter ¶
func (gc *GuardrailsCoordinator) AddOutputFilter(f guardrails.Filter)
添加 OutputFilter 为输出验证器添加了过滤器 。
func (*GuardrailsCoordinator) AddOutputValidator ¶
func (gc *GuardrailsCoordinator) AddOutputValidator(v guardrails.Validator)
添加输出变量在输出验证符中添加一个验证符.
func (*GuardrailsCoordinator) BuildValidationFeedbackMessage ¶
func (gc *GuardrailsCoordinator) BuildValidationFeedbackMessage(result *guardrails.ValidationResult) string
BuildValidationFeed BackMessage为验证失败创建了反馈消息. 此消息可以发回LLM,请求更正回复.
func (*GuardrailsCoordinator) Enabled ¶
func (gc *GuardrailsCoordinator) Enabled() bool
启用是否启用了守护栏 。
func (*GuardrailsCoordinator) GetConfig ¶
func (gc *GuardrailsCoordinator) GetConfig() *guardrails.GuardrailsConfig
GetConfig 返回守护链配置 。
func (*GuardrailsCoordinator) GetInputValidatorChain ¶
func (gc *GuardrailsCoordinator) GetInputValidatorChain() *guardrails.ValidatorChain
GetInputValidator Chain 返回输入验证器链.
func (*GuardrailsCoordinator) GetOutputValidator ¶
func (gc *GuardrailsCoordinator) GetOutputValidator() *guardrails.OutputValidator
GetOutputValidator 返回输出验证器 。
func (*GuardrailsCoordinator) InputValidatorCount ¶
func (gc *GuardrailsCoordinator) InputValidatorCount() int
输入ValidatorCount 返回输入验证器的数量 。
func (*GuardrailsCoordinator) SetEnabled ¶
func (gc *GuardrailsCoordinator) SetEnabled(enabled bool)
设置可启用或禁用护栏 。
func (*GuardrailsCoordinator) ValidateInput ¶
func (gc *GuardrailsCoordinator) ValidateInput(ctx context.Context, input string) (*guardrails.ValidationResult, error)
验证输入验证输入内容. 返回验证结果时发现任何错误 。
func (*GuardrailsCoordinator) ValidateOutput ¶
func (gc *GuardrailsCoordinator) ValidateOutput(ctx context.Context, output string) (string, *guardrails.ValidationResult, error)
校验输出验证和过滤输出内容. 返回被过滤的输出和验证结果。
type GuardrailsError ¶
type GuardrailsError struct {
Type GuardrailsErrorType `json:"type"`
Message string `json:"message"`
Errors []guardrails.ValidationError `json:"errors"`
}
Guardrails Error 代表一个 Guardrails 验证错误 要求1.6:有故障原因退回详细错误信息
type GuardrailsErrorType ¶
type GuardrailsErrorType string
Guardrails ErrorType 定义了 Guardrails 错误的类型
const ( // Guardrails 错误输入表示输入验证失败 GuardrailsErrorTypeInput GuardrailsErrorType = "input" // Guardrails ErrorTypeOutput 表示输出验证失败 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
}
LLM执行器处理LLM交互.
func NewLLMExecutor ¶
func NewLLMExecutor(provider llm.Provider, config LLMExecutorConfig, logger *zap.Logger) *LLMExecutor
NewLLMExecutor创建了新的LLMExecutor.
func (*LLMExecutor) Complete ¶
func (e *LLMExecutor) Complete(ctx context.Context, messages []llm.Message) (*llm.ChatResponse, error)
完整向LLM发送完成请求.
func (*LLMExecutor) SetContextManager ¶
func (e *LLMExecutor) SetContextManager(cm ContextManager)
SetContextManager 设置信息优化的上下文管理器.
func (*LLMExecutor) Stream ¶
func (e *LLMExecutor) Stream(ctx context.Context, messages []llm.Message) (<-chan llm.StreamChunk, error)
Stream 向 LLM 发送流报请求 。
type LLMExecutorConfig ¶
LLMExecutorconfig 配置 LLM 执行器 。
type LSPClientRunner ¶ added in v1.0.0
LSPClientRunner represents an LSP client instance. Implemented by: *lsp.LSPClient (agent/lsp/) Used in Teardown for Shutdown call.
type LSPLifecycleOwner ¶ added in v1.0.0
type LSPLifecycleOwner interface {
Close() error
}
LSPLifecycleOwner represents an optional lifecycle owner for LSP (e.g. *ManagedLSP). Used in Teardown for Close call.
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 ¶
MCPServer 选项配置构建器如何创建默认的 MCP 服务器. Deprecated: Use WithDefaultMCPServer(name, version) instead.
type MCPServerRunner ¶ added in v1.0.0
type MCPServerRunner interface{}
MCPServerRunner represents an MCP server instance. Implemented by: *mcp.MCPServer (agent/protocol/mcp/) Currently used only for nil-check (feature status); no methods called directly.
type ManagedLSP ¶
type ManagedLSP struct {
Client *agentlsp.LSPClient
Server *agentlsp.LSPServer
// contains filtered or unexported fields
}
ManagedLSP 封装了进程内的 LSP client/server 及其生命周期。
func NewManagedLSP ¶
func NewManagedLSP(info agentlsp.ServerInfo, logger *zap.Logger) *ManagedLSP
NewManagedLSP 创建并启动一个进程内的 LSP runtime。
type MemoryConfig ¶
type MemoryConfig struct {
Enabled bool `json:"enabled,omitempty"`
}
type MemoryCoordinator ¶
type MemoryCoordinator struct {
// contains filtered or unexported fields
}
内存协调员在缓存支持下协调内存操作. 它囊括了先前在BaseAgent中的内存管理逻辑.
func NewMemoryCoordinator ¶
func NewMemoryCoordinator(agentID string, memory MemoryManager, logger *zap.Logger) *MemoryCoordinator
新记忆协调员创建了新的记忆协调员.
func (*MemoryCoordinator) ClearRecentMemory ¶
func (mc *MemoryCoordinator) ClearRecentMemory()
ClearRecent Memory 清除了被缓存的最近记忆.
func (*MemoryCoordinator) GetMemoryManager ¶
func (mc *MemoryCoordinator) GetMemoryManager() MemoryManager
Get MemoryManager 返回基本内存管理器.
func (*MemoryCoordinator) GetRecentMemory ¶
func (mc *MemoryCoordinator) GetRecentMemory() []MemoryRecord
GetRecentMemory 返回缓存的最近记忆 。
func (*MemoryCoordinator) LoadRecent ¶
func (mc *MemoryCoordinator) LoadRecent(ctx context.Context, kind MemoryKind, limit int) error
最近将最近的记忆加载到缓存中 。
func (*MemoryCoordinator) RecallRelevant ¶
func (mc *MemoryCoordinator) RecallRelevant(ctx context.Context, query string, topK int) ([]MemoryRecord, error)
RecallRelvant 回顾与查询相关的记忆.
func (*MemoryCoordinator) Save ¶
func (mc *MemoryCoordinator) Save(ctx context.Context, content string, kind MemoryKind, metadata map[string]any) error
保存内存记录 。
func (*MemoryCoordinator) SaveConversation ¶
func (mc *MemoryCoordinator) SaveConversation(ctx context.Context, input, output string) error
保存 Conversation 保存一个对话转折(输入和输出).
func (*MemoryCoordinator) Search ¶
func (mc *MemoryCoordinator) Search(ctx context.Context, query string, topK int) ([]MemoryRecord, error)
搜索匹配查询的记忆 。
type MemoryKind ¶
type MemoryKind = types.MemoryCategory
MemoryKind 记忆类型 折旧:使用类型。 用于新代码的内存类型 。 此别名用于后向相容性 。
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 统一记忆结构 用途类型。 用于 Kind 字段的内存类型,以确保一致性 。
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(next func(ctx context.Context, input *Input) (*Output, error)) func(ctx context.Context, input *Input) (*Output, error)
}
MiddlewarePlugin 包装代理执行 。
type ModularAgent ¶
type ModularAgent struct {
// contains filtered or unexported fields
}
模块化代理(ModularAgent)是一种使用组成来取代继承的再造代理. 它将责任下放给专门部门。
func NewModularAgent ¶
func NewModularAgent( config ModularAgentConfig, provider llm.Provider, memory MemoryManager, tools ToolManager, bus EventBus, logger *zap.Logger, ) *ModularAgent
新ModularAgent创建了新的ModularAgent.
func (*ModularAgent) Observe ¶
func (a *ModularAgent) Observe(ctx context.Context, feedback *Feedback) error
观察处理反馈.
func (*ModularAgent) Plan ¶
func (a *ModularAgent) Plan(ctx context.Context, input *Input) (*PlanResult, error)
计划产生一个执行计划。
type ModularAgentConfig ¶
type ModularAgentConfig struct {
ID string
Name string
Type AgentType
Description string
LLM LLMExecutorConfig
}
ModularAgentConfig 配置一个ModularAgent.
type ObservabilityRunner ¶ added in v1.0.0
type ObservabilityRunner interface {
StartTrace(traceID, agentID string)
EndTrace(traceID, status string, err error)
RecordTask(agentID string, success bool, duration time.Duration, tokens int, cost, quality float64)
}
ObservabilityRunner provides metrics, tracing, and logging. Implemented by: *observability.ObservabilitySystem (agent/observability/)
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]any `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() string
// 类型返回插件类型 。
Type() PluginType
// Init 初始化插件 。
Init(ctx context.Context) error
// Shutdown 优雅关闭插件 。
Shutdown(ctx context.Context) error
}
插件定义代理插件的接口 。
type PluginEnabledAgent ¶
type PluginEnabledAgent struct {
// contains filtered or unexported fields
}
插件可启用代理用插件支持将代理包入。
func NewPluginEnabledAgent ¶
func NewPluginEnabledAgent(agent Agent, registry *PluginRegistry) *PluginEnabledAgent
NewPluginEnabled Agent 创建了插件启用的代理包.
func (*PluginEnabledAgent) Init ¶
func (a *PluginEnabledAgent) Init(ctx context.Context) error
初始化代理和插件 。
func (*PluginEnabledAgent) Observe ¶
func (a *PluginEnabledAgent) Observe(ctx context.Context, feedback *Feedback) error
观察处理反馈.
func (*PluginEnabledAgent) Plan ¶
func (a *PluginEnabledAgent) Plan(ctx context.Context, input *Input) (*PlanResult, error)
计划产生一个执行计划。
func (*PluginEnabledAgent) Registry ¶
func (a *PluginEnabledAgent) Registry() *PluginRegistry
注册返回插件注册 。
func (*PluginEnabledAgent) Teardown ¶
func (a *PluginEnabledAgent) Teardown(ctx context.Context) error
倒地清理代理和插件.
func (*PluginEnabledAgent) UnderlyingAgent ¶
func (a *PluginEnabledAgent) UnderlyingAgent() Agent
地下特工还原被包裹的特工.
type PluginRegistry ¶
type PluginRegistry struct {
// contains filtered or unexported fields
}
插件注册管理插件注册和生命周期.
func (*PluginRegistry) Init ¶
func (r *PluginRegistry) Init(ctx context.Context) error
Init 初始化所有插件 。
func (*PluginRegistry) MiddlewarePlugins ¶
func (r *PluginRegistry) MiddlewarePlugins() []MiddlewarePlugin
MiddlewarePlugins返回所有中间软件插件.
func (*PluginRegistry) PostProcessPlugins ¶
func (r *PluginRegistry) PostProcessPlugins() []PostProcessPlugin
PostProcessPlugins 返回所有后进程插件.
func (*PluginRegistry) PreProcessPlugins ¶
func (r *PluginRegistry) PreProcessPlugins() []PreProcessPlugin
PrecessPlugins 返回所有预处理插件 。
func (*PluginRegistry) Shutdown ¶ added in v1.0.0
func (r *PluginRegistry) Shutdown(ctx context.Context) error
关闭所有插件 。
func (*PluginRegistry) Unregister ¶
func (r *PluginRegistry) Unregister(name string) error
未注册删除插件 。
type PluginType ¶
type PluginType string
插件Type 定义了插件的类型 。
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(ctx context.Context, output *Output) (*Output, error)
}
后ProcessPlugin在代理执行后运行.
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 ...any) error
QueryRow(ctx context.Context, query string, args ...any) Row
Query(ctx context.Context, query string, args ...any) (Rows, error)
}
PostgreSQLClient PostgreSQL 客户端接口
type PreProcessPlugin ¶
type PreProcessPlugin interface {
Plugin
// Precess 执行前处理输入.
PreProcess(ctx context.Context, input *Input) (*Input, error)
}
PrecessPlugin 在代理执行前运行.
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
ExpressEngineeringConfig 是用于向后兼容的ExpressEngineeringConfig的别名
func DefaultPromptEngineeringConfig ¶
func DefaultPromptEngineeringConfig() PromptEngineeringConfig
默认PromptEngineeringConfig 返回默认的快速工程配置
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
}
快速EnhancerConfig 快速工程配置
func DefaultPromptEnhancerConfig ¶
func DefaultPromptEnhancerConfig() *PromptEnhancerConfig
默认Prompt EnhancerConfig 返回默认的快速增强器配置
type PromptEnhancerRunner ¶ added in v1.0.0
PromptEnhancerRunner enhances user prompts with additional context. Implemented by: *PromptEnhancer (agent/prompt_enhancer.go)
func AsPromptEnhancerRunner ¶ added in v1.0.0
func AsPromptEnhancerRunner(enhancer *PromptEnhancer) PromptEnhancerRunner
AsPromptEnhancerRunner wraps a *PromptEnhancer as a PromptEnhancerRunner.
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
EnableLSP bool
EnableEnhancedMemory bool
EnableObservability bool
// 配置
ReflectionMaxIterations int
ToolSelectionMaxTools int
SkillsDirectory string
MCPServerName string
LSPServerName string
LSPServerVersion 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
}
反射执行器配置
func DefaultReflectionConfig ¶
func DefaultReflectionConfig() *ReflectionExecutorConfig
默认反射 Config 返回默认反射配置
func DefaultReflectionExecutorConfig ¶
func DefaultReflectionExecutorConfig() ReflectionExecutorConfig
默认反射 ExecutorConfig 返回默认反射配置
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 ReflectionRunner ¶ added in v1.0.0
type ReflectionRunner interface {
ExecuteWithReflection(ctx context.Context, input *Input) (any, error)
}
ReflectionRunner executes a task with iterative self-reflection. Implemented by: *ReflectionExecutor (agent/reflection.go)
func AsReflectionRunner ¶ added in v1.0.0
func AsReflectionRunner(executor *ReflectionExecutor) ReflectionRunner
AsReflectionRunner wraps a *ReflectionExecutor as a ReflectionRunner.
type RunConfig ¶
type RunConfig struct {
Model *string `json:"model,omitempty"`
Temperature *float32 `json:"temperature,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
TopP *float32 `json:"top_p,omitempty"`
Stop []string `json:"stop,omitempty"`
ToolChoice *string `json:"tool_choice,omitempty"`
Timeout *time.Duration `json:"timeout,omitempty"`
MaxReActIterations *int `json:"max_react_iterations,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Tags []string `json:"tags,omitempty"`
}
RunConfig provides runtime overrides for Agent execution. All pointer fields use nil to indicate "no override" — only non-nil values are applied, leaving the base Config defaults intact.
func GetRunConfig ¶
GetRunConfig retrieves the RunConfig from the context. Returns nil if no RunConfig is present.
func (*RunConfig) ApplyToRequest ¶
func (rc *RunConfig) ApplyToRequest(req *llm.ChatRequest, baseCfg Config)
ApplyToRequest applies RunConfig overrides to a ChatRequest. Fields in baseCfg are used as defaults; only non-nil RunConfig fields override them. If rc is nil, this is a no-op.
func (*RunConfig) EffectiveMaxReActIterations ¶
EffectiveMaxReActIterations returns the RunConfig override if set, otherwise falls back to defaultVal.
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"`
ToolCallID string `json:"tool_call_id,omitempty"`
ToolName string `json:"tool_name,omitempty"`
Data any `json:"data,omitempty"`
}
type RuntimeStreamEventType ¶
type RuntimeStreamEventType string
const ( RuntimeStreamToken RuntimeStreamEventType = "token" RuntimeStreamToolCall RuntimeStreamEventType = "tool_call" RuntimeStreamToolResult RuntimeStreamEventType = "tool_result" RuntimeStreamToolProgress RuntimeStreamEventType = "tool_progress" )
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
}
服务管理员提供全球服务登记处。
func (*ServiceLocator) GetEventBus ¶
func (sl *ServiceLocator) GetEventBus() (EventBus, bool)
GetEventBus 检索活动总线 。
func (*ServiceLocator) GetLogger ¶
func (sl *ServiceLocator) GetLogger() (*zap.Logger, bool)
让Logger拿回日志
func (*ServiceLocator) GetMemory ¶
func (sl *ServiceLocator) GetMemory() (MemoryManager, bool)
让Memory找回记忆管理器
func (*ServiceLocator) GetProvider ¶
func (sl *ServiceLocator) GetProvider() (llm.Provider, bool)
Get Provider 获取 LLM 提供者 。
func (*ServiceLocator) GetToolManager ¶
func (sl *ServiceLocator) GetToolManager() (ToolManager, bool)
GetToolManager检索工具管理器.
func (*ServiceLocator) MustGet ¶
func (sl *ServiceLocator) MustGet(name string) any
如果找不到, 必须获取服务或恐慌 。
func (*ServiceLocator) Register ¶
func (sl *ServiceLocator) Register(name string, service any)
登记服务。
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 SkillDiscoverer ¶ added in v1.0.0
type SkillDiscoverer interface {
DiscoverSkills(ctx context.Context, task string) ([]*skills.Skill, error)
}
SkillDiscoverer discovers skills relevant to a task. Implemented by: *skills.DefaultSkillManager (agent/skills/)
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管理代理状态过渡(轻量级版).
func NewStateManager ¶
func NewStateManager(agentID string, bus EventBus, logger *zap.Logger) *StateManager
新州管理者创建了新的州管理者.
func (*StateManager) EnsureReady ¶
func (sm *StateManager) EnsureReady() error
如果特工处于准备状态, 请确保准备检查 。
func (*StateManager) Transition ¶
func (sm *StateManager) Transition(ctx context.Context, to State) error
过渡通过验证实现国家过渡。
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为Agent运行时间摘要了"工具列表+工具执行"的能力.
设计目标: - 直接根据pkg/剂/工具避免pkg/剂(取消进口周期) - 允许在应用程序层注入不同的执行(默认使用工具)。 工具管理器)
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"`
// 分数
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
// 甄选战略
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
默认工具SecutConfig 返回默认工具选择配置
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
¶
- agent_tool.go
- async_execution.go
- base.go
- builder.go
- checkpoint.go
- completion.go
- components.go
- container.go
- defensive_prompt.go
- doc.go
- errors.go
- event.go
- feature_manager.go
- guardrails_coordinator.go
- human_in_loop.go
- integration.go
- interfaces.go
- lifecycle.go
- lsp_runtime.go
- memory.go
- memory_coordinator.go
- plugin.go
- prompt_bundle.go
- prompt_engineering.go
- react.go
- reflection.go
- registry.go
- resolver.go
- run_config.go
- runtime_stream.go
- state.go
- tool_manager.go
- tool_selector.go
Directories
¶
| Path | Synopsis |
|---|---|
|
包 artifacts 为智能体提供产物的生成、存储与生命周期管理能力。
|
包 artifacts 为智能体提供产物的生成、存储与生命周期管理能力。 |
|
包 browser 为智能体提供浏览器自动化与网页交互能力。
|
包 browser 为智能体提供浏览器自动化与网页交互能力。 |
|
Package collaboration 提供多 Agent 协作模式,包括辩论、共识和投票等交互策略。
|
Package collaboration 提供多 Agent 协作模式,包括辩论、共识和投票等交互策略。 |
|
包 context 为智能体提供上下文窗口管理、压缩与自适应调控能力。
|
包 context 为智能体提供上下文窗口管理、压缩与自适应调控能力。 |
|
包 conversation 提供多智能体对话编排与对话状态管理能力。
|
包 conversation 提供多智能体对话编排与对话状态管理能力。 |
|
包 crews 提供基于角色分工的多智能体团队协作框架。
|
包 crews 提供基于角色分工的多智能体团队协作框架。 |
|
包 deliberation 提供智能体行动前的多步推理与审议引擎。
|
包 deliberation 提供智能体行动前的多步推理与审议引擎。 |
|
包 deployment 提供智能体的部署管理与运行环境适配能力。
|
包 deployment 提供智能体的部署管理与运行环境适配能力。 |
|
包 discovery 提供多智能体场景下的能力发现与匹配机制。
|
包 discovery 提供多智能体场景下的能力发现与匹配机制。 |
|
包 evaluation 提供智能体评测、实验与质量分析能力。
|
包 evaluation 提供智能体评测、实验与质量分析能力。 |
|
checkpointer.go is intentionally empty.
|
checkpointer.go is intentionally empty. |
|
包 federation 提供跨组织智能体联合协作与任务编排能力。
|
包 federation 提供跨组织智能体联合协作与任务编排能力。 |
|
包 guardrails 为智能体提供输入与输出安全防护能力。
|
包 guardrails 为智能体提供输入与输出安全防护能力。 |
|
包 handoff 提供智能体间的任务交接协议与上下文传递能力。
|
包 handoff 提供智能体间的任务交接协议与上下文传递能力。 |
|
Package hierarchical 提供基于 Supervisor-Worker 模式的层次化 Agent 编排。
|
Package hierarchical 提供基于 Supervisor-Worker 模式的层次化 Agent 编排。 |
|
包 hitl 提供 Human-in-the-Loop 工作流中断与恢复能力。
|
包 hitl 提供 Human-in-the-Loop 工作流中断与恢复能力。 |
|
包 hosted 提供由平台托管的工具注册与远程服务接入能力。
|
包 hosted 提供由平台托管的工具注册与远程服务接入能力。 |
|
包 k8s 提供 Kubernetes 场景下的智能体生命周期管理与运维能力。
|
包 k8s 提供 Kubernetes 场景下的智能体生命周期管理与运维能力。 |
|
包 longrunning 提供面向智能体的长时任务执行与断点恢复能力。
|
包 longrunning 提供面向智能体的长时任务执行与断点恢复能力。 |
|
Package lsp 提供 Language Server Protocol (LSP) 支持, 使 Agent 能够通过 LSP 协议与 IDE 和编辑器集成。
|
Package lsp 提供 Language Server Protocol (LSP) 支持, 使 Agent 能够通过 LSP 协议与 IDE 和编辑器集成。 |
|
Package mcp 提供 MCP (Model Context Protocol) 的稳定导入路径。
|
Package mcp 提供 MCP (Model Context Protocol) 的稳定导入路径。 |
|
包 memory 提供面向智能体的分层记忆系统。
|
包 memory 提供面向智能体的分层记忆系统。 |
|
包 observability 提供面向智能体的可观测性与可解释性系统。
|
包 observability 提供面向智能体的可观测性与可解释性系统。 |
|
Package orchestration provides a unified orchestrator that dynamically selects between collaboration, crews, hierarchical, and handoff patterns based on task characteristics and agent composition.
|
Package orchestration provides a unified orchestrator that dynamically selects between collaboration, crews, hierarchical, and handoff patterns based on task characteristics and agent composition. |
|
包 persistence 提供面向智能体的消息与任务持久化存储抽象及多后端实现。
|
包 persistence 提供面向智能体的消息与任务持久化存储抽象及多后端实现。 |
|
protocol
|
|
|
a2a
包 a2a 提供 Agent-to-Agent(A2A)协议的核心实现。
|
包 a2a 提供 Agent-to-Agent(A2A)协议的核心实现。 |
|
mcp
Package mcp 实现 Anthropic Model Context Protocol (MCP) 规范。
|
Package mcp 实现 Anthropic Model Context Protocol (MCP) 规范。 |
|
包 reasoning 提供面向智能体的多种高级推理模式。
|
包 reasoning 提供面向智能体的多种高级推理模式。 |
|
Package runtime 提供 Agent 一键构建工具,通过 BuildOptions 控制 可选子系统(LSP、MCP、Memory、Skills、Observability 等)的启停。
|
Package runtime 提供 Agent 一键构建工具,通过 BuildOptions 控制 可选子系统(LSP、MCP、Memory、Skills、Observability 等)的启停。 |
|
包 skills 提供 Agent 技能的注册、发现、加载与调用管理能力。
|
包 skills 提供 Agent 技能的注册、发现、加载与调用管理能力。 |
|
包 streaming 提供实时双向流式交互能力。
|
包 streaming 提供实时双向流式交互能力。 |
|
包 voice 提供语音 Agent 与实时音频交互能力。
|
包 voice 提供语音 Agent 与实时音频交互能力。 |