tools.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. Name() string
  60. Run(ctx context.Context, params ToolCall) (ToolResponse, error)
  61. }
  62. func GetContextValues(ctx context.Context) (string, string) {
  63. sessionID := ctx.Value(SessionIDContextKey)
  64. messageID := ctx.Value(MessageIDContextKey)
  65. if sessionID == nil {
  66. return "", ""
  67. }
  68. if messageID == nil {
  69. return sessionID.(string), ""
  70. }
  71. return sessionID.(string), messageID.(string)
  72. }