tools.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. const (
  14. ToolResponseTypeText toolResponseType = "text"
  15. ToolResponseTypeImage toolResponseType = "image"
  16. SessionIDContextKey = "session_id"
  17. MessageIDContextKey = "message_id"
  18. )
  19. type ToolResponse struct {
  20. Type toolResponseType `json:"type"`
  21. Content string `json:"content"`
  22. Metadata string `json:"metadata,omitempty"`
  23. IsError bool `json:"is_error"`
  24. }
  25. func NewTextResponse(content string) ToolResponse {
  26. return ToolResponse{
  27. Type: ToolResponseTypeText,
  28. Content: content,
  29. }
  30. }
  31. func WithResponseMetadata(response ToolResponse, metadata any) ToolResponse {
  32. if metadata != nil {
  33. metadataBytes, err := json.Marshal(metadata)
  34. if err != nil {
  35. return response
  36. }
  37. response.Metadata = string(metadataBytes)
  38. }
  39. return response
  40. }
  41. func NewTextErrorResponse(content string) ToolResponse {
  42. return ToolResponse{
  43. Type: ToolResponseTypeText,
  44. Content: content,
  45. IsError: true,
  46. }
  47. }
  48. type ToolCall struct {
  49. ID string `json:"id"`
  50. Name string `json:"name"`
  51. Input string `json:"input"`
  52. }
  53. type BaseTool interface {
  54. Info() ToolInfo
  55. Run(ctx context.Context, params ToolCall) (ToolResponse, error)
  56. }
  57. func GetContextValues(ctx context.Context) (string, string) {
  58. sessionID := ctx.Value(SessionIDContextKey)
  59. messageID := ctx.Value(MessageIDContextKey)
  60. if sessionID == nil {
  61. return "", ""
  62. }
  63. if messageID == nil {
  64. return sessionID.(string), ""
  65. }
  66. return sessionID.(string), messageID.(string)
  67. }