tools

package
v0.1.4 Latest Latest
Warning

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

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

Documentation

Overview

Package tools - ToolCollection and Pipeline functionality

Package tools - HuggingFace Hub integration for loading tools

Package tools - Model Context Protocol (MCP) integration

Package tools provides the tool system for smolagents.

This includes the core Tool interface, base implementations, input validation, type conversion, serialization, and integration capabilities.

Package tools - Vision web browser for web automation and interaction

Index

Constants

This section is empty.

Variables

View Source
var AuthorizedTypes = []string{
	"string",
	"boolean",
	"integer",
	"number",
	"image",
	"audio",
	"array",
	"object",
	"any",
	"null",
}

AuthorizedTypes lists all valid input/output types for tools

View Source
var ConversionDict = map[string]string{
	"string":  "string",
	"int":     "integer",
	"int32":   "integer",
	"int64":   "integer",
	"float32": "number",
	"float64": "number",
	"bool":    "boolean",
}

ConversionDict maps Go types to JSON schema types

View Source
var DefaultMCPRegistry = NewMCPToolRegistry()

DefaultMCPRegistry is the default MCP tool registry

Functions

func AddMCPServer

func AddMCPServer(name, serverPath string, serverArgs []string, options map[string]interface{}) error

AddMCPServer is a convenience function to add an MCP server to the default registry

func ClearRegistry

func ClearRegistry()

ClearRegistry clears the global tool registry

func GetToolJSONSchema

func GetToolJSONSchema(tool Tool) map[string]interface{}

GetToolJSONSchema converts a tool to OpenAI-compatible JSON schema

func RegisterTool

func RegisterTool(tool Tool) error

RegisterTool registers a tool globally

Types

type AutomatedBrowserSession

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

AutomatedBrowserSession represents a browser automation session

func NewAutomatedBrowserSession

func NewAutomatedBrowserSession(browser *VisionWebBrowser) *AutomatedBrowserSession

NewAutomatedBrowserSession creates a new browser automation session

func (*AutomatedBrowserSession) ExecuteScript

func (abs *AutomatedBrowserSession) ExecuteScript(script []map[string]interface{}) (string, error)

ExecuteScript executes a sequence of browser actions

func (*AutomatedBrowserSession) GetSessionSummary

func (abs *AutomatedBrowserSession) GetSessionSummary() map[string]interface{}

GetSessionSummary returns a summary of the automation session

type BaseTool

type BaseTool struct {
	Name        string                `json:"name"`
	Description string                `json:"description"`
	Inputs      map[string]*ToolInput `json:"inputs"`
	OutputType  string                `json:"output_type"`

	// Implementation function (for function-based tools)
	ForwardFunc func(args ...interface{}) (interface{}, error) `json:"-"`
	// contains filtered or unexported fields
}

BaseTool provides default implementations for the Tool interface

func NewBaseTool

func NewBaseTool(name, description string, inputs map[string]*ToolInput, outputType string) *BaseTool

NewBaseTool creates a new BaseTool instance

func (*BaseTool) Call

func (bt *BaseTool) Call(args ...interface{}) (interface{}, error)

Call implements Tool

func (*BaseTool) Forward

func (bt *BaseTool) Forward(args ...interface{}) (interface{}, error)

Forward implements Tool (default implementation)

func (*BaseTool) GetDescription

func (bt *BaseTool) GetDescription() string

GetDescription implements Tool

func (*BaseTool) GetInput

func (bt *BaseTool) GetInput(name string) *ToolInput

GetInput returns a specific input parameter

func (*BaseTool) GetInputs

func (bt *BaseTool) GetInputs() map[string]*ToolInput

GetInputs implements Tool

func (*BaseTool) GetName

func (bt *BaseTool) GetName() string

GetName implements Tool

func (*BaseTool) GetOutputType

func (bt *BaseTool) GetOutputType() string

GetOutputType implements Tool

func (*BaseTool) IsSetup

func (bt *BaseTool) IsSetup() bool

IsSetup implements Tool

func (*BaseTool) SetSetup

func (bt *BaseTool) SetSetup(setup bool)

SetSetup implements Tool

func (*BaseTool) Setup

func (bt *BaseTool) Setup() error

Setup implements Tool (default implementation)

func (*BaseTool) Teardown

func (bt *BaseTool) Teardown() error

Teardown cleans up any resources used by the tool

func (*BaseTool) ToDict

