googletool

package
v0.9.21 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package googletool converts unified toolcall.Tool definitions into Gemini-compatible genai.FunctionDeclaration metadata for use with the [googleexecutor].

This package mirrors [claudetool] and [openaistool], providing tool conversion and error formatting for tool handlers that receive genai.FunctionCall values.

Tool Conversion

Use FromTool to convert a single unified tool, or Map to batch-convert an entire tool map:

tools := googletool.Map[MyResponse](unifiedTools)

Each converted tool automatically injects a "reasoning" parameter that the model must fill in to explain its intent before making the call.

Error Formatting

Use Error and ErrorWithContext to build genai.FunctionResponse error responses tagged with the originating call's ID and name:

return googletool.Error(call, "file not found: %s", path)

Thread Safety

All functions in this package are safe for concurrent use.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Error

func Error(call *genai.FunctionCall, format string, args ...any) *genai.FunctionResponse

Error creates a FunctionResponse with an error message

Example

ExampleError demonstrates creating error responses for function calls.

package main

import (
	"fmt"

	"chainguard.dev/driftlessaf/agents/toolcall/googletool"
	"google.golang.org/genai"
)

func main() {
	call := &genai.FunctionCall{
		ID:   "call_error",
		Name: "process_data",
	}

	// Simple error
	errResp := googletool.Error(call, "Invalid data format")
	fmt.Printf("Error ID: %s\n", errResp.ID)
	fmt.Printf("Error message: %v\n", errResp.Response["error"])

	// Formatted error
	filename := "data.csv"
	line := 42
	errResp = googletool.Error(call, "Parse error in %s at line %d", filename, line)
	fmt.Printf("Formatted error: %v\n", errResp.Response["error"])

}
Output:
Error ID: call_error
Error message: Invalid data format
Formatted error: Parse error in data.csv at line 42

func ErrorWithContext

func ErrorWithContext(call *genai.FunctionCall, err error, context map[string]any) *genai.FunctionResponse

ErrorWithContext creates a FunctionResponse with an error and additional context

Example

ExampleErrorWithContext demonstrates creating error responses with additional context.

package main

import (
	"errors"
	"fmt"

	"chainguard.dev/driftlessaf/agents/toolcall/googletool"
	"google.golang.org/genai"
)

func main() {
	call := &genai.FunctionCall{
		ID:   "call_context",
		Name: "upload_file",
		Args: map[string]any{
			"filename": "large_file.zip",
		},
	}

	// Simulate an error condition
	err := errors.New("file size exceeds limit")

	// Create error response with context
	errResp := googletool.ErrorWithContext(call, err, map[string]any{
		"filename":    "large_file.zip",
		"size_mb":     156.7,
		"limit_mb":    100,
		"retry_after": 3600,
	})

	// The response includes both the error and context
	fmt.Printf("Error: %v\n", errResp.Response["error"])
	fmt.Printf("Size: %.1f MB\n", errResp.Response["size_mb"])
	fmt.Printf("Limit: %d MB\n", errResp.Response["limit_mb"])

}
Output:
Error: file size exceeds limit
Size: 156.7 MB
Limit: 100 MB

func Map

func Map[Resp any](tools map[string]toolcall.Tool[Resp]) map[string]Metadata[Resp]

Map converts a unified tool map to Google-specific metadata.

Example

ExampleMap demonstrates converting a map of unified tools to Google-specific metadata.

package main

import (
	"context"
	"fmt"

	"chainguard.dev/driftlessaf/agents/agenttrace"
	"chainguard.dev/driftlessaf/agents/toolcall"
	"chainguard.dev/driftlessaf/agents/toolcall/googletool"
)

