Debian Codegraph @

examples/tool-runner/main.go

raw
1 // Example demonstrating the Tool Runner framework
2 package main
3
4 import (
5 "context"
6 "fmt"
7 "strconv"
8
9 "github.com/anthropics/anthropic-sdk-go"
10 "github.com/anthropics/anthropic-sdk-go/toolrunner"
11 )
12
13 type CalculatorInput struct {
14 Operation string `json:"operation" jsonschema:"required,description=The arithmetic operation to perform,enum=add,subtract,multiply,divide"`
15 A float64 `json:"a" jsonschema:"required,description=The first number"`
16 B float64 `json:"b" jsonschema:"required,description=The second number"`
17 }
18
19 func calculate(ctx context.Context, calc CalculatorInput) (anthropic.BetaToolResultBlockParamContentUnion, error) {
20 var floatResult float64
21 fmt.Printf("🔧 Calculator tool called with: %+v\n", calc)
22 switch calc.Operation {
23 case "add":
24 floatResult = calc.A + calc.B
25 case "subtract":
26 floatResult = calc.A - calc.B
27 case "multiply":
28 floatResult = calc.A * calc.B
29 case "divide":
30 if calc.B == 0 {
31 return anthropic.BetaToolResultBlockParamContentUnion{}, fmt.Errorf("division by zero")
32 }
33 floatResult = calc.A / calc.B
34 default:
35 return anthropic.BetaToolResultBlockParamContentUnion{}, fmt.Errorf("unknown operation: %s", calc.Operation)
36 }
37
38 return anthropic.BetaToolResultBlockParamContentUnion{
39 OfText: &anthropic.BetaTextBlockParam{Text: strconv.FormatFloat(floatResult, 'g', -1, 64)},
40 }, nil
41 }
42
43 func main() {
44 client := anthropic.NewClient()
45 ctx := context.Background()
46
47 calculatorTool, err := toolrunner.NewBetaToolFromJSONSchema("calculator", "Perform basic arithmetic operations", calculate)
48 if err != nil {
49 fmt.Printf("Error creating calculator tool: %v\n", err)
50 return
51 }
52
53 fmt.Printf("Starting tool runner with calculator tool: %+v\n", calculatorTool)
54
55 tools := []anthropic.BetaTool{calculatorTool}
56
57 runner := client.Beta.Messages.NewToolRunner(tools, anthropic.BetaToolRunnerParams{
58 BetaMessageNewParams: anthropic.BetaMessageNewParams{
59 Model: anthropic.ModelClaudeSonnet4_20250514,
60 MaxTokens: 1000,
61 Messages: []anthropic.BetaMessageParam{
62 anthropic.NewBetaUserMessage(
63 anthropic.NewBetaTextBlock("Calculate 15 * 23, then add 10 to the result"),
64 ),
65 },
66 },
67 MaxIterations: 5,
68 })
69
70 finalMessage, err := runner.RunToCompletion(ctx)
71 if err != nil {
72 fmt.Printf("Error running tools: %v\n", err)
73 return
74 }
75
76 fmt.Printf("Final message content:\n")
77 fmt.Printf("%+v\n", finalMessage)
78 }