tools

package
v0.35.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RiskLevelSafe     = 0 // 完全安全
	RiskLevelLow      = 1 // 低风险
	RiskLevelMedium   = 2 // 中等风险
	RiskLevelHigh     = 3 // 高风险
	RiskLevelCritical = 4 // 极高风险
)

RiskLevel 风险级别常量

View Source
const (
	CategoryFilesystem = "filesystem" // 文件系统操作
	CategoryExecution  = "execution"  // 命令执行
	CategoryNetwork    = "network"    // 网络请求
	CategoryDatabase   = "database"   // 数据库操作
	CategorySystem     = "system"     // 系统操作
	CategoryMCP        = "mcp"        // MCP 工具
	CategoryCustom     = "custom"     // 自定义工具
)

Category 工具分类常量

Variables

View Source
var AnnotationsDatabaseDestructive = &ToolAnnotations{
	ReadOnly:             false,
	Destructive:          true,
	Idempotent:           false,
	OpenWorld:            false,
	RiskLevel:            RiskLevelCritical,
	Category:             CategoryDatabase,
	RequiresConfirmation: true,
}

AnnotationsDatabaseDestructive 数据库破坏性操作 适用于: DELETE, DROP 等

View Source
var AnnotationsDatabaseRead = &ToolAnnotations{
	ReadOnly:    true,
	Destructive: false,
	Idempotent:  true,
	OpenWorld:   false,
	RiskLevel:   RiskLevelSafe,
	Category:    CategoryDatabase,
}

AnnotationsDatabaseRead 数据库只读操作 适用于: SELECT 查询等

View Source
var AnnotationsDatabaseWrite = &ToolAnnotations{
	ReadOnly:    false,
	Destructive: false,
	Idempotent:  false,
	OpenWorld:   false,
	RiskLevel:   RiskLevelMedium,
	Category:    CategoryDatabase,
}

AnnotationsDatabaseWrite 数据库写操作 适用于: INSERT, UPDATE 等

View Source
var AnnotationsDestructiveWrite = &ToolAnnotations{
	ReadOnly:             false,
	Destructive:          true,
	Idempotent:           false,
	OpenWorld:            false,
	RiskLevel:            RiskLevelHigh,
	Category:             CategoryFilesystem,
	RequiresConfirmation: true,
}

AnnotationsDestructiveWrite 破坏性写操作 适用于: 删除文件、清空目录等操作

View Source
var AnnotationsExecution = &ToolAnnotations{
	ReadOnly:    false,
	Destructive: true,
	Idempotent:  false,
	OpenWorld:   true,
	RiskLevel:   RiskLevelHigh,
	Category:    CategoryExecution,
}

AnnotationsExecution 命令执行 适用于: Bash 等命令执行工具

View Source
var AnnotationsMCPTool = &ToolAnnotations{
	ReadOnly:    false,
	Destructive: false,
	Idempotent:  false,
	OpenWorld:   true,
	RiskLevel:   RiskLevelMedium,
	Category:    CategoryMCP,
}

AnnotationsMCPTool MCP 工具默认注解

View Source
var AnnotationsNetworkRead = &ToolAnnotations{
	ReadOnly:    true,
	Destructive: false,
	Idempotent:  true,
	OpenWorld:   true,
	RiskLevel:   RiskLevelLow,
	Category:    CategoryNetwork,
}

AnnotationsNetworkRead 网络只读操作 适用于: WebFetch, WebSearch 等网络读取工具

View Source
var AnnotationsNetworkWrite = &ToolAnnotations{
	ReadOnly:    false,
	Destructive: false,
	Idempotent:  false,
	OpenWorld:   true,
	RiskLevel:   RiskLevelMedium,
	Category:    CategoryNetwork,
}

AnnotationsNetworkWrite 网络写操作 适用于: HTTP POST/PUT/DELETE 等修改操作

View Source
var AnnotationsSafeReadOnly = &ToolAnnotations{
	ReadOnly:    true,
	Destructive: false,
	Idempotent:  true,
	OpenWorld:   false,
	RiskLevel:   RiskLevelSafe,
	Category:    CategoryFilesystem,
}

AnnotationsSafeReadOnly 安全只读操作 适用于: Read, Glob, Grep 等只读工具

View Source
var AnnotationsSafeWrite = &ToolAnnotations{
	ReadOnly:    false,
	Destructive: false,
	Idempotent:  true,
	OpenWorld:   false,
	RiskLevel:   RiskLevelLow,
	Category:    CategoryFilesystem,
}

AnnotationsSafeWrite 安全写操作 适用于: Write, Edit 等文件写入工具

View Source
var AnnotationsUserInteraction = &ToolAnnotations{
	ReadOnly:    true,
	Destructive: false,
	Idempotent:  true,
	OpenWorld:   false,
	RiskLevel:   RiskLevelSafe,
	Category:    CategoryCustom,
}

AnnotationsUserInteraction 用户交互工具 适用于: AskUserQuestion 等

View Source
var ToolChoiceAny = &ToolChoice{Type: "any"}

ToolChoiceAny 必须使用工具(任意一个)

