Added support for tools

This commit is contained in:
alejandro-angulo 2025-06-03 22:13:25 -07:00
parent 9d238ea9dc
commit 74feac4e25
Signed by: alejandro-angulo
GPG key ID: 75579581C74554B6

27
main.go
View file

@ -3,6 +3,7 @@ package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"os"
@ -19,24 +20,27 @@ func main() {
}
return scanner.Text(), true
}
tools := []ToolDefinition{}
agent := NewAgent(&client, getUserMessage)
agent := NewAgent(&client, getUserMessage, tools)
err := agent.Run(context.TODO())
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
}
}
func NewAgent(client *anthropic.Client, getUserMessage func() (string, bool)) *Agent {
func NewAgent(client *anthropic.Client, getUserMessage func() (string, bool), tools []ToolDefinition) *Agent {
return &Agent{
client: client,
getUserMessage: getUserMessage,
tools: tools,
}
}
type Agent struct {
client *anthropic.Client
getUserMessage func() (string, bool)
tools []ToolDefinition
}
func (a *Agent) Run(ctx context.Context) error {
@ -72,10 +76,29 @@ func (a *Agent) Run(ctx context.Context) error {
}
func (a *Agent) runInference(ctx context.Context, conversation []anthropic.MessageParam) (*anthropic.Message, error) {
anthropicTools := []anthropic.ToolUnionParam{}
for _, tool := range a.tools {
anthropicTools = append(anthropicTools, anthropic.ToolUnionParam{
OfTool: &anthropic.ToolParam{
Name: tool.Name,
Description: anthropic.String(tool.Description),
InputSchema: tool.InputSchema,
},
})
}
message, err := a.client.Messages.New(ctx, anthropic.MessageNewParams{
Model: anthropic.ModelClaude3_7SonnetLatest,
MaxTokens: int64(1024),
Messages: conversation,
Tools: anthropicTools,
})
return message, err
}
type ToolDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema anthropic.ToolInputSchemaParam `json:"input_schema"`
Function func(input json.RawMessage) (string, error)
}