Documentation
¶
Overview ¶
Package toolkit provides a hierarchical tool orchestration framework for AI-powered applications. This file contains the builder functions (NewChild, NewParent) that simplify the creation of tool components without requiring manual interface implementation.
Package toolkit provides a hierarchical tool orchestration framework for AI-powered applications. It enables defining, composing, and executing multiple tools in a single invocation while handling schema generation, error management, and response aggregation automatically.
Core concepts:
- Toolkit: The top-level container that manages multiple Parent tools
- Parent: A category of related tools that acts as a namespace for Child tools
- Child: An individual tool that performs a specific operation with args and returns results
This file defines the core interfaces that all Parent and Child implementations must satisfy.
Package toolkit provides a hierarchical tool orchestration framework for AI-powered applications. It enables defining, composing, and executing multiple tools in a single invocation while handling schema generation, error management, and response aggregation automatically.
Package toolkit provides a hierarchical tool orchestration framework for AI-powered applications. This file defines the data structures used for requests, responses, errors, and schema generation within the toolkit framework.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GenerateSchema ¶
func GenerateSchema[T any]() interface{}
GenerateSchema creates a JSON schema representation for the provided generic type T. It uses reflection through the github.com/invopop/jsonschema library to generate a complete schema that can be used for documentation, validation, and providing to LLMs for tool use.
The schema generation respects jsonschema tags on struct fields, including: - required: Whether the field is required - description: Field descriptions for documentation
Example usage:
type MyArgs struct {
Name string `json:"name" jsonschema:"required,description=The user's name"`
Age int `json:"age" jsonschema:"description=The user's age in years"`
}
schema := GenerateSchema[MyArgs]()
func GetToolKitSchemaForAnthropic ¶
func GetToolKitSchemaForAnthropic() interface{}
GetToolKitSchemaForAnthropic generates the specific JSON schema structure expected by Anthropic's Claude API for the top-level ToolKit request. This schema is used when registering the toolkit with Anthropic's tool use capability.
func NewError ¶
NewError creates a new ToolKitError instance with the specified code and message. This is the preferred way to create and return errors from tool implementations to ensure consistent error handling across the toolkit.
Common error codes:
- "invalid_arguments": When tool arguments don't match the expected schema
- "handler_execution_error": When the tool execution fails
- "child_not_found": When a requested child tool doesn't exist
- "parent_not_found": When a requested parent doesn't exist
Types ¶
type Child ¶
type Child interface {
// GetName returns the unique name of the child tool within its parent.
// This name is used for lookup in execution requests and must be unique
// within its parent.
GetName() string
// GetDescription provides a human-readable description of what the tool does.
// This description is used in schema generation and documentation.
GetDescription() string
// GetInputSchema returns the JSON schema definition for the arguments
// this tool expects. This schema is used for validation and documentation
// in AI model prompts.
GetInputSchema() interface{}
// Handle executes the core logic of the tool with the provided arguments.
// It unmarshals the raw JSON arguments into the expected type, performs
// the operation, and returns the result or an error.
// Implementations should use the provided context for cancellation support
// and should return ToolKitError instances for structured error handling.
Handle(ctx context.Context, args json.RawMessage) (interface{}, error)
}
Child represents an individual tool or function that can be executed. Each Child belongs to a Parent and defines its own name, description, input schema, and execution logic. Implementations should handle their specific business logic while conforming to the expected interface.
func NewChild ¶
func NewChild[ArgsT any](name, description string, handlerFunc func(ctx context.Context, args ArgsT) (interface{}, error)) Child
NewChild creates a new Child tool definition using a type-safe builder pattern. It handles input schema generation, argument validation, and error mapping automatically, significantly simplifying tool creation compared to manual interface implementation.
Parameters:
- name: The unique name for this child tool within its parent (must be unique within a parent)
- description: A human-readable description of what the tool does (used for documentation)
- handlerFunc: The function that implements the tool's core logic
The handlerFunc signature must be func(ctx context.Context, args ArgsT) (interface{}, error), where ArgsT is a struct type defining the expected arguments. The schema for ArgsT is automatically generated from struct tags and type information.
Example:
type ReadFileArgs struct {
Path string `json:"path" jsonschema:"required,description=File path to read"`
}
type ReadFileResponse struct {
Content string `json:"content"`
Success bool `json:"success"`
}
readFileTool := toolkit.NewChild(
"read_file",
"Reads content from a file",
func(ctx context.Context, args ReadFileArgs) (interface{}, error) {
content, err := os.ReadFile(args.Path)
if err != nil {
return ReadFileResponse{Success: false}, err
}
return ReadFileResponse{Content: string(content), Success: true}, nil
},
)
Returns:
- A fully configured Child instance ready to be added to a Parent
type ChildResponse ¶
type ChildResponse struct {
Name string `json:"name"`
Response interface{} `json:"response,omitempty"`
}
ChildResponse represents the response from executing a single child tool. The Response field can contain either the successful result (as returned by the tool's handler) or a ToolKitError if an error occurred during execution, providing a consistent error handling mechanism.
type Parent ¶
type Parent interface {
// GetName returns the unique name of the parent toolset.
// This name is used for lookup in toolkit requests and must be unique
// within a toolkit instance.
GetName() string
// GetDescription provides a human-readable description of the parent's purpose.
// This description is used in schema generation and documentation.
GetDescription() string
// GetChildren returns a map of the child tools managed by this parent,
// keyed by their unique names. These names are used for lookup during execution.
GetChildren() map[string]Child
// HandleChildren processes a list of child tool execution requests.
// It manages the execution workflow, including tool lookup, argument validation,
// execution, and error handling, returning a consolidated ParentResponse.
// The context should be propagated to each child's Handle method to support
// cancellation, timeouts, and other context-aware operations.
HandleChildren(ctx context.Context, childRequests []ToolKitChild) ParentResponse
}
Parent represents a category of related tools (Children) that share a common purpose. It acts as a namespace and orchestrates the execution of its child tools. Implementations should handle execution errors gracefully for each child tool while preserving the structure of the response.
func NewParent ¶
NewParent creates a new Parent toolkit definition using a builder pattern. It groups related Child tools under a common namespace and handles their execution orchestration automatically.
Parameters:
- name: The unique name for this parent toolkit (must be unique within a Toolkit)
- description: A human-readable description of the category's purpose
- children: A variadic list of Child instances to include in this parent
Behavior:
- Nil children are skipped with a warning
- If duplicate child names are detected, the last one overwrites previous instances
Example:
// Create child tools first
readFileTool := toolkit.NewChild("read_file", "Reads a file", handleReadFile)
writeFileTool := toolkit.NewChild("write_file", "Writes a file", handleWriteFile)
// Group them into a parent category
fileOpsParent := toolkit.NewParent(
"file_operations",
"Tools for file system operations",
readFileTool, writeFileTool,
)
Returns:
- A fully configured Parent instance ready to be added to a Toolkit
type ParentResponse ¶
type ParentResponse struct {
Name string `json:"name"`
ChildsResponses []ChildResponse `json:"childsResponses,omitempty"`
}
ParentResponse represents the aggregated response from processing a specific parent toolkit within a request. It contains the parent's name and an ordered list of responses from each child tool that was executed, maintaining the original execution order.
func (*ParentResponse) AddResponse ¶
func (pr *ParentResponse) AddResponse(cr ChildResponse)
AddResponse appends a ChildResponse to the ParentResponse's list of child responses. This helper method is used by Parent implementations to build the response structure during child tool execution.
type ToolKit ¶
type ToolKit struct {
Name string `json:"name" jsonschema:"required,description=The name of the toolkit."`
ToolKitParents []ToolKitParent `json:"parents" jsonschema:"required,description=The parent toolkits to execute within the toolkit."`
}
ToolKit represents the top-level structure of a toolkit execution request. It defines the format that AI models or external clients use to invoke tools. Multiple parent and child tools can be invoked in a single request, enabling parallel execution and reducing round-trip latency.
type ToolKitChild ¶
type ToolKitChild struct {
Name string `json:"name" jsonschema:"required,description=The name of the child tool to execute."`
Args json.RawMessage `json:"args" jsonschema:"required,description=The arguments for the child tool, as a JSON object."`
}
ToolKitChild represents an individual child tool requested for execution within a ToolKitParent request. It holds the tool name and its arguments as raw JSON, allowing for delayed parsing by the specific tool handler during execution.
type ToolKitError ¶
type ToolKitError struct {
Code string `json:"Code"` // A machine-readable error code (e.g., "invalid_arguments", "handler_execution_error")
Message string `json:"Message"` // A human-readable description of the error
}
ToolKitError provides a standardized structure for errors occurring within the toolkit framework. It encapsulates both a machine-readable error code for programmatic handling and a human-readable message for debugging and user feedback.
func (ToolKitError) Error ¶
func (e ToolKitError) Error() string
Error implements the standard error interface for ToolKitError. This enables ToolKitError to be used with standard Go error handling mechanisms while preserving the structured error information.
type ToolKitParent ¶
type ToolKitParent struct {
Name string `json:"name" jsonschema:"required,description=The name of the parent toolkit to execute."`
ToolKitChilds []ToolKitChild `json:"childs" jsonschema:"required,description=The child tools to execute within this parent."`
}
ToolKitParent represents a specific parent toolkit requested for execution within a ToolKit request. It encapsulates a collection of related child tools that should be executed together under the same parent namespace.
type ToolKitResponse ¶
type ToolKitResponse struct {
Name string `json:"name"`
Responses []ParentResponse `json:"responses,omitempty"`
}
ToolKitResponse represents the top-level structure of the response returned after processing a ToolKit request. It preserves the hierarchical structure of the request, containing responses from all parent and child tools that were executed.
func (*ToolKitResponse) AddResponse ¶
func (tr *ToolKitResponse) AddResponse(pr ParentResponse)
AddResponse appends a ParentResponse to the ToolKitResponse's list of responses. This helper method is used during the toolkit processing workflow to build the hierarchical response structure.
type Toolkit ¶
type Toolkit struct {
// contains filtered or unexported fields
}
Toolkit orchestrates the execution of hierarchical tool structures. It serves as the top-level container for Parent tools and provides methods for generating descriptions, JSON schemas, and processing execution requests. Each Toolkit instance maintains a registry of Parent tools identified by unique names.
func New ¶
New creates a new Toolkit instance with the provided name and parent toolkits. It registers the provided Parent implementations for execution and provides safeguards against nil or duplicate parents.
Parameters:
- name: A unique identifier for this toolkit instance
- parents: A variadic list of Parent implementations to register in this toolkit
Behavior:
- Nil parents are skipped with a warning
- If duplicate parent names are detected, the last one overwrites previous instances
- No default parents are added automatically
Returns:
- A pointer to the initialized Toolkit instance
Example:
fileOpsParent := toolkit.NewParent("file_ops", "File operations", fileReadTool, fileWriteTool)
networkParent := toolkit.NewParent("network", "Network operations", httpFetchTool)
toolkit := toolkit.New("my_toolkit", fileOpsParent, networkParent)
func (*Toolkit) GetToolkitDescription ¶
GetToolkitDescription generates a human-readable XML-like description of the toolkit structure. This description is typically used for providing context to language models about the available tools and their capabilities.
The description includes:
- The toolkit name and a general explanation of the toolkit structure
- A list of all parents with their descriptions
- For each parent, a list of its child tools with descriptions and input schemas
Returns:
- A formatted string containing the full toolkit description
This description is designed to be understood by LLMs for effective tool use and follows a consistent XML-like format that highlights the hierarchical structure.
func (*Toolkit) GetToolkitName ¶
GetToolkitName returns the configured name of the toolkit instance. This name is used in responses and can be useful for identifying which toolkit handled a particular request in multi-toolkit environments.
func (*Toolkit) GetToolkitSchema ¶
GetToolkitSchema returns a JSON schema representation for the toolkit's request structure. The schema is provider-specific and currently supports "anthropic" (Claude) format, which is used as the default for unsupported providers.
Parameters:
- provider: The target provider identifier (e.g., "anthropic" for Claude)
Returns:
- A JSON schema object suitable for the specified provider
The schema includes the full structure of the ToolKit request format, including definitions for parents and children, and is suitable for direct use with LLM tool registration endpoints.
func (*Toolkit) HandleToolKit ¶
func (t *Toolkit) HandleToolKit(ctx context.Context, input json.RawMessage) (ToolKitResponse, error)
HandleToolKit is the main entry point for processing toolkit execution requests. It accepts raw JSON input containing parent and child tool invocations, parses it, and orchestrates the execution of the requested tools.
Parameters:
- ctx: The execution context for propagating cancellation, deadlines, and values
- input: Raw JSON payload containing the toolkit request (must follow ToolKit structure)
Returns:
- ToolKitResponse: Hierarchical response containing results from all executed tools
- error: Any error encountered during processing, or nil on success
The method handles various failure scenarios gracefully:
- If JSON parsing fails, it returns a structured error response
- If requested parents are not found, it includes error responses for those parents
- If child tools fail, their errors are included in the appropriate child responses
This enables clients to process both successful and failed operations in a consistent way.