View Source
var ToolChoiceAuto = &ToolChoice{Type: "auto"}

ToolChoiceAuto 自动选择工具

Functions

func GetToolRiskLevel added in v0.33.0

func GetToolRiskLevel(tool Tool) int

GetToolRiskLevel 获取工具风险级别

func IsToolSafeForAutoApproval added in v0.33.0

func IsToolSafeForAutoApproval(tool Tool) bool

IsToolSafeForAutoApproval 判断工具是否可以自动批准

func ValidateInput

func ValidateInput(tool Tool, input map[string]any) error

ValidateInput 验证工具输入

Types

type AnnotatedTool added in v0.33.0

type AnnotatedTool interface {
	Tool
	// Annotations 返回工具安全注解
	Annotations() *ToolAnnotations
}

AnnotatedTool 带安全注解的工具接口 实现此接口的工具可以提供安全注解,帮助权限系统做出智能决策

type BaseEnhancedTool

type BaseEnhancedTool struct {
	// contains filtered or unexported fields
}

BaseEnhancedTool 增强工具的基础实现 提供默认行为,简化自定义工具开发

func NewBaseEnhancedTool

func NewBaseEnhancedTool(name, description string) *BaseEnhancedTool

func (*BaseEnhancedTool) Description

func (t *BaseEnhancedTool) Description() string

func (*BaseEnhancedTool) Execute

func (t *BaseEnhancedTool) Execute(ctx context.Context, args map[string]any) (any, error)

Execute 需要由具体工具实现

func (*BaseEnhancedTool) IsLongRunning

func (t *BaseEnhancedTool) IsLongRunning() bool

func (*BaseEnhancedTool) Metadata

func (t *BaseEnhancedTool) Metadata() map[string]any

func (*BaseEnhancedTool) Name

func (t *BaseEnhancedTool) Name() string

func (*BaseEnhancedTool) Priority

func (t *BaseEnhancedTool) Priority() int

func (*BaseEnhancedTool) RequiresApproval

func (t *BaseEnhancedTool) RequiresApproval() bool

func (*BaseEnhancedTool) RetryPolicy

func (t *BaseEnhancedTool) RetryPolicy() *RetryPolicy

func (*BaseEnhancedTool) Schema

func (t *BaseEnhancedTool) Schema() *types.ToolSchema

func (*BaseEnhancedTool) SetLongRunning

func (t *BaseEnhancedTool) SetLongRunning(v bool)

func (*BaseEnhancedTool) SetMetadata

func (t *BaseEnhancedTool) SetMetadata(key string, value any)

func (*BaseEnhancedTool) SetPriority

func (t *BaseEnhancedTool) SetPriority(p int)

func (*BaseEnhancedTool) SetRequireApproval

func (t *BaseEnhancedTool) SetRequireApproval(v bool)

func (*BaseEnhancedTool) SetRetryPolicy

func (t *BaseEnhancedTool) SetRetryPolicy(policy *RetryPolicy)

func (*BaseEnhancedTool) SetSchema

func (t *BaseEnhancedTool) SetSchema(schema *types.ToolSchema)

Setter 方法

func (*BaseEnhancedTool) SetTimeout

func (t *BaseEnhancedTool) SetTimeout(d time.Duration)

func (*BaseEnhancedTool) Timeout

func (t *BaseEnhancedTool) Timeout() time.Duration

type BaseLongRunningTool

type BaseLongRunningTool struct {
	BaseTool
	// contains filtered or unexported fields
}

BaseLongRunningTool 长时运行工具的基础实现 可以嵌入到具体工具中

func NewBaseLongRunningTool

func NewBaseLongRunningTool(name, description string, executor *LongRunningExecutor) *BaseLongRunningTool

NewBaseLongRunningTool 创建基础长时运行工具

func (*BaseLongRunningTool) Cancel

func (t *BaseLongRunningTool) Cancel(ctx context.Context, taskID string) error

Cancel 实现 LongRunningTool 接口

func (*BaseLongRunningTool) Execute

func (t *BaseLongRunningTool) Execute(ctx context.Context, args map[string]any, tc *ToolContext) (any, error)

Execute 需要由具体工具实现

func (*BaseLongRunningTool) GetStatus

func (t *BaseLongRunningTool) GetStatus(ctx context.Context, taskID string) (*TaskStatus, error)

GetStatus 实现 LongRunningTool 接口

func (*BaseLongRunningTool) IsLongRunning

func (t *BaseLongRunningTool) IsLongRunning() bool

IsLongRunning 实现 LongRunningTool 接口

func (*BaseLongRunningTool) StartAsync

func (t *BaseLongRunningTool) StartAsync(ctx context.Context, args map[string]any) (string, error)

StartAsync 实现 LongRunningTool 接口

type BaseTool

type BaseTool struct {
	ToolName        string // 导出字段
	ToolDescription string // 导出字段
}

BaseTool 基础工具实现(提供默认的空方法)

func NewBaseTool

func NewBaseTool(name, description string) *BaseTool

NewBaseTool 创建基础工具

func (*BaseTool) Description

