tools

package
v0.0.0-...-52cc1ce Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package tools provides concrete implementations of tool types.

Package tools provides local search tool implementation.

Package tools provides concrete implementations of tool types.

Package tools provides enhanced FunctionTool implementation with parameter validation and JSON schema generation.

Package tools provides examples of using the enhanced FunctionTool.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddNumbers

func AddNumbers(a, b int) int

AddNumbers is a simple function that adds two numbers.

func AdvancedCalculation

func AdvancedCalculation(numbers []float64, operation string) (float64, string, error)

AdvancedCalculation demonstrates a complex function with multiple return values.

func BenchmarkFunction

func BenchmarkFunction(iterations int, delay string) (string, error)

BenchmarkFunction is a simple function for performance testing.

func CalculateWithContext

func CalculateWithContext(ctx context.Context, operation string, a, b float64) (float64, error)

CalculateWithContext demonstrates using context in a tool function.

func ConcurrentProcessor

func ConcurrentProcessor(ctx context.Context, toolCtx *core.ToolContext, items []string, workers int) (map[string]interface{}, error)

ConcurrentProcessor demonstrates concurrent processing with proper cancellation.

func ExampleUsage

func ExampleUsage()

ExampleUsage demonstrates how to create and use enhanced function tools.

func FileOperationWithArtifacts

func FileOperationWithArtifacts(ctx context.Context, toolCtx *core.ToolContext, filename string, content string, operation string) (string, error)

FileOperationWithArtifacts demonstrates using ToolContext for artifacts.

func FileProcessingTask

func FileProcessingTask(ctx context.Context, toolCtx *core.ToolContext, filenames []string, operation string) (map[string]interface{}, error)

FileProcessingTask demonstrates file processing with cancellation support.

func FormatTextWithToolContext

func FormatTextWithToolContext(toolCtx *core.ToolContext, text string, format string) (string, error)

FormatTextWithToolContext demonstrates using ToolContext in a function.

func LongRunningTask

func LongRunningTask(ctx context.Context, toolCtx *core.ToolContext, steps int, stepDuration string) (map[string]interface{}, error)

LongRunningTask demonstrates a more complex long-running operation with progress reporting.

func NetworkRequestWithRetry

func NetworkRequestWithRetry(ctx context.Context, url string, maxRetries int, retryDelay string) (map[string]interface{}, error)

NetworkRequestWithRetry demonstrates network operations with cancellation and retry logic.

func ProcessItems

func ProcessItems(items []string, operation string) ([]string, error)

ProcessItems demonstrates working with arrays/slices.

func TimerFunction

func TimerFunction(ctx context.Context, duration string, message string) (string, error)

TimerFunction demonstrates a long-running operation with proper cancellation.

func ValidateFunction

func ValidateFunction(fn interface{}) error

ValidateFunction validates that a function is suitable for wrapping as a tool.

func ValidationExamples

func ValidationExamples()

ValidationExamples demonstrates function validation.

Types

type AgentTool

type AgentTool struct {
	*BaseToolImpl
	// contains filtered or unexported fields
}

AgentTool wraps another agent as a tool.

func NewAgentTool

func NewAgentTool(agent core.BaseAgent) *AgentTool

NewAgentTool creates a new agent tool.

func (*AgentTool) GetDeclaration

func (t *AgentTool) GetDeclaration() *core.FunctionDeclaration

GetDeclaration returns the function declaration for the agent tool.

func (*AgentTool) RunAsync

func (t *AgentTool) RunAsync(toolCtx *core.ToolContext, args map[string]any) (any, error)

RunAsync executes the wrapped agent with the given request.

type AgentToolConfig

type AgentToolConfig struct {
	// Timeout specifies the maximum duration for agent execution
	Timeout time.Duration
	// IsolateState determines if state changes should be isolated
	IsolateState bool
	// ErrorStrategy defines how errors are handled
	ErrorStrategy ErrorStrategy
	// CustomInstruction provides additional context for the agent
	CustomInstruction string
}

AgentToolConfig configures the behavior of an EnhancedAgentTool.

func DefaultAgentToolConfig

func DefaultAgentToolConfig() *AgentToolConfig

DefaultAgentToolConfig returns a sensible default configuration.

type BaseToolImpl

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

BaseToolImpl provides a basic implementation of the BaseTool interface.