func main() {
	// Define a set of unified tools.
	type Result struct{ Answer string }

	tools := map[string]toolcall.Tool[Result]{
		"greet": {
			Def: toolcall.Definition{
				Name:        "greet",
				Description: "Greet a user by name.",
				Parameters: []toolcall.Parameter{{
					Name:        "name",
					Type:        "string",
					Description: "The name of the user.",
					Required:    true,
				}},
			},
			Handler: func(_ context.Context, call toolcall.ToolCall, _ *agenttrace.Trace[Result], _ *Result) map[string]any {
				return map[string]any{"greeting": "Hello!"}
			},
		},
		"farewell": {
			Def: toolcall.Definition{
				Name:        "farewell",
				Description: "Say farewell to a user.",
				Parameters:  []toolcall.Parameter{},
			},
			Handler: func(_ context.Context, _ toolcall.ToolCall, _ *agenttrace.Trace[Result], _ *Result) map[string]any {
				return map[string]any{"message": "Goodbye!"}
			},
		},
	}

	// Convert the entire map to Google-specific metadata.
	meta := googletool.Map(tools)

	fmt.Printf("Tool count: %d\n", len(meta))
	fmt.Printf("greet handler set: %v\n", meta["greet"].Handler != nil)
	fmt.Printf("farewell handler set: %v\n", meta["farewell"].Handler != nil)

}
Output:
Tool count: 2
greet handler set: true
farewell handler set: true

Types

type Metadata

type Metadata[Response any] struct {
	// Definition is the Google AI tool definition.
	Definition *genai.FunctionDeclaration

	// Handler is the function that processes tool calls.
	// It receives the context, tool call, trace, and a result pointer.
	// If the handler sets *result to a non-zero value, the executor will immediately exit with that response.
	Handler func(ctx context.Context, call *genai.FunctionCall, trace *agenttrace.Trace[Response], result *Response) *genai.FunctionResponse
}

Metadata describes a tool available to the Google AI agent.

func FromTool

func FromTool[Resp any](t toolcall.Tool[Resp]) Metadata[Resp]

FromTool converts a unified tool to Google-specific metadata.

Example

ExampleFromTool demonstrates converting a unified tool to Google-specific metadata.

package main

import (
	"context"
	"fmt"

	"chainguard.dev/driftlessaf/agents/agenttrace"
	"chainguard.dev/driftlessaf/agents/toolcall"
	"chainguard.dev/driftlessaf/agents/toolcall/googletool"
)

func main() {
	// Define a unified tool that works with any provider.
	type Result struct{ Summary string }

	t := toolcall.Tool[Result]{
		Def: toolcall.Definition{
			Name:        "summarize",
			Description: "Summarize the provided text.",
			Parameters: []toolcall.Parameter{{
				Name:        "text",
				Type:        "string",
				Description: "The text to summarize.",
				Required:    true,
			}},
		},
		Handler: func(_ context.Context, call toolcall.ToolCall, _ *agenttrace.Trace[Result], _ *Result) map[string]any {
			text, errResp := toolcall.OptionalParam(call, "text", "")
			if errResp != nil {
				return errResp
			}
			return map[string]any{"summary": "Summary of: " + text}
		},
	}

	// Convert the unified tool to Google-specific metadata.
	meta := googletool.FromTool(t)

	fmt.Printf("Name: %s\n", meta.Definition.Name)
	fmt.Printf("Description: %s\n", meta.Definition.Description)
	fmt.Printf("Handler set: %v\n", meta.Handler != nil)

}
Output:
Name: summarize
Description: Summarize the provided text.
Handler set: true

type SubmitMetadata added in v0.7.59

type SubmitMetadata[Response any] struct {
	// Definition is the Google AI tool definition.
	Definition *genai.FunctionDeclaration

	// Handler parses a submit tool call into a SubmitOutcome. It performs no
	// side effects on the run: committing the response is the executor's
	// decision. The handler records the trace tool call for parameter and
	// parse failures (Accepted=false); the executor records accepted calls so
	// their completion reflects the validation verdict.
	Handler func(
		ctx context.Context,
		call *genai.FunctionCall,
		trace *agenttrace.Trace[Response],
	) toolcall.SubmitOutcome[Response]
}

SubmitMetadata describes the terminal submit tool for the Google executor. It is registered via the executor's WithSubmitResultProvider option rather than the regular tool map because the submit tool is special: its accepted outcome — once the executor's result validators pass — becomes the run's final result and ends the agent loop.

Jump to

Keyboard shortcuts

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