func (t *BaseTool) Description() string

func (*BaseTool) Execute

func (t *BaseTool) Execute(ctx context.Context, input map[string]any, tc *ToolContext) (any, error)

func (*BaseTool) InputSchema

func (t *BaseTool) InputSchema() map[string]any

func (*BaseTool) Name

func (t *BaseTool) Name() string

func (*BaseTool) Prompt

func (t *BaseTool) Prompt() string

type BlacklistConstraints added in v0.17.0

type BlacklistConstraints struct {
	// contains filtered or unexported fields
}

BlacklistConstraints 黑名单约束

func NewBlacklistConstraints added in v0.17.0

func NewBlacklistConstraints(tools []string) *BlacklistConstraints

NewBlacklistConstraints 创建黑名单约束

func (*BlacklistConstraints) GetAllowedTools added in v0.17.0

func (b *BlacklistConstraints) GetAllowedTools(ctx context.Context) []string

func (*BlacklistConstraints) GetConstraintType added in v0.17.0

func (b *BlacklistConstraints) GetConstraintType() ConstraintType

func (*BlacklistConstraints) IsAllowed added in v0.17.0

func (b *BlacklistConstraints) IsAllowed(ctx context.Context, toolName string) bool

type CacheConfig added in v0.13.0

type CacheConfig struct {
	// Enabled 是否启用缓存
	Enabled bool

	// Strategy 缓存策略
	Strategy CacheStrategy

	// TTL 缓存过期时间
	TTL time.Duration

	// CacheDir 文件缓存目录(仅用于 file 和 both 策略)
	CacheDir string

	// MaxMemoryItems 内存缓存最大条目数(0 表示无限制)
	MaxMemoryItems int

	// MaxFileSize 单个缓存文件最大大小(字节,0 表示无限制)
	MaxFileSize int64
}

CacheConfig 缓存配置

func DefaultCacheConfig added in v0.13.0

func DefaultCacheConfig() *CacheConfig

DefaultCacheConfig 默认缓存配置

type CacheEntry added in v0.13.0

type CacheEntry struct {
	Key       string
	Value     any
	CreatedAt time.Time
	ExpiresAt time.Time
	Size      int64
}

CacheEntry 缓存条目

func (*CacheEntry) IsExpired added in v0.13.0

func (e *CacheEntry) IsExpired() bool

IsExpired 检查是否过期

type CacheStats added in v0.13.0

type CacheStats struct {
	Hits          int64
	Misses        int64
	Sets          int64
	Evictions     int64
	Errors        int64
	TotalSize     int64
	ItemCount     int64
	LastCleanupAt time.Time
}

CacheStats 缓存统计

type CacheStrategy added in v0.13.0

type CacheStrategy string

CacheStrategy 缓存策略

const (
	CacheStrategyMemory CacheStrategy = "memory" // 内存缓存
	CacheStrategyFile   CacheStrategy = "file"   // 文件缓存
	CacheStrategyBoth   CacheStrategy = "both"   // 内存+文件双层缓存
)

type CachedTool added in v0.13.0

type CachedTool struct {
	// contains filtered or unexported fields
}

CachedTool 带缓存的工具包装器

func NewCachedTool added in v0.13.0

func NewCachedTool(tool Tool, cache *ToolCache) *CachedTool

NewCachedTool 创建带缓存的工具

func (*CachedTool) Description added in v0.13.0

func (ct *CachedTool) Description() string

Description 实现 Tool 接口

func (*CachedTool) Execute added in v0.13.0

func (ct *CachedTool) Execute(ctx context.Context, input map[string]any, tc *ToolContext) (any, error)

Execute 实现 Tool 接口(带缓存)

func (*CachedTool) InputSchema added in v0.13.0

func (ct *CachedTool) InputSchema() map[string]any

InputSchema 实现 Tool 接口

func (*CachedTool) Name added in v0.13.0

func (ct *CachedTool) Name() string

Name 实现 Tool 接口

func (*CachedTool) Prompt added in v0.13.0

func (ct *CachedTool) Prompt() string

Prompt 实现 Tool 接口

type ConstraintType added in v0.17.0

type ConstraintType string

ConstraintType 约束类型

const (
	// ConstraintTypeNone 无约束(所有工具可用)
	ConstraintTypeNone ConstraintType = "none"

	// ConstraintTypeWhitelist 白名单(只有列表中的工具可用)
	ConstraintTypeWhitelist ConstraintType = "whitelist"

	// ConstraintTypeBlacklist 黑名单(列表中的工具不可用)
	ConstraintTypeBlacklist ConstraintType = "blacklist"

	// ConstraintTypeRequired 必需工具(必须使用指定工具)
	ConstraintTypeRequired ConstraintType = "required"

	// ConstraintTypeAuto 自动选择(由系统决定)
	ConstraintTypeAuto ConstraintType = "auto"
)

type ConstraintsBuilder added in v0.17.0

type ConstraintsBuilder struct {
	// contains filtered or unexported fields
}

ConstraintsBuilder 约束构建器

func NewConstraintsBuilder added in v0.17.0

