-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
178 lines (161 loc) · 5.22 KB
/
Copy pathmain.go
File metadata and controls
178 lines (161 loc) · 5.22 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"strings"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
)
// Agent wraps Claude with a set of tools and handles the reasoning loop automatically.
type Agent struct {
client *anthropic.Client
tools []anthropic.ToolParam
history []anthropic.MessageParam
system []anthropic.TextBlockParam
}
// NewAgent creates an agent with a system prompt and a set of tools.
func NewAgent(client *anthropic.Client, systemPrompt string, tools []anthropic.ToolParam) *Agent {
return &Agent{
client: client,
tools: tools,
system: []anthropic.TextBlockParam{
anthropic.NewTextBlockParam(systemPrompt),
},
}
}
// Run sends a user message and continues the tool-use loop until Claude returns end_turn.
func (a *Agent) Run(ctx context.Context, userMsg string) (string, error) {
a.history = append(a.history, anthropic.NewUserMessage(anthropic.NewTextBlock(userMsg)))
for {
resp, err := a.client.Messages.New(ctx, anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus4_7,
MaxTokens: 2048,
System: a.system,
Tools: a.tools,
Messages: a.history,
})
if err != nil {
return "", err
}
a.history = append(a.history, anthropic.NewAssistantMessage(resp.Content...))
if resp.StopReason == "end_turn" {
var sb strings.Builder
for _, block := range resp.Content {
switch b := block.AsAny().(type) {
case anthropic.TextBlock:
sb.WriteString(b.Text)
}
}
return sb.String(), nil
}
if resp.StopReason == "tool_use" {
var toolResults []anthropic.ToolResultBlockParam
for _, block := range resp.Content {
switch b := block.AsAny().(type) {
case anthropic.ToolUseBlock:
fmt.Printf(" → calling %s\n", b.Name)
result := dispatchTool(b.Name, b.Input)
toolResults = append(toolResults, anthropic.ToolResultBlockParam{
ToolUseID: b.ID,
Content: []anthropic.ToolResultBlockParamContentUnion{
{OfRequestTextBlock: &anthropic.TextBlockParam{Text: result}},
},
})
}
}
blocks := make([]anthropic.ContentBlockParamUnion, len(toolResults))
for i, tr := range toolResults {
blocks[i] = anthropic.ContentBlockParamUnion{OfToolResult: &tr}
}
a.history = append(a.history, anthropic.NewUserMessage(blocks...))
}
}
}
// Tool registry
var availableTools = []anthropic.ToolParam{
{
Name: "search_web",
Description: anthropic.String("Search the web for current information on a topic"),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: map[string]interface{}{
"query": map[string]interface{}{"type": "string", "description": "Search query"},
},
Required: []string{"query"},
},
},
{
Name: "read_file",
Description: anthropic.String("Read the contents of a local file"),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: map[string]interface{}{
"path": map[string]interface{}{"type": "string", "description": "File path to read"},
},
Required: []string{"path"},
},
},
{
Name: "write_file",
Description: anthropic.String("Write content to a local file"),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: map[string]interface{}{
"path": map[string]interface{}{"type": "string", "description": "File path to write"},
"content": map[string]interface{}{"type": "string", "description": "Content to write"},
},
Required: []string{"path", "content"},
},
},
{
Name: "run_command",
Description: anthropic.String("Run a shell command and return its output"),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: map[string]interface{}{
"command": map[string]interface{}{"type": "string", "description": "Shell command to run"},
},
Required: []string{"command"},
},
},
}
func dispatchTool(name string, input json.RawMessage) string {
switch name {
case "search_web":
var p struct{ Query string `json:"query"` }
json.Unmarshal(input, &p)
return fmt.Sprintf(`{"results":["Result 1 for '%s'","Result 2 for '%s'"]}`, p.Query, p.Query)
case "read_file":
var p struct{ Path string `json:"path"` }
json.Unmarshal(input, &p)
return fmt.Sprintf(`{"content":"(stub) contents of %s"}`, p.Path)
case "write_file":
var p struct {
Path string `json:"path"`
Content string `json:"content"`
}
json.Unmarshal(input, &p)
return fmt.Sprintf(`{"success":true,"path":"%s"}`, p.Path)
case "run_command":
var p struct{ Command string `json:"command"` }
json.Unmarshal(input, &p)
return fmt.Sprintf(`{"output":"(stub) ran: %s"}`, p.Command)
default:
return fmt.Sprintf(`{"error":"unknown tool %q"}`, name)
}
}
func main() {
client := anthropic.NewClient(option.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")))
ctx := context.Background()
agent := NewAgent(
client,
"You are a research assistant. Use your tools to gather information, then write a concise summary. Think step by step.",
availableTools,
)
task := "Research the latest Go release, find any release notes in ./NOTES.md, and write a summary to ./SUMMARY.md"
fmt.Printf("Task: %s\n\n", task)
result, err := agent.Run(ctx, task)
if err != nil {
fmt.Fprintf(os.Stderr, "agent error: %v\n", err)
os.Exit(1)
}
fmt.Printf("\nFinal answer:\n%s\n", result)
}