tool

package
v0.8.5 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package tool provides a collection of ready-to-use tools for LangGraph Go agents.

This package includes various tools that extend agent capabilities, including web search, file operations, code execution, and integration with popular APIs and services. Tools are designed to be easily integrated with prebuilt agents or custom implementations.

Available Tools

## Web Search Tools

### Tavily Search Perform web searches using the Tavily API:

import "github.com/smallnest/langgraphgo/tool"

searchTool, err := tool.NewTavilySearchTool("your-tavily-api-key")
if err != nil {
	return err
}

// Use with an agent
agent, _ := prebuilt.CreateReactAgent(llm, []tools.Tool{searchTool}, 10)

// Or use directly
result, err := searchTool.Call(ctx, `{
	"query": "latest developments in quantum computing",
	"max_results": 5
}`)

### Brave Search Use Brave Search API for web searching:

braveTool, err := tool.NewBraveSearchTool("your-brave-api-key")
if err != nil {
	return err
}

### Bocha Search Chinese search engine integration:

bochaTool, err := tool.NewBochaSearchTool("your-bocha-api-key")

### EXA Search Advanced neural search with EXA:

exaTool, err := tool.NewEXASearchTool("your-exa-api-key")

## File Operations

### File Tool Basic file system operations:

fileTool := &tool.FileTool{}

// Read a file
result, _ := fileTool.Call(ctx, `{
	"action": "read",
	"path": "/path/to/file.txt"
}`)

// Write a file
result, _ := fileTool.Call(ctx, `{
	"action": "write",
	"path": "/path/to/output.txt",
	"content": "Hello, World!"
}`)

// List directory
result, _ := fileTool.Call(ctx, `{
	"action": "list",
	"path": "/path/to/directory"
}`)

### Knowledge Tool Load and search knowledge bases:

knowledgeTool := tool.NewKnowledgeTool("/path/to/knowledge")

result, _ := knowledgeTool.Call(ctx, `{
	"query": "How to install LangGraph Go?",
	"max_results": 3
}`)

## Code Execution

### Shell Tool Execute shell commands and scripts:

// Execute shell code
shellTool := &tool.ShellTool{}
result, _ := shellTool.Call(ctx, `{
	"code": "ls -la /home/user"
}`)

// Execute with arguments
result, _ := shellTool.Call(ctx, `{
	"code": "echo $1 $2",
	"args": {"Hello", "World"}
}`)

### Python Tool Execute Python code:

pythonTool := &tool.PythonTool{}
result, _ := pythonTool.Call(ctx, `{
	"code": "import math; print(math.sqrt(16))"
}`)

// With imports and global variables
result, _ := pythonTool.Call(ctx, `{
	"code": "print(data['value'] * 2)",
	"imports": ["numpy", "pandas"],
	"globals": {"value": 42}
}`)

## Web Tools

### Web Tool Simple HTTP requests:

webTool := &tool.WebTool{}

// GET request
result, _ := webTool.Call(ctx, `{
	"url": "https://api.example.com/data",
	"method": "GET"
}`)

// POST request with headers
result, _ := webTool.Call(ctx, `{
	"url": "https://api.example.com/submit",
	"method": "POST",
	"headers": {"Content-Type": "application/json"},
	"body": "{\"key\": \"value\"}"
}`)

### Web Search Tool Generic web search tool:

searchTool := &tool.WebSearchTool{}
result, _ := searchTool.Call(ctx, `{
	"query": "LangGraph Go documentation",
	"num_results": 5
}`)

Tool Implementation

## Creating Custom Tools

Implement the Tool interface:

import (
	"github.com/tmc/langchaingo/tools"
)

type CustomTool struct {
	apiKey string
}

func (t *CustomTool) Name() string {
	return "custom_api_call"
}

func (t *CustomTool) Description() string {
	return "Makes a call to the custom API"
}

func (t *CustomTool) Call(ctx context.Context, input string) (string, error) {
	// Parse input
	var params struct {
		Query string `json:"query"`
	}
	if err := json.Unmarshal([]byte(input), &params); err != nil {
		return "", err
	}

	// Make API call
	result, err := t.callAPI(params.Query)
	if err != nil {
		return "", err
	}

	// Return result
	return json.Marshal(result)
}

Tool Categories

## Base Tools Common tools available to all agents:

baseTools := tool.GetBaseTools()
// Includes:
// - run_shell_code: Execute shell code
// - run_shell_script: Execute shell script
// - run_python_code: Execute Python code
// - web_search: Perform web search
// - file_operations: File system operations