func NewConstraintsBuilder() *ConstraintsBuilder

NewConstraintsBuilder 创建约束构建器

func (*ConstraintsBuilder) Build added in v0.17.0

Build 构建约束

func (*ConstraintsBuilder) WithBlacklist added in v0.17.0

func (b *ConstraintsBuilder) WithBlacklist(tools ...string) *ConstraintsBuilder

WithBlacklist 设置黑名单

func (*ConstraintsBuilder) WithRequired added in v0.17.0

func (b *ConstraintsBuilder) WithRequired(toolName string) *ConstraintsBuilder

WithRequired 设置必需工具

func (*ConstraintsBuilder) WithWhitelist added in v0.17.0

func (b *ConstraintsBuilder) WithWhitelist(tools ...string) *ConstraintsBuilder

WithWhitelist 设置白名单

type Context

type Context interface {
	// Context 返回 Go 标准 context
	Context() context.Context

	// Value 获取上下文值
	Value(key any) any
}

Context 工具执行的基础上下文接口 提供最小的上下文信息

type DefaultToolSelector added in v0.17.0

type DefaultToolSelector struct{}

DefaultToolSelector 默认工具选择器

func (*DefaultToolSelector) SelectTools added in v0.17.0

func (s *DefaultToolSelector) SelectTools(ctx context.Context, allTools []Tool, constraints ToolConstraints) ([]Tool, error)

SelectTools 选择工具

func (*DefaultToolSelector) ShouldUseToolChoice added in v0.17.0

func (s *DefaultToolSelector) ShouldUseToolChoice(ctx context.Context, constraints ToolConstraints) (*ToolChoice, bool)

ShouldUseToolChoice 判断是否应该使用 tool_choice

type DeferrableConfig added in v0.17.0

type DeferrableConfig struct {
	// DeferLoading 是否延迟加载,为 true 时工具不会预先加载到 LLM 上下文
	DeferLoading bool `json:"defer_loading"`

	// Category 工具分类,用于搜索过滤
	// 例如: "filesystem", "execution", "network", "mcp", "custom"
	Category string `json:"category,omitempty"`

	// Keywords 搜索关键词,用于 BM25 索引
	Keywords []string `json:"keywords,omitempty"`
}

DeferrableConfig 延迟加载配置 用于工具搜索工具的按需发现机制

type DeferrableTool added in v0.17.0

type DeferrableTool interface {
	Tool
	// DeferConfig 返回延迟加载配置
	DeferConfig() *DeferrableConfig
}

DeferrableTool 支持延迟加载的工具接口 实现此接口的工具可以被工具搜索工具按需发现和激活

type EnhancedContext

type EnhancedContext interface {
	Context // 继承基础接口

	// CallID 工具调用的唯一标识符
	CallID() string

	// AgentID 当前 Agent ID
	AgentID() string

	// SessionID 当前会话 ID
	SessionID() string

	// InvocationID 当前调用 ID
	InvocationID() string

	// State 访问会话状态
	State() session.State

	// Actions 获取事件动作
	Actions() *session.EventActions

	// SearchMemory 搜索 Agent 记忆
	SearchMemory(ctx context.Context, query string) ([]MemoryResult, error)

	// GetArtifact 获取 Artifact
	GetArtifact(ctx context.Context, name string) (any, error)

	// SaveArtifact 保存 Artifact
	SaveArtifact(ctx context.Context, name string, data any) error

	// EmitEvent 发送自定义事件
	EmitEvent(event *types.Event) error

	// Logger 获取日志记录器
	Logger() Logger

	// Tracer 获取追踪器
	Tracer() Tracer

	// Metrics 获取指标收集器
	Metrics() Metrics
}

EnhancedContext 增强的工具执行上下文 参考 Google ADK-Go 的 tool.Context 设计

type EnhancedTool

type EnhancedTool interface {
	Tool // 继承基础接口

	// IsLongRunning 是否为长时运行工具
	// 长时运行工具会先返回资源 ID,稍后完成操作
	IsLongRunning() bool

	// Timeout 工具执行超时时间
	// 返回 0 表示使用默认超时
	Timeout() time.Duration

	// RequiresApproval 是否需要人工审批
	RequiresApproval() bool

	// Priority 工具优先级 (用于并发控制)
	// 数值越大优先级越高
	Priority() int

	// RetryPolicy 重试策略
	RetryPolicy() *RetryPolicy

	// Metadata 工具元数据
	Metadata() map[string]any
}

EnhancedTool 增强的工具接口 参考 Google ADK-Go 的工具设计

type ExampleableTool added in v0.17.0

type ExampleableTool interface {
	Tool
	// Examples 返回工具使用示例列表
	// 建议提供 1-5 个示例,涵盖常见使用场景
	Examples() []ToolExample
}

ExampleableTool 支持使用示例的工具接口 实现此接口的工具可以提供使用示例,帮助 LLM 更准确地调用工具

type ExecuteRequest

type ExecuteRequest struct {
	Tool    Tool
	Input   map[string]any
	Context *ToolContext
	Timeout time.Duration
}