func NewBaseTool

func NewBaseTool(name, description string) *BaseToolImpl

NewBaseTool creates a new base tool implementation.

func (*BaseToolImpl) Description

func (t *BaseToolImpl) Description() string

Description returns a description of the tool's purpose.

func (*BaseToolImpl) GetDeclaration

func (t *BaseToolImpl) GetDeclaration() *core.FunctionDeclaration

GetDeclaration returns the function declaration for LLM integration. Base implementation returns nil - concrete tools should override this.

func (*BaseToolImpl) IsLongRunning

func (t *BaseToolImpl) IsLongRunning() bool

IsLongRunning indicates if this is a long-running operation.

func (*BaseToolImpl) Name

func (t *BaseToolImpl) Name() string

Name returns the tool's unique identifier.

func (*BaseToolImpl) ProcessLLMRequest

func (t *BaseToolImpl) ProcessLLMRequest(toolCtx *core.ToolContext, request *core.LLMRequest) error

ProcessLLMRequest allows the tool to modify LLM requests. Base implementation does nothing - tools can override as needed.

func (*BaseToolImpl) RunAsync

func (t *BaseToolImpl) RunAsync(toolCtx *core.ToolContext, args map[string]any) (any, error)

RunAsync executes the tool with the given arguments and context. Base implementation returns an error - concrete tools must override this.

func (*BaseToolImpl) SetLongRunning

func (t *BaseToolImpl) SetLongRunning(longRunning bool)

SetLongRunning sets whether this tool is long-running.

type DuckDuckGoResponse

type DuckDuckGoResponse struct {
	Abstract      string                   `json:"Abstract"`
	AbstractText  string                   `json:"AbstractText"`
	AbstractURL   string                   `json:"AbstractURL"`
	Answer        string                   `json:"Answer"`
	AnswerType    string                   `json:"AnswerType"`
	Definition    string                   `json:"Definition"`
	Entity        string                   `json:"Entity"`
	Heading       string                   `json:"Heading"`
	Image         string                   `json:"Image"`
	ImageHeight   interface{}              `json:"ImageHeight"` // Can be int or string
	ImageWidth    interface{}              `json:"ImageWidth"`  // Can be int or string
	Infobox       interface{}              `json:"Infobox"`     // Can be map or string
	Redirect      string                   `json:"Redirect"`
	RelatedTopics []map[string]interface{} `json:"RelatedTopics"`
	Results       []map[string]interface{} `json:"Results"`
	Type          string                   `json:"Type"`
}

DuckDuckGoResponse represents the response from DuckDuckGo API

type DuckDuckGoSearchTool

type DuckDuckGoSearchTool struct {
	*BaseToolImpl
	// contains filtered or unexported fields
}

DuckDuckGoSearchTool implements a local web search using DuckDuckGo Instant Answer API

func NewDuckDuckGoSearchTool

func NewDuckDuckGoSearchTool() *DuckDuckGoSearchTool

NewDuckDuckGoSearchTool creates a new local search tool

func (*DuckDuckGoSearchTool) GetDeclaration

func (t *DuckDuckGoSearchTool) GetDeclaration() *core.FunctionDeclaration

GetDeclaration returns the function declaration for this tool

func (*DuckDuckGoSearchTool) ProcessLLMRequest

func (t *DuckDuckGoSearchTool) ProcessLLMRequest(toolCtx *core.ToolContext, request *core.LLMRequest) error

ProcessLLMRequest is not needed for local tools

func (*DuckDuckGoSearchTool) RunAsync

func (t *DuckDuckGoSearchTool) RunAsync(toolCtx *core.ToolContext, args map[string]any) (any, error)

RunAsync executes the search

type EnhancedAgentTool

type EnhancedAgentTool struct {
	*BaseToolImpl
	// contains filtered or unexported fields
}

EnhancedAgentTool wraps another agent as a tool with enhanced capabilities. This tool enables multi-agent workflows by allowing one agent to call another agent as a tool.

func NewEnhancedAgentTool

func NewEnhancedAgentTool(agent core.BaseAgent) *EnhancedAgentTool

NewEnhancedAgentTool creates a new enhanced agent tool with default configuration.

func NewEnhancedAgentToolWithConfig

func NewEnhancedAgentToolWithConfig(agent core.BaseAgent, config *AgentToolConfig) *EnhancedAgentTool