## Specialized Tools Tools for specific domains:

// Search tools
tavilyTool, _ := tool.NewTavilySearchTool(apiKey)
braveTool, _ := tool.NewBraveSearchTool(apiKey)
exaTool, _ := tool.NewEXASearchTool(apiKey)
bochaTool, _ := tool.NewBochaSearchTool(apiKey)

// Execution tools
shellTool := &tool.ShellTool{}
pythonTool := &tool.PythonTool{}
fileTool := &tool.FileTool{}

// Web tools
webTool := &tool.WebTool{}
webSearchTool := &tool.WebSearchTool{}

Integration Examples

## With ReAct Agent

// Combine multiple tools
tools := []tools.Tool{
	&tool.ShellTool{},
	&tool.FileTool{},
	searchTool,
	pythonTool,
}

agent, _ := prebuilt.CreateReactAgent(llm, tools, 15)

## With PTC Agent

ptcTools := []tools.Tool{
	&tool.ShellTool{},
	&tool.PythonTool{},
	&tool.FileTool{},
}

ptcAgent, _ := ptc.CreatePTCAgent(ptc.PTCAgentConfig{
	Model:    llm,
	Tools:    ptcTools,
	Language: ptc.LanguagePython,
})

Tool Configuration

Many tools support configuration:

// Tavily with custom options
tavilyTool, _ := tool.NewTavilySearchToolWithConfig(
	apiKey,
	tool.TavilyConfig{
		MaxResults: 10,
		SearchDepth: "advanced",
		IncludeRawContent: true,
	},
)

// Shell tool with allowed commands
shellTool := tool.NewShellToolWithConfig(
	tool.ShellConfig{
		AllowedCommands: []string{"ls", "cat", "grep"},
		Timeout: 30 * time.Second,
		WorkingDir: "/safe/directory",
	},
)

Security Considerations

  • Validate all tool inputs
  • Use chroot/sandboxing for code execution
  • Set timeouts for network operations
  • Restrict file system access
  • Sanitize shell commands
  • Use API keys securely
  • Monitor tool usage

Error Handling

Tools provide structured error responses:

type ToolError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Details any    `json:"details,omitempty"`
}

result, err := tool.Call(ctx, input)
if err != nil {
	var toolErr *ToolError
	if errors.As(err, &toolErr) {
		// Handle specific tool error
		fmt.Printf("Tool error: %s - %s\n", toolErr.Code, toolErr.Message)
	}
}

Best Practices

  1. Choose appropriate tools for your use case
  2. Provide clear tool descriptions
  3. Validate inputs before processing
  4. Handle errors gracefully
  5. Use timeouts for long-running operations
  6. Monitor tool usage and performance
  7. Secure sensitive operations
  8. Test tools with various inputs

Tool Composition

Tools can be composed for complex workflows:

// Create a composite tool that uses multiple sub-tools
type CompositeTool struct {
	searchTool *tool.WebSearchTool
	fileTool   *tool.FileTool
}