func (bt *BaseTool) ToDict() map[string]interface{}

ToDict implements Tool

func (*BaseTool) ToOpenAITool

func (bt *BaseTool) ToOpenAITool() map[string]interface{}

ToOpenAITool converts the tool to OpenAI tool format

func (*BaseTool) Validate

func (bt *BaseTool) Validate() error

Validate implements Tool

type FunctionTool

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

FunctionTool represents a tool created from a Go function

func CreateSimpleTool

func CreateSimpleTool(name, description, outputType string, function interface{}) (*FunctionTool, error)

CreateSimpleTool creates a simple tool with basic validation

func NewFunctionTool

func NewFunctionTool(
	name string,
	description string,
	inputs map[string]*ToolInput,
	outputType string,
	function interface{},
) (*FunctionTool, error)

NewFunctionTool creates a tool from a Go function with metadata

func NumberTool

func NumberTool(name, description string, function func(float64) (float64, error)) (*FunctionTool, error)

NumberTool creates a simple tool that processes numbers

func StringTool

func StringTool(name, description string, function func(string) (string, error)) (*FunctionTool, error)

StringTool creates a simple tool that returns a string

func (*FunctionTool) ToDict

func (ft *FunctionTool) ToDict() map[string]interface{}

ToDict implements Tool for FunctionTool

type HubClient

type HubClient struct {
	BaseURL   string            `json:"base_url"`
	Token     string            `json:"-"` // API token (not serialized)
	Headers   map[string]string `json:"headers"`
	UserAgent string            `json:"user_agent"`
	Timeout   time.Duration     `json:"timeout"`
	// contains filtered or unexported fields
}

HubClient provides access to HuggingFace Hub for tool loading

var DefaultHubClient *HubClient

DefaultHubClient is the default Hub client instance

func NewHubClient

func NewHubClient(token string, options map[string]interface{}) *HubClient

NewHubClient creates a new HuggingFace Hub client

func (*HubClient) GetToolDetails

func (hc *HubClient) GetToolDetails(toolPath string) (*ToolMetadata, error)

GetToolDetails returns detailed information about a specific tool

func (*HubClient) ListPopularTools

func (hc *HubClient) ListPopularTools(limit int) ([]*ToolMetadata, error)

ListPopularTools returns a list of popular tools from the Hub

func (*HubClient) SearchTools

func (hc *HubClient) SearchTools(query string, options map[string]interface{}) ([]*ToolMetadata, error)

SearchTools searches for tools on the HuggingFace Hub

type HubTool

type HubTool struct {
	*BaseTool
	Metadata  *ToolMetadata `json:"metadata"`
	HubID     string        `json:"hub_id"`
	Revision  string        `json:"revision"`
	LocalPath string        `json:"local_path"`
	// contains filtered or unexported fields
}

HubTool represents a tool loaded from the HuggingFace Hub

func LoadTool

func LoadTool(hubID string, options map[string]interface{}) (*HubTool, error)

LoadTool is a convenience function to load a tool using the default client

func LoadToolFromHub

func LoadToolFromHub(hubID string, client *HubClient, options map[string]interface{}) (*HubTool, error)

LoadToolFromHub loads a tool from the HuggingFace Hub

type HubToolRegistry

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

HubToolRegistry manages a collection of Hub tools

func NewHubToolRegistry

func NewHubToolRegistry(client *HubClient) *HubToolRegistry

NewHubToolRegistry creates a new hub tool registry

func (*HubToolRegistry) GetTool

func (htr *HubToolRegistry) GetTool(name string) (*HubTool, bool)

GetTool retrieves a tool from the registry

func (*HubToolRegistry) ListTools

func (htr *HubToolRegistry) ListTools() map[string]*HubTool

ListTools returns all tools in the registry

func (*HubToolRegistry) LoadTool

func (htr *HubToolRegistry) LoadTool(hubID string, options map[string]interface{}) (*HubTool, error)

LoadTool loads a tool from the Hub and adds it to the registry

func (*HubToolRegistry) RemoveTool

func (htr *HubToolRegistry) RemoveTool(name string) bool

RemoveTool removes a tool from the registry

func (*HubToolRegistry) UpdateTool

func (htr *HubToolRegistry) UpdateTool(name string, options map[string]interface{}) error

UpdateTool updates a tool to the latest version

type MCPCapabilities

