Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
106 lines (88 loc) · 2.13 KB
/
Copy pathmain.go
File metadata and controls
106 lines (88 loc) · 2.13 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
package main
import (
"context"
"fmt"
"log"
"strconv"
"strings"
"github.com/smallnest/langgraphgo/llms"
openai "github.com/smallnest/langgraphgo/llms/nativeopenai"
"github.com/smallnest/langgraphgo/prebuilt"
"github.com/smallnest/langgraphgo/tool"
)
// CalculatorTool is a simple tool for demonstration
type CalculatorTool struct{}
func (t CalculatorTool) Name() string {
return "calculator"
}
func (t CalculatorTool) Description() string {
return "Useful for performing basic arithmetic operations. Input should be a string like '2 + 2' or '5 * 10'."
}
func (t CalculatorTool) Call(ctx context.Context, input string) (string, error) {
// Very simple parser for demo purposes
parts := strings.Fields(input)
if len(parts) != 3 {
return "", fmt.Errorf("invalid input format, expected 'a op b'")
}
a, err := strconv.ParseFloat(parts[0], 64)
if err != nil {
return "", err
}
b, err := strconv.ParseFloat(parts[2], 64)
if err != nil {
return "", err
}
op := parts[1]
var result float64
switch op {
case "+":
result = a + b
case "-":
result = a - b
case "*":
result = a * b
case "/":
if b == 0 {
return "", fmt.Errorf("division by zero")
}
result = a / b
default:
return "", fmt.Errorf("unknown operator: %s", op)
}
return fmt.Sprintf("%f", result), nil
}
func main() {
llm, err := openai.New()
if err != nil {
log.Fatal(err)
}
// Define Tools
inputTools := []tool.Tool{
CalculatorTool{},
}
// Create ReAct Agent using map state convenience function
agent, err := prebuilt.CreateAgentMap(llm, inputTools, 20)
if err != nil {
log.Fatal(err)
}
// Execute
query := "What is 25 * 4?"
fmt.Printf("User: %s\n", query)
initialState := map[string]any{
"messages": []llms.MessageContent{
llms.TextParts(llms.ChatMessageTypeHuman, query),
},
}
res, err := agent.Invoke(context.Background(), initialState)
if err != nil {
log.Fatal(err)
}
// Print Result
messages := res["messages"].([]llms.MessageContent)
lastMsg := messages[len(messages)-1]
if len(lastMsg.Parts) > 0 {
if textPart, ok := lastMsg.Parts[0].(llms.TextContent); ok {
fmt.Printf("Agent: %s\n", textPart.Text)
}
}
}