func (t *CompositeTool) Call(ctx context.Context, input string) (string, error) {
	// Search for information
	searchResult, _ := t.searchTool.Call(ctx, input)

	// Save results to file
	saveResult, _ := t.fileTool.Call(ctx, map[string]any{
		"action": "write",
		"path":   "/tmp/search_results.txt",
		"content": searchResult,
	})

	return saveResult, nil
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendToMarkdownSection added in v0.8.5

func AppendToMarkdownSection(filePath, sectionName, content string) error

AppendToMarkdownSection appends content to a specific section in a Markdown file

func CreateTaskPlan added in v0.8.5

func CreateTaskPlan(filePath, goal string, phases []TaskPhase) error

CreateTaskPlan creates a new task plan file with goal and phases

func ExtractSectionContent added in v0.8.5

func ExtractSectionContent(filePath, sectionName string) (string, error)

ExtractSectionContent extracts content from a specific section in a Markdown file

func GenerateTaskPlanMarkdown added in v0.8.5

func GenerateTaskPlanMarkdown(goal string, phases []TaskPhase) string

GenerateTaskPlanMarkdown creates a task plan Markdown content from goal and phases

func GetBaseTools added in v0.6.0

func GetBaseTools() []openai.Tool

GetBaseTools returns the list of base tools available to all skills.

func GetCompletedPhases added in v0.8.5

func GetCompletedPhases(filePath string) ([]string, error)

GetCompletedPhases returns a list of completed phase names from a task plan

func GetPendingPhases added in v0.8.5

func GetPendingPhases(filePath string) ([]string, error)

GetPendingPhases returns a list of pending (incomplete) phase names from a task plan

func LogErrorToMarkdown added in v0.8.5

func LogErrorToMarkdown(filePath, errorMessage string) error

LogErrorToMarkdown logs an error with timestamp to a Markdown file

func ReadFile added in v0.6.0

func ReadFile(filePath string) (string, error)

ReadFile reads the content of a file and returns it as a string.

func RunPythonScript added in v0.6.0

func RunPythonScript(scriptPath string, args []string) (string, error)

RunPythonScript executes a Python script and returns its combined stdout and stderr. It tries to use 'python3' first, then falls back to 'python'.

func RunShellScript added in v0.6.0

func RunShellScript(scriptPath string, args []string) (string, error)

RunShellScript executes a shell script and returns its combined stdout and stderr.

func UpdateMarkdownCheckboxes added in v0.8.5

func UpdateMarkdownCheckboxes(filePath string, updates map[string]bool) (string, error)

UpdateMarkdownCheckboxes updates the checkbox status in a Markdown file

func UpdatePhaseStatus added in v0.8.5

func UpdatePhaseStatus(filePath, phaseName string, complete bool) error

UpdatePhaseStatus updates the status (complete/incomplete) of a specific phase

func WebFetch added in v0.6.0

func WebFetch(urlString string) (string, error)

WebFetch retrieves the main text content from a given URL. It uses goquery to parse the HTML and extract text, removing script and style tags.

func WikipediaSearch added in v0.6.0

func WikipediaSearch(query string) (string, error)

WikipediaSearch performs a search on Wikipedia for the given query and returns a summary. It uses the Wikipedia API.

func WriteFile added in v0.6.0

func WriteFile(filePath string, content string) error

WriteFile writes the given content to a file. If the file does not exist, it will be created. If it exists, its content will be truncated.

func WriteMarkdown added in v0.8.5

func WriteMarkdown(filePath string, content string, frontmatter map[string]any) error

WriteMarkdown writes content to a Markdown file with optional frontmatter

Types

type BochaOption added in v0.3.2

type BochaOption func(*BochaSearch)

func WithBochaBaseURL added in v0.3.2

func WithBochaBaseURL(url string) BochaOption

WithBochaBaseURL sets the base URL for the Bocha API.

func WithBochaCount added in v0.3.2

func WithBochaCount(count int) BochaOption

WithBochaCount sets the number of results to return.

func WithBochaFreshness added in v0.3.2

func WithBochaFreshness(freshness string) BochaOption

WithBochaFreshness sets the freshness filter for the search. Valid values: "oneDay", "oneWeek", "oneMonth", "oneYear", "noLimit".

func WithBochaSummary added in v0.3.2

func WithBochaSummary(summary bool) BochaOption

WithBochaSummary sets whether to return a summary.

type BochaSearch added in v0.3.2

type BochaSearch struct {
	APIKey    string
	BaseURL   string
	Count     int
	Freshness string
	Summary   bool
}

BochaSearch is a tool that uses the Bocha API to search the web.

func NewBochaSearch added in v0.3.2

func NewBochaSearch(apiKey string, opts ...BochaOption) (*BochaSearch, error)

NewBochaSearch creates a new BochaSearch tool. If apiKey is empty, it tries to read from BOCHA_API_KEY environment variable.

func (*BochaSearch) Call added in v0.3.2

func (b *BochaSearch) Call(ctx context.Context, input string) (string, error)

Call executes the search.

func (*BochaSearch) Description added in v0.3.2

func (b *BochaSearch) Description() string

Description returns the description of the tool.

func (*BochaSearch) Name added in v0.3.2

func (b *BochaSearch) Name() string

Name returns the name of the tool.

type BraveOption added in v0.3.2

type BraveOption func(*BraveSearch)

func WithBraveBaseURL added in v0.3.2

func WithBraveBaseURL(baseURL string) BraveOption

WithBraveBaseURL sets the base URL for the Brave Search API.

func WithBraveCount added in v0.3.2

func WithBraveCount(count int) BraveOption

WithBraveCount sets the number of results to return (1-20).

func WithBraveCountry added in v0.3.2

func WithBraveCountry(country string) BraveOption

WithBraveCountry sets the country code for search results (e.g., "US", "CN").

func WithBraveLang added in v0.3.2

func WithBraveLang(lang string) BraveOption

WithBraveLang sets the language code for search results (e.g., "en", "zh").

type BraveSearch added in v0.3.2

type BraveSearch struct {
	APIKey  string
	BaseURL string
	Count   int
	Country string
	Lang    string
}

BraveSearch is a tool that uses the Brave Search API to search the web.

func NewBraveSearch added in v0.3.2

func NewBraveSearch(apiKey string, opts ...BraveOption) (*BraveSearch, error)

NewBraveSearch creates a new BraveSearch tool. If apiKey is empty, it tries to read from BRAVE_API_KEY environment variable.

func (*BraveSearch) Call added in v0.3.2

func (b *BraveSearch) Call(ctx context.Context, input string) (string, error)

Call executes the search.

func (*BraveSearch) Description added in v0.3.2

func (b *BraveSearch) Description() string

Description returns the description of the tool.

func (*BraveSearch) Name added in v0.3.2

func (b *BraveSearch) Name() string

Name returns the name of the tool.

type ExaOption

type ExaOption func(*ExaSearch)

func WithExaBaseURL

func WithExaBaseURL(url string) ExaOption

WithExaBaseURL sets the base URL for the Exa API.

func WithExaNumResults

func WithExaNumResults(num int) ExaOption

WithExaNumResults sets the number of results to return.

type ExaSearch

type ExaSearch struct {
	APIKey     string
	BaseURL    string
	NumResults int
}

ExaSearch is a tool that uses the Exa API to search the web.

func NewExaSearch

func NewExaSearch(apiKey string, opts ...ExaOption) (*ExaSearch, error)

NewExaSearch creates a new ExaSearch tool. If apiKey is empty, it tries to read from EXA_API_KEY environment variable.

func (*ExaSearch) Call

func (t *ExaSearch) Call(ctx context.Context, input string) (string, error)

Call executes the search.

func (*ExaSearch) Description

func (t *ExaSearch) Description() string

Description returns the description of the tool.

func (*ExaSearch) Name

func (t *ExaSearch) Name() string

Name returns the name of the tool.

type MarkdownFile added in v0.8.5

type MarkdownFile struct {
	Path        string
	Frontmatter map[string]any
	Content     string
}

MarkdownFile represents a Markdown file with frontmatter and content

func ReadMarkdown added in v0.8.5

func ReadMarkdown(filePath string) (*MarkdownFile, error)

ReadMarkdown reads a Markdown file and parses its frontmatter and content

type PythonTool added in v0.6.0

type PythonTool struct {
}

func (*PythonTool) Run added in v0.6.0

func (t *PythonTool) Run(args map[string]any, code string) (string, error)

type SearchResult added in v0.3.2

type SearchResult struct {
	Text   string
	Images []string
}

SearchResult represents a single search result with images

type ShellTool added in v0.6.0

type ShellTool struct {
}

func (*ShellTool) Run added in v0.6.0

func (t *ShellTool) Run(args map[string]any, code string) (string, error)

type TaskPhase added in v0.8.5

type TaskPhase struct {
	Number      int
	Name        string
	Description string
	Node        string
	Complete    bool
}

TaskPhase represents a single phase in a task plan

func ParseTaskPlan added in v0.8.5

func ParseTaskPlan(filePath string) (goal string, phases []TaskPhase, err error)

ParseTaskPlan extracts phases and goals from a task plan Markdown file

type TavilyOption

type TavilyOption func(*TavilySearch)

func WithTavilyBaseURL

func WithTavilyBaseURL(url string) TavilyOption

WithTavilyBaseURL sets the base URL for the Tavily API.

func WithTavilySearchDepth

func WithTavilySearchDepth(depth string) TavilyOption

WithTavilySearchDepth sets the search depth for the Tavily API. Valid values are "basic" and "advanced".

type TavilySearch

type TavilySearch struct {
	APIKey      string
	BaseURL     string
	SearchDepth string
}

TavilySearch is a tool that uses the Tavily API to search the web.

func NewTavilySearch

func NewTavilySearch(apiKey string, opts ...TavilyOption) (*TavilySearch, error)

NewTavilySearch creates a new TavilySearch tool. If apiKey is empty, it tries to read from TAVILY_API_KEY environment variable.

func (*TavilySearch) Call

func (t *TavilySearch) Call(ctx context.Context, input string) (string, error)

Call executes the search.

func (*TavilySearch) CallWithImages added in v0.3.2

func (t *TavilySearch) CallWithImages(ctx context.Context, input string) (*SearchResult, error)

CallWithImages executes the search and returns both text and images.

func (*TavilySearch) Description

func (t *TavilySearch) Description() string

Description returns the description of the tool.

func (*TavilySearch) Name

func (t *TavilySearch) Name() string

Name returns the name of the tool.

Jump to

Keyboard shortcuts

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