type MCPCapabilities struct {
	Experimental map[string]interface{} `json:"experimental,omitempty"`
	Logging      map[string]interface{} `json:"logging,omitempty"`
	Prompts      map[string]interface{} `json:"prompts,omitempty"`
	Resources    map[string]interface{} `json:"resources,omitempty"`
	Tools        map[string]interface{} `json:"tools,omitempty"`
}

MCPCapabilities represents the capabilities of an MCP server

type MCPClient

type MCPClient struct {
	ServerPath  string            `json:"server_path"`
	ServerArgs  []string          `json:"server_args"`
	Environment map[string]string `json:"environment"`
	Timeout     time.Duration     `json:"timeout"`
	MaxRetries  int               `json:"max_retries"`
	// contains filtered or unexported fields
}

MCPClient represents a client for communicating with MCP servers

func NewMCPClient

func NewMCPClient(serverPath string, serverArgs []string, options map[string]interface{}) *MCPClient

NewMCPClient creates a new MCP client

func (*MCPClient) CallTool

func (mc *MCPClient) CallTool(name string, arguments map[string]interface{}) (interface{}, error)

CallTool executes a tool on the MCP server

func (*MCPClient) Close

func (mc *MCPClient) Close() error

Close closes the connection to the MCP server

func (*MCPClient) Connect

func (mc *MCPClient) Connect() error

Connect establishes a connection to the MCP server

func (*MCPClient) ListTools

func (mc *MCPClient) ListTools() ([]*MCPToolDefinition, error)

ListTools retrieves available tools from the MCP server

type MCPError

type MCPError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

MCPError represents an error in MCP communication

type MCPMessage

type MCPMessage struct {
	JSONRPC string      `json:"jsonrpc"`
	ID      interface{} `json:"id,omitempty"`
	Method  string      `json:"method,omitempty"`
	Params  interface{} `json:"params,omitempty"`
	Result  interface{} `json:"result,omitempty"`
	Error   *MCPError   `json:"error,omitempty"`
}

MCPMessage represents a JSON-RPC 2.0 message for MCP

type MCPTool

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

MCPTool represents a tool that communicates via MCP

func GetMCPTool

func GetMCPTool(name string) (*MCPTool, bool)

GetMCPTool is a convenience function to get an MCP tool from the default registry

func LoadMCPTool

func LoadMCPTool(client *MCPClient, toolName string) (*MCPTool, error)

LoadMCPTool creates a tool wrapper for an MCP tool

type MCPToolDefinition

type MCPToolDefinition struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	InputSchema map[string]interface{} `json:"inputSchema"`
}

MCPToolDefinition represents a tool definition from an MCP server

type MCPToolRegistry

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

MCPToolRegistry manages a collection of MCP tools

func NewMCPToolRegistry

func NewMCPToolRegistry() *MCPToolRegistry

NewMCPToolRegistry creates a new MCP tool registry

func (*MCPToolRegistry) AddMCPServer

func (mtr *MCPToolRegistry) AddMCPServer(name, serverPath string, serverArgs []string, options map[string]interface{}) error

AddMCPServer adds an MCP server to the registry

func (*MCPToolRegistry) Close

func (mtr *MCPToolRegistry) Close() error

Close closes all MCP connections

func (*MCPToolRegistry) GetTool

func (mtr *MCPToolRegistry) GetTool(name string) (*MCPTool, bool)

GetTool retrieves an MCP tool by name

func (*MCPToolRegistry) ListTools

func (mtr *MCPToolRegistry) ListTools() map[string]*MCPTool

ListTools returns all available MCP tools

func (*MCPToolRegistry) RemoveServer

func (mtr *MCPToolRegistry) RemoveServer(name string) error

RemoveServer removes an MCP server and its tools

type PipelineTool

type PipelineTool struct {
	*BaseTool

	// Pipeline configuration
	ModelClass         string `json:"model_class,omitempty"`
	DefaultCheckpoint  string `json:"default_checkpoint,omitempty"`
	PreProcessorClass  string `json:"pre_processor_class,omitempty"`
	PostProcessorClass string `json:"post_processor_class,omitempty"`

	// Pipeline functions
	EncodeFunc func(interface{}) (interface{}, error) `json:"-"`
	DecodeFunc func(interface{}) (interface{}, error) `json:"-"`
	// contains filtered or unexported fields
}

PipelineTool represents a tool that processes data through a pipeline

func NewPipelineTool

func NewPipelineTool(
	name, description string,
	inputs map[string]*ToolInput,
	outputType string,
	options map[string]interface{},
) *PipelineTool

