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), ¶ms); 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 ¶
- Choose appropriate tools for your use case
- Provide clear tool descriptions
- Validate inputs before processing
- Handle errors gracefully
- Use timeouts for long-running operations
- Monitor tool usage and performance
- Secure sensitive operations
- 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 ¶
- func AppendToMarkdownSection(filePath, sectionName, content string) error
- func CreateTaskPlan(filePath, goal string, phases []TaskPhase) error
- func ExtractSectionContent(filePath, sectionName string) (string, error)
- func GenerateTaskPlanMarkdown(goal string, phases []TaskPhase) string
- func GetBaseTools() []openai.Tool
- func GetCompletedPhases(filePath string) ([]string, error)
- func GetPendingPhases(filePath string) ([]string, error)
- func LogErrorToMarkdown(filePath, errorMessage string) error
- func ReadFile(filePath string) (string, error)
- func RunPythonScript(scriptPath string, args []string) (string, error)
- func RunShellScript(scriptPath string, args []string) (string, error)
- func UpdateMarkdownCheckboxes(filePath string, updates map[string]bool) (string, error)
- func UpdatePhaseStatus(filePath, phaseName string, complete bool) error
- func WebFetch(urlString string) (string, error)
- func WikipediaSearch(query string) (string, error)
- func WriteFile(filePath string, content string) error
- func WriteMarkdown(filePath string, content string, frontmatter map[string]any) error
- type BochaOption
- type BochaSearch
- type BraveOption
- type BraveSearch
- type ExaOption
- type ExaSearch
- type MarkdownFile
- type PythonTool
- type SearchResult
- type ShellTool
- type TaskPhase
- type TavilyOption
- type TavilySearch
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AppendToMarkdownSection ¶ added in v0.8.5
AppendToMarkdownSection appends content to a specific section in a Markdown file
func CreateTaskPlan ¶ added in v0.8.5
CreateTaskPlan creates a new task plan file with goal and phases
func ExtractSectionContent ¶ added in v0.8.5
ExtractSectionContent extracts content from a specific section in a Markdown file
func GenerateTaskPlanMarkdown ¶ added in v0.8.5
GenerateTaskPlanMarkdown creates a task plan Markdown content from goal and phases
func GetBaseTools ¶ added in v0.6.0
GetBaseTools returns the list of base tools available to all skills.
func GetCompletedPhases ¶ added in v0.8.5
GetCompletedPhases returns a list of completed phase names from a task plan
func GetPendingPhases ¶ added in v0.8.5
GetPendingPhases returns a list of pending (incomplete) phase names from a task plan
func LogErrorToMarkdown ¶ added in v0.8.5
LogErrorToMarkdown logs an error with timestamp to a Markdown file
func RunPythonScript ¶ added in v0.6.0
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
RunShellScript executes a shell script and returns its combined stdout and stderr.
func UpdateMarkdownCheckboxes ¶ added in v0.8.5
UpdateMarkdownCheckboxes updates the checkbox status in a Markdown file
func UpdatePhaseStatus ¶ added in v0.8.5
UpdatePhaseStatus updates the status (complete/incomplete) of a specific phase
func WebFetch ¶ added in v0.6.0
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
WikipediaSearch performs a search on Wikipedia for the given query and returns a summary. It uses the Wikipedia API.
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
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) 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
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) 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 ¶
WithExaBaseURL sets the base URL for the Exa API.
func WithExaNumResults ¶
WithExaNumResults sets the number of results to return.
type ExaSearch ¶
ExaSearch is a tool that uses the Exa API to search the web.
func NewExaSearch ¶
NewExaSearch creates a new ExaSearch tool. If apiKey is empty, it tries to read from EXA_API_KEY environment variable.
func (*ExaSearch) Description ¶
Description returns the description of the tool.
type MarkdownFile ¶ added in v0.8.5
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 {
}
type SearchResult ¶ added in v0.3.2
SearchResult represents a single search result with images
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 ¶
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) 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.