Tools Example
Function calling with the PromptKit SDK.
What You’ll Learn
Section titled “What You’ll Learn”- Defining tools in pack files
- Registering tool handlers with
OnTool() - Automatic JSON serialization
- Multiple tool handlers with
OnTools()
Prerequisites
Section titled “Prerequisites”- Go 1.21+
- OpenAI API key
Running the Example
Section titled “Running the Example”export OPENAI_API_KEY=your-keygo run .Code Overview
Section titled “Code Overview”conv, err := sdk.Open("./tools.pack.json", "assistant")if err != nil { log.Fatal(err)}defer conv.Close()
// Register tool handlersconv.OnTool("get_time", func(args map[string]any) (any, error) { timezone := args["timezone"].(string) return map[string]string{ "time": "14:30:00", "timezone": timezone, }, nil})
conv.OnTool("get_weather", func(args map[string]any) (any, error) { city := args["city"].(string) return map[string]any{ "city": city, "temperature": 22.5, "conditions": "Sunny", }, nil})
// LLM will automatically call tools when neededresp, _ := conv.Send(ctx, "What's the weather in London?")fmt.Println(resp.Text())Pack File Structure
Section titled “Pack File Structure”Tools must be:
- Defined in the
toolssection - Listed in the prompt’s
toolsarray
{ "prompts": { "assistant": { "system_template": "You are a helpful assistant...", "tools": ["get_weather", "get_time"] } }, "tools": { "get_weather": { "name": "get_weather", "description": "Get current weather for a city", "parameters": { "type": "object", "properties": { "city": { "type": "string" }, "country": { "type": "string" } }, "required": ["city", "country"] } } }}Handler Signature
Section titled “Handler Signature”func(args map[string]any) (any, error)- args: Parameters from the LLM (matches tool schema)
- return: Any JSON-serializable value, or error
Multiple Tools
Section titled “Multiple Tools”Register all handlers at once:
conv.OnTools(map[string]sdk.ToolHandler{ "get_time": timeHandler, "get_weather": weatherHandler, "search": searchHandler,})Return Structs
Section titled “Return Structs”Return Go structs - they’re automatically serialized:
type Weather struct { City string `json:"city"` Temperature float64 `json:"temperature"`}
conv.OnTool("get_weather", func(args map[string]any) (any, error) { return Weather{City: "London", Temperature: 18.5}, nil})Key Concepts
Section titled “Key Concepts”- Declarative Tools - Define in pack, implement in code
- Auto Serialization - Return any Go value
- Error Handling - Return errors to inform the LLM
- Tool Calls - LLM decides when to use tools
Next Steps
Section titled “Next Steps”- Hello Example - Basic conversation
- Streaming Example - Real-time responses
- HITL Example - Human-in-the-loop approval