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