ExecuteRequest 执行请求

type ExecuteResult

type ExecuteResult struct {
	Success    bool
	Output     any
	Error      error
	DurationMs int64
	StartedAt  time.Time
	EndedAt    time.Time
}

ExecuteResult 执行结果

type Executor

type Executor struct {
	// contains filtered or unexported fields
}

Executor 工具执行器

func NewExecutor

func NewExecutor(config ExecutorConfig) *Executor

NewExecutor 创建工具执行器

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, req *ExecuteRequest) *ExecuteResult

Execute 执行单个工具

func (*Executor) ExecuteBatch

func (e *Executor) ExecuteBatch(ctx context.Context, requests []*ExecuteRequest) []*ExecuteResult

ExecuteBatch 批量执行工具

func (*Executor) Wait

func (e *Executor) Wait()

Wait 等待所有执行完成

type ExecutorConfig

type ExecutorConfig struct {
	MaxConcurrency int           // 最大并发数
	DefaultTimeout time.Duration // 默认超时时间
}

ExecutorConfig 执行器配置

type Field

type Field struct {
	Key   string
	Value any
}

Field 日志字段

type Interruptible added in v0.16.0

type Interruptible interface {
	Pause() error
	Resume() error
	Cancel() error
}

Interruptible 可中断/恢复的工具接口

type Logger

type Logger interface {
	Debug(msg string, fields ...Field)
	Info(msg string, fields ...Field)
	Warn(msg string, fields ...Field)
	Error(msg string, fields ...Field)
}

Logger 日志接口

type LongRunningExecutor

type LongRunningExecutor struct {
	// contains filtered or unexported fields
}

LongRunningExecutor 长时运行工具执行器 管理异步任务的生命周期

func NewLongRunningExecutor

func NewLongRunningExecutor() *LongRunningExecutor

NewLongRunningExecutor 创建长时运行工具执行器

func (*LongRunningExecutor) Cancel

func (e *LongRunningExecutor) Cancel(ctx context.Context, taskID string) error

Cancel 取消任务

func (*LongRunningExecutor) Cleanup

func (e *LongRunningExecutor) Cleanup(before time.Time) int

Cleanup 清理已完成的任务 清理指定时间之前完成的任务

func (*LongRunningExecutor) GetStatus

func (e *LongRunningExecutor) GetStatus(ctx context.Context, taskID string) (*TaskStatus, error)

GetStatus 获取任务状态

func (*LongRunningExecutor) ListTasks

func (e *LongRunningExecutor) ListTasks(filter func(*TaskStatus) bool) []*TaskStatus

ListTasks 列出所有任务

func (*LongRunningExecutor) StartAsync

func (e *LongRunningExecutor) StartAsync(
	ctx context.Context,
	tool Tool,
	args map[string]any,
) (string, error)

StartAsync 异步启动工具

func (*LongRunningExecutor) UpdateProgress

func (e *LongRunningExecutor) UpdateProgress(taskID string, progress float64, metadata map[string]any) error

UpdateProgress 更新任务进度(供工具内部调用)

type LongRunningTool

type LongRunningTool interface {
	Tool

	// IsLongRunning 标记为长时运行工具
	IsLongRunning() bool

	// StartAsync 异步启动工具执行
	// 返回任务 ID,可用于查询状态或取消
	StartAsync(ctx context.Context, args map[string]any) (string, error)

	// GetStatus 获取任务执行状态
	GetStatus(ctx context.Context, taskID string) (*TaskStatus, error)

	// Cancel 取消正在执行的任务
	Cancel(ctx context.Context, taskID string) error
}

LongRunningTool 长时运行工具接口 参考 Google ADK-Go 的长时运行工具设计

使用场景: - 文件上传/下载 - 数据库备份 - 机器学习训练 - 大数据处理

type MCPManagerInterface added in v0.31.0

type MCPManagerInterface interface {
	// ListServers 列出所有 MCP 服务器 ID
	ListServers() []string
	// GetServer 获取指定的 MCP 服务器
	GetServer(serverID string) (any, bool)
}

MCPManagerInterface MCP 管理器接口 用于工具访问 MCP 服务器和资源

type MemoryResult

type MemoryResult struct {
	Content   string
	Score     float64
	Timestamp time.Time
	Metadata  map[string]any
}

MemoryResult 记忆搜索结果

type Metrics

type Metrics interface {
	IncrementCounter(name string, value int64)
	RecordDuration(name string, duration time.Duration)
}

Metrics 指标接口 (简化版)

type NoConstraints added in v0.17.0

type NoConstraints struct{}

NoConstraints 无约束实现

func (*NoConstraints) GetAllowedTools added in v0.17.0

func (n *NoConstraints) GetAllowedTools(ctx context.Context) []string

func (*NoConstraints) GetConstraintType added in v0.17.0

func (n *NoConstraints) GetConstraintType() ConstraintType

func (*NoConstraints) IsAllowed added in v0.17.0

func (n *NoConstraints) IsAllowed(ctx context.Context, toolName string) bool

type Predicate

type Predicate func(ctx ReadonlyContext, tool Tool) bool