NewPipelineTool creates a new pipeline tool

func (*PipelineTool) Decode

func (pt *PipelineTool) Decode(output interface{}) (interface{}, error)

Decode processes output through the postprocessor

func (*PipelineTool) Encode

func (pt *PipelineTool) Encode(input interface{}) (interface{}, error)

Encode processes input through the preprocessor

func (*PipelineTool) Forward

func (pt *PipelineTool) Forward(args ...interface{}) (interface{}, error)

Forward implements Tool for PipelineTool

func (*PipelineTool) GetDevice

func (pt *PipelineTool) GetDevice() string

GetDevice returns the current device

func (*PipelineTool) SetDevice

func (pt *PipelineTool) SetDevice(device string)

SetDevice sets the device for the pipeline

func (*PipelineTool) Setup

func (pt *PipelineTool) Setup() error

Setup implements Tool for PipelineTool

func (*PipelineTool) ToDict

func (pt *PipelineTool) ToDict() map[string]interface{}

ToDict implements Tool for PipelineTool

type Tool

type Tool interface {
	// Core execution method - must be implemented by all tools
	Forward(args ...interface{}) (interface{}, error)

	// Entry point that handles input/output sanitization
	Call(args ...interface{}) (interface{}, error)

	// Lazy initialization for expensive operations
	Setup() error

	// Validates tool configuration
	Validate() error

	// Serialization methods
	ToDict() map[string]interface{}

	// Metadata accessors
	GetName() string
	GetDescription() string
	GetInputs() map[string]*ToolInput
	GetOutputType() string

	// State management
	IsSetup() bool
	SetSetup(bool)
}

Tool represents the main interface for all tools used by agents

func GetRegisteredTool

func GetRegisteredTool(name string) (Tool, bool)

GetRegisteredTool retrieves a globally registered tool

func ListRegisteredTools

func ListRegisteredTools() []Tool

ListRegisteredTools returns all globally registered tools

func ToolFromMap

func ToolFromMap(toolMap map[string]interface{}) (Tool, error)

ToolFromMap creates a tool from a map representation

type ToolCollection

type ToolCollection struct {
	Tools    []Tool          `json:"tools"`
	ToolsMap map[string]Tool `json:"-"`
	// contains filtered or unexported fields
}

ToolCollection manages a collection of tools

func NewToolCollection

func NewToolCollection(tools ...[]Tool) *ToolCollection

NewToolCollection creates a new tool collection

func (*ToolCollection) Add

func (tc *ToolCollection) Add(tool Tool) error

Add adds a tool to the collection

func (*ToolCollection) AddTool

func (tc *ToolCollection) AddTool(tool Tool) error

AddTool is an alias for Add to match test expectations

func (*ToolCollection) Clear

func (tc *ToolCollection) Clear()

Clear removes all tools from the collection

func (*ToolCollection) Count

func (tc *ToolCollection) Count() int

Count returns the number of tools in the collection

func (*ToolCollection) Filter

func (tc *ToolCollection) Filter(predicate func(Tool) bool) *ToolCollection

Filter returns a new collection with tools that match the predicate

func (*ToolCollection) FindByPrefix

func (tc *ToolCollection) FindByPrefix(prefix string) []Tool

FindByPrefix returns all tools whose names start with the given prefix

func (*ToolCollection) FindByType

func (tc *ToolCollection) FindByType(outputType string) []Tool

FindByType returns all tools with the specified output type

func (*ToolCollection) FromDict

func (tc *ToolCollection) FromDict(data map[string]interface{}) error

FromDict creates a tool collection from a dictionary representation

func (*ToolCollection) Get

func (tc *ToolCollection) Get(name string) (Tool, bool)

Get retrieves a tool by name

func (*ToolCollection) GetTool

func (tc *ToolCollection) GetTool(name string) (Tool, bool)

GetTool retrieves a tool by name

func (*ToolCollection) Has

func (tc *ToolCollection) Has(name string) bool

Has checks if a tool exists in the collection

func (*ToolCollection) List

func (tc *ToolCollection) List() []Tool

List returns all tools in the collection in insertion order

func (*ToolCollection) ListNames

func (tc *ToolCollection) ListNames() []string

ListNames returns all tool names in insertion order

func (*ToolCollection) ListTools

func (tc *ToolCollection) ListTools() []string

ListTools is an alias for ListNames to match test expectations

