tools

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

包 tools 提供大模型工具调用的注册、调度与执行能力。

该包用于构建“模型推理 + 外部工具”执行闭环,支持工具注册、 并行执行、权限控制、速率限制、审计与成本治理。

核心能力

  • 工具注册中心:维护工具函数与 Schema 元数据
  • 执行器:支持单次与批量工具调用执行
  • 并发编排:支持并行工具执行与结果聚合
  • 治理能力:支持权限、限流、超时、审计、成本控制

适用场景

  • ReAct 循环中的工具调用
  • 检索增强与外部 API 聚合
  • 多工具流水线任务执行
  • 高风险工具的安全管控与审计
Example (GetWeatherTool)

示例:定义一个简单的 GetWeather 工具

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	llmpkg "github.com/BaSui01/agentflow/llm"
	"github.com/BaSui01/agentflow/llm/tools"
	"go.uber.org/zap"
)

func main() {
	logger, _ := zap.NewDevelopment()
	defer logger.Sync()

	// 1. 创建工具注册表
	registry := tools.NewDefaultRegistry(logger)

	// 2. 定义 GetWeather 工具函数
	getWeatherFunc := func(ctx context.Context, args json.RawMessage) (json.RawMessage, error) {
		// 解析参数
		var params struct {
			Location string `json:"location"`
			Unit     string `json:"unit,omitempty"`
		}
		if err := json.Unmarshal(args, &params); err != nil {
			return nil, fmt.Errorf("invalid parameters: %w", err)
		}

		// 模拟获取天气
		weather := map[string]any{
			"location":    params.Location,
			"temperature": 22,
			"unit":        "celsius",
			"condition":   "sunny",
			"humidity":    60,
		}

		if params.Unit == "fahrenheit" {
			weather["temperature"] = 72
			weather["unit"] = "fahrenheit"
		}

		result, _ := json.Marshal(weather)
		return result, nil
	}

	// 3. 定义工具元数据
	metadata := tools.ToolMetadata{
		Schema: llmpkg.ToolSchema{
			Name:        "get_weather",
			Description: "Get the current weather for a location",
			Parameters: json.RawMessage(`{
				"type": "object",
				"properties": {
					"location": {
						"type": "string",
						"description": "The city and state, e.g. San Francisco, CA"
					},
					"unit": {
						"type": "string",
						"enum": ["celsius", "fahrenheit"],
						"description": "The temperature unit"
					}
				},
				"required": ["location"]
			}`),
		},
		Timeout: 5 * time.Second,
		RateLimit: &tools.RateLimitConfig{
			MaxCalls: 10,
			Window:   time.Minute,
		},
	}

	// 4. 注册工具
	if err := registry.Register("get_weather", getWeatherFunc, metadata); err != nil {
		logger.Fatal("failed to register tool", zap.Error(err))
	}

	// 5. 创建工具执行器
	executor := tools.NewDefaultExecutor(registry, logger)

	// 6. 模拟 LLM 返回的 ToolCalls
	toolCalls := []llmpkg.ToolCall{
		{
			ID:   "call_123",
			Name: "get_weather",
			Arguments: json.RawMessage(`{
				"location": "San Francisco, CA",
				"unit": "fahrenheit"
			}`),
		},
	}

	// 7. 执行工具调用
	ctx := context.Background()
	results := executor.Execute(ctx, toolCalls)

	// 8. 打印结果
	for _, result := range results {
		fmt.Printf("Tool: %s\n", result.Name)
		if result.Error != "" {
			fmt.Printf("Error: %s\n", result.Error)
		} else {
			fmt.Printf("Result: %s\n", string(result.Result))
		}
	}

	// 输出 :
	// 工具: get weather
	// 结果:{"条件":"生","湿":"地":"旧金山,CA""温":72"单位":"平"]
}
Example (ReActLoop)

示例:ReAct 循环集成(伪代码,需要真实的 Provider)

package main

import (
	llmpkg "github.com/BaSui01/agentflow/llm"
	"github.com/BaSui01/agentflow/llm/tools"
	"go.uber.org/zap"
)

func main() {
	logger, _ := zap.NewDevelopment()
	defer logger.Sync()

	// 1. 创建工具注册表并注册工具
	registry := tools.NewDefaultRegistry(logger)
	// ... 注册工具(同上)

	// 2. 创建工具执行器
	toolExecutor := tools.NewDefaultExecutor(registry, logger)

	// 3. 假设我们有一个 LLM Provider(这里需要真实实现)
	// 提供者:= (OpenAI, Claude等)

	// 4. 创建 ReAct 执行器
	config := tools.ReActConfig{
		MaxIterations: 5,
		StopOnError:   false,
	}
	// 反应执行器:=工具. NewReAct执行器(提供器,工具执行器,配置器,日志)

	// 5. 准备请求
	req := &llmpkg.ChatRequest{
		TraceID: "trace_123",
		Model:   "gpt-4",
		Messages: []llmpkg.Message{
			{
				Role:    llmpkg.RoleSystem,
				Content: "You are a helpful assistant that can get weather information.",
			},
			{
				Role:    llmpkg.RoleUser,
				Content: "What's the weather like in San Francisco?",
			},
		},
		Tools: registry.List(), // 传递所有可用工具
	}

	// 6. 执行 ReAct 循环
	// resp, 步骤, 错误 : = 反应Executor.Execute(context.Background (, req))
	// 如果错误 ! = 无 {
	//     logger. Error ("ReAct执行失败", zap. Error( err)) :
	//     返回时
	// }

	// 7. 打印结果
	// fmt.Printf ("最后反应: %s\n", resp.Choices [0]. 传言. 内容)
	// fmt.Printf ("总步数:%d\n", len( 步数))

	_ = toolExecutor // 避免未使用变量错误
	_ = config       // 避免未使用变量错误
	_ = req          // 避免未使用变量错误
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuditMiddleware

func AuditMiddleware(auditLogger AuditLogger) func(ToolFunc) ToolFunc

AuditMiddleware 创建记录工具执行的中间件.

func CostControlMiddleware

func CostControlMiddleware(cc CostController, auditLogger AuditLogger) func(ToolFunc) ToolFunc

CostControlMiddleware 创建一个执行成本控制的中间件.

func LogCostAlert

func LogCostAlert(auditLogger AuditLogger, agentID, userID string, cost float64, alertType string)

LogCostAlert 是记录成本告警的便捷函数.

func LogPermissionCheck

func LogPermissionCheck(auditLogger AuditLogger, permCtx *PermissionContext, decision PermissionDecision, reason string)

LogPermissionCheck 是记录权限检查的便捷函数.

func LogRateLimitHit

func LogRateLimitHit(auditLogger AuditLogger, agentID, userID, toolName, limitType string)

LogRateLimitHit 是记录速率限制触发的便捷函数.

func LogToolCall

func LogToolCall(auditLogger AuditLogger, agentID, userID, toolName string, args json.RawMessage)

LogToolCall 是记录工具调用的便捷函数.

func LogToolResult

func LogToolResult(auditLogger AuditLogger, agentID, userID, toolName string, result json.RawMessage, err error, duration time.Duration)

LogToolResult 是记录工具结果的便捷函数.

func NewWebScrapeTool

func NewWebScrapeTool(config WebScrapeToolConfig, logger *zap.Logger) (ToolFunc, ToolMetadata)

新WebScrapeTool创建了用于网络刮取的工具Func. 用工具登记器注册, 以便提供给代理商 。

func NewWebSearchTool

func NewWebSearchTool(config WebSearchToolConfig, logger *zap.Logger) (ToolFunc, ToolMetadata)

新WebSearchTool创建了用于网页搜索的工具Func. 用工具登记器注册, 以便提供给代理商 。

func PermissionMiddleware

func PermissionMiddleware(pm PermissionManager) func(ToolFunc) ToolFunc

PermissionMiddleware 创建一个在工具执行前检查权限的中间件.

func RateLimitMiddleware

func RateLimitMiddleware(rlm RateLimitManager, auditLogger AuditLogger) func(ToolFunc) ToolFunc

RateLimitMiddleware 创建一个执行速率限制的中间件.

func RegisterWebScrapeTool

func RegisterWebScrapeTool(registry ToolRegistry, config WebScrapeToolConfig, logger *zap.Logger) error

RegisterWebScrapeTool 是创建并注册网页抓取工具的便捷函数.

func RegisterWebSearchTool

func RegisterWebSearchTool(registry ToolRegistry, config WebSearchToolConfig, logger *zap.Logger) error

RegisterWebSearchTool 是创建并注册网络搜索工具的便捷函数.

func WithPermissionContext

func WithPermissionContext(ctx context.Context, permCtx *PermissionContext) context.Context

With PermissionContext 为上下文添加许可上下文 。

Types

type AgentPermission

type AgentPermission struct {
	AgentID         string    `json:"agent_id"`
	AllowedTools    []string  `json:"allowed_tools,omitempty"` // Explicit allow list
	DeniedTools     []string  `json:"denied_tools,omitempty"`  // Explicit deny list
	InheritFrom     string    `json:"inherit_from,omitempty"`  // Parent agent ID
	MaxCallsPerHour int       `json:"max_calls_per_hour,omitempty"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
}

AgentPermission定义了特定代理权限.

type ApprovalHandler

type ApprovalHandler interface {
	RequestApproval(ctx context.Context, permCtx *PermissionContext, rule *PermissionRule) (approvalID string, err error)
	CheckApprovalStatus(ctx context.Context, approvalID string) (approved bool, err error)
}

审批人处理要求审批申请 审批决定.

type AuditBackend

type AuditBackend interface {
	// Write 将审计条目写入后端。
	Write(ctx context.Context, entry *AuditEntry) error

	// Query 从后端检索审计条目.
	Query(ctx context.Context, filter *AuditFilter) ([]*AuditEntry, error)

	// Close 关闭后端。
	Close() error
}

AuditBackend 定义审计存储后端的接口.

type AuditEntry

type AuditEntry struct {
	ID        string            `json:"id"`
	Timestamp time.Time         `json:"timestamp"`
	EventType AuditEventType    `json:"event_type"`
	AgentID   string            `json:"agent_id"`
	UserID    string            `json:"user_id"`
	SessionID string            `json:"session_id,omitempty"`
	TraceID   string            `json:"trace_id,omitempty"`
	ToolName  string            `json:"tool_name"`
	Arguments json.RawMessage   `json:"arguments,omitempty"`
	Result    json.RawMessage   `json:"result,omitempty"`
	Error     string            `json:"error,omitempty"`
	Duration  time.Duration     `json:"duration,omitempty"`
	Decision  string            `json:"decision,omitempty"` // For permission checks
	Cost      float64           `json:"cost,omitempty"`     // For cost tracking
	Metadata  map[string]string `json:"metadata,omitempty"`
	RequestIP string            `json:"request_ip,omitempty"`
}

AuditEntry 表示单条审计记录.

type AuditEventType

type AuditEventType string

AuditEventType 表示审计事件的类型.

const (
	AuditEventToolCall        AuditEventType = "tool_call"
	AuditEventToolResult      AuditEventType = "tool_result"
	AuditEventPermissionCheck AuditEventType = "permission_check"
	AuditEventRateLimitHit    AuditEventType = "rate_limit_hit"
	AuditEventCostAlert       AuditEventType = "cost_alert"
)

type AuditFilter

type AuditFilter struct {
	AgentID   string         `json:"agent_id,omitempty"`
	UserID    string         `json:"user_id,omitempty"`
	ToolName  string         `json:"tool_name,omitempty"`
	EventType AuditEventType `json:"event_type,omitempty"`
	StartTime *time.Time     `json:"start_time,omitempty"`
	EndTime   *time.Time     `json:"end_time,omitempty"`
	SessionID string         `json:"session_id,omitempty"`
	TraceID   string         `json:"trace_id,omitempty"`
	Limit     int            `json:"limit,omitempty"`
	Offset    int            `json:"offset,omitempty"`
}

AuditFilter 定义查询审计条目的过滤器.

type AuditLogger

type AuditLogger interface {
	// Log 同步记录一条审计条目。
	Log(ctx context.Context, entry *AuditEntry) error

	// LogAsync 异步记录审计条目.
	LogAsync(entry *AuditEntry)

	// Query 根据过滤器检索审计条目。
	Query(ctx context.Context, filter *AuditFilter) ([]*AuditEntry, error)

	// Close 关闭审计日志并刷新待写入条目。
	Close() error
}

AuditLogger 定义工具层审计日志的接口.

注意:项目中存在三个 AuditLogger 接口,各自服务不同领域,无法统一:

  • llm.AuditLogger — 框架级,记录 AuditEvent(通用事件)
  • llm/tools.AuditLogger(本接口) — 工具层,记录 *AuditEntry(工具调用/权限/成本),含 LogAsync/Close
  • agent/guardrails.AuditLogger — 护栏层,记录 *AuditLogEntry(验证失败/PII/注入),含 Count

三者的事件类型、过滤器结构和方法签名均不同,统一会导致接口膨胀。

type AuditLoggerConfig

type AuditLoggerConfig struct {
	Backends       []AuditBackend
	AsyncQueueSize int
	AsyncWorkers   int
	IDGenerator    func() string
}

AuditLoggerConfig 配置审计日志。

type BatchExecutor

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

批量执行器提供批量执行,并自动分批处理类似工具调用.

func NewBatchExecutor

func NewBatchExecutor(parallel *ParallelExecutor, logger *zap.Logger) *BatchExecutor

NewBatch 执行器创建批次执行器 。

func (*BatchExecutor) ExecuteBatched

func (b *BatchExecutor) ExecuteBatched(ctx context.Context, calls []llmpkg.ToolCall) *ParallelResult

执行Batched类类似工具调用并高效地执行.

type Budget

type Budget struct {
	ID              string       `json:"id"`
	Name            string       `json:"name"`
	Description     string       `json:"description,omitempty"`
	Scope           BudgetScope  `json:"scope"`
	ScopeID         string       `json:"scope_id,omitempty"` // Agent ID, User ID, etc.
	Limit           float64      `json:"limit"`              // Budget limit
	Unit            CostUnit     `json:"unit"`
	Period          BudgetPeriod `json:"period"`
	AlertThresholds []float64    `json:"alert_thresholds,omitempty"` // Percentages (e.g., 50, 80, 100)
	Enabled         bool         `json:"enabled"`
	CreatedAt       time.Time    `json:"created_at"`
	UpdatedAt       time.Time    `json:"updated_at"`
}

Budget 定义预算配置。

func CreateAgentBudget

func CreateAgentBudget(id, name, agentID string, limit float64, period BudgetPeriod) *Budget

CreateAgentBudget 创建针对特定 Agent 的预算.

func CreateGlobalBudget

func CreateGlobalBudget(id, name string, limit float64, period BudgetPeriod) *Budget

CreateGlobalBudget 创建全局预算。

func CreateUserBudget

func CreateUserBudget(id, name, userID string, limit float64, period BudgetPeriod) *Budget

CreateUserBudget 创建针对用户的预算.

type BudgetPeriod

type BudgetPeriod string

BudgetPeriod 定义预算的周期。

const (
	BudgetPeriodHourly  BudgetPeriod = "hourly"
	BudgetPeriodDaily   BudgetPeriod = "daily"
	BudgetPeriodWeekly  BudgetPeriod = "weekly"
	BudgetPeriodMonthly BudgetPeriod = "monthly"
	BudgetPeriodTotal   BudgetPeriod = "total" // No reset
)

type BudgetScope

type BudgetScope string

BudgetScope 定义预算的作用域。

const (
	BudgetScopeGlobal  BudgetScope = "global"
	BudgetScopeAgent   BudgetScope = "agent"
	BudgetScopeUser    BudgetScope = "user"
	BudgetScopeSession BudgetScope = "session"
	BudgetScopeTool    BudgetScope = "tool"
)

type CostAlert

type CostAlert struct {
	ID         string         `json:"id"`
	Timestamp  time.Time      `json:"timestamp"`
	Level      CostAlertLevel `json:"level"`
	BudgetID   string         `json:"budget_id"`
	Message    string         `json:"message"`
	Current    float64        `json:"current"`
	Limit      float64        `json:"limit"`
	Percentage float64        `json:"percentage"`
}

CostAlert 表示成本告警.

type CostAlertHandler

type CostAlertHandler interface {
	HandleAlert(ctx context.Context, alert *CostAlert) error
}

CostAlertHandler 处理成本告警.

type CostAlertLevel

type CostAlertLevel string

CostAlertLevel 表示成本告警的严重级别.

const (
	CostAlertLevelInfo     CostAlertLevel = "info"
	CostAlertLevelWarning  CostAlertLevel = "warning"
	CostAlertLevelCritical CostAlertLevel = "critical"
)

type CostCheckResult

type CostCheckResult struct {
	Allowed      bool       `json:"allowed"`
	Cost         float64    `json:"cost"`
	Budget       *Budget    `json:"budget,omitempty"`
	CurrentUsage float64    `json:"current_usage"`
	Remaining    float64    `json:"remaining"`
	Alert        *CostAlert `json:"alert,omitempty"`
	Reason       string     `json:"reason,omitempty"`
}

CostCheckResult 包含成本检查的结果.

type CostController

type CostController interface {
	// CalculateCost 计算工具调用的成本。
	CalculateCost(toolName string, args json.RawMessage) (float64, error)

	// CheckBudget 检查是否在预算范围内。
	CheckBudget(ctx context.Context, agentID, userID, sessionID, toolName string, cost float64) (*CostCheckResult, error)

	// RecordCost 记录成本。
	RecordCost(record *CostRecord) error

	// SetToolCost 设置工具的成本配置。
	SetToolCost(cost *ToolCost) error

	// GetToolCost 获取工具的成本配置.
	GetToolCost(toolName string) (*ToolCost, bool)

	// AddBudget 添加预算。
	AddBudget(budget *Budget) error

	// RemoveBudget 删除预算。
	RemoveBudget(budgetID string) error

	// GetBudget 根据 ID 获取预算.
	GetBudget(budgetID string) (*Budget, bool)

	// ListBudgets 列出所有预算.
	ListBudgets() []*Budget

	// GetUsage 获取指定作用域的当前用量。
	GetUsage(scope BudgetScope, scopeID string, period BudgetPeriod) float64

	// GetOptimizations 获取成本优化建议.
	GetOptimizations(agentID, userID string) []*CostOptimization

	// GetCostReport 生成成本报告。
	GetCostReport(filter *CostReportFilter) (*CostReport, error)
}

CostController 管理成本控制。

type CostOptimization

type CostOptimization struct {
	Type        string  `json:"type"`
	Description string  `json:"description"`
	Savings     float64 `json:"savings,omitempty"`
	Priority    int     `json:"priority"`
}

CostOptimization 表示成本优化建议。

type CostRecord

type CostRecord struct {
	ID        string            `json:"id"`
	Timestamp time.Time         `json:"timestamp"`
	AgentID   string            `json:"agent_id"`
	UserID    string            `json:"user_id"`
	SessionID string            `json:"session_id,omitempty"`
	ToolName  string            `json:"tool_name"`
	Cost      float64           `json:"cost"`
	Unit      CostUnit          `json:"unit"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

CostRecord 表示单条成本记录。

type CostReport

type CostReport struct {
	TotalCost   float64            `json:"total_cost"`
	TotalCalls  int64              `json:"total_calls"`
	AverageCost float64            `json:"average_cost"`
	ByTool      map[string]float64 `json:"by_tool,omitempty"`
	ByAgent     map[string]float64 `json:"by_agent,omitempty"`
	ByUser      map[string]float64 `json:"by_user,omitempty"`
	ByDay       map[string]float64 `json:"by_day,omitempty"`
	TopTools    []ToolCostSummary  `json:"top_tools,omitempty"`
	GeneratedAt time.Time          `json:"generated_at"`
}

CostReport 表示成本报告。

type CostReportFilter

type CostReportFilter struct {
	AgentID   string     `json:"agent_id,omitempty"`
	UserID    string     `json:"user_id,omitempty"`
	ToolName  string     `json:"tool_name,omitempty"`
	StartTime *time.Time `json:"start_time,omitempty"`
	EndTime   *time.Time `json:"end_time,omitempty"`
	GroupBy   string     `json:"group_by,omitempty"` // agent, user, tool, day, hour
}

CostReportFilter 定义成本报告的过滤器.

type CostUnit

type CostUnit string

CostUnit 表示成本计量单位.

const (
	CostUnitCredits CostUnit = "credits"
	CostUnitDollars CostUnit = "dollars"
	CostUnitTokens  CostUnit = "tokens"
)

type DatabaseAuditBackend

type DatabaseAuditBackend interface {
	AuditBackend
	// Migrate 创建或更新数据库表结构。
	Migrate(ctx context.Context) error
}

DatabaseAuditBackend 定义数据库审计后端的接口. 实现可以使用 PostgreSQL、MySQL、MongoDB 等.

type DefaultAuditLogger

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

DefaultAuditLogger 是 AuditLogger 的默认实现.

func NewAuditLogger

func NewAuditLogger(cfg *AuditLoggerConfig, logger *zap.Logger) *DefaultAuditLogger

NewAuditLogger 创建新的审计日志.

func (*DefaultAuditLogger) Close

func (al *DefaultAuditLogger) Close() error

Close 关闭审计日志并刷新待写入条目。

func (*DefaultAuditLogger) Log

func (al *DefaultAuditLogger) Log(ctx context.Context, entry *AuditEntry) error

Log 同步记录审计条目。

func (*DefaultAuditLogger) LogAsync

func (al *DefaultAuditLogger) LogAsync(entry *AuditEntry)

LogAsync 异步记录审计条目.

func (*DefaultAuditLogger) Query

func (al *DefaultAuditLogger) Query(ctx context.Context, filter *AuditFilter) ([]*AuditEntry, error)

Query 根据过滤器检索审计条目。

type DefaultCostController

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

DefaultCostController 是 CostController 的默认实现。

func NewCostController

func NewCostController(logger *zap.Logger) *DefaultCostController

NewCostController 创建新的成本控制器。

func (*DefaultCostController) AddBudget

func (cc *DefaultCostController) AddBudget(budget *Budget) error

AddBudget 添加预算。

func (*DefaultCostController) CalculateCost

func (cc *DefaultCostController) CalculateCost(toolName string, args json.RawMessage) (float64, error)

CalculateCost 计算工具调用的成本。

func (*DefaultCostController) CheckBudget

func (cc *DefaultCostController) CheckBudget(ctx context.Context, agentID, userID, sessionID, toolName string, cost float64) (*CostCheckResult, error)

CheckBudget 检查是否在预算范围内。

func (*DefaultCostController) GetBudget

func (cc *DefaultCostController) GetBudget(budgetID string) (*Budget, bool)

GetBudget 根据 ID 获取预算.

func (*DefaultCostController) GetCostReport

func (cc *DefaultCostController) GetCostReport(filter *CostReportFilter) (*CostReport, error)

GetCostReport 生成成本报告。

func (*DefaultCostController) GetOptimizations

func (cc *DefaultCostController) GetOptimizations(agentID, userID string) []*CostOptimization

GetOptimizations 获取成本优化建议.

func (*DefaultCostController) GetToolCost

func (cc *DefaultCostController) GetToolCost(toolName string) (*ToolCost, bool)

GetToolCost 获取工具的成本配置.

func (*DefaultCostController) GetUsage

func (cc *DefaultCostController) GetUsage(scope BudgetScope, scopeID string, period BudgetPeriod) float64

GetUsage 获取指定作用域的当前用量。

func (*DefaultCostController) ListBudgets

func (cc *DefaultCostController) ListBudgets() []*Budget

ListBudgets 列出所有预算.

func (*DefaultCostController) RecordCost

func (cc *DefaultCostController) RecordCost(record *CostRecord) error

RecordCost 记录成本。

func (*DefaultCostController) RemoveBudget

func (cc *DefaultCostController) RemoveBudget(budgetID string) error

RemoveBudget 删除预算。

func (*DefaultCostController) SetAlertHandler

func (cc *DefaultCostController) SetAlertHandler(handler CostAlertHandler)

SetAlertHandler 设置告警处理器.

func (*DefaultCostController) SetToolCost

func (cc *DefaultCostController) SetToolCost(cost *ToolCost) error

SetToolCost 设置工具的成本配置。

type DefaultExecutor

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

func NewDefaultExecutor

func NewDefaultExecutor(registry ToolRegistry, logger *zap.Logger) *DefaultExecutor

NewDefaultExecutor 创建默认的工具执行器。

func (*DefaultExecutor) Execute

func (e *DefaultExecutor) Execute(ctx context.Context, calls []llm.ToolCall) []ToolResult

func (*DefaultExecutor) ExecuteOne

func (e *DefaultExecutor) ExecuteOne(ctx context.Context, call llm.ToolCall) ToolResult

type DefaultPermissionManager

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

默认许可管理器是权限管理器的默认执行.

func NewPermissionManager

func NewPermissionManager(logger *zap.Logger) *DefaultPermissionManager

NewPermissionManager创建了新的许可管理器.

func (*DefaultPermissionManager) AddRole

func (pm *DefaultPermissionManager) AddRole(role *Role) error

添加Role增加了一个角色.

func (*DefaultPermissionManager) AddRule

func (pm *DefaultPermissionManager) AddRule(rule *PermissionRule) error

添加规则添加了权限规则 。

func (*DefaultPermissionManager) AssignRoleToUser

func (pm *DefaultPermissionManager) AssignRoleToUser(userID, roleID string) error

AssignRoleToUser为用户分配一个角色.

func (*DefaultPermissionManager) CheckPermission

检查是否允许调用工具 。

func (*DefaultPermissionManager) GetAgentPermission

func (pm *DefaultPermissionManager) GetAgentPermission(agentID string) (*AgentPermission, bool)

Get AgentPermission获得特定代理权限.

func (*DefaultPermissionManager) GetRole

func (pm *DefaultPermissionManager) GetRole(roleID string) (*Role, bool)

GetRole通过ID检索角色.

func (*DefaultPermissionManager) GetRule

func (pm *DefaultPermissionManager) GetRule(ruleID string) (*PermissionRule, bool)

Get Rule 以 ID 检索许可规则 。

func (*DefaultPermissionManager) GetUserRoles

func (pm *DefaultPermissionManager) GetUserRoles(userID string) []string

GetUserRoles为用户获得所有角色.

func (*DefaultPermissionManager) ListRules

func (pm *DefaultPermissionManager) ListRules() []*PermissionRule

List Rules 列出所有许可规则 。

func (*DefaultPermissionManager) RemoveRole

func (pm *DefaultPermissionManager) RemoveRole(roleID string) error

删除 Role 删除一个角色 。

func (*DefaultPermissionManager) RemoveRule

func (pm *DefaultPermissionManager) RemoveRule(ruleID string) error

删除规则删除权限规则 。

func (*DefaultPermissionManager) SetAgentPermission

func (pm *DefaultPermissionManager) SetAgentPermission(perm *AgentPermission) error

Set AgentPermission 设置特定代理权限.

func (*DefaultPermissionManager) SetApprovalHandler

func (pm *DefaultPermissionManager) SetApprovalHandler(handler ApprovalHandler)

SetApprovalHandler设定审批处理器.

type DefaultRateLimitManager

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

DefaultRateLimitManager 是 RateLimitManager 的默认实现.

func NewRateLimitManager

func NewRateLimitManager(logger *zap.Logger) *DefaultRateLimitManager

NewRateLimitManager 创建新的速率限制管理器.

func (*DefaultRateLimitManager) AddRule

func (rlm *DefaultRateLimitManager) AddRule(rule *RateLimitRule) error

AddRule 添加速率限制规则。

func (*DefaultRateLimitManager) CheckRateLimit

func (rlm *DefaultRateLimitManager) CheckRateLimit(ctx context.Context, rlCtx *RateLimitContext) (*RateLimitResult, error)

CheckRateLimit 检查请求是否被允许。

func (*DefaultRateLimitManager) GetRule

func (rlm *DefaultRateLimitManager) GetRule(ruleID string) (*RateLimitRule, bool)

GetRule 根据 ID 检索速率限制规则。

func (*DefaultRateLimitManager) GetStats

func (rlm *DefaultRateLimitManager) GetStats(scope RateLimitScope, key string) *RateLimitStats

GetStats 返回速率限制统计信息.

func (*DefaultRateLimitManager) ListRules

func (rlm *DefaultRateLimitManager) ListRules() []*RateLimitRule

ListRules 列出所有速率限制规则。

func (*DefaultRateLimitManager) RemoveRule

func (rlm *DefaultRateLimitManager) RemoveRule(ruleID string) error

RemoveRule 删除速率限制规则。

func (*DefaultRateLimitManager) Reset

func (rlm *DefaultRateLimitManager) Reset(scope RateLimitScope, key string) error

Reset 重置指定 key 的速率限制计数器。

func (*DefaultRateLimitManager) SetDegradeHandler

func (rlm *DefaultRateLimitManager) SetDegradeHandler(handler DegradeHandler)

SetDegradeHandler 设置降级处理器。

func (*DefaultRateLimitManager) SetQueueHandler

func (rlm *DefaultRateLimitManager) SetQueueHandler(handler QueueHandler)

SetQueueHandler 设置队列处理器。

type DefaultRegistry

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

func NewDefaultRegistry

func NewDefaultRegistry(logger *zap.Logger) *DefaultRegistry

NewDefaultRegistry 创建默认的工具注册中心。

func (*DefaultRegistry) Get

func (*DefaultRegistry) Has

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

func (*DefaultRegistry) List

func (r *DefaultRegistry) List() []llm.ToolSchema

func (*DefaultRegistry) Register

func (r *DefaultRegistry) Register(name string, fn ToolFunc, metadata ToolMetadata) error

func (*DefaultRegistry) Unregister

func (r *DefaultRegistry) Unregister(name string) error

type DegradeHandler

type DegradeHandler interface {
	GetDegradedResponse(ctx context.Context, rlCtx *RateLimitContext) (json.RawMessage, error)
}

DegradeHandler 处理降级服务.

type FallbackConfig

type FallbackConfig struct {
	MaxRetries      int               `json:"max_retries"`
	RetryDelayMs    int               `json:"retry_delay_ms"`
	Alternates      map[string]string `json:"alternates"`     // 工具名 -> 备用工具名
	SkipOnErrors    []string          `json:"skip_on_errors"` // 遇到这些错误时跳过
	DefaultStrategy FallbackStrategy  `json:"default_strategy"`
}

FallbackConfig 回退配置

func DefaultFallbackConfig

func DefaultFallbackConfig() *FallbackConfig

DefaultFallbackConfig 默认回退配置

type FallbackStrategy

type FallbackStrategy string

FallbackStrategy 回退策略

const (
	// FallbackRetry 重试当前工具
	FallbackRetry FallbackStrategy = "retry"
	// FallbackAlternate 切换到备用工具
	FallbackAlternate FallbackStrategy = "alternate"
	// FallbackSkip 跳过工具调用,让模型直接回答
	FallbackSkip FallbackStrategy = "skip"
	// FallbackError 返回错误
	FallbackError FallbackStrategy = "error"
)

type FileAuditBackend

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

FileAuditBackend 将审计条目存储在文件中.

func NewFileAuditBackend

func NewFileAuditBackend(cfg *FileAuditBackendConfig, logger *zap.Logger) (*FileAuditBackend, error)

NewFileAuditBackend 创建新的文件审计后端.

func (*FileAuditBackend) Close

func (f *FileAuditBackend) Close() error

Close 关闭文件后端。

func (*FileAuditBackend) Query

func (f *FileAuditBackend) Query(ctx context.Context, filter *AuditFilter) ([]*AuditEntry, error)

Query 从文件中检索审计条目(功能有限).

func (*FileAuditBackend) Write

func (f *FileAuditBackend) Write(ctx context.Context, entry *AuditEntry) error

Write 将审计条目写入文件。

type FileAuditBackendConfig

type FileAuditBackendConfig struct {
	Directory   string
	MaxFileSize int64 // Max file size in bytes before rotation
}

FileAuditBackendConfig 配置文件审计后端.

type FixedWindowLimiter

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

FixedWindowLimiter 实现固定窗口速率限制.

func NewFixedWindowLimiter

func NewFixedWindowLimiter(maxRequests int, window time.Duration) *FixedWindowLimiter

NewFixedWindowLimiter 创建新的固定窗口限制器.

func (*FixedWindowLimiter) Allow

func (l *FixedWindowLimiter) Allow() bool

Allow 检查请求是否被允许。

func (*FixedWindowLimiter) Remaining

func (l *FixedWindowLimiter) Remaining() int

Remaining 返回剩余请求数。

func (*FixedWindowLimiter) Reset

func (l *FixedWindowLimiter) Reset()

Reset 重置限制器。

func (*FixedWindowLimiter) ResetAt

func (l *FixedWindowLimiter) ResetAt() time.Time

ResetAt 返回窗口重置时间。

type LLMCallInfo

type LLMCallInfo struct {
	Request  llm.ChatRequest  `json:"request"`
	Response llm.ChatResponse `json:"response"`
}

LLMCallInfo 记录 LLM 调用详情(用于向后兼容).

type Limiter

type Limiter interface {
	Allow() bool
	Remaining() int
	ResetAt() time.Time
	Reset()
}

Limiter 定义限速器的接口.

type MemoryAuditBackend

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

MemoryAuditBackend 将审计条目存储在内存中.

func NewMemoryAuditBackend

func NewMemoryAuditBackend(maxSize int) *MemoryAuditBackend

NewMemoryAuditBackend 创建新的内存审计后端.

func (*MemoryAuditBackend) Close

func (m *MemoryAuditBackend) Close() error

Close 关闭内存后端。

func (*MemoryAuditBackend) Query

func (m *MemoryAuditBackend) Query(ctx context.Context, filter *AuditFilter) ([]*AuditEntry, error)

Query 从内存中检索审计条目。

func (*MemoryAuditBackend) Write

func (m *MemoryAuditBackend) Write(ctx context.Context, entry *AuditEntry) error

Write 将审计条目写入内存。

type ParallelConfig

type ParallelConfig struct {
	MaxConcurrency   int           // Maximum concurrent tool executions (0 = unlimited)
	ExecutionTimeout time.Duration // Global timeout for all parallel executions
	FailFast         bool          // Stop all executions on first error
	RetryOnError     bool          // Retry failed tool calls
	MaxRetries       int           // Maximum retry attempts per tool
	RetryDelay       time.Duration // Delay between retries
	CollectPartial   bool          // Return partial results on timeout/cancel
	DependencyGraph  bool          // Enable dependency-aware execution order
}

并行Config定义了并行工具执行的配置.

func DefaultParallelConfig

func DefaultParallelConfig() ParallelConfig

默认ParallelConfig 返回并行执行的合理默认值 。

type ParallelExecutor

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

并行执行器同时执行多个工具调用和高级功能.

func NewParallelExecutor

func NewParallelExecutor(registry ToolRegistry, config ParallelConfig, logger *zap.Logger) *ParallelExecutor

NewParallelExecutor创建了一个新的并行工具执行器.

func (*ParallelExecutor) Execute

func (p *ParallelExecutor) Execute(ctx context.Context, calls []llmpkg.ToolCall) *ParallelResult

Execute运行多个工具调用与货币控制并行.

func (*ParallelExecutor) ExecuteWithDependencies

func (p *ParallelExecutor) ExecuteWithDependencies(ctx context.Context, calls []ToolCallWithDeps) *ParallelResult

执行与相互依存执行工具调用尊重依赖命令 。

func (*ParallelExecutor) Stats

func (p *ParallelExecutor) Stats() (total, success, failed int64, avgDuration time.Duration)

Stats 返回执行统计 。

type ParallelResult

type ParallelResult struct {
	Results       []ToolResult  `json:"results"`
	TotalDuration time.Duration `json:"total_duration"`
	Completed     int           `json:"completed"`
	Failed        int           `json:"failed"`
	Cancelled     int           `json:"cancelled"`
	PartialResult bool          `json:"partial_result"`
}

并行结果包含并行工具执行的结果.

type PermissionCheckResult

type PermissionCheckResult struct {
	Decision     PermissionDecision `json:"decision"`
	MatchedRule  *PermissionRule    `json:"matched_rule,omitempty"`
	Reason       string             `json:"reason"`
	ApprovalID   string             `json:"approval_id,omitempty"` // For require_approval decisions
	CheckedAt    time.Time          `json:"checked_at"`
	CheckLatency time.Duration      `json:"check_latency"`
}

权限检查结果 。

type PermissionContext

type PermissionContext struct {
	AgentID   string            `json:"agent_id"`
	UserID    string            `json:"user_id"`
	Roles     []string          `json:"roles"`
	ToolName  string            `json:"tool_name"`
	Arguments map[string]any    `json:"arguments,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	RequestIP string            `json:"request_ip,omitempty"`
	RequestAt time.Time         `json:"request_at"`
	TraceID   string            `json:"trace_id,omitempty"`
	SessionID string            `json:"session_id,omitempty"`
}

权限Context为权限检查提供了上下文.

func GetPermissionContext

func GetPermissionContext(ctx context.Context) (*PermissionContext, bool)

Get PermissionContext 从上下文检索权限上下文 。

type PermissionDecision

type PermissionDecision string

权限决定代表权限检查的结果.

const (
	PermissionAllow           PermissionDecision = "allow"
	PermissionDeny            PermissionDecision = "deny"
	PermissionRequireApproval PermissionDecision = "require_approval"
)

type PermissionManager

type PermissionManager interface {
	// 检查是否允许调用工具 。
	CheckPermission(ctx context.Context, permCtx *PermissionContext) (*PermissionCheckResult, error)

	// 添加规则添加了权限规则 。
	AddRule(rule *PermissionRule) error

	// 删除规则删除权限规则 。
	RemoveRule(ruleID string) error

	// Get Rule 以 ID 检索许可规则 。
	GetRule(ruleID string) (*PermissionRule, bool)

	// List Rules 列出所有许可规则 。
	ListRules() []*PermissionRule

	// 添加Role增加了一个角色.
	AddRole(role *Role) error

	// 删除 Role 删除一个角色 。
	RemoveRole(roleID string) error

	// GetRole通过ID检索角色.
	GetRole(roleID string) (*Role, bool)

	// AssignRoleToUser为用户分配一个角色.
	AssignRoleToUser(userID, roleID string) error

	// GetUserRoles为用户获得所有角色.
	GetUserRoles(userID string) []string

	// Set AgentPermission 设置特定代理权限.
	SetAgentPermission(perm *AgentPermission) error

	// Get AgentPermission获得特定代理权限.
	GetAgentPermission(agentID string) (*AgentPermission, bool)
}

权限管理器管理工具权限 。

type PermissionRule

type PermissionRule struct {
	ID          string             `json:"id"`
	Name        string             `json:"name"`
	Description string             `json:"description,omitempty"`
	ToolPattern string             `json:"tool_pattern"`          // Tool name pattern (supports wildcards)
	Decision    PermissionDecision `json:"decision"`              // allow/deny/require_approval
	Priority    int                `json:"priority"`              // Higher priority rules are evaluated first
	Conditions  []RuleCondition    `json:"conditions,omitempty"`  // Additional conditions
	ValidFrom   *time.Time         `json:"valid_from,omitempty"`  // Permission start time
	ValidUntil  *time.Time         `json:"valid_until,omitempty"` // Permission expiry time
	CreatedAt   time.Time          `json:"created_at"`
	UpdatedAt   time.Time          `json:"updated_at"`
}

权限规则定义了工具访问的权限规则.

type QueueHandler

type QueueHandler interface {
	Enqueue(ctx context.Context, rlCtx *RateLimitContext) error
	Dequeue(ctx context.Context) (*RateLimitContext, error)
}

QueueHandler 处理已排队的请求。

type RateLimitAction

type RateLimitAction string

RateLimitAction 定义超过速率限制时要采取的动作.

const (
	RateLimitActionReject  RateLimitAction = "reject"  // Reject the request immediately
	RateLimitActionQueue   RateLimitAction = "queue"   // Queue the request for later execution
	RateLimitActionDegrade RateLimitAction = "degrade" // Degrade service (e.g., use cached response)
)

type RateLimitConfig

type RateLimitConfig struct {
	MaxCalls int           // Maximum calls
	Window   time.Duration // Time window
}

RateLimitConfig 定义速率限制配置.

type RateLimitContext

type RateLimitContext struct {
	AgentID   string    `json:"agent_id"`
	UserID    string    `json:"user_id"`
	SessionID string    `json:"session_id,omitempty"`
	ToolName  string    `json:"tool_name"`
	RequestAt time.Time `json:"request_at"`
}

RateLimitContext 为速率限制检查提供上下文.

type RateLimitManager

type RateLimitManager interface {
	// CheckRateLimit 检查请求是否被允许。
	CheckRateLimit(ctx context.Context, rlCtx *RateLimitContext) (*RateLimitResult, error)

	// AddRule 添加速率限制规则。
	AddRule(rule *RateLimitRule) error

	// RemoveRule 删除速率限制规则。
	RemoveRule(ruleID string) error

	// GetRule 根据 ID 检索速率限制规则。
	GetRule(ruleID string) (*RateLimitRule, bool)

	// ListRules 列出所有速率限制规则。
	ListRules() []*RateLimitRule

	// GetStats 返回速率限制统计信息.
	GetStats(scope RateLimitScope, key string) *RateLimitStats

	// Reset 重置指定 key 的速率限制计数器。
	Reset(scope RateLimitScope, key string) error
}

RateLimitManager 管理速率限制.

type RateLimitResult

type RateLimitResult struct {
	Allowed        bool            `json:"allowed"`
	Rule           *RateLimitRule  `json:"rule,omitempty"`
	Action         RateLimitAction `json:"action,omitempty"`
	RetryAfter     time.Duration   `json:"retry_after,omitempty"`
	RemainingCalls int             `json:"remaining_calls"`
	ResetAt        time.Time       `json:"reset_at,omitempty"`
	Reason         string          `json:"reason,omitempty"`
}

RateLimitResult 包含速率限制检查的结果.

type RateLimitRule

type RateLimitRule struct {
	ID          string            `json:"id"`
	Name        string            `json:"name"`
	Description string            `json:"description,omitempty"`
	Scope       RateLimitScope    `json:"scope"`
	Strategy    RateLimitStrategy `json:"strategy"`
	ToolPattern string            `json:"tool_pattern,omitempty"` // For tool-specific limits
	MaxRequests int               `json:"max_requests"`           // Maximum requests allowed
	Window      time.Duration     `json:"window"`                 // Time window
	BurstSize   int               `json:"burst_size,omitempty"`   // For token bucket
	RefillRate  float64           `json:"refill_rate,omitempty"`  // Tokens per second for token bucket
	Action      RateLimitAction   `json:"action"`                 // Action when limit exceeded
	Priority    int               `json:"priority"`               // Higher priority rules are checked first
	Enabled     bool              `json:"enabled"`
	CreatedAt   time.Time         `json:"created_at"`
	UpdatedAt   time.Time         `json:"updated_at"`
}

RateLimitRule 定义速率限制规则.

func CreateAgentRateLimit

func CreateAgentRateLimit(id, name string, maxRequests int, window time.Duration) *RateLimitRule

CreateAgentRateLimit 创建按 Agent 的速率限制规则。

func CreateGlobalRateLimit

func CreateGlobalRateLimit(id, name string, maxRequests int, window time.Duration) *RateLimitRule

CreateGlobalRateLimit 创建全局速率限制规则。

func CreateTokenBucketRateLimit

func CreateTokenBucketRateLimit(id, name string, bucketSize int, refillRate float64) *RateLimitRule

CreateTokenBucketRateLimit 创建令牌桶速率限制规则。

func CreateToolRateLimit

func CreateToolRateLimit(id, name, toolPattern string, maxRequests int, window time.Duration) *RateLimitRule

CreateToolRateLimit 创建按工具的速率限制规则.

func CreateUserRateLimit

func CreateUserRateLimit(id, name string, maxRequests int, window time.Duration) *RateLimitRule

CreateUserRateLimit 创建按用户的速率限制规则.

type RateLimitScope

type RateLimitScope string

RateLimitScope 定义速率限制的作用域.

const (
	RateLimitScopeGlobal  RateLimitScope = "global"  // Global rate limit
	RateLimitScopeTool    RateLimitScope = "tool"    // Per-tool rate limit
	RateLimitScopeAgent   RateLimitScope = "agent"   // Per-agent rate limit
	RateLimitScopeUser    RateLimitScope = "user"    // Per-user rate limit
	RateLimitScopeSession RateLimitScope = "session" // Per-session rate limit
)

type RateLimitStats

type RateLimitStats struct {
	Scope            RateLimitScope `json:"scope"`
	Key              string         `json:"key"`
	TotalRequests    int64          `json:"total_requests"`
	AllowedRequests  int64          `json:"allowed_requests"`
	RejectedRequests int64          `json:"rejected_requests"`
	CurrentCount     int            `json:"current_count"`
	WindowStart      time.Time      `json:"window_start"`
	WindowEnd        time.Time      `json:"window_end"`
}

RateLimitStats 包含速率限制统计信息.

type RateLimitStrategy

type RateLimitStrategy string

RateLimitStrategy 定义限速策略.

const (
	RateLimitStrategySlidingWindow RateLimitStrategy = "sliding_window"
	RateLimitStrategyTokenBucket   RateLimitStrategy = "token_bucket"
	RateLimitStrategyFixedWindow   RateLimitStrategy = "fixed_window"
)

type ReActConfig

type ReActConfig struct {
	MaxIterations int  // Maximum iterations (prevents infinite loops)
	StopOnError   bool // Stop on tool execution error
}

ReActConfig 定义了 ReAct 循环配置.

type ReActExecutor

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

ReActExecutor 执行 ReAct(推理与行动)循环. 自动处理 LLM -> Tool -> LLM 多轮对话.

func NewReActExecutor

func NewReActExecutor(provider llm.Provider, toolExecutor ToolExecutor, config ReActConfig, logger *zap.Logger) *ReActExecutor

NewReActExecutor 创建 ReAct 执行器.

func (*ReActExecutor) Execute

Execute 运行 ReAct 循环,返回最终响应和所有步骤.

func (*ReActExecutor) ExecuteStream

func (r *ReActExecutor) ExecuteStream(ctx context.Context, req *llm.ChatRequest) (<-chan ReActStreamEvent, error)

ExecuteStream 执行流式 ReAct 循环.

func (*ReActExecutor) ExecuteWithTrace

func (r *ReActExecutor) ExecuteWithTrace(ctx context.Context, req *llm.ChatRequest) (*llm.ChatResponse, *ReActTrace, error)

ExecuteWithTrace 执行 ReAct 循环并返回完整跟踪信息.

type ReActStep

type ReActStep struct {
	StepNumber   int            `json:"step_number"`
	Thought      string         `json:"thought,omitempty"`
	Actions      []llm.ToolCall `json:"actions,omitempty"`
	Observations []ToolResult   `json:"observations,omitempty"`
	Timestamp    string         `json:"timestamp"`
	TokensUsed   int            `json:"tokens_used,omitempty"`
}

ReActStep 表示 ReAct 循环(Thought -> Action -> Observation)的一步.

type ReActStreamEvent

type ReActStreamEvent struct {
	Type          string            `json:"type"`
	Iteration     int               `json:"iteration,omitempty"`
	Chunk         *llm.StreamChunk  `json:"chunk,omitempty"`
	ToolCalls     []llm.ToolCall    `json:"tool_calls,omitempty"`
	ToolResults   []ToolResult      `json:"tool_results,omitempty"`
	FinalResponse *llm.ChatResponse `json:"final_response,omitempty"`
	Error         string            `json:"error,omitempty"`
}

ReActStreamEvent 表示流式 ReAct 循环事件.

type ReActTrace

type ReActTrace struct {
	TraceID      string      `json:"trace_id"`
	Steps        []ReActStep `json:"steps"`
	TotalTokens  int         `json:"total_tokens"`
	TotalSteps   int         `json:"total_steps"`
	Success      bool        `json:"success"`
	FinalAnswer  string      `json:"final_answer,omitempty"`
	ErrorMessage string      `json:"error_message,omitempty"`
}

ReActTrace 表示完整的 ReAct 执行追踪.

type ResilientExecutor

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

ResilientExecutor 具有回退能力的工具执行器

func NewResilientExecutor

func NewResilientExecutor(registry ToolRegistry, config *FallbackConfig, logger *zap.Logger) *ResilientExecutor

NewResilientExecutor 创建具有回退能力的执行器

func (*ResilientExecutor) Execute

func (e *ResilientExecutor) Execute(ctx context.Context, calls []llmpkg.ToolCall) []ToolResult

Execute 执行工具调用(带回退)

func (*ResilientExecutor) ExecuteOne

func (e *ResilientExecutor) ExecuteOne(ctx context.Context, call llmpkg.ToolCall) ToolResult

ExecuteOne 执行单个工具调用(带回退)

type Role

type Role struct {
	ID          string    `json:"id"`
	Name        string    `json:"name"`
	Description string    `json:"description,omitempty"`
	ParentRoles []string  `json:"parent_roles,omitempty"` // For role inheritance
	Permissions []string  `json:"permissions,omitempty"`  // Permission rule IDs
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

角色定义一个带有相关权限的角色.

type RuleCondition

type RuleCondition struct {
	Type     string `json:"type"`     // time_range, ip_range, parameter_check, etc.
	Operator string `json:"operator"` // eq, ne, gt, lt, contains, matches
	Field    string `json:"field"`    // Field to check
	Value    string `json:"value"`    // Expected value
}

规则条件定义了许可规则的额外条件.

type ScrapedImage

type ScrapedImage struct {
	Alt string `json:"alt"`
	URL string `json:"url"`
}

已删除 图像代表页面中找到的图像 。

type ScrapedLink struct {
	Text string `json:"text"`
	URL  string `json:"url"`
}

ScrapedLink代表页面中找到的超链接.

type SlidingWindowLimiter

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

SlidingWindowLimiter 实现滑动窗口速率限制.

func NewSlidingWindowLimiter

func NewSlidingWindowLimiter(maxRequests int, window time.Duration) *SlidingWindowLimiter

NewSlidingWindowLimiter 创建新的滑动窗口限制器.

func (*SlidingWindowLimiter) Allow

func (l *SlidingWindowLimiter) Allow() bool

Allow 检查请求是否被允许。

func (*SlidingWindowLimiter) Remaining

func (l *SlidingWindowLimiter) Remaining() int

Remaining 返回剩余请求数。

func (*SlidingWindowLimiter) Reset

func (l *SlidingWindowLimiter) Reset()

Reset 重置限制器。

func (*SlidingWindowLimiter) ResetAt

func (l *SlidingWindowLimiter) ResetAt() time.Time

ResetAt 返回窗口重置时间。

type TokenBucketLimiter

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

TokenBucketLimiter 实现令牌桶速率限制。

func NewTokenBucketLimiter

func NewTokenBucketLimiter(bucketSize int, refillRate float64) *TokenBucketLimiter

NewTokenBucketLimiter 创建新的令牌桶限制器.

func (*TokenBucketLimiter) Allow

func (l *TokenBucketLimiter) Allow() bool

Allow 检查请求是否被允许。

func (*TokenBucketLimiter) Remaining

func (l *TokenBucketLimiter) Remaining() int

Remaining 返回剩余令牌数。

func (*TokenBucketLimiter) Reset

func (l *TokenBucketLimiter) Reset()

Reset 重置限制器。

func (*TokenBucketLimiter) ResetAt

func (l *TokenBucketLimiter) ResetAt() time.Time

ResetAt 返回令牌桶恢复满容量的时间。

type TokenCounter

type TokenCounter interface {
	CountTokens(text string) (int, error)
}

TokenCounter 可选的 token 计数器接口。

注意:agent/context.TokenCounter 签名为 CountTokens(string) int(无 error), 本接口返回 error 以支持真实 tokenizer 的错误处理。两者无法统一。

type ToolCallChain

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

ToolCallChain 工具调用链(支持多步骤工具调用)

func NewToolCallChain

func NewToolCallChain(executor *ResilientExecutor, logger *zap.Logger) *ToolCallChain

NewToolCallChain 创建工具调用链

func (*ToolCallChain) ExecuteChain

func (c *ToolCallChain) ExecuteChain(ctx context.Context, calls []llmpkg.ToolCall) ([]ToolResult, error)

ExecuteChain 执行工具调用链 支持工具之间的依赖关系,前一个工具的输出可以作为后一个工具的输入

type ToolCallWithDeps

type ToolCallWithDeps struct {
	Call         llmpkg.ToolCall                                     `json:"call"`
	DependsOn    []string                                            `json:"depends_on,omitempty"` // IDs of tool calls that must complete first
	ResultMapper func(results map[string]ToolResult) json.RawMessage `json:"-"`                    // Optional: modify args based on deps
}

执行与依赖关系执行工具 。 依赖性被指定为工具调用ID,在调用之前必须完成.

type ToolCost

type ToolCost struct {
	ToolName    string   `json:"tool_name"`
	BaseCost    float64  `json:"base_cost"`     // Base cost per call
	CostPerUnit float64  `json:"cost_per_unit"` // Cost per unit (e.g., per token)
	Unit        CostUnit `json:"unit"`          // Cost unit
	Description string   `json:"description,omitempty"`
}

ToolCost 定义工具的成本配置.

func CreateToolCost

func CreateToolCost(toolName string, baseCost, costPerUnit float64) *ToolCost

CreateToolCost 创建工具成本配置。

type ToolCostSummary

type ToolCostSummary struct {
	ToolName  string  `json:"tool_name"`
	TotalCost float64 `json:"total_cost"`
	CallCount int64   `json:"call_count"`
	AvgCost   float64 `json:"avg_cost"`
}

ToolCostSummary 汇总工具的成本。

type ToolExecutor

type ToolExecutor interface {
	Execute(ctx context.Context, calls []llm.ToolCall) []ToolResult
	ExecuteOne(ctx context.Context, call llm.ToolCall) ToolResult
}

ToolExecutor 定义工具执行器接口.

type ToolFunc

type ToolFunc func(ctx context.Context, args json.RawMessage) (json.RawMessage, error)

ToolFunc 定义工具函数签名.

type ToolMetadata

type ToolMetadata struct {
	Schema      llm.ToolSchema   // Tool JSON Schema
	Permission  string           // Required permission (optional)
	RateLimit   *RateLimitConfig // Rate limit config (optional)
	Timeout     time.Duration    // Execution timeout (default 30s)
	Description string           // Detailed description
}

ToolMetadata 描述工具元数据.

type ToolRegistry

type ToolRegistry interface {
	Register(name string, fn ToolFunc, metadata ToolMetadata) error
	Unregister(name string) error
	Get(name string) (ToolFunc, ToolMetadata, error)
	List() []llm.ToolSchema
	Has(name string) bool
}

ToolRegistry 定义工具注册接口.

type ToolResult

type ToolResult struct {
	ToolCallID string          `json:"tool_call_id"`
	Name       string          `json:"name"`
	Result     json.RawMessage `json:"result"`
	Error      string          `json:"error,omitempty"`
	Duration   time.Duration   `json:"duration"`
}

ToolResult 表示工具执行结果.

func (ToolResult) ToJSON

func (tr ToolResult) ToJSON() (json.RawMessage, error)

ToJSON 将 ToolResult 序列化为 JSON.

func (ToolResult) ToMessage

func (tr ToolResult) ToMessage() llm.Message

ToMessage 将 ToolResult 转换为 LLM 消息.

type WebScrapeOptions

type WebScrapeOptions struct {
	Format           string   `json:"format"`                      // Output format: "markdown", "text", "html"
	IncludeLinks     bool     `json:"include_links,omitempty"`     // Include hyperlinks in output
	IncludeImages    bool     `json:"include_images,omitempty"`    // Include image descriptions
	MaxLength        int      `json:"max_length,omitempty"`        // Maximum content length in characters
	WaitForJS        bool     `json:"wait_for_js,omitempty"`       // Wait for JavaScript rendering
	Selectors        []string `json:"selectors,omitempty"`         // CSS selectors to extract specific elements
	ExcludeSelectors []string `json:"exclude_selectors,omitempty"` // CSS selectors to exclude
}

WebScrape 选项配置了网络刮擦请求 。

func DefaultWebScrapeOptions

func DefaultWebScrapeOptions() WebScrapeOptions

默认WebScrape 选项返回明智的默认 。

type WebScrapeProvider

type WebScrapeProvider interface {
	// Scrape 从 URL 获取并提取内容 。
	Scrape(ctx context.Context, url string, opts WebScrapeOptions) (*WebScrapeResult, error)
	// 名称返回提供者名称 。
	Name() string
}

WebScrape Provider定义了网络刮取后端的界面. 执行器可以包装Firecrawl,Playwright,Colly,或者自定义的刮取器.

type WebScrapeResult

type WebScrapeResult struct {
	URL       string         `json:"url"`
	Title     string         `json:"title"`
	Content   string         `json:"content"`
	Format    string         `json:"format"`
	WordCount int            `json:"word_count"`
	Links     []ScrapedLink  `json:"links,omitempty"`
	Images    []ScrapedImage `json:"images,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
	ScrapedAt time.Time      `json:"scraped_at"`
}

WebScrapeResult 代表从 URL 删除的内容 。

type WebScrapeToolConfig

type WebScrapeToolConfig struct {
	Provider    WebScrapeProvider // Scraping backend provider
	DefaultOpts WebScrapeOptions  // Default scrape options
	Timeout     time.Duration     // Per-scrape timeout
	RateLimit   *RateLimitConfig  // Rate limiting
}

WebScrapeToolConfig 配置了网页刮擦工具.

func DefaultWebScrapeToolConfig

func DefaultWebScrapeToolConfig() WebScrapeToolConfig

默认WebScrapeToolConfig返回合理的默认值 。

type WebSearchOptions

type WebSearchOptions struct {
	MaxResults     int      `json:"max_results"`               // Maximum number of results (default: 10)
	Language       string   `json:"language,omitempty"`        // Language code (e.g., "en", "zh")
	Region         string   `json:"region,omitempty"`          // Region code (e.g., "us", "cn")
	SafeSearch     bool     `json:"safe_search,omitempty"`     // Enable safe search filtering
	TimeRange      string   `json:"time_range,omitempty"`      // Time range: "day", "week", "month", "year"
	Domains        []string `json:"domains,omitempty"`         // Restrict to specific domains
	ExcludeDomains []string `json:"exclude_domains,omitempty"` // Exclude specific domains
}

WebSearch 选项配置网络搜索请求。

func DefaultWebSearchOptions

func DefaultWebSearchOptions() WebSearchOptions

默认WebSearch 选项返回合理的默认值 。

type WebSearchProvider

type WebSearchProvider interface {
	// 搜索进行网络搜索并返回结果 。
	Search(ctx context.Context, query string, opts WebSearchOptions) ([]WebSearchResult, error)
	// 名称返回提供者名称 。
	Name() string
}

WebSearch Provider定义了网络搜索后端的界面. 执行可以将Firecrawl,SerpAPI,Tavily,Jina,Google自定义搜索等包装.

type WebSearchResult

type WebSearchResult struct {
	Title       string         `json:"title"`
	URL         string         `json:"url"`
	Snippet     string         `json:"snippet"`
	Content     string         `json:"content,omitempty"`      // Full content if available
	PublishedAt string         `json:"published_at,omitempty"` // Publication date
	Score       float64        `json:"score,omitempty"`        // Relevance score (0-1)
	Metadata    map[string]any `json:"metadata,omitempty"`
}

WebSearchResult代表单一搜索结果.

type WebSearchToolConfig

type WebSearchToolConfig struct {
	Provider    WebSearchProvider // Search backend provider
	DefaultOpts WebSearchOptions  // Default search options
	Timeout     time.Duration     // Per-search timeout
	RateLimit   *RateLimitConfig  // Rate limiting
}

WebSearchToolFig 配置了网络搜索工具.

func DefaultWebSearchToolConfig

func DefaultWebSearchToolConfig() WebSearchToolConfig

默认WebSearch ToolFig 返回合理的默认值 。

Jump to

Keyboard shortcuts

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