Debian Codegraph @

examples/tools-streaming/main.go

raw
1 package main
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7
8 "github.com/anthropics/anthropic-sdk-go"
9 )
10
11 func main() {
12 client := anthropic.NewClient()
13
14 content := "What is the weather in San Francisco, CA?"
15
16 println(color("[user]: ") + content)
17
18 messages := []anthropic.MessageParam{
19 anthropic.NewUserMessage(anthropic.NewTextBlock(content)),
20 }
21
22 toolParams := []anthropic.ToolParam{
23 {
24 Name: "get_coordinates",
25 Description: anthropic.String("Accepts a place as an address, then returns the latitude and longitude coordinates."),
26 InputSchema: anthropic.ToolInputSchemaParam{
27 Properties: map[string]any{
28 "location": map[string]any{
29 "type": "string",
30 "description": "The location to look up.",
31 },
32 },
33 },
34 },
35 {
36 Name: "get_temperature_unit",
37 InputSchema: anthropic.ToolInputSchemaParam{
38 Properties: map[string]any{
39 "country": map[string]any{
40 "type": "string",
41 "description": "The country",
42 },
43 },
44 },
45 },
46 {
47 Name: "get_weather",
48 Description: anthropic.String("Get the weather at a specific location"),
49 InputSchema: anthropic.ToolInputSchemaParam{
50 Properties: map[string]any{
51 "lat": map[string]any{
52 "type": "number",
53 "description": "The lattitude of the location to check weather.",
54 },
55 "long": map[string]any{
56 "type": "number",
57 "description": "The longitude of the location to check weather.",
58 },
59 "unit": map[string]any{
60 "type": "string",
61 "enum": []string{"celsius", "fahrenheit"},
62 "description": "Unit for the output",
63 },
64 },
65 },
66 },
67 }
68 tools := make([]anthropic.ToolUnionParam, len(toolParams))
69 for i, toolParam := range toolParams {
70 tools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}
71 }
72
73 for {
74 stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{
75 Model: anthropic.ModelClaudeSonnet4_5_20250929,
76 MaxTokens: 1024,
77 Messages: messages,
78 Tools: tools,
79 })
80
81 print(color("[assistant]: "))
82
83 message := anthropic.Message{}
84 for stream.Next() {
85 event := stream.Current()
86 err := message.Accumulate(event)
87 if err != nil {
88 panic(err)
89 }
90
91 switch event := event.AsAny().(type) {
92 case anthropic.ContentBlockStartEvent:
93 if event.ContentBlock.Name != "" {
94 print(event.ContentBlock.Name + ": ")
95 }
96 case anthropic.ContentBlockDeltaEvent:
97 print(event.Delta.Text)
98 print(event.Delta.PartialJSON)
99 case anthropic.ContentBlockStopEvent:
100 println()
101 println()
102 case anthropic.MessageStopEvent:
103 println()
104 }
105 }
106
107 if stream.Err() != nil {
108 panic(stream.Err())
109 }
110
111 messages = append(messages, message.ToParam())
112 toolResults := []anthropic.ContentBlockParamUnion{}
113
114 for _, block := range message.Content {
115 switch variant := block.AsAny().(type) {
116 case anthropic.ToolUseBlock:
117 print(color("[user (" + block.Name + ")]: "))
118
119 var response any
120 switch block.Name {
121 case "get_coordinates":
122 var input struct {
123 Location string `json:"location"`
124 }
125 err := json.Unmarshal([]byte(variant.JSON.Input.Raw()), &input)
126 if err != nil {
127 panic(err)
128 }
129 response = GetCoordinates(input.Location)
130 case "get_temperature_unit":
131 var input struct {
132 Country string `json:"country"`
133 }
134 err := json.Unmarshal([]byte(variant.JSON.Input.Raw()), &input)
135 if err != nil {
136 panic(err)
137 }
138 response = GetTemperatureUnit(input.Country)
139 case "get_weather":
140 var input struct {
141 Lat float64 `json:"lat"`
142 Long float64 `json:"long"`
143 Unit string `json:"unit"`
144 }
145 err := json.Unmarshal([]byte(variant.JSON.Input.Raw()), &input)
146 if err != nil {
147 panic(err)
148 }
149 response = GetWeather(input.Lat, input.Long, input.Unit)
150 }
151
152 b, err := json.Marshal(response)
153 if err != nil {
154 panic(err)
155 }
156
157 println(string(b))
158
159 toolResults = append(toolResults, anthropic.NewToolResultBlock(block.ID, string(b), false))
160 }
161 }
162
163 if len(toolResults) == 0 {
164 break
165 }
166
167 messages = append(messages, anthropic.NewUserMessage(toolResults...))
168 }
169 }
170
171 type CoordinateResponse struct {
172 Long float64 `json:"long"`
173 Lat float64 `json:"lat"`
174 }
175
176 func GetCoordinates(location string) CoordinateResponse {
177 return CoordinateResponse{
178 Long: -122.4194,
179 Lat: 37.7749,
180 }
181 }
182
183 func GetTemperatureUnit(country string) string {
184 return "farenheit"
185 }
186
187 type WeatherResponse struct {
188 Unit string `json:"unit"`
189 Temperature float64 `json:"temperature"`
190 }
191
192 func GetWeather(lat, long float64, unit string) WeatherResponse {
193 return WeatherResponse{
194 Unit: "farenheit",
195 Temperature: 122,
196 }
197 }
198
199 func color(s string) string {
200 return fmt.Sprintf("\033[1;%sm%s\033[0m", "33", s)
201 }