62 lines
1.4 KiB
Go
62 lines
1.4 KiB
Go
package client
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type ToolHandlerInfo struct {
|
|
UserId uuid.UUID
|
|
ImageId uuid.UUID
|
|
}
|
|
|
|
type ToolHandler struct {
|
|
Fn func(info ToolHandlerInfo, args string, call ToolCall) (string, error)
|
|
}
|
|
|
|
type ToolsHandlers struct {
|
|
handlers *map[string]ToolHandler
|
|
}
|
|
|
|
func (handler ToolsHandlers) Handle(info ToolHandlerInfo, toolCallMessage AgentAssistantToolCall) (AgentTextMessage, error) {
|
|
fnName := toolCallMessage.ToolCalls[0].Function.Name
|
|
arguments := toolCallMessage.ToolCalls[0].Function.Arguments
|
|
|
|
fnHandler, exists := (*handler.handlers)[fnName]
|
|
if !exists {
|
|
return AgentTextMessage{}, errors.New("Could not find tool with this name.")
|
|
}
|
|
|
|
res, err := fnHandler.Fn(info, arguments, toolCallMessage.ToolCalls[0])
|
|
if err != nil {
|
|
return AgentTextMessage{}, err
|
|
}
|
|
|
|
return AgentTextMessage{
|
|
Role: "tool",
|
|
Name: fnName,
|
|
Content: res,
|
|
ToolCallId: toolCallMessage.ToolCalls[0].Id,
|
|
}, nil
|
|
}
|
|
|
|
func (handler ToolsHandlers) AddTool(name string, fn func(info ToolHandlerInfo, args string, call ToolCall) (any, error)) {
|
|
(*handler.handlers)[name] = ToolHandler{
|
|
Fn: func(info ToolHandlerInfo, args string, call ToolCall) (string, error) {
|
|
res, err := fn(info, args, call)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
marshalledRes, err := json.Marshal(res)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return string(marshalledRes), nil
|
|
},
|
|
}
|
|
}
|