-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
154 lines (138 loc) · 4.5 KB
/
Copy pathmain.go
File metadata and controls
154 lines (138 loc) · 4.5 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
)
// Tool definitions describe the functions Claude can call.
// The JSON schema tells Claude what parameters each function expects.
var tools = []anthropic.ToolParam{
{
Name: "get_weather",
Description: anthropic.String("Get the current weather for a given city"),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: map[string]interface{}{
"city": map[string]interface{}{
"type": "string",
"description": "The city to get weather for",
},
"unit": map[string]interface{}{
"type": "string",
"enum": []string{"celsius", "fahrenheit"},
"description": "Temperature unit",
},
},
Required: []string{"city"},
},
},
{
Name: "calculate",
Description: anthropic.String("Perform a basic arithmetic calculation"),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: map[string]interface{}{
"expression": map[string]interface{}{
"type": "string",
"description": "A math expression like '2 + 2' or '10 * 5'",
},
},
Required: []string{"expression"},
},
},
}
func main() {
client := anthropic.NewClient(option.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")))
ctx := context.Background()
// Run the tool-use loop
runToolLoop(ctx, client, "What's the weather in London and Dublin? Also, what is 42 * 17?")
}
// runToolLoop implements the full tool-use cycle:
// 1. Send messages + tool definitions to Claude
// 2. If Claude returns tool_use blocks, execute the requested tools
// 3. Append results and call Claude again
// 4. Repeat until Claude returns a final text response (stop_reason == "end_turn")
func runToolLoop(ctx context.Context, client *anthropic.Client, userMsg string) {
history := []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(userMsg)),
}
for {
resp, err := client.Messages.New(ctx, anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus4_7,
MaxTokens: 1024,
Tools: tools,
Messages: history,
})
if err != nil {
fmt.Fprintf(os.Stderr, "API error: %v\n", err)
os.Exit(1)
}
// Append Claude's response to history
history = append(history, anthropic.NewAssistantMessage(resp.Content...))
// If Claude is done (no more tool calls), print the final answer
if resp.StopReason == "end_turn" {
for _, block := range resp.Content {
switch b := block.AsAny().(type) {
case anthropic.TextBlock:
fmt.Println(b.Text)
}
}
break
}
// Claude wants to use tools — collect all tool_use blocks and execute them
if resp.StopReason == "tool_use" {
var toolResults []anthropic.ToolResultBlockParam
for _, block := range resp.Content {
switch b := block.AsAny().(type) {
case anthropic.ToolUseBlock:
fmt.Printf("[Tool call] %s(%s)\n", b.Name, string(b.Input))
result := executeTool(b.Name, b.Input)
fmt.Printf("[Tool result] %s\n", result)
toolResults = append(toolResults, anthropic.ToolResultBlockParam{
ToolUseID: b.ID,
Content: []anthropic.ToolResultBlockParamContentUnion{
{OfRequestTextBlock: &anthropic.TextBlockParam{Text: result}},
},
})
}
}
// Feed all tool results back to Claude in a single user turn
history = append(history, anthropic.NewUserMessage(
func() []anthropic.ContentBlockParamUnion {
blocks := make([]anthropic.ContentBlockParamUnion, len(toolResults))
for i, tr := range toolResults {
blocks[i] = anthropic.ContentBlockParamUnion{OfToolResult: &tr}
}
return blocks
}()...,
))
}
}
}
// executeTool routes a tool call to the appropriate Go function.
func executeTool(name string, input json.RawMessage) string {
switch name {
case "get_weather":
var params struct {
City string `json:"city"`
Unit string `json:"unit"`
}
json.Unmarshal(input, ¶ms)
unit := params.Unit
if unit == "" {
unit = "celsius"
}
// Stub implementation — replace with a real weather API call
return fmt.Sprintf(`{"city":"%s","temperature":18,"unit":"%s","condition":"partly cloudy"}`, params.City, unit)
case "calculate":
var params struct {
Expression string `json:"expression"`
}
json.Unmarshal(input, ¶ms)
// Stub — in a real app you'd evaluate the expression safely
return fmt.Sprintf(`{"expression":"%s","result":"(calculated)"}`, params.Expression)
default:
return fmt.Sprintf(`{"error":"unknown tool %q"}`, name)
}
}