Predicate 工具过滤谓词 用于动态决定是否暴露某个工具给 LLM

func AndPredicate

func AndPredicate(predicates ...Predicate) Predicate

AndPredicate 组合多个谓词 (AND)

func NotPredicate

func NotPredicate(predicate Predicate) Predicate

NotPredicate 取反谓词

func OrPredicate

func OrPredicate(predicates ...Predicate) Predicate

OrPredicate 组合多个谓词 (OR)

func PrefixPredicate

func PrefixPredicate(prefix string) Predicate

PrefixPredicate 基于前缀的过滤器

func StringPredicate

func StringPredicate(allowedTools []string) Predicate

StringPredicate 基于工具名称的过滤器

type ReadonlyContext

type ReadonlyContext interface {
	AgentID() string
	SessionID() string
	State() session.ReadonlyState
}

ReadonlyContext 只读上下文

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry 工具注册表

func NewRegistry

func NewRegistry() *Registry

NewRegistry 创建工具注册表

func (*Registry) Create

func (r *Registry) Create(name string, config map[string]any) (Tool, error)

Create 创建工具实例

func (*Registry) Has

func (r *Registry) Has(name string) bool

Has 检查工具是否已注册

func (*Registry) List

func (r *Registry) List() []string

List 列出所有已注册的工具

func (*Registry) Register

func (r *Registry) Register(name string, factory ToolFactory)

Register 注册工具

type Reporter added in v0.16.0

type Reporter interface {
	Progress(progress float64, message string, step, total int, metadata map[string]any, etaMs int64)
	Intermediate(label string, data any)
}

Reporter 工具执行实时反馈接口

type RequiredToolConstraints added in v0.17.0

type RequiredToolConstraints struct {
	// contains filtered or unexported fields
}

RequiredToolConstraints 必需工具约束

func NewRequiredToolConstraints added in v0.17.0

func NewRequiredToolConstraints(toolName string) *RequiredToolConstraints

NewRequiredToolConstraints 创建必需工具约束

func (*RequiredToolConstraints) GetAllowedTools added in v0.17.0

func (r *RequiredToolConstraints) GetAllowedTools(ctx context.Context) []string

func (*RequiredToolConstraints) GetConstraintType added in v0.17.0

func (r *RequiredToolConstraints) GetConstraintType() ConstraintType

func (*RequiredToolConstraints) GetRequiredTool added in v0.17.0

func (r *RequiredToolConstraints) GetRequiredTool() string

func (*RequiredToolConstraints) IsAllowed added in v0.17.0

func (r *RequiredToolConstraints) IsAllowed(ctx context.Context, toolName string) bool

type RetryPolicy

type RetryPolicy struct {
	// MaxRetries 最大重试次数
	MaxRetries int

	// InitialBackoff 初始退避时间
	InitialBackoff time.Duration

	// MaxBackoff 最大退避时间
	MaxBackoff time.Duration

	// BackoffMultiplier 退避倍数
	BackoffMultiplier float64

	// RetryableErrors 可重试的错误类型
	RetryableErrors []string
}

RetryPolicy 重试策略

func DefaultRetryPolicy

func DefaultRetryPolicy() *RetryPolicy

DefaultRetryPolicy 默认重试策略

func NoRetryPolicy

func NoRetryPolicy() *RetryPolicy

NoRetryPolicy 不重试策略

type Span

type Span interface {
	End()
	SetAttribute(key string, value any)
	RecordError(err error)
}

Span 追踪 span 接口

type TaskState

type TaskState int

TaskState 任务状态枚举

const (
	TaskStatePending   TaskState = iota // 待执行
	TaskStateRunning                    // 执行中
	TaskStateCompleted                  // 已完成
	TaskStateFailed                     // 失败
	TaskStateCancelled                  // 已取消
)

func (TaskState) IsTerminal

func (s TaskState) IsTerminal() bool

IsTerminal 判断是否为终态

func (TaskState) String

func (s TaskState) String() string

String 返回状态的字符串表示

type TaskStatus

type TaskStatus struct {
	TaskID    string         // 任务 ID
	State     TaskState      // 当前状态
	Progress  float64        // 进度 0.0 - 1.0
	Result    any            // 执行结果(完成时)
	Error     error          // 错误信息(失败时)
	StartTime time.Time      // 开始时间
	EndTime   *time.Time     // 结束时间(完成/失败/取消时)
	Metadata  map[string]any // 额外元数据
}

TaskStatus 任务状态

func WaitForCompletion

func WaitForCompletion(executor *LongRunningExecutor, taskID string, pollInterval time.Duration, timeout time.Duration) (*TaskStatus, error)

WaitFor 等待任务完成(辅助函数)

type Tool

type Tool interface {
	// Name 工具名称
	Name() string

	// Description 工具描述
	Description() string

	// InputSchema JSON Schema定义
	InputSchema() map[string]any

	// Execute 执行工具
	Execute(ctx context.Context, input map[string]any, tc *ToolContext) (any, error)

	// Prompt 工具使用说明(可选)
	Prompt() string
}