NewEnhancedAgentToolWithConfig creates a new enhanced agent tool with custom configuration.

func (*EnhancedAgentTool) Agent

func (t *EnhancedAgentTool) Agent() core.BaseAgent

Agent returns the wrapped agent.

func (*EnhancedAgentTool) GetDeclaration

func (t *EnhancedAgentTool) GetDeclaration() *core.FunctionDeclaration

GetDeclaration returns the function declaration for the enhanced agent tool.

func (*EnhancedAgentTool) RunAsync

func (t *EnhancedAgentTool) RunAsync(ctx context.Context, args map[string]any, toolCtx *core.ToolContext) (any, error)

RunAsync executes the wrapped agent with the given request and enhanced error handling.

func (*EnhancedAgentTool) SetErrorStrategy

func (t *EnhancedAgentTool) SetErrorStrategy(strategy ErrorStrategy)

SetErrorStrategy configures the error handling strategy.

func (*EnhancedAgentTool) SetIsolateState

func (t *EnhancedAgentTool) SetIsolateState(isolate bool)

SetIsolateState configures whether state changes should be isolated.

func (*EnhancedAgentTool) SetTimeout

func (t *EnhancedAgentTool) SetTimeout(timeout time.Duration)

SetTimeout updates the execution timeout.

type EnhancedFunctionSchema

type EnhancedFunctionSchema struct {
	Parameters map[string]*ParameterSchema `json:"parameters"`
	Required   []string                    `json:"required"`
}

EnhancedFunctionSchema provides detailed schema information for function parameters.

type EnhancedFunctionTool

type EnhancedFunctionTool struct {
	*BaseToolImpl
	// contains filtered or unexported fields
}

EnhancedFunctionTool provides an improved version of FunctionTool with: - Proper parameter name extraction from function signature - Enhanced JSON schema generation - Parameter validation - Support for optional parameters with default values - Better error handling and debugging

func NewEnhancedFunctionTool

func NewEnhancedFunctionTool(name, description string, fn interface{}) (*EnhancedFunctionTool, error)

NewEnhancedFunctionTool creates a new enhanced function tool from a Go function. It automatically extracts parameter names, types, and generates JSON schema.

func (*EnhancedFunctionTool) GetDeclaration

func (t *EnhancedFunctionTool) GetDeclaration() *core.FunctionDeclaration

GetDeclaration returns the function declaration for LLM integration.

func (*EnhancedFunctionTool) GetMetadata

func (t *EnhancedFunctionTool) GetMetadata() *FunctionMetadata

GetMetadata returns metadata about the wrapped function.

func (*EnhancedFunctionTool) RunAsync

func (t *EnhancedFunctionTool) RunAsync(ctx context.Context, args map[string]any, toolCtx *core.ToolContext) (any, error)

RunAsync executes the wrapped function with parameter validation and type conversion.

func (*EnhancedFunctionTool) SetIgnoreParams

func (t *EnhancedFunctionTool) SetIgnoreParams(params []string)

SetIgnoreParams sets the list of parameter names to ignore in schema generation.

type ErrorStrategy

type ErrorStrategy int

ErrorStrategy defines how the tool handles errors from the wrapped agent.

const (
	// ErrorStrategyPropagate propagates errors up to the calling agent
	ErrorStrategyPropagate ErrorStrategy = iota
	// ErrorStrategyReturnError returns the error as a string result
	ErrorStrategyReturnError
	// ErrorStrategyReturnEmpty returns an empty result on errors
	ErrorStrategyReturnEmpty
)

type FunctionMetadata

type FunctionMetadata struct {
	Name        string
	Description string
	Parameters  []ParameterMetadata
	ReturnType  string
	IsAsync     bool
	HasError    bool
}

FunctionMetadata provides metadata about the wrapped function.

type FunctionSchema

type FunctionSchema struct {
	Parameters map[string]ParameterInfo `json:"parameters"`
	Required   []string                 `json:"required"`
}

FunctionSchema describes the parameters of a function.

type FunctionTool

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

FunctionTool wraps a Go function as a tool.

func NewFunctionTool

func NewFunctionTool(name, description string, fn interface{}) (*FunctionTool, error)

NewFunctionTool creates a new function tool from a Go function.