func (*ToolCollection) MarshalJSON

func (tc *ToolCollection) MarshalJSON() ([]byte, error)

JSON serialization

func (*ToolCollection) Merge

func (tc *ToolCollection) Merge(other *ToolCollection) error

Merge merges another tool collection into this one

func (*ToolCollection) Remove

func (tc *ToolCollection) Remove(name string) bool

Remove removes a tool from the collection

func (*ToolCollection) RemoveTool

func (tc *ToolCollection) RemoveTool(name string) bool

RemoveTool removes a tool from the collection

func (*ToolCollection) ToDict

func (tc *ToolCollection) ToDict() map[string]interface{}

ToDict converts the collection to a dictionary representation

func (*ToolCollection) UnmarshalJSON

func (tc *ToolCollection) UnmarshalJSON(data []byte) error

func (*ToolCollection) ValidateAll

func (tc *ToolCollection) ValidateAll() error

ValidateAll validates all tools in the collection

type ToolDecorator

type ToolDecorator struct {
	Name        string
	Description string
	OutputType  string
	Inputs      map[string]*ToolInput
}

ToolDecorator represents metadata for creating tools from functions

func NewToolDecorator

func NewToolDecorator(name, description, outputType string) *ToolDecorator

NewToolDecorator creates a new tool decorator

func (*ToolDecorator) AddInput

func (td *ToolDecorator) AddInput(name, inputType, description string, nullable ...bool) *ToolDecorator

AddInput adds an input parameter to the decorator

func (*ToolDecorator) Decorate

func (td *ToolDecorator) Decorate(function interface{}) (*FunctionTool, error)

Decorate creates a tool from a function using this decorator

type ToolInput

type ToolInput struct {
	Type        string      `json:"type"`
	Description string      `json:"description"`
	Nullable    bool        `json:"nullable,omitempty"`
	Required    bool        `json:"required,omitempty"`
	Default     interface{} `json:"default,omitempty"`
}

ToolInput represents an input parameter for a tool

func NewToolInput

func NewToolInput(inputType, description string, nullable ...bool) *ToolInput

NewToolInput creates a new ToolInput

func (*ToolInput) ToDict

func (ti *ToolInput) ToDict() map[string]interface{}

ToDict converts the tool input to a dictionary representation

type ToolMetadata

type ToolMetadata struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Author      string                 `json:"author"`
	Version     string                 `json:"version"`
	Inputs      map[string]*ToolInput  `json:"inputs"`
	OutputType  string                 `json:"output_type"`
	Category    string                 `json:"category"`
	Tags        []string               `json:"tags"`
	License     string                 `json:"license"`
	CreatedAt   string                 `json:"created_at"`
	UpdatedAt   string                 `json:"updated_at"`
	Downloads   int                    `json:"downloads"`
	Likes       int                    `json:"likes"`
	Config      map[string]interface{} `json:"config"`
}

ToolMetadata represents metadata about a tool from the Hub

func SearchTools

func SearchTools(query string, options map[string]interface{}) ([]*ToolMetadata, error)

SearchTools is a convenience function to search tools using the default client

type ToolRegistry

type ToolRegistry struct {
	*ToolCollection
}

ToolRegistry provides a global registry for tools

func GetRegistry

func GetRegistry() *ToolRegistry

GetRegistry returns the global tool registry

type VisionWebBrowser

type VisionWebBrowser struct {
	*BaseTool
	UserAgent      string        `json:"user_agent"`
	Timeout        time.Duration `json:"timeout"`
	ScreenshotPath string        `json:"screenshot_path"`
	BrowserPath    string        `json:"browser_path"`
	Headless       bool          `json:"headless"`
	WindowSize     string        `json:"window_size"`
	WaitTime       time.Duration `json:"wait_time"`
}

VisionWebBrowser provides web automation with visual capabilities

func NewVisionWebBrowser

func NewVisionWebBrowser() *VisionWebBrowser

NewVisionWebBrowser creates a new vision web browser tool

func (*VisionWebBrowser) GetBrowserInfo

func (vwb *VisionWebBrowser) GetBrowserInfo() map[string]interface{}

GetBrowserInfo returns information about the available browser

func (*VisionWebBrowser) SetBrowserOptions

func (vwb *VisionWebBrowser) SetBrowserOptions(options map[string]interface{})

SetBrowserOptions configures browser options

Jump to

Keyboard shortcuts

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