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
| package main
import ( "context" "fmt" "log" "math" "strconv" "strings"
"github.com/tmc/langchaingo/agents" "github.com/tmc/langchaingo/callbacks" "github.com/tmc/langchaingo/chains" "github.com/tmc/langchaingo/llms/ollama" "github.com/tmc/langchaingo/tools" )
type Max struct { callbacksHandler callbacks.Handler }
var _ tools.Tool = (*Max)(nil)
func NewMax(callbacksHandler callbacks.Handler) *Max { return &Max{ callbacksHandler: callbacksHandler, } }
func (m *Max) Name() string { return "max" }
func (m *Max) Description() string { return `Identify Numbers and Return the Maximum Value. This tool should take a comma-separated list of numbers as input. It can be used to compare the numbers and return the maximum value among them.` }
func (m *Max) Call(ctx context.Context, input string) (string, error) { if m.callbacksHandler != nil { m.callbacksHandler.HandleToolStart(ctx, input) }
numbers := strings.Split(input, ",") if len(numbers) == 0 { return fmt.Sprintf("no numbers found"), nil }
value := math.Inf(-1) for _, number := range numbers { n, err := strconv.ParseFloat(strings.TrimSpace(number), 64) if err != nil { return fmt.Sprintf("error parsing number %q: %v", number, err), nil } if n > value { value = n } }
result := strconv.FormatFloat(value, 'f', -1, 64)
if m.callbacksHandler != nil { m.callbacksHandler.HandleToolEnd(ctx, result) }
return "The maximum value is " + result, nil }
func main() { model, err := ollama.New( ollama.WithServerURL("http://localhost:11434"), ollama.WithModel("llama3.1"), ) if err != nil { log.Fatal("ollama", err) }
agent := agents.NewOneShotAgent(model, []tools.Tool{ NewMax(callbacks.LogHandler{}), }) executor := agents.NewExecutor(agent, agents.WithCallbacksHandler(callbacks.LogHandler{}))
result, err := chains.Run( context.Background(), executor, "9.9和9.11谁大?", ) if err != nil { log.Fatal(err) }
log.Println("result:", strings.TrimSpace(result)) }
|