tools.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package tools
  2. import (
  3. "context"
  4. "os"
  5. "strconv"
  6. "strings"
  7. "testing"
  8. )
  9. type (
  10. sessionIDContextKey string
  11. messageIDContextKey string
  12. supportsImagesKey string
  13. modelNameKey string
  14. )
  15. const (
  16. // SessionIDContextKey is the key for the session ID in the context.
  17. SessionIDContextKey sessionIDContextKey = "session_id"
  18. // MessageIDContextKey is the key for the message ID in the context.
  19. MessageIDContextKey messageIDContextKey = "message_id"
  20. // SupportsImagesContextKey is the key for the model's image support capability.
  21. SupportsImagesContextKey supportsImagesKey = "supports_images"
  22. // ModelNameContextKey is the key for the model name in the context.
  23. ModelNameContextKey modelNameKey = "model_name"
  24. )
  25. // getContextValue is a generic helper that retrieves a typed value from context.
  26. // If the value is not found or has the wrong type, it returns the default value.
  27. func getContextValue[T any](ctx context.Context, key any, defaultValue T) T {
  28. value := ctx.Value(key)
  29. if value == nil {
  30. return defaultValue
  31. }
  32. if typedValue, ok := value.(T); ok {
  33. return typedValue
  34. }
  35. return defaultValue
  36. }
  37. // GetSessionFromContext retrieves the session ID from the context.
  38. func GetSessionFromContext(ctx context.Context) string {
  39. return getContextValue(ctx, SessionIDContextKey, "")
  40. }
  41. // GetMessageFromContext retrieves the message ID from the context.
  42. func GetMessageFromContext(ctx context.Context) string {
  43. return getContextValue(ctx, MessageIDContextKey, "")
  44. }
  45. // GetSupportsImagesFromContext retrieves whether the model supports images from the context.
  46. func GetSupportsImagesFromContext(ctx context.Context) bool {
  47. return getContextValue(ctx, SupportsImagesContextKey, false)
  48. }
  49. // GetModelNameFromContext retrieves the model name from the context.
  50. func GetModelNameFromContext(ctx context.Context) string {
  51. return getContextValue(ctx, ModelNameContextKey, "")
  52. }
  53. // FirstLineDescription returns just the first non-empty line from the embedded
  54. // markdown description when CRUSH_SHORT_TOOL_DESCRIPTIONS is set, significantly
  55. // reducing token usage. Otherwise returns the full description.
  56. func FirstLineDescription(content []byte) string {
  57. if !testing.Testing() {
  58. if v, _ := strconv.ParseBool(os.Getenv("CRUSH_SHORT_TOOL_DESCRIPTIONS")); !v {
  59. return strings.TrimSpace(string(content))
  60. }
  61. }
  62. for line := range strings.SplitSeq(string(content), "\n") {
  63. line = strings.TrimSpace(line)
  64. if line != "" {
  65. return line
  66. }
  67. }
  68. return ""
  69. }