Skip to main content
Tools allow models to call functions during generation.

DefineTool()

Defines and registers a tool.
import (
    "github.com/firebase/genkit/go/ai"
    "github.com/firebase/genkit/go/genkit"
)

type WeatherInput struct {
    City string `json:"city"`
}

type WeatherOutput struct {
    Temperature int    `json:"temperature"`
    Conditions  string `json:"conditions"`
}

weatherTool := genkit.DefineTool(g, "getWeather",
    "Gets current weather for a city",
    func(ctx *ai.ToolContext, input WeatherInput) (WeatherOutput, error) {
        // Tool implementation
        return WeatherOutput{
            Temperature: 72,
            Conditions:  "sunny",
        }, nil
    },
)

Type Parameters

In
any
required
Input type (must have JSON tags for schema generation)
Out
any
required
Output type (must have JSON tags for schema generation)

Parameters

g
*Genkit
required
Genkit instance
name
string
required
Unique tool name
description
string
required
Description of what the tool does (helps model understand when to use it)
fn
ToolFunc[In, Out]
required
Tool implementation functionSignature:
func(ctx *ToolContext, input In) (Out, error)
opts
...ToolOption
Optional tool configurationAvailable options:
  • ai.WithInputSchema(map[string]any) - Custom input JSON schema
  • ai.WithInputSchemaName(string) - Reference registered schema

Returns

tool
*ToolDef[In, Out]
Tool definition that can be passed to WithTools()

DefineMultipartTool()

Defines a tool that returns content parts (text + media).
type ImageGenInput struct {
    Prompt string `json:"prompt"`
}

imageGenTool := genkit.DefineMultipartTool(g, "generateImage",
    "Generates an image from a prompt",
    func(ctx *ai.ToolContext, input ImageGenInput) (*ai.MultipartToolResponse, error) {
        imageBytes := generateImage(input.Prompt)
        
        return &ai.MultipartToolResponse{
            Output: map[string]any{
                "status": "success",
                "prompt": input.Prompt,
            },
            Content: []*ai.Part{
                ai.NewMediaPart("image/png", string(imageBytes)),
            },
        }, nil
    },
)

Type Parameters

In
any
required
Input type

Parameters

Same as DefineTool() except function returns *MultipartToolResponse.

Returns

tool
*ToolDef[In, *MultipartToolResponse]
Multipart tool definition

DefineToolWithInputSchema()

Deprecated: Use DefineTool() with ai.WithInputSchema() instead.
Defines a tool with custom input schema.
inputSchema := map[string]any{
    "type": "object",
    "properties": map[string]any{
        "city": map[string]any{"type": "string"},
    },
}

weatherTool := genkit.DefineToolWithInputSchema[WeatherOutput](
    g, "getWeather",
    "Gets weather",
    inputSchema,
    func(ctx *ai.ToolContext, input any) (WeatherOutput, error) {
        city := input.(map[string]any)["city"].(string)
        return WeatherOutput{Temperature: 72}, nil
    },
)

Tool Context

ToolContext

type ToolContext struct {
    // Context fields available to tools
}
The ToolContext provides access to runtime information during tool execution.

Types

Tool

type Tool interface {
    Name() string
    Definition() *ToolDefinition
    // ...
}

ToolDefinition

type ToolDefinition struct {
    Name         string
    Description  string
    InputSchema  map[string]any
    OutputSchema map[string]any
}

MultipartToolResponse

type MultipartToolResponse struct {
    Output   any
    Content  []*Part
    Metadata map[string]any
}

ToolDef

type ToolDef[In, Out any] struct {
    // Tool definition with type parameters
}

// Methods
func (t *ToolDef[In, Out]) Name() string
func (t *ToolDef[In, Out]) Definition() *ToolDefinition

Example: Complete Tool Usage

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/firebase/genkit/go/ai"
    "github.com/firebase/genkit/go/genkit"
    "github.com/firebase/genkit/go/plugins/googlegenai"
)

type CalculatorInput struct {
    Operation string  `json:"operation"`
    A         float64 `json:"a"`
    B         float64 `json:"b"`
}

type CalculatorOutput struct {
    Result float64 `json:"result"`
}

func main() {
    ctx := context.Background()
    
    g := genkit.Init(ctx,
        genkit.WithPlugins(&googlegenai.GoogleAI{}),
    )
    
    // Define calculator tool
    calcTool := genkit.DefineTool(g, "calculator",
        "Performs basic arithmetic operations (add, subtract, multiply, divide)",
        func(ctx *ai.ToolContext, input CalculatorInput) (CalculatorOutput, error) {
            var result float64
            
            switch input.Operation {
            case "add":
                result = input.A + input.B
            case "subtract":
                result = input.A - input.B
            case "multiply":
                result = input.A * input.B
            case "divide":
                if input.B == 0 {
                    return CalculatorOutput{}, fmt.Errorf("division by zero")
                }
                result = input.A / input.B
            default:
                return CalculatorOutput{}, fmt.Errorf("unknown operation: %s", input.Operation)
            }
            
            return CalculatorOutput{Result: result}, nil
        },
    )
    
    // Use the tool
    resp, err := genkit.Generate(ctx, g,
        ai.WithModelName("googleai/gemini-2.0-flash"),
        ai.WithPrompt("What is 15 multiplied by 7?"),
        ai.WithTools(calcTool),
    )
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println(resp.Text())
}

Build docs developers (and LLMs) love