tools.go 1.7 KB

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