tools.go

 1package tools
 2
 3import (
 4	"context"
 5	"encoding/json"
 6)
 7
 8type ToolInfo struct {
 9	Name        string
10	Description string
11	Parameters  map[string]any
12	Required    []string
13}
14
15type toolResponseType string
16
17const (
18	ToolResponseTypeText  toolResponseType = "text"
19	ToolResponseTypeImage toolResponseType = "image"
20
21	SessionIDContextKey = "session_id"
22	MessageIDContextKey = "message_id"
23)
24
25type ToolResponse struct {
26	Type     toolResponseType `json:"type"`
27	Content  string           `json:"content"`
28	Metadata string           `json:"metadata,omitempty"`
29	IsError  bool             `json:"is_error"`
30}
31
32func NewTextResponse(content string) ToolResponse {
33	return ToolResponse{
34		Type:    ToolResponseTypeText,
35		Content: content,
36	}
37}
38
39func WithResponseMetadata(response ToolResponse, metadata any) ToolResponse {
40	if metadata != nil {
41		metadataBytes, err := json.Marshal(metadata)
42		if err != nil {
43			return response
44		}
45		response.Metadata = string(metadataBytes)
46	}
47	return response
48}
49
50func NewTextErrorResponse(content string) ToolResponse {
51	return ToolResponse{
52		Type:    ToolResponseTypeText,
53		Content: content,
54		IsError: true,
55	}
56}
57
58type ToolCall struct {
59	ID    string `json:"id"`
60	Name  string `json:"name"`
61	Input string `json:"input"`
62}
63
64type BaseTool interface {
65	Info() ToolInfo
66	Run(ctx context.Context, params ToolCall) (ToolResponse, error)
67}
68
69func GetContextValues(ctx context.Context) (string, string) {
70	sessionID := ctx.Value(SessionIDContextKey)
71	messageID := ctx.Value(MessageIDContextKey)
72	if sessionID == nil {
73		return "", ""
74	}
75	if messageID == nil {
76		return sessionID.(string), ""
77	}
78	return sessionID.(string), messageID.(string)
79}