tools

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2025 License: Apache-2.0 Imports: 21 Imported by: 0

README

Tools System

完整的工具系统实现,借鉴 LangChain 的 Tool 设计理念。

概述

Tools 系统提供了一个统一的接口来定义、管理和执行各种工具。每个工具都是一个 Runnable,支持同步/异步执行、流式处理、批量执行和回调集成。

核心概念

Tool 接口

所有工具都实现 Tool 接口:

type Tool interface {
    Runnable[*ToolInput, *ToolOutput]

    Name() string
    Description() string
    ArgsSchema() string  // JSON Schema for arguments
}
工具输入输出
type ToolInput struct {
    Args     map[string]interface{} // 参数映射
    Context  context.Context        // 上下文
    CallerID string                 // 调用者 ID
    TraceID  string                 // 追踪 ID
}

type ToolOutput struct {
    Result   interface{}            // 结果数据
    Success  bool                   // 是否成功
    Error    string                 // 错误信息
    Metadata map[string]interface{} // 元数据
}

内置工具

1. BaseTool

基础工具实现,可以包装任意函数:

tool := tools.NewBaseTool(
    "hello",
    "Says hello to a name",
    `{"type": "object", "properties": {"name": {"type": "string"}}}`,
    func(ctx context.Context, input *tools.ToolInput) (*tools.ToolOutput, error) {
        name, _ := input.Args["name"].(string)
        return &tools.ToolOutput{
            Result:  fmt.Sprintf("Hello, %s!", name),
            Success: true,
        }, nil
    },
)
2. FunctionTool

函数包装工具,提供更灵活的创建方式:

// 基础用法
tool := tools.NewFunctionTool(
    "calculator",
    "Performs calculations",
    `{...}`,
    func(ctx context.Context, args map[string]interface{}) (interface{}, error) {
        // 实现逻辑
        return result, nil
    },
)

// 使用构建器
tool := tools.NewFunctionToolBuilder("multiplier").
    WithDescription("Multiplies two numbers").
    WithArgsSchema(`{...}`).
    WithFunction(func(ctx context.Context, args map[string]interface{}) (interface{}, error) {
        a := args["a"].(float64)
        b := args["b"].(float64)
        return a * b, nil
    }).
    Build()

// 简单函数工具
tool := tools.NewSimpleFunctionTool(
    "get_time",
    "Gets current time",
    func(ctx context.Context) (interface{}, error) {
        return time.Now().String(), nil
    },
)

// 类型安全工具
type CalculatorInput struct {
    Operation string  `json:"operation"`
    A         float64 `json:"a"`
    B         float64 `json:"b"`
}

tool := tools.NewTypedFunctionTool[CalculatorInput, float64](
    "calculator",
    "Performs calculations",
    `{...}`,
    func(ctx context.Context, input CalculatorInput) (float64, error) {
        // 类型安全的实现
        return result, nil
    },
)
3. CalculatorTool

数学计算工具:

tool := tools.NewCalculatorTool()

output, _ := tool.Invoke(ctx, &tools.ToolInput{
    Args: map[string]interface{}{
        "expression": "2 + 3 * 4",
    },
})

// 支持的表达式:
// - 基本运算: +, -, *, /
// - 幂运算: ^
// - 括号: ()
// - 示例: "2 + 3", "(2 + 3) * 4", "2^8"

高级计算器工具:

tool := tools.NewAdvancedCalculatorTool(tools.CalculatorOperations{
    Add:      true,
    Subtract: true,
    Multiply: true,
    Divide:   true,
    Power:    true,
    Sqrt:     true,
    Abs:      true,
})

output, _ := tool.Invoke(ctx, &tools.ToolInput{
    Args: map[string]interface{}{
        "operation": "sqrt",
        "operands":  []interface{}{16.0},
    },
})
4. SearchTool

搜索工具,支持多种搜索引擎:

// 使用模拟搜索引擎
engine := tools.NewMockSearchEngine()
tool := tools.NewSearchTool(engine)

// 使用 Google 搜索
engine := tools.NewGoogleSearchEngine(apiKey, cx)
tool := tools.NewSearchTool(engine)

// 使用聚合搜索引擎
engine := tools.NewAggregatedSearchEngine(
    tools.NewGoogleSearchEngine(apiKey, cx),
    tools.NewDuckDuckGoSearchEngine(),
)
tool := tools.NewSearchTool(engine)

// 执行搜索
output, _ := tool.Invoke(ctx, &tools.ToolInput{
    Args: map[string]interface{}{
        "query":       "Go programming",
        "max_results": 5.0,
    },
})
5. ShellTool

安全的 Shell 命令执行工具:

// 使用构建器
tool := tools.NewShellToolBuilder().
    WithAllowedCommands("ls", "pwd", "echo", "cat").
    WithTimeout(30 * time.Second).
    Build()

// 执行命令
output, _ := tool.Invoke(ctx, &tools.ToolInput{
    Args: map[string]interface{}{
        "command": "echo",
        "args":    []interface{}{"Hello, World!"},
        "work_dir": "/tmp",
        "timeout": 10,
    },
})

// 便捷方法
output, _ := tool.ExecuteScript(ctx, "/path/to/script.sh", []string{"arg1", "arg2"})
output, _ := tool.ExecutePipeline(ctx, []string{"ls -la", "grep test"})
6. APITool

HTTP API 调用工具:

// 使用构建器
tool := tools.NewAPIToolBuilder().
    WithBaseURL("https://api.example.com").
    WithTimeout(30 * time.Second).
    WithHeader("Content-Type", "application/json").
    WithAuth("your-token").
    Build()

// 执行请求
output, _ := tool.Invoke(ctx, &tools.ToolInput{
    Args: map[string]interface{}{
        "method": "POST",
        "url":    "/api/users",
        "body": map[string]interface{}{
            "name": "John Doe",
            "email": "john@example.com",
        },
        "headers": map[string]string{
            "X-Custom-Header": "value",
        },
    },
})

// 便捷方法
output, _ := tool.Get(ctx, "/api/users", headers)
output, _ := tool.Post(ctx, "/api/users", body, headers)
output, _ := tool.Put(ctx, "/api/users/1", body, headers)
output, _ := tool.Delete(ctx, "/api/users/1", headers)
output, _ := tool.Patch(ctx, "/api/users/1", body, headers)

工具集 (Toolkit)

创建工具集
// 标准工具集
toolkit := tools.NewStandardToolkit()

// 开发工具集
toolkit := tools.NewDevelopmentToolkit()

// 自定义工具集
toolkit := tools.NewBaseToolkit(
    tools.NewCalculatorTool(),
    tools.NewSearchTool(engine),
    tools.NewShellTool(commands, timeout),
)

// 使用构建器
toolkit := tools.NewToolkitBuilder().
    WithCalculator().
    WithSearch(engine).
    WithShell(allowedCommands).
    WithAPI(baseURL, headers).
    AddTool(customTool).
    Build()
使用工具集
// 获取所有工具
tools := toolkit.GetTools()

// 获取工具名称
names := toolkit.GetToolNames()