Tool 工具接口

type ToolAnnotations added in v0.33.0

type ToolAnnotations struct {
	// ReadOnly 工具是否只读(不修改任何状态)
	// 只读工具在 SmartApprove 模式下可以自动批准
	ReadOnly bool `json:"read_only"`

	// Destructive 工具是否具有破坏性(可能导致数据丢失)
	// 破坏性工具在大多数模式下都需要用户确认
	Destructive bool `json:"destructive"`

	// Idempotent 工具是否幂等(多次执行结果相同)
	// 幂等工具更安全,可以重试
	Idempotent bool `json:"idempotent"`

	// OpenWorld 工具是否涉及外部系统(网络、第三方 API)
	// 涉及外部系统的工具即使只读也可能有安全风险
	OpenWorld bool `json:"open_world"`

	// RiskLevel 风险级别 (0-4)
	// 0: safe - 完全安全的只读操作
	// 1: low - 低风险,可逆操作
	// 2: medium - 中等风险,需要注意
	// 3: high - 高风险,可能导致数据丢失
	// 4: critical - 极高风险,可能导致不可逆损失
	RiskLevel int `json:"risk_level"`

	// Category 工具分类
	// 例如: "filesystem", "execution", "network", "database", "system"
	Category string `json:"category,omitempty"`

	// RequiresConfirmation 是否需要用户确认
	// 设为 true 时,无论权限模式如何都需要确认
	RequiresConfirmation bool `json:"requires_confirmation,omitempty"`
}

ToolAnnotations 工具安全注解 用于描述工具的安全特性,帮助权限系统做出智能决策

func GetAnnotations added in v0.33.0

func GetAnnotations(tool Tool) *ToolAnnotations

GetAnnotations 获取工具的安全注解 如果工具实现了 AnnotatedTool 接口,返回其注解 否则返回默认的中等风险注解

func (*ToolAnnotations) Clone added in v0.33.0

func (a *ToolAnnotations) Clone() *ToolAnnotations

Clone 克隆注解(用于修改)

func (*ToolAnnotations) IsSafeForAutoApproval added in v0.33.0

func (a *ToolAnnotations) IsSafeForAutoApproval() bool

IsSafeForAutoApproval 判断是否可以自动批准 在 SmartApprove 模式下,只读且不涉及外部系统的工具可以自动批准

func (*ToolAnnotations) RiskLevelName added in v0.33.0

func (a *ToolAnnotations) RiskLevelName() string

RiskLevelName 获取风险级别名称

func (*ToolAnnotations) WithCategory added in v0.33.0

func (a *ToolAnnotations) WithCategory(category string) *ToolAnnotations

WithCategory 设置分类(链式调用)

func (*ToolAnnotations) WithRequiresConfirmation added in v0.33.0

func (a *ToolAnnotations) WithRequiresConfirmation(requires bool) *ToolAnnotations

WithRequiresConfirmation 设置是否需要确认(链式调用)

func (*ToolAnnotations) WithRiskLevel added in v0.33.0

func (a *ToolAnnotations) WithRiskLevel(level int) *ToolAnnotations

WithRiskLevel 设置风险级别(链式调用)

type ToolCache added in v0.13.0

type ToolCache struct {
	// contains filtered or unexported fields
}

ToolCache 工具缓存

func NewToolCache added in v0.13.0

func NewToolCache(config *CacheConfig) *ToolCache

NewToolCache 创建工具缓存

func (*ToolCache) Clear added in v0.13.0

func (c *ToolCache) Clear() error

Clear 清空所有缓存

func (*ToolCache) Delete added in v0.13.0

func (c *ToolCache) Delete(key string) error

Delete 删除缓存

func (*ToolCache) GenerateKey added in v0.13.0

func (c *ToolCache) GenerateKey(toolName string, input map[string]any) string

GenerateKey 生成缓存键

func (*ToolCache) Get added in v0.13.0

func (c *ToolCache) Get(ctx context.Context, key string) (any, bool)

Get 获取缓存

func (*ToolCache) GetStats added in v0.13.0

func (c *ToolCache) GetStats() *CacheStats

GetStats 获取统计信息

func (*ToolCache) Set added in v0.13.0

func (c *ToolCache) Set(ctx context.Context, key string, value any, ttl time.Duration) error

Set 设置缓存

type ToolCallRecordBuilder

type ToolCallRecordBuilder struct {
	// contains filtered or unexported fields
}

ToolCallRecordBuilder 工具调用记录构建器

func NewToolCallRecord

func NewToolCallRecord(id, name string, input map[string]any) *ToolCallRecordBuilder

NewToolCallRecord 创建工具调用记录

func (*ToolCallRecordBuilder) Build

Build 构建记录

func (*ToolCallRecordBuilder) SetApproval

SetApproval 设置审批信息

func (*ToolCallRecordBuilder) SetResult

func (b *ToolCallRecordBuilder) SetResult(result any, err error) *ToolCallRecordBuilder

SetResult 设置结果

func (*ToolCallRecordBuilder) SetState

SetState 设置状态

func (*ToolCallRecordBuilder) SetTiming