func (*FunctionTool) GetDeclaration

func (t *FunctionTool) GetDeclaration() *core.FunctionDeclaration

GetDeclaration returns the function declaration for LLM integration.

func (*FunctionTool) RunAsync

func (t *FunctionTool) RunAsync(toolCtx *core.ToolContext, args map[string]any) (any, error)

RunAsync executes the wrapped function with the given arguments.

type MathUtilities

type MathUtilities struct{}

MathUtilities provides mathematical utility functions.

func (MathUtilities) Factorial

func (mu MathUtilities) Factorial(n int) (int, error)

Factorial calculates factorial of a number.

func (MathUtilities) FromBase

func (mu MathUtilities) FromBase(number string, base int) (int, error)

FromBase converts a number from a different base to base 10.

func (MathUtilities) GCD

func (mu MathUtilities) GCD(a, b int) int

GCD calculates the greatest common divisor.

func (MathUtilities) IsPrime

func (mu MathUtilities) IsPrime(n int) bool

IsPrime checks if a number is prime.

func (MathUtilities) LCM

func (mu MathUtilities) LCM(a, b int) int

LCM calculates the least common multiple.

func (MathUtilities) ToBase

func (mu MathUtilities) ToBase(number int, base int) (string, error)

ToBase converts a number to a different base.

type ParameterInfo

type ParameterInfo struct {
	Type        string `json:"type"`
	Description string `json:"description"`
}

ParameterInfo describes a function parameter.

type ParameterMetadata

type ParameterMetadata struct {
	Name        string
	Type        reflect.Type
	JSONType    string
	Description string
	Required    bool
	Default     interface{}
	Index       int
}

ParameterMetadata describes a function parameter.

type ParameterSchema

type ParameterSchema struct {
	Type        string                      `json:"type"`
	Description string                      `json:"description,omitempty"`
	Default     interface{}                 `json:"default,omitempty"`
	Enum        []interface{}               `json:"enum,omitempty"`
	Items       *ParameterSchema            `json:"items,omitempty"`      // For array types
	Properties  map[string]*ParameterSchema `json:"properties,omitempty"` // For object types
	Required    []string                    `json:"required,omitempty"`   // For object types
	Optional    bool                        `json:"optional"`
}

ParameterSchema describes a function parameter with enhanced metadata.

type ProcessingConfig

type ProcessingConfig struct {
	Mode      string            `json:"mode"`
	Options   map[string]string `json:"options"`
	Enabled   bool              `json:"enabled"`
	Threshold float64           `json:"threshold"`
}

ComplexDataProcessor demonstrates handling complex data structures.

type ProcessingResult

type ProcessingResult struct {
	Status    string    `json:"status"`
	Processed int       `json:"processed"`
	Errors    []string  `json:"errors"`
	Timestamp time.Time `json:"timestamp"`
}

func ComplexDataProcessor

func ComplexDataProcessor(data []string, config ProcessingConfig) (ProcessingResult, error)

type Result

type Result struct {
	Title   string `json:"title"`
	URL     string `json:"url"`
	Snippet string `json:"snippet"`
}

Result represents a single search result

type SearchResult

type SearchResult struct {
	Query   string   `json:"query"`
	Results []Result `json:"results"`
}

SearchResult represents a search result

type StringUtilities

type StringUtilities struct{}

StringUtilities provides various string manipulation functions.

func (StringUtilities) Count

func (su StringUtilities) Count(input, substring string) int

Count counts occurrences of a substring.

func (StringUtilities) Reverse

func (su StringUtilities) Reverse(input string) string

Reverse reverses a string.

func (StringUtilities) Split

func (su StringUtilities) Split(input, delimiter string) []string

Split splits a string by delimiter.

func (StringUtilities) WordCount

func (su StringUtilities) WordCount(input string) map[string]interface{}

WordCount counts words in a string.

type UserInfo

type UserInfo struct {
	Name  string `json:"name"`
	Age   int    `json:"age"`
	Email string `json:"email"`
}

UserInfo demonstrates working with structs.

func CreateUserProfile

func CreateUserProfile(name string, age int, email string) UserInfo

CreateUserProfile creates a user profile with the given information.

Directories

Path Synopsis
Package async provides examples of async tool implementations.
Package async provides examples of async tool implementations.

Jump to

Keyboard shortcuts

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