// 根据名称获取工具
tool, err := toolkit.GetToolByName("calculator")

// 执行工具
output, err := tool.Invoke(ctx, input)

工具注册表

全局工具注册和发现:

// 创建注册表
registry := tools.NewToolRegistry()

// 注册工具
_ = registry.Register(tools.NewCalculatorTool())
_ = registry.Register(customTool)

// 获取工具
tool, _ := registry.Get("calculator")

// 列出所有工具
allTools := registry.List()

// 从注册表创建工具集
toolkit, _ := registry.CreateToolkit("calculator", "search")

// 使用全局注册表
tools.RegisterTool(myTool)
tool, _ := tools.GetTool("myTool")
allTools := tools.ListTools()

工具执行器

高级工具执行功能:

executor := tools.NewToolExecutor(toolkit)

// 执行单个工具
output, err := executor.Execute(ctx, "calculator", input)

// 顺序执行多个工具
executor.WithParallel(false)
results, err := executor.ExecuteMultiple(ctx, map[string]*tools.ToolInput{
    "calculator": calcInput,
    "search": searchInput,
})

// 并行执行多个工具
executor.WithParallel(true)
results, err := executor.ExecuteMultiple(ctx, requests)

回调集成

工具支持完整的回调系统:

// 创建回调
callback := &MyCallback{
    BaseCallback: agentcore.NewBaseCallback(),
}

func (c *MyCallback) OnToolStart(ctx context.Context, toolName string, input interface{}) error {
    fmt.Printf("Tool '%s' started\n", toolName)
    return nil
}

func (c *MyCallback) OnToolEnd(ctx context.Context, toolName string, output interface{}) error {
    fmt.Printf("Tool '%s' completed\n", toolName)
    return nil
}

// 为工具添加回调
toolWithCallback := tool.WithCallbacks(callback).(tools.Tool)

// 执行会触发回调
output, _ := toolWithCallback.Invoke(ctx, input)

Runnable 特性

所有工具都是 Runnable,支持:

1. 单个执行
output, err := tool.Invoke(ctx, input)
2. 流式执行
stream, err := tool.Stream(ctx, input)
for chunk := range stream {
    if chunk.Error != nil {
        // 处理错误
    }
    // 处理数据
}
3. 批量执行
inputs := []*tools.ToolInput{input1, input2, input3}
outputs, err := tool.Batch(ctx, inputs)
4. 管道连接
// 连接工具形成管道
pipeline := tool1.Pipe(tool2).Pipe(tool3)
output, err := pipeline.Invoke(ctx, input)
5. 配置
config := agentcore.RunnableConfig{
    MaxConcurrency: 10,
    RetryPolicy: &agentcore.RetryPolicy{
        MaxRetries: 3,
    },
}

toolWithConfig := tool.WithConfig(config)

最佳实践

1. 安全性
  • Shell 工具始终使用白名单
  • API 工具验证输入
  • 设置合理的超时时间
// 好的做法
tool := tools.NewShellTool([]string{"ls", "cat", "grep"}, 30*time.Second)

// 不好的做法 - 不要允许所有命令
tool := tools.NewShellTool([]string{"bash", "sh"}, 0)
2. 错误处理

始终检查工具执行结果:

output, err := tool.Invoke(ctx, input)
if err != nil {
    // 处理执行错误
    return err
}

if !output.Success {
    // 处理业务错误
    log.Printf("Tool failed: %s", output.Error)
}
3. 使用构建器

使用构建器创建复杂工具:

tool := tools.NewAPIToolBuilder().
    WithBaseURL("https://api.example.com").
    WithTimeout(30 * time.Second).
    WithAuth(token).
    Build()
4. 工具组合

使用工具集和执行器组合多个工具:

toolkit := tools.NewToolkitBuilder().
    WithCalculator().
    WithSearch(engine).
    WithAPI(baseURL, nil).
    Build()

executor := tools.NewToolExecutor(toolkit).
    WithParallel(true)
5. 监控和日志

使用回调进行监控:

metricsCallback := &MetricsCallback{}
loggingCallback := &LoggingCallback{}

tool := tool.WithCallbacks(metricsCallback, loggingCallback)

示例

完整示例见 examples/tools/main.go

# 运行示例
go run examples/tools/main.go

测试

运行测试:

# 运行所有测试
go test -v ./tools/

# 运行性能测试
go test -bench=. ./tools/

# 查看覆盖率
go test -cover ./tools/

扩展

创建自定义工具
type MyCustomTool struct {
    *tools.BaseTool
    config MyConfig
}

func NewMyCustomTool(config MyConfig) *MyCustomTool {
    tool := &MyCustomTool{
        config: config,
    }

    tool.BaseTool = tools.NewBaseTool(
        "my_tool",
        "My custom tool description",
        `{"type": "object", "properties": {...}}`,
        tool.run,
    )

    return tool
}

func (m *MyCustomTool) run(ctx context.Context, input *tools.ToolInput) (*tools.ToolOutput, error) {
    // 实现工具逻辑
    return &tools.ToolOutput{
        Result:  result,
        Success: true,
    }, nil
}
创建自定义搜索引擎
type MySearchEngine struct{}

func (m *MySearchEngine) Search(ctx context.Context, query string, maxResults int) ([]tools.SearchResult, error) {
    // 实现搜索逻辑
    return results, nil
}

// 使用自定义搜索引擎
engine := &MySearchEngine{}
tool := tools.NewSearchTool(engine)

架构设计

Tool (Interface)
    ├── Runnable[*ToolInput, *ToolOutput]
    ├── Name() string
    ├── Description() string
    └── ArgsSchema() string

BaseTool
    ├── BaseRunnable
    ├── name, description, argsSchema
    └── runFunc

具体工具
    ├── FunctionTool
    ├── CalculatorTool
    ├── SearchTool
    ├── ShellTool
    └── APITool

工具集
    ├── Toolkit (Interface)
    ├── BaseToolkit
    ├── StandardToolkit
    └── DevelopmentToolkit

工具注册表
    └── ToolRegistry

工具执行器
    └── ToolExecutor

性能考虑

  1. 并发执行: 使用 ToolExecutor.WithParallel(true) 并行执行多个工具
  2. 批量处理: 使用 Batch() 方法批量处理多个输入
  3. 资源池: Shell 和 API 工具内部使用连接池
  4. 缓存: 考虑为搜索结果等添加缓存层

总结

Tools 系统提供了:

  • 统一的工具接口和实现
  • 丰富的内置工具(计算器、搜索、Shell、API)
  • 灵活的工具组合和管理(Toolkit、Registry)
  • 完整的 Runnable 特性支持
  • 强大的回调和监控能力
  • 类型安全和易用的 API

通过这个系统,你可以轻松创建、组合和执行各种工具,构建强大的 AI Agent 应用。

Documentation

Index

Constants

View Source
const (
	// Compute tools
	ToolCalculator = "calculator"

	// HTTP tools
	ToolAPI = "api"

	// Search tools
	ToolSearch = "search"

	// Shell tools
	ToolShell = "shell"

	// Practical tools
	ToolFileOperations = "file_operations"
	ToolDatabaseQuery  = "database_query"
	ToolWebScraper     = "web_scraper"
	ToolAPICaller      = "api_caller"
)