func (b *ToolCallRecordBuilder) SetTiming(startedAt, completedAt time.Time) *ToolCallRecordBuilder

SetTiming 设置时间信息

type ToolChoice added in v0.17.0

type ToolChoice struct {
	// Type 选择类型: "auto", "any", "tool"
	Type string `json:"type"`

	// Name 当 Type="tool" 时,指定工具名称
	Name string `json:"name,omitempty"`

	// DisableParallelToolUse 禁用并行工具调用
	DisableParallelToolUse bool `json:"disable_parallel_tool_use,omitempty"`
}

ToolChoice 工具选择策略 对应 Anthropic API 的 tool_choice 参数

func ToolChoiceRequired added in v0.17.0

func ToolChoiceRequired(toolName string) *ToolChoice

ToolChoiceRequired 必须使用指定工具

func (*ToolChoice) ToConstraints added in v0.17.0

func (tc *ToolChoice) ToConstraints() ToolConstraints

ToConstraints 将 ToolChoice 转换为 ToolConstraints

type ToolConfig added in v0.12.1

type ToolConfig struct {
	Name       string         `json:"name"`
	RegistryID string         `json:"registry_id,omitempty"`
	Config     map[string]any `json:"config,omitempty"`
}

ToolConfig 工具配置(用于持久化)

type ToolConstraints added in v0.17.0

type ToolConstraints interface {
	// IsAllowed 检查工具是否被允许使用
	IsAllowed(ctx context.Context, toolName string) bool

	// GetAllowedTools 获取所有允许的工具名称
	GetAllowedTools(ctx context.Context) []string

	// GetConstraintType 获取约束类型
	GetConstraintType() ConstraintType
}

ToolConstraints 工具约束接口 用于控制在特定上下文中哪些工具可用 这是 Manus 团队"工具状态机"理念的实现

type ToolContext

type ToolContext struct {
	AgentID    string
	Sandbox    sandbox.Sandbox
	Signal     context.Context
	Reporter   Reporter
	Emit       func(eventType string, data any) // Deprecated: use Reporter
	Services   map[string]any
	ThreadID   string              // Working Memory 会话 ID
	ResourceID string              // Working Memory 资源 ID
	MCPManager MCPManagerInterface // MCP 管理器,用于访问 MCP 资源
}

ToolContext 工具执行上下文

type ToolExample added in v0.17.0

type ToolExample struct {
	// Description 示例描述,说明这个示例演示的场景
	Description string `json:"description"`

	// Input 示例输入参数
	Input map[string]any `json:"input"`

	// Output 可选的预期输出,用于展示工具返回格式
	Output any `json:"output,omitempty"`
}

ToolExample 工具使用示例 用于向 LLM 展示工具的正确使用方式,提升复杂参数处理的准确率

type ToolFactory

type ToolFactory func(config map[string]any) (Tool, error)

ToolFactory 工具工厂函数

type ToolNotFoundError

type ToolNotFoundError struct {
	Name string
}

ToolNotFoundError 工具未找到错误

func (*ToolNotFoundError) Error

func (e *ToolNotFoundError) Error() string

type ToolSelector added in v0.17.0

type ToolSelector interface {
	// SelectTools 根据上下文选择工具
	SelectTools(ctx context.Context, allTools []Tool, constraints ToolConstraints) ([]Tool, error)

	// ShouldUseToolChoice 判断是否应该使用 tool_choice
	ShouldUseToolChoice(ctx context.Context, constraints ToolConstraints) (*ToolChoice, bool)
}

ToolSelector 工具选择器接口 用于根据上下文动态选择可用工具

type Toolset

type Toolset interface {
	// Name 工具集名称
	Name() string

	// Description 工具集描述
	Description() string

	// Tools 返回工具列表
	// 可以根据上下文动态决定返回哪些工具
	Tools(ctx ReadonlyContext) ([]Tool, error)

	// Initialize 初始化工具集
	Initialize(ctx context.Context) error

	// Cleanup 清理工具集资源
	Cleanup(ctx context.Context) error
}

Toolset 工具集接口 参考 Google ADK-Go 的 Toolset 设计

type Tracer

type Tracer interface {
	StartSpan(ctx context.Context, name string) (context.Context, Span)
}

Tracer 追踪接口 (简化版)

type WhitelistConstraints added in v0.17.0

type WhitelistConstraints struct {
	// contains filtered or unexported fields
}

WhitelistConstraints 白名单约束

func NewWhitelistConstraints added in v0.17.0

func NewWhitelistConstraints(tools []string) *WhitelistConstraints

NewWhitelistConstraints 创建白名单约束

func (*WhitelistConstraints) GetAllowedTools added in v0.17.0

func (w *WhitelistConstraints) GetAllowedTools(ctx context.Context) []string

func (*WhitelistConstraints) GetConstraintType added in v0.17.0

func (w *WhitelistConstraints) GetConstraintType() ConstraintType

func (*WhitelistConstraints) IsAllowed added in v0.17.0

func (w *WhitelistConstraints) IsAllowed(ctx context.Context, toolName string) bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL