tools

package
v0.70.0 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package tools provides resilient tool execution for AI agents. This package implements retry logic, fallback strategies, and metrics reporting.

Package tools provides fallback strategies for tool execution failures.

Index

Constants

View Source
const (
	// DefaultTimezone is used when no timezone is specified.
	DefaultTimezone = "Asia/Shanghai"
)

Variables

View Source
var DefaultFallbackRules = map[string]FallbackFunc{
	"memo_search":    fallbackMemoSearch,
	"schedule_query": fallbackScheduleQuery,
	"schedule_add":   fallbackScheduleAdd,
	"memo_create":    fallbackMemoCreate,
}

DefaultFallbackRules contains the default fallback strategies for common tools.

Functions

func ClearScheduleCache

func ClearScheduleCache()

ClearScheduleCache clears all cached schedule data.

func SetCachedSchedules

func SetCachedSchedules(userID int32, query string, data string)

SetCachedSchedules stores schedule data in the cache with user isolation. This should be called after successful schedule queries.

func WithUserID

func WithUserID(ctx context.Context, userID int32) context.Context

WithUserID adds user ID to context for cache isolation.

Types

type ActivityPattern

type ActivityPattern struct {
	Title           string `json:"title"`
	TypicalLocation string `json:"typical_location,omitempty"`
	TypicalDuration int    `json:"typical_duration_minutes"`
	TypicalHour     int    `json:"typical_hour"`
	Frequency       int    `json:"frequency"`
}

ActivityPattern represents a detected activity pattern.

type ClaudeCodeInput

type ClaudeCodeInput struct {
	Prompt string `json:"prompt"` // Required: The coding task or question
}

ClaudeCodeInput represents the input for Claude Code CLI.

type ClaudeCodeSession

type ClaudeCodeSession struct {
	CreatedAt   time.Time
	SessionName string
	WorkDir     string
	UserID      int32
	FileChanges atomic.Int32
}

ClaudeCodeSession manages a Claude Code CLI session for a user. Maintains session state and resource limits. Uses atomic operations for FileChanges to ensure thread safety.

type ClaudeCodeTool

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

ClaudeCodeTool integrates Claude Code CLI for code-related tasks. Only available when Geek Mode is enabled by the user. Uses sync.Map for concurrent-safe session storage.

func NewClaudeCodeTool

func NewClaudeCodeTool(
	enabled bool,
	workDir string,
	userIDGetter func(ctx context.Context) int32,
) (*ClaudeCodeTool, error)

NewClaudeCodeTool creates a new Claude Code CLI integration tool. NewClaudeCodeTool 创建一个新的 Claude Code CLI 集成工具。

The tool requires Claude Code CLI to be installed on the system. When disabled, Run() returns a friendly error message.

func (*ClaudeCodeTool) CleanupOldSessions

func (t *ClaudeCodeTool) CleanupOldSessions(olderThan time.Duration)

CleanupOldSessions removes sessions older than the specified duration. Uses sync.Map.Range for concurrent-safe iteration.

func (*ClaudeCodeTool) Description

func (t *ClaudeCodeTool) Description() string

Description returns a description of what the tool does. Description 返回工具描述。

func (*ClaudeCodeTool) IsEnabled

func (t *ClaudeCodeTool) IsEnabled() bool

IsEnabled returns whether the tool is enabled.

func (*ClaudeCodeTool) Name

func (t *ClaudeCodeTool) Name() string

Name returns the name of the tool. Name 返回工具名称。

func (*ClaudeCodeTool) Run

func (t *ClaudeCodeTool) Run(ctx context.Context, input string) (string, error)

Run executes the Claude Code CLI tool. Run 执行 Claude Code CLI 工具。

type ExecutionResult

type ExecutionResult struct {
	Result        *Result
	Error         error
	FallbackError error // Error from fallback execution, if any
	Attempts      int
	TotalLatency  time.Duration
	UsedFallback  bool
}

ExecutionResult contains detailed information about a tool execution.

type ExecutorOption

type ExecutorOption func(*ResilientToolExecutor)

ExecutorOption configures a ResilientToolExecutor.

func WithFallbackRules

func WithFallbackRules(rules map[string]FallbackFunc) ExecutorOption

WithFallbackRules sets custom fallback rules. The rules map is copied to avoid concurrent modification issues.

func WithMaxRetries

func WithMaxRetries(n int) ExecutorOption

WithMaxRetries sets the maximum number of retry attempts.

func WithRetryDelay

func WithRetryDelay(d time.Duration) ExecutorOption

WithRetryDelay sets the delay between retry attempts.

func WithTimeout

func WithTimeout(d time.Duration) ExecutorOption

WithTimeout sets the timeout for each execution attempt.

type FallbackFunc

type FallbackFunc func(ctx context.Context, tool Tool, input string, err error) (*Result, error)

FallbackFunc defines the signature for fallback handlers. It receives the context, the failed tool, the original input, and the error. It returns a graceful degradation result.

func ErrorAwareFallback

func ErrorAwareFallback(baseMessage string) FallbackFunc

ErrorAwareFallback creates a fallback that logs error details but returns a safe message. Error details are logged for debugging but not exposed to users.

func GenericFallback

func GenericFallback(message string) FallbackFunc

GenericFallback creates a generic fallback handler with a custom message.

type FallbackRegistry

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

FallbackRegistry allows dynamic registration of fallback handlers.

func NewFallbackRegistry

func NewFallbackRegistry() *FallbackRegistry

NewFallbackRegistry creates a new FallbackRegistry with default handlers.

func (*FallbackRegistry) Get

func (r *FallbackRegistry) Get(toolName string) (FallbackFunc, bool)

Get retrieves the fallback handler for the given tool.

func (*FallbackRegistry) GetAll

func (r *FallbackRegistry) GetAll() map[string]FallbackFunc

GetAll returns a copy of all registered handlers.

func (*FallbackRegistry) Register

func (r *FallbackRegistry) Register(toolName string, handler FallbackFunc)

Register adds or replaces a fallback handler for the given tool.

type FindFreeTimeTool

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

FindFreeTimeTool finds available time slots for scheduling.

func NewFindFreeTimeTool

func NewFindFreeTimeTool(service schedule.Service, userIDGetter func(ctx context.Context) int32) *FindFreeTimeTool

NewFindFreeTimeTool creates a new find free time tool.

func (*FindFreeTimeTool) Description

func (t *FindFreeTimeTool) Description() string

Description returns the tool description for the LLM.

func (*FindFreeTimeTool) InputType

func (t *FindFreeTimeTool) InputType() map[string]interface{}

InputType returns the expected input type schema.

func (*FindFreeTimeTool) Name

func (t *FindFreeTimeTool) Name() string

Name returns the tool name.

func (*FindFreeTimeTool) Run

func (t *FindFreeTimeTool) Run(ctx context.Context, inputJSON string) (string, error)

Run executes the find free time tool.

func (*FindFreeTimeTool) SetTimezone

func (t *FindFreeTimeTool) SetTimezone(timezone string)

SetTimezone sets the user's timezone for date parsing.

type MemoSearchInput

type MemoSearchInput struct {
	Query    string  `json:"query"`
	Strategy string  `json:"strategy,omitempty"`
	Limit    int     `json:"limit,omitempty"`
	MinScore float32 `json:"min_score,omitempty"`
}

MemoSearchInput represents the input for memo search. MemoSearchInput 表示笔记搜索的输入。

type MemoSearchTool

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

MemoSearchTool searches for memos using semantic and keyword search. MemoSearchTool 使用语义和关键词搜索来查找笔记。

func NewMemoSearchTool

func NewMemoSearchTool(
	retriever *retrieval.AdaptiveRetriever,
	userIDGetter func(ctx context.Context) int32,
) (*MemoSearchTool, error)

NewMemoSearchTool creates a new memo search tool. NewMemoSearchTool 创建一个新的笔记搜索工具。

func (*MemoSearchTool) Description

func (t *MemoSearchTool) Description() string

Description returns a description of what the tool does. Description 返回工具描述。

func (*MemoSearchTool) Name

func (t *MemoSearchTool) Name() string

Name returns the name of the tool. Name 返回工具名称。

func (*MemoSearchTool) Run

func (t *MemoSearchTool) Run(ctx context.Context, input string) (string, error)

Run executes the memo search tool. Run 执行笔记搜索工具。

func (*MemoSearchTool) RunWithStructuredResult

func (t *MemoSearchTool) RunWithStructuredResult(ctx context.Context, input string) (*MemoSearchToolResult, error)

RunWithStructuredResult executes the tool and returns a structured result. RunWithStructuredResult 执行工具并返回结构化结果。

type MemoSearchToolResult

type MemoSearchToolResult struct {
	Query string        `json:"query"`
	Memos []MemoSummary `json:"memos"`
	Count int           `json:"count"`
}

MemoSearchToolResult represents the structured result of memo search. MemoSearchToolResult 表示笔记搜索的结构化结果。

type MemoSummary

type MemoSummary struct {
	UID     string  `json:"uid"`
	Content string  `json:"content"`
	Score   float32 `json:"score"`
}

MemoSummary represents a simplified memo for query results.

type PreferredTimeSlot

type PreferredTimeSlot struct {
	DayOfWeek string `json:"day_of_week,omitempty"`
	Hour      int    `json:"hour"`
	Frequency int    `json:"frequency"`
}

PreferredTimeSlot represents a preferred time slot.

type ResilientToolExecutor

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

ResilientToolExecutor provides retry and fallback capabilities for tool execution.

func NewResilientToolExecutor

func NewResilientToolExecutor(metricsService metrics.MetricsService, opts ...ExecutorOption) *ResilientToolExecutor

NewResilientToolExecutor creates a new ResilientToolExecutor with the given options.

func (*ResilientToolExecutor) Execute

func (e *ResilientToolExecutor) Execute(ctx context.Context, tool Tool, input string) (*Result, error)

Execute runs the tool with retry and fallback support. It attempts to execute the tool, retrying on transient errors. If all attempts fail, it executes the fallback strategy if available.

func (*ResilientToolExecutor) ExecuteDetailed

func (e *ResilientToolExecutor) ExecuteDetailed(ctx context.Context, tool Tool, input string) ExecutionResult

ExecuteDetailed runs the tool and returns detailed execution information.

type Result

type Result struct {
	Data    any    `json:"data,omitempty"`
	Output  string `json:"output"`
	Success bool   `json:"success"`
}

Result represents the output of a tool execution.

type ScheduleAddTool

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

ScheduleAddTool creates a new schedule event.

func NewScheduleAddTool

func NewScheduleAddTool(service schedule.Service, userIDGetter func(ctx context.Context) int32) *ScheduleAddTool

NewScheduleAddTool creates a new schedule add tool.

func (*ScheduleAddTool) Description

func (t *ScheduleAddTool) Description() string

Description returns the tool description for the LLM.

func (*ScheduleAddTool) InputType

func (t *ScheduleAddTool) InputType() map[string]interface{}

InputType returns the expected input type schema.

func (*ScheduleAddTool) Name

func (t *ScheduleAddTool) Name() string

Name returns the tool name.

func (*ScheduleAddTool) Run

func (t *ScheduleAddTool) Run(ctx context.Context, inputJSON string) (string, error)

Run executes the tool.

func (*ScheduleAddTool) Validate

func (t *ScheduleAddTool) Validate(ctx context.Context, inputJSON string) error

Validate runs before execution to check input validity.

type ScheduleQueryTool

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

ScheduleQueryTool searches for schedule events within a specific time range.

func NewScheduleQueryTool

func NewScheduleQueryTool(service schedule.Service, userIDGetter func(ctx context.Context) int32) *ScheduleQueryTool

NewScheduleQueryTool creates a new schedule query tool.

func (*ScheduleQueryTool) Description

func (t *ScheduleQueryTool) Description() string

Description returns the tool description for the LLM.

func (*ScheduleQueryTool) InputType

func (t *ScheduleQueryTool) InputType() map[string]interface{}

InputType returns the expected input type schema.

func (*ScheduleQueryTool) Name

func (t *ScheduleQueryTool) Name() string

Name returns the tool name.

func (*ScheduleQueryTool) Run

func (t *ScheduleQueryTool) Run(ctx context.Context, inputJSON string) (string, error)

Run executes the tool.

func (*ScheduleQueryTool) RunWithStructuredResult

func (t *ScheduleQueryTool) RunWithStructuredResult(ctx context.Context, inputJSON string) (*ScheduleQueryToolResult, error)

RunWithStructuredResult executes the tool and returns a structured result. RunWithStructuredResult 执行工具并返回结构化结果。

func (*ScheduleQueryTool) Validate

func (t *ScheduleQueryTool) Validate(ctx context.Context, inputJSON string) error

Validate runs before execution to check input validity.

type ScheduleQueryToolResult

type ScheduleQueryToolResult struct {
	Query                string            `json:"query"`
	TimeRangeDescription string            `json:"time_range_description"`
	QueryType            string            `json:"query_type"`
	Schedules            []ScheduleSummary `json:"schedules"`
	Count                int               `json:"count"`
}

ScheduleQueryToolResult represents the structured result of schedule query.

type ScheduleSummary

type ScheduleSummary struct {
	UID      string `json:"uid"`
	Title    string `json:"title"`
	Location string `json:"location,omitempty"`
	Status   string `json:"status"`
	StartTs  int64  `json:"start_ts"`
	EndTs    int64  `json:"end_ts"`
	AllDay   bool   `json:"all_day"`
}

ScheduleSummary represents a simplified schedule for query results.

type ScheduleUpdateTool

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

ScheduleUpdateTool updates an existing schedule event.

func NewScheduleUpdateTool

func NewScheduleUpdateTool(service schedule.Service, userIDGetter func(ctx context.Context) int32) *ScheduleUpdateTool

NewScheduleUpdateTool creates a new schedule update tool.

func (*ScheduleUpdateTool) Description

func (t *ScheduleUpdateTool) Description() string

Description returns the tool description for the LLM.

func (*ScheduleUpdateTool) InputType

func (t *ScheduleUpdateTool) InputType() map[string]interface{}

InputType returns the expected input type schema.

func (*ScheduleUpdateTool) Name

func (t *ScheduleUpdateTool) Name() string

Name returns the tool name.

func (*ScheduleUpdateTool) Run

func (t *ScheduleUpdateTool) Run(ctx context.Context, inputJSON string) (string, error)

Run executes the tool.

type Tool

type Tool interface {
	// Name returns the tool's identifier.
	Name() string
	// Run executes the tool with the given input.
	Run(ctx context.Context, input string) (*Result, error)
}

Tool defines the interface for executable tools.

type UserPreferenceInput

type UserPreferenceInput struct {
	// Query type: "duration", "time_slot", "location", "all"
	QueryType string `json:"query_type"`
	// Optional: specific activity type to query (e.g., "meeting", "exercise")
	ActivityType string `json:"activity_type,omitempty"`
}

UserPreferenceInput is the input for the preference tool.

type UserPreferenceOutput

type UserPreferenceOutput struct {
	// Average duration in minutes for different activities
	AverageDurations map[string]int `json:"average_durations"`
	// Preferred time slots (hour of day)
	PreferredTimeSlots []PreferredTimeSlot `json:"preferred_time_slots"`
	// Frequently used locations
	FrequentLocations []string `json:"frequent_locations"`
	// Activity patterns
	ActivityPatterns []ActivityPattern `json:"activity_patterns"`
}

UserPreferenceOutput contains learned user preferences.

type UserPreferenceTool

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

UserPreferenceTool analyzes user's schedule history to learn preferences. It helps the schedule agent auto-fill default values based on user habits.

func NewUserPreferenceTool

func NewUserPreferenceTool(scheduleSvc schedule.Service, getUserID func(ctx context.Context) int32) *UserPreferenceTool

NewUserPreferenceTool creates a new UserPreferenceTool.

func (*UserPreferenceTool) Description

func (t *UserPreferenceTool) Description() string

Description returns the tool description.

func (*UserPreferenceTool) InputType

func (t *UserPreferenceTool) InputType() map[string]interface{}

InputType returns the JSON Schema for the input.

func (*UserPreferenceTool) Name

func (t *UserPreferenceTool) Name() string

Name returns the tool name.

func (*UserPreferenceTool) Run

func (t *UserPreferenceTool) Run(ctx context.Context, input string) (string, error)

Run executes the tool.

Jump to

Keyboard shortcuts

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