Tool names

View Source
const (
	// Compute tools
	DescCalculator = "计算器工具,支持基本数学运算(加减乘除、幂运算、括号)"

	// HTTP tools
	DescAPI = "HTTP API 调用工具,支持 GET、POST、PUT、DELETE、PATCH 等方法"

	// Search tools
	DescSearch = "搜索工具,提供网络搜索功能"

	// Shell tools
	DescShell = "Shell 命令执行工具,安全地执行白名单中的系统命令"

	// Practical tools
	DescFileOperations = "文件操作工具,支持读取、写入、删除文件"
	DescDatabaseQuery  = "数据库查询工具,支持执行 SQL 查询"
	DescWebScraper     = "网页抓取工具,提取网页内容和结构化数据"
	DescAPICaller      = "API 调用工具,简化 RESTful API 调用流程"
)

Tool descriptions

View Source
const (
	ErrToolNotFound      = "tool not found"
	ErrInvalidInput      = "invalid tool input"
	ErrExecutionFailed   = "tool execution failed"
	ErrTimeout           = "tool execution timeout"
	ErrUnauthorized      = "tool execution unauthorized"
	ErrToolAlreadyExists = "tool already exists"
)

Tool error messages

View Source
const (
	DefaultToolTimeout     = 30 // seconds
	MaxConcurrentToolCalls = 10
	MaxRetries             = 3
)

Tool execution constants

Variables

View Source
var (
	ErrKeyNotFound       = errors.New("key not found")
	ErrValueNotFound     = errors.New("value not found")
	ErrStateAccessDenied = errors.New("state access is disabled")
	ErrStoreAccessDenied = errors.New("store access is disabled")
)

Sentinel errors

Functions

func BenchmarkCompareShardedVsNormal

func BenchmarkCompareShardedVsNormal()

BenchmarkCompareShardedVsNormal 基准测试对比分片缓存和普通缓存

func ExampleCacheOperations

func ExampleCacheOperations()

ExampleCacheOperations 展示基本缓存操作

func ExampleDynamicConfiguration

func ExampleDynamicConfiguration()

ExampleDynamicConfiguration 展示如何根据系统资源动态配置

func ExampleMonitoringAndTuning

func ExampleMonitoringAndTuning()

ExampleMonitoringAndTuning 展示监控和调优

func ExampleShardedCacheUsage

func ExampleShardedCacheUsage()

ExampleShardedCacheUsage 展示如何使用分片缓存的选项模式

func ValidateAndInvoke added in v0.5.0

func ValidateAndInvoke(ctx context.Context, tool interfaces.Tool, input *interfaces.ToolInput) (*interfaces.ToolOutput, error)

ValidateAndInvoke 验证后执行工具(便捷方法)

func ValidateInputWithSchema added in v0.5.0

func ValidateInputWithSchema(schema *core.ToolSchema, input map[string]interface{}, strict bool) error

ValidateInputWithSchema 使用 MCP ToolSchema 验证输入参数

验证步骤: 1. 检查必需字段 2. 验证每个输入字段的类型和约束 3. 在非 AdditionalProperties 模式下验证未定义字段

func ValidateToolSchema added in v0.5.0

func ValidateToolSchema(schema *core.ToolSchema) error

ValidateToolSchema 验证 MCP ToolSchema 定义本身

验证内容: 1. Type 必须是 "object" 2. Required 字段必须在 Properties 中定义 3. 每个属性的类型必须有效 4. 数组类型必须定义 Items 5. 数值/字符串约束必须合理(最小值 <= 最大值)

func WithMiddleware added in v0.2.0

func WithMiddleware(tool interfaces.Tool, middlewares ...interface{}) interfaces.Tool

WithMiddleware 为工具应用中间件

支持两种中间件类型:

  • ToolMiddleware: 基于接口的中间件(旧接口,已废弃)
  • ToolMiddlewareFunc: 基于函数的中间件(推荐)

参数:

  • tool: 要包装的工具
  • middlewares: 中间件列表,按顺序应用

返回:

  • interfaces.Tool: 包装后的工具

使用示例:

// 使用函数式中间件(推荐)
wrappedTool := WithMiddleware(tool,
    middleware.Logging(),
    middleware.Caching(),
)

// 使用接口式中间件(旧接口)
wrappedTool := WithMiddleware(tool,
    middleware.NewLoggingMiddleware(),
    middleware.NewCachingMiddleware(),
)

Types

type BaseRuntimeTool

type BaseRuntimeTool struct {
	*BaseTool
	// contains filtered or unexported fields
}

BaseRuntimeTool provides a base implementation for runtime tools

func (*BaseRuntimeTool) GetRuntime

func (t *BaseRuntimeTool) GetRuntime() *ToolRuntime

GetRuntime returns the current runtime

func (*BaseRuntimeTool) SetRuntime

func (t *BaseRuntimeTool) SetRuntime(runtime *ToolRuntime)

SetRuntime sets the runtime for the tool

type BaseTool

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

BaseTool 提供 Tool 的基础实现

实现了 interfaces.Tool 接口的通用功能 具体的执行逻辑通过 RunFunc 函数提供

func NewBaseTool

func NewBaseTool(
	name string,
	description string,
	argsSchema string,
	runFunc func(context.Context, *interfaces.ToolInput) (*interfaces.ToolOutput, error),
) *BaseTool

NewBaseTool 创建基础工具

func (*BaseTool) ArgsSchema

func (t *BaseTool) ArgsSchema() string

ArgsSchema 返回参数 JSON Schema

func (*BaseTool) Description

func (t *BaseTool) Description() string

Description 返回工具描述

func (*BaseTool) Invoke

Invoke 执行工具

func (*BaseTool) Name

func (t *BaseTool) Name() string

Name 返回工具名称

type CacheStats

type CacheStats struct {
	Hits          atomic.Int64
	Misses        atomic.Int64
	Evicts        atomic.Int64
	Invalidations atomic.Int64 // 失效次数
}

CacheStats 缓存统计信息

func (*CacheStats) HitRate

func (s *CacheStats) HitRate() float64

HitRate 计算命中率

type CachedTool

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

CachedTool 带缓存的工具包装器 (保持不变,使用SimpleToolCache)

func NewCachedTool

func NewCachedTool(tool interfaces.Tool, ttl time.Duration) *CachedTool

NewCachedTool 创建带缓存的工具

func (*CachedTool) ArgsSchema

func (c *CachedTool) ArgsSchema() string

ArgsSchema 返回参数 Schema

func (*CachedTool) Description

func (c *CachedTool) Description() string

Description 返回工具描述

func (*CachedTool) Invoke

Invoke 执行工具 (带缓存)

func (*CachedTool) Name

func (c *CachedTool) Name() string

Name 返回工具名称

type CleanupIntervalRecommendation

type CleanupIntervalRecommendation struct {
	CacheSize           int           // Total cache capacity
	TTL                 time.Duration // Default TTL
	ExpectedChurn       float64       // Expected percentage of entries changing per minute
	RecommendedInterval time.Duration
	Rationale           string
}

CleanupIntervalRecommendation provides cleanup interval recommendations

func GetCleanupIntervalRecommendation

func GetCleanupIntervalRecommendation(cacheSize int, ttl time.Duration, churnRate float64) CleanupIntervalRecommendation

GetCleanupIntervalRecommendation returns recommended cleanup interval

type CleanupStrategy

type CleanupStrategy int

CleanupStrategy defines cleanup strategies

const (
	// PeriodicCleanup performs cleanup at fixed intervals
	PeriodicCleanup CleanupStrategy = iota
	// LazyCleanup performs cleanup only on access
	LazyCleanup
	// AdaptiveCleanup adjusts cleanup frequency based on load
	AdaptiveCleanup
	// HybridCleanup combines periodic and lazy cleanup
	HybridCleanup
)

type ErrorHandler

type ErrorHandler func(call *ToolCall, err error) error

ErrorHandler 错误处理器

type EvictionPolicy

type EvictionPolicy int

EvictionPolicy defines cache eviction strategies

const (
	// LRUEviction evicts least recently used items
	LRUEviction EvictionPolicy = iota
	// LFUEviction evicts least frequently used items
	LFUEviction
	// FIFOEviction evicts oldest items first
	FIFOEviction
	// RandomEviction evicts random items
	RandomEviction
)

type ExecutorOption

type ExecutorOption func(*ToolExecutor)

ExecutorOption 执行器选项

func WithErrorHandler

func WithErrorHandler(handler ErrorHandler) ExecutorOption

WithErrorHandler 设置错误处理器

func WithMaxConcurrency

func WithMaxConcurrency(max int) ExecutorOption

WithMaxConcurrency 设置最大并发数

func WithRetryPolicy

func WithRetryPolicy(policy *RetryPolicy) ExecutorOption

WithRetryPolicy 设置重试策略

func WithTimeout

func WithTimeout(timeout time.Duration) ExecutorOption

WithTimeout 设置超时时间

type FunctionTool

type FunctionTool struct {
	*BaseTool
	// contains filtered or unexported fields
}

FunctionTool 函数包装工具

将普通 Go 函数包装成工具 支持自动参数转换和结果包装

func NewFunctionTool

func NewFunctionTool(
	name string,
	description string,
	argsSchema string,
	fn func(context.Context, map[string]interface{}) (interface{}, error),
) *FunctionTool

NewFunctionTool 创建函数工具

Parameters:

  • name: 工具名称
  • description: 工具描述
  • argsSchema: 参数 JSON Schema
  • fn: 执行函数

func NewSimpleFunctionTool

func NewSimpleFunctionTool(
	name string,
	description string,
	fn SimpleFunction,
) *FunctionTool

NewSimpleFunctionTool 创建简单函数工具

用于快速包装无参数或简单参数的函数

func NewTypedFunctionTool

func NewTypedFunctionTool[I, O any](
	name string,
	description string,
	argsSchema string,
	fn TypedFunction[I, O],
) *FunctionTool

NewTypedFunctionTool 创建类型安全的函数工具

使用泛型提供编译时类型检查

type FunctionToolBuilder

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

FunctionToolBuilder 函数工具构建器

提供更灵活的函数工具创建方式

func NewFunctionToolBuilder

func NewFunctionToolBuilder(name string) *FunctionToolBuilder

NewFunctionToolBuilder 创建函数工具构建器

func (*FunctionToolBuilder) Build

func (b *FunctionToolBuilder) Build() (*FunctionTool, error)

Build 构建工具

Returns an error if the function is not set. This replaces the previous panic behavior with proper error handling.

func (*FunctionToolBuilder) MustBuild

func (b *FunctionToolBuilder) MustBuild() *FunctionTool

MustBuild 构建工具,如果失败则 panic

用于初始化时确定配置正确的场景。 对于运行时构建,应使用 Build() 方法并处理错误。

func (*FunctionToolBuilder) WithArgsSchema

func (b *FunctionToolBuilder) WithArgsSchema(schema string) *FunctionToolBuilder

WithArgsSchema 设置参数 Schema

func (*FunctionToolBuilder) WithArgsSchemaFromStruct

func (b *FunctionToolBuilder) WithArgsSchemaFromStruct(v interface{}) *FunctionToolBuilder

WithArgsSchemaFromStruct 从结构体生成参数 Schema

func (*FunctionToolBuilder) WithDescription

func (b *FunctionToolBuilder) WithDescription(description string) *FunctionToolBuilder

WithDescription 设置描述

func (*FunctionToolBuilder) WithFunction

func (b *FunctionToolBuilder) WithFunction(
	fn func(context.Context, map[string]interface{}) (interface{}, error),
) *FunctionToolBuilder

WithFunction 设置执行函数

type InputValidator added in v0.5.0

type InputValidator struct {
	// StrictMode 严格模式,不允许额外的未定义参数
	StrictMode bool

	// ValidateTypes 是否验证参数类型
	ValidateTypes bool

	// ValidateRequired 是否验证必需参数
	ValidateRequired bool
}

InputValidator 提供工具输入验证功能

func NewInputValidator added in v0.5.0

func NewInputValidator() *InputValidator

NewInputValidator 创建默认配置的验证器

func NewStrictInputValidator added in v0.5.0

func NewStrictInputValidator() *InputValidator

NewStrictInputValidator 创建严格模式的验证器

func (*InputValidator) Validate added in v0.5.0

func (v *InputValidator) Validate(ctx context.Context, tool interfaces.Tool, input *interfaces.ToolInput) error

Validate 验证工具输入

验证步骤: 1. 如果工具实现了 ValidatableTool 接口,调用其 Validate 方法 2. 解析工具的 JSON Schema 3. 验证必需参数 4. 验证参数类型 5. 在严格模式下验证是否有未定义的参数

type LoadBalancingStrategy

type LoadBalancingStrategy int

LoadBalancingStrategy defines how keys are distributed across shards

const (
	// HashBasedBalancing uses hash function for distribution
	HashBasedBalancing LoadBalancingStrategy = iota
	// ConsistentHashBalancing uses consistent hashing
	ConsistentHashBalancing
	// RoundRobinBalancing distributes evenly in round-robin fashion
	RoundRobinBalancing
	// LeastLoadedBalancing routes to least loaded shard
	LeastLoadedBalancing
)

type MemoryCacheConfig

type MemoryCacheConfig struct {
	// Capacity 最大容量(条目数)
	Capacity int

	// DefaultTTL 默认 TTL
	DefaultTTL time.Duration

	// CleanupInterval 清理间隔
	CleanupInterval time.Duration
}

MemoryCacheConfig 内存缓存配置

type MemoryToolCache

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

MemoryToolCache 内存工具缓存

基于 LRU (Least Recently Used) 策略的内存缓存实现

func NewMemoryToolCache

func NewMemoryToolCache(config MemoryCacheConfig) *MemoryToolCache

NewMemoryToolCache 创建内存工具缓存

使用 context 进行生命周期管理,确保清理 goroutine 可以优雅关闭

func (*MemoryToolCache) AddDependency

func (c *MemoryToolCache) AddDependency(dependentTool, dependsOnTool string)

AddDependency 添加工具依赖关系

声明 dependentTool 依赖 dependsOnTool。 当 dependsOnTool 的缓存失效时,dependentTool 的缓存也会自动失效。

func (*MemoryToolCache) Clear

func (c *MemoryToolCache) Clear() error

Clear 清空所有缓存

func (*MemoryToolCache) Close

func (c *MemoryToolCache) Close()

Close 关闭缓存,清理资源

使用 context cancellation 优雅关闭清理 goroutine。 使用 atomic 操作确保 Close 的幂等性(多次调用是安全的)。

func (*MemoryToolCache) Delete

func (c *MemoryToolCache) Delete(ctx context.Context, key string) error

Delete 删除缓存

func (*MemoryToolCache) Get

Get 获取缓存结果

func (*MemoryToolCache) GetStats

func (c *MemoryToolCache) GetStats() CacheStats

GetStats 获取统计信息

func (*MemoryToolCache) GetVersion

func (c *MemoryToolCache) GetVersion() int64

GetVersion 获取当前缓存版本号

func (*MemoryToolCache) InvalidateByPattern

func (c *MemoryToolCache) InvalidateByPattern(ctx context.Context, pattern string) (int, error)

InvalidateByPattern 根据正则表达式模式失效缓存

支持正则表达式模式匹配缓存键。返回失效的条目数量。 只删除匹配的条目,不影响其他缓存项。

func (*MemoryToolCache) InvalidateByTool

func (c *MemoryToolCache) InvalidateByTool(ctx context.Context, toolName string) (int, error)

InvalidateByTool 根据工具名称失效缓存

失效指定工具的所有缓存条目,并级联失效依赖该工具的其他工具。 只删除相关的条目,不影响其他缓存项。 返回失效的条目数量。

func (*MemoryToolCache) RemoveDependency

func (c *MemoryToolCache) RemoveDependency(dependentTool, dependsOnTool string)

RemoveDependency 移除工具依赖关系

func (*MemoryToolCache) Set

func (c *MemoryToolCache) Set(ctx context.Context, key string, output *interfaces.ToolOutput, ttl time.Duration) error

Set 设置缓存结果

func (*MemoryToolCache) Size

func (c *MemoryToolCache) Size() int

Size 返回缓存大小

type MiddlewareTool added in v0.2.0

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

MiddlewareTool wraps a tool with middleware support.

It implements the Tool interface and applies middleware to tool invocations. This allows adding cross-cutting concerns like logging, caching, and rate limiting.

使用示例:

tool := NewCalculatorTool()
wrappedTool := tools.WithMiddleware(tool,
    middleware.Logging(),
    middleware.Caching(middleware.WithTTL(5*time.Minute)),
    middleware.RateLimit(middleware.WithQPS(10)),
)

func (*MiddlewareTool) ArgsSchema added in v0.2.0

func (w *MiddlewareTool) ArgsSchema() string

ArgsSchema 返回参数模式

func (*MiddlewareTool) Description added in v0.2.0

func (w *MiddlewareTool) Description() string

Description 返回工具描述

func (*MiddlewareTool) Invoke added in v0.2.0

Invoke 执行工具调用(通过中间件)

func (*MiddlewareTool) Name added in v0.2.0

func (w *MiddlewareTool) Name() string

Name 返回工具名称

func (*MiddlewareTool) Unwrap added in v0.2.0

func (w *MiddlewareTool) Unwrap() interfaces.Tool

Unwrap 返回被包装的原始工具

这允许访问原始工具的方法或检查工具类型

type PerformanceProfile

type PerformanceProfile int

PerformanceProfile defines preset configurations for different workloads

const (
	// LowLatencyProfile optimizes for minimal response time
	LowLatencyProfile PerformanceProfile = iota
	// HighThroughputProfile optimizes for maximum throughput
	HighThroughputProfile
	// BalancedProfile provides balanced performance
	BalancedProfile
	// MemoryEfficientProfile minimizes memory usage
	MemoryEfficientProfile
)

type Registry

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

Registry manages tool registration and lookup

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new tool registry

func (*Registry) Clear

func (r *Registry) Clear()

Clear removes all registered tools

func (*Registry) Get

func (r *Registry) Get(name string) interfaces.Tool

Get retrieves a tool by name

func (*Registry) List

func (r *Registry) List() []interfaces.Tool

List returns all registered tools

func (*Registry) Names

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

Names returns all registered tool names

func (*Registry) Register

func (r *Registry) Register(tool interfaces.Tool) error

Register adds a tool to the registry

func (*Registry) Size

func (r *Registry) Size() int

Size returns the number of registered tools

type RetryPolicy

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

	// InitialDelay 初始延迟
	InitialDelay time.Duration

	// MaxDelay 最大延迟
	MaxDelay time.Duration

	// Multiplier 延迟倍数
	Multiplier float64

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

RetryPolicy 重试策略

type RuntimeConfig

type RuntimeConfig struct {
	// EnableStateAccess allows tools to read/write agent state
	EnableStateAccess bool

	// EnableStoreAccess allows tools to access long-term store
	EnableStoreAccess bool

	// EnableStreaming allows tools to stream data
	EnableStreaming bool

	// MaxExecutionTime limits tool execution time
	MaxExecutionTime int // seconds

	// AllowedNamespaces restricts store access to specific namespaces
	AllowedNamespaces []string
}

RuntimeConfig configures the tool runtime

func DefaultRuntimeConfig

func DefaultRuntimeConfig() *RuntimeConfig

DefaultRuntimeConfig returns default configuration

type RuntimeTool

type RuntimeTool interface {
	interfaces.Tool
	// ExecuteWithRuntime executes the tool with runtime context
	ExecuteWithRuntime(ctx context.Context, input *interfaces.ToolInput, runtime *ToolRuntime) (*interfaces.ToolOutput, error)
}

RuntimeTool interface for tools that use runtime

type RuntimeToolAdapter

type RuntimeToolAdapter struct {
	*BaseTool
	// contains filtered or unexported fields
}

RuntimeToolAdapter adapts a RuntimeTool to the standard Tool interface

func NewRuntimeToolAdapter

func NewRuntimeToolAdapter(tool RuntimeTool, runtime *ToolRuntime) *RuntimeToolAdapter

NewRuntimeToolAdapter creates a new adapter

func (*RuntimeToolAdapter) Invoke

Invoke implements the Tool interface through BaseTool

type SavePreferenceTool

type SavePreferenceTool struct {
	*BaseRuntimeTool
}

SavePreferenceTool saves user preferences using runtime

func NewSavePreferenceTool

func NewSavePreferenceTool() *SavePreferenceTool

NewSavePreferenceTool creates a new save preference tool

func (*SavePreferenceTool) ExecuteWithRuntime

func (t *SavePreferenceTool) ExecuteWithRuntime(ctx context.Context, input *interfaces.ToolInput, runtime *ToolRuntime) (*interfaces.ToolOutput, error)

ExecuteWithRuntime saves a preference using runtime

type ShardCountRecommendation

type ShardCountRecommendation struct {
	ExpectedQPS      int    // Expected queries per second
	RecommendedCount uint32 // Recommended shard count
	Rationale        string // Explanation for the recommendation
}

ShardCountRecommendation provides shard count recommendations based on expected load

func GetShardCountRecommendation

func GetShardCountRecommendation(expectedQPS int) ShardCountRecommendation

GetShardCountRecommendation returns recommended shard count based on expected QPS

type ShardedCacheConfig

type ShardedCacheConfig struct {
	// ShardCount 分片数量(建议为 2 的幂,默认 32)
	ShardCount uint32

	// Capacity 总容量(每个分片的容量 = Capacity / ShardCount)
	Capacity int

	// DefaultTTL 默认 TTL
	DefaultTTL time.Duration

	// CleanupInterval 清理间隔
	CleanupInterval time.Duration

	// EvictionPolicy 淘汰策略
	EvictionPolicy EvictionPolicy

	// CleanupStrategy 清理策略
	CleanupStrategy CleanupStrategy

	// LoadBalancing 负载均衡策略
	LoadBalancing LoadBalancingStrategy

	// AutoTuning 自动调优
	AutoTuning bool

	// MetricsEnabled 是否启用指标收集
	MetricsEnabled bool

	// MaxConcurrency 每个分片的最大并发数
	MaxConcurrency int

	// WarmupEntries 预热条目
	WarmupEntries map[string]*interfaces.ToolOutput

	// CompressionThreshold 压缩阈值(字节)
	CompressionThreshold int

	// MaxEntrySize 单个条目最大大小(字节)
	MaxEntrySize int

	// MemoryLimit 内存限制(字节)
	MemoryLimit int64

	// WorkloadType 工作负载类型
	WorkloadType WorkloadType
}

ShardedCacheConfig 分片缓存配置

func DefaultShardedCacheConfig

func DefaultShardedCacheConfig() ShardedCacheConfig

DefaultShardedCacheConfig returns the default configuration

type ShardedCacheOption

type ShardedCacheOption func(*ShardedCacheConfig)

ShardedCacheOption is a functional option for configuring ShardedToolCache

func WithAutoTuning

func WithAutoTuning(enabled bool) ShardedCacheOption

WithAutoTuning enables automatic performance tuning The cache will automatically adjust parameters based on workload patterns

func WithCapacity

func WithCapacity(capacity int) ShardedCacheOption

WithCapacity sets the total cache capacity The capacity is distributed evenly across shards

func WithCleanupInterval

func WithCleanupInterval(interval time.Duration) ShardedCacheOption

WithCleanupInterval sets the interval for periodic cleanup

func WithCleanupStrategy

func WithCleanupStrategy(strategy CleanupStrategy) ShardedCacheOption

WithCleanupStrategy sets the cleanup strategy

func WithCompressionThreshold

func WithCompressionThreshold(bytes int) ShardedCacheOption

WithCompressionThreshold enables compression for entries larger than threshold

func WithDefaultTTL

func WithDefaultTTL(ttl time.Duration) ShardedCacheOption

WithDefaultTTL sets the default TTL for cache entries

func WithEvictionPolicy

func WithEvictionPolicy(policy EvictionPolicy) ShardedCacheOption

WithEvictionPolicy sets the eviction policy for the cache

func WithLoadBalancing

func WithLoadBalancing(strategy LoadBalancingStrategy) ShardedCacheOption

WithLoadBalancing sets the load balancing strategy for shard selection

func WithMaxEntrySize

func WithMaxEntrySize(bytes int) ShardedCacheOption

WithMaxEntrySize sets the maximum size for a single cache entry

func WithMaxShardConcurrency

func WithMaxShardConcurrency(max int) ShardedCacheOption

WithMaxShardConcurrency sets the maximum concurrent operations per shard

func WithMemoryLimit

func WithMemoryLimit(bytes int64) ShardedCacheOption

WithMemoryLimit sets the maximum memory usage for the cache

func WithMetrics

func WithMetrics(enabled bool) ShardedCacheOption

WithMetrics enables or disables metrics collection

func WithPerformanceProfile

func WithPerformanceProfile(profile PerformanceProfile) ShardedCacheOption

WithPerformanceProfile applies a preset performance profile

func WithShardCount

func WithShardCount(count uint32) ShardedCacheOption

WithShardCount sets the number of shards Recommended values: - Light load (< 100 req/s): 8-16 shards - Medium load (100-1000 req/s): 32-64 shards - Heavy load (> 1000 req/s): 128-256 shards - Auto: 0 (will use CPU cores * 4)

func WithWarmup

func WithWarmup(entries map[string]*interfaces.ToolOutput) ShardedCacheOption

WithWarmup enables cache warmup with specified entries

func WithWorkloadType

func WithWorkloadType(workload WorkloadType) ShardedCacheOption

WithWorkloadType optimizes the cache for specific workload patterns

type ShardedToolCache

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

ShardedToolCache 分片工具缓存

使用分片策略降低锁竞争的高性能缓存实现

func NewShardedToolCache

func NewShardedToolCache(config ShardedCacheConfig) *ShardedToolCache

NewShardedToolCache 创建分片工具缓存(使用配置结构体)

func NewShardedToolCacheWithOptions

func NewShardedToolCacheWithOptions(opts ...ShardedCacheOption) *ShardedToolCache

NewShardedToolCacheWithOptions 使用选项模式创建分片工具缓存

func (*ShardedToolCache) AddDependency

func (c *ShardedToolCache) AddDependency(dependentTool, dependsOnTool string)

AddDependency 添加工具依赖关系

func (*ShardedToolCache) Clear

func (c *ShardedToolCache) Clear() error

Clear 清空所有缓存

func (*ShardedToolCache) Close

func (c *ShardedToolCache) Close()

Close 关闭缓存,清理资源

func (*ShardedToolCache) Delete

func (c *ShardedToolCache) Delete(ctx context.Context, key string) error

Delete 删除缓存

func (*ShardedToolCache) Get

Get 获取缓存结果

func (*ShardedToolCache) GetStats

func (c *ShardedToolCache) GetStats() CacheStats

GetStats 获取统计信息

func (*ShardedToolCache) GetStatsValues

func (c *ShardedToolCache) GetStatsValues() (hits, misses, evicts, invalidations int64)

GetStatsValues 获取统计信息的数值

func (*ShardedToolCache) GetVersion

func (c *ShardedToolCache) GetVersion() int64

GetVersion 获取当前缓存版本号(分片缓存不使用版本号)

func (*ShardedToolCache) InvalidateByPattern

func (c *ShardedToolCache) InvalidateByPattern(ctx context.Context, pattern string) (int, error)

InvalidateByPattern 根据正则表达式模式失效缓存

func (*ShardedToolCache) InvalidateByTool

func (c *ShardedToolCache) InvalidateByTool(ctx context.Context, toolName string) (int, error)

InvalidateByTool 根据工具名称失效缓存

func (*ShardedToolCache) RemoveDependency

func (c *ShardedToolCache) RemoveDependency(dependentTool, dependsOnTool string)

RemoveDependency 移除工具依赖关系

func (*ShardedToolCache) Set

Set 设置缓存结果

func (*ShardedToolCache) Size

func (c *ShardedToolCache) Size() int

Size 返回缓存大小

type SimpleFunction

type SimpleFunction func(context.Context) (interface{}, error)

SimpleFunction 简单函数类型 用于快速创建不需要复杂参数的工具

type SimpleToolCache added in v0.5.0

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

SimpleToolCache 简化的工具缓存

基于 cache.SimpleCache (sync.Map + TTL),删除所有过度设计: - 删除 LRU (container/list) - 删除分片 (32个分片 + FNV-1a哈希) - 删除版本号失效 - 删除依赖级联失效 - 删除正则模式失效 - 删除自动调优

func NewSimpleToolCache added in v0.5.0

func NewSimpleToolCache(ttl time.Duration) *SimpleToolCache

NewSimpleToolCache 创建简化工具缓存

func (*SimpleToolCache) Clear added in v0.5.0

func (c *SimpleToolCache) Clear() error

Clear 清空所有缓存

func (*SimpleToolCache) Close added in v0.5.0

func (c *SimpleToolCache) Close()

Close 关闭缓存

func (*SimpleToolCache) Delete added in v0.5.0

func (c *SimpleToolCache) Delete(ctx context.Context, key string) error

Delete 删除缓存

func (*SimpleToolCache) Get added in v0.5.0

Get 获取缓存结果

func (*SimpleToolCache) InvalidateByPattern added in v0.5.0

func (c *SimpleToolCache) InvalidateByPattern(ctx context.Context, pattern string) (int, error)

InvalidateByPattern 根据正则表达式模式失效缓存

简化实现:仅支持前缀匹配,删除复杂的正则表达式支持

func (*SimpleToolCache) InvalidateByTool added in v0.5.0

func (c *SimpleToolCache) InvalidateByTool(ctx context.Context, toolName string) (int, error)

InvalidateByTool 根据工具名称失效缓存

简化实现:清空所有缓存,删除复杂的工具名称解析和依赖管理

func (*SimpleToolCache) Set added in v0.5.0

func (c *SimpleToolCache) Set(ctx context.Context, key string, output *interfaces.ToolOutput, ttl time.Duration) error

Set 设置缓存结果

func (*SimpleToolCache) Size added in v0.5.0

func (c *SimpleToolCache) Size() int

Size 返回缓存大小

type ToolCache

type ToolCache interface {
	// Get 获取缓存结果
	Get(ctx context.Context, key string) (*interfaces.ToolOutput, bool)

	// Set 设置缓存结果
	Set(ctx context.Context, key string, output *interfaces.ToolOutput, ttl time.Duration) error

	// Delete 删除缓存
	Delete(ctx context.Context, key string) error

	// Clear 清空所有缓存
	Clear() error

	// Size 返回缓存大小
	Size() int

	// InvalidateByPattern 根据正则表达式模式失效缓存
	InvalidateByPattern(ctx context.Context, pattern string) (int, error)

	// InvalidateByTool 根据工具名称失效缓存
	InvalidateByTool(ctx context.Context, toolName string) (int, error)
}

ToolCache 工具缓存接口

func CreateShardedCache

func CreateShardedCache() ToolCache

CreateShardedCache 创建分片缓存的辅助函数

type ToolCall

type ToolCall struct {
	// Tool 要调用的工具
	Tool interfaces.Tool

	// Input 输入参数
	Input *interfaces.ToolInput

	// ID 调用标识符(用于追踪)
	ID string

	// Dependencies 依赖的其他工具调用 ID
	Dependencies []string
}

ToolCall 工具调用

type ToolError

type ToolError struct {
	ToolName string
	Message  string
	Err      error
}

ToolError 工具执行错误

func NewToolError

func NewToolError(toolName, message string, err error) *ToolError

NewToolError 创建工具错误

func (*ToolError) Error

func (e *ToolError) Error() string

Error 实现 error 接口

func (*ToolError) Unwrap

func (e *ToolError) Unwrap() error

Unwrap 支持 errors.Unwrap

type ToolExecutor

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

ToolExecutor 工具执行器

支持并发和顺序执行工具,提供超时、重试等功能

func NewToolExecutor

func NewToolExecutor(opts ...ExecutorOption) *ToolExecutor

NewToolExecutor 创建工具执行器

func (*ToolExecutor) ExecuteBatch

func (e *ToolExecutor) ExecuteBatch(ctx context.Context, tool interfaces.Tool, inputs []*interfaces.ToolInput) ([]*ToolResult, error)

ExecuteBatch 批量执行相同工具的不同输入

func (*ToolExecutor) ExecuteParallel

func (e *ToolExecutor) ExecuteParallel(ctx context.Context, calls []*ToolCall) ([]*ToolResult, error)

ExecuteParallel 并行执行多个工具

func (*ToolExecutor) ExecuteSequential

func (e *ToolExecutor) ExecuteSequential(ctx context.Context, calls []*ToolCall) ([]*ToolResult, error)

ExecuteSequential 顺序执行工具

func (*ToolExecutor) ExecuteWithDependencies

func (e *ToolExecutor) ExecuteWithDependencies(ctx context.Context, graph *ToolGraph) ([]*ToolResult, error)

ExecuteWithDependencies 根据依赖关系执行

type ToolGraph

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

ToolGraph 工具依赖图

管理工具之间的依赖关系,支持 DAG (有向无环图) 执行

func NewToolGraph

func NewToolGraph() *ToolGraph

NewToolGraph 创建工具依赖图

func (*ToolGraph) AddEdge

func (g *ToolGraph) AddEdge(from, to string) error

AddEdge 添加边(依赖关系)

from 依赖于 to(即 from 必须在 to 之后执行)

func (*ToolGraph) AddNode

func (g *ToolGraph) AddNode(node *ToolNode) error

AddNode 添加节点

func (*ToolGraph) Clear

func (g *ToolGraph) Clear()

Clear 清空图

func (*ToolGraph) Clone

func (g *ToolGraph) Clone() *ToolGraph

Clone 克隆图

func (*ToolGraph) GetDependencies

func (g *ToolGraph) GetDependencies(id string) []string

GetDependencies 获取节点的所有依赖

func (*ToolGraph) GetDependents

func (g *ToolGraph) GetDependents(id string) []string

GetDependents 获取依赖某个节点的所有节点

func (*ToolGraph) GetNode

func (g *ToolGraph) GetNode(id string) *ToolNode

GetNode 获取节点

func (*ToolGraph) GetNodes

func (g *ToolGraph) GetNodes() []*ToolNode

GetNodes 获取所有节点

func (*ToolGraph) HasNode

func (g *ToolGraph) HasNode(id string) bool

HasNode 检查节点是否存在

func (*ToolGraph) RemoveNode

func (g *ToolGraph) RemoveNode(id string) error

RemoveNode 移除节点

func (*ToolGraph) Size

func (g *ToolGraph) Size() int

Size 返回节点数量

func (*ToolGraph) TopologicalSort

func (g *ToolGraph) TopologicalSort() ([]string, error)

TopologicalSort 拓扑排序

返回执行顺序(节点 ID 列表)

func (*ToolGraph) Validate

func (g *ToolGraph) Validate() error

Validate 验证图的有效性

type ToolGraphBuilder

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

ToolGraphBuilder 工具图构建器

func NewToolGraphBuilder

func NewToolGraphBuilder() *ToolGraphBuilder

NewToolGraphBuilder 创建工具图构建器

func (*ToolGraphBuilder) AddDependency

func (b *ToolGraphBuilder) AddDependency(from, to string) *ToolGraphBuilder

AddDependency 添加依赖

func (*ToolGraphBuilder) AddTool

AddTool 添加工具

func (*ToolGraphBuilder) Build

func (b *ToolGraphBuilder) Build() (*ToolGraph, error)

Build 构建图

type ToolNode

type ToolNode struct {
	// ID 节点标识符
	ID string

	// Tool 工具实例
	Tool interfaces.Tool

	// Input 输入参数
	Input *interfaces.ToolInput

	// Dependencies 依赖的节点 ID 列表
	Dependencies []string

	// Metadata 元数据
	Metadata map[string]interface{}
}

ToolNode 工具节点

type ToolResult

type ToolResult struct {
	// CallID 调用标识符
	CallID string

	// Output 输出结果
	Output *interfaces.ToolOutput

	// Duration 执行耗时
	Duration time.Duration

	// Error 错误信息
	Error error
}

ToolResult 工具执行结果

type ToolRuntime

type ToolRuntime struct {
	// Core components
	State   core.State      // Agent's current state
	Context context.Context // Request context
	Store   store.Store     // Long-term memory store
	Config  *RuntimeConfig  // Runtime configuration

	// Execution context
	ToolCallID string // Current tool call ID
	AgentID    string // ID of the agent executing the tool
	SessionID  string // Session ID for tracking

	// Streaming support
	StreamWriter func(interface{}) error // Stream custom data

	// Additional context
	Metadata map[string]interface{} // Additional metadata
	// contains filtered or unexported fields
}

ToolRuntime provides access to agent state and context from within tools

func NewToolRuntime

func NewToolRuntime(ctx context.Context, state core.State, store store.Store) *ToolRuntime

NewToolRuntime creates a new tool runtime

func (*ToolRuntime) Clone

func (r *ToolRuntime) Clone() *ToolRuntime

Clone creates a copy of the runtime

func (*ToolRuntime) GetFromStore

func (r *ToolRuntime) GetFromStore(namespace []string, key string) (interface{}, error)

GetFromStore retrieves data from long-term store

func (*ToolRuntime) GetMetadata

func (r *ToolRuntime) GetMetadata(key string) (interface{}, bool)

GetMetadata retrieves metadata value

func (*ToolRuntime) GetState

func (r *ToolRuntime) GetState(key string) (interface{}, error)

GetState retrieves a value from agent state

func (*ToolRuntime) PutToStore

func (r *ToolRuntime) PutToStore(namespace []string, key string, value interface{}) error

PutToStore saves data to long-term store

func (*ToolRuntime) SetState

func (r *ToolRuntime) SetState(key string, value interface{}) error

SetState updates a value in agent state

func (*ToolRuntime) Stream

func (r *ToolRuntime) Stream(data interface{}) error

Stream sends data to the stream writer

func (*ToolRuntime) WithConfig

func (r *ToolRuntime) WithConfig(config *RuntimeConfig) *ToolRuntime

WithConfig sets the runtime configuration

func (*ToolRuntime) WithMetadata

func (r *ToolRuntime) WithMetadata(key string, value interface{}) *ToolRuntime

WithMetadata adds metadata to the runtime

func (*ToolRuntime) WithStreamWriter

func (r *ToolRuntime) WithStreamWriter(writer func(interface{}) error) *ToolRuntime

WithStreamWriter sets the stream writer

type ToolRuntimeManager

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

ToolRuntimeManager manages runtime instances for tools

func NewToolRuntimeManager

func NewToolRuntimeManager() *ToolRuntimeManager

NewToolRuntimeManager creates a new manager

func (*ToolRuntimeManager) CreateRuntimeWithContext

func (m *ToolRuntimeManager) CreateRuntimeWithContext(ctx context.Context, callID string, state core.State, store store.Store) *ToolRuntime

CreateRuntimeWithContext creates a new runtime for a tool call with a parent context

func (*ToolRuntimeManager) GetRuntime

func (m *ToolRuntimeManager) GetRuntime(callID string) (*ToolRuntime, bool)

GetRuntime retrieves a runtime by call ID

func (*ToolRuntimeManager) RemoveRuntime

func (m *ToolRuntimeManager) RemoveRuntime(callID string)

RemoveRuntime removes a runtime

type TypedFunction

type TypedFunction[I, O any] func(context.Context, I) (O, error)

TypedFunction 类型安全的函数类型 使用泛型提供类型安全

type UpdateStateTool

type UpdateStateTool struct {
	*BaseRuntimeTool
}

UpdateStateTool modifies agent state directly

func NewUpdateStateTool

func NewUpdateStateTool() *UpdateStateTool

NewUpdateStateTool creates a new update state tool

func (*UpdateStateTool) ExecuteWithRuntime

func (t *UpdateStateTool) ExecuteWithRuntime(ctx context.Context, input *interfaces.ToolInput, runtime *ToolRuntime) (*interfaces.ToolOutput, error)

ExecuteWithRuntime updates state using runtime

type UserInfoTool

type UserInfoTool struct {
	*BaseRuntimeTool
}

UserInfoTool retrieves user information using runtime

func NewUserInfoTool

func NewUserInfoTool() *UserInfoTool

NewUserInfoTool creates a new user info tool

func (*UserInfoTool) ExecuteWithRuntime

func (t *UserInfoTool) ExecuteWithRuntime(ctx context.Context, input *interfaces.ToolInput, runtime *ToolRuntime) (*interfaces.ToolOutput, error)

ExecuteWithRuntime retrieves user info using runtime

type WorkloadType

type WorkloadType int

WorkloadType defines the type of workload the cache will handle

const (
	// ReadHeavyWorkload for read-dominated workloads (90%+ reads)
	ReadHeavyWorkload WorkloadType = iota
	// WriteHeavyWorkload for write-dominated workloads
	WriteHeavyWorkload
	// MixedWorkload for balanced read/write workloads
	MixedWorkload
	// BurstyWorkload for workloads with traffic bursts
	BurstyWorkload
)

Directories

Path Synopsis
Package plugingen provides code generation tools for type-safe plugin boundaries.
Package plugingen provides code generation tools for type-safe plugin boundaries.
cmd/plugingen command
plugingen is a command-line tool for generating type-safe Go code from plugin schemas.
plugingen is a command-line tool for generating type-safe Go code from plugin schemas.

Jump to

Keyboard shortcuts

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