tools.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package tools
  2. import (
  3. "context"
  4. )
  5. type (
  6. sessionIDContextKey string
  7. messageIDContextKey string
  8. supportsImagesKey string
  9. modelNameKey string
  10. )
  11. const (
  12. // SessionIDContextKey is the key for the session ID in the context.
  13. SessionIDContextKey sessionIDContextKey = "session_id"
  14. // MessageIDContextKey is the key for the message ID in the context.
  15. MessageIDContextKey messageIDContextKey = "message_id"
  16. // SupportsImagesContextKey is the key for the model's image support capability.
  17. SupportsImagesContextKey supportsImagesKey = "supports_images"
  18. // ModelNameContextKey is the key for the model name in the context.
  19. ModelNameContextKey modelNameKey = "model_name"
  20. )
  21. // getContextValue is a generic helper that retrieves a typed value from context.
  22. // If the value is not found or has the wrong type, it returns the default value.
  23. func getContextValue[T any](ctx context.Context, key any, defaultValue T) T {
  24. value := ctx.Value(key)
  25. if value == nil {
  26. return defaultValue
  27. }
  28. if typedValue, ok := value.(T); ok {
  29. return typedValue
  30. }
  31. return defaultValue
  32. }
  33. // GetSessionFromContext retrieves the session ID from the context.
  34. func GetSessionFromContext(ctx context.Context) string {
  35. return getContextValue(ctx, SessionIDContextKey, "")
  36. }
  37. // GetMessageFromContext retrieves the message ID from the context.
  38. func GetMessageFromContext(ctx context.Context) string {
  39. return getContextValue(ctx, MessageIDContextKey, "")
  40. }
  41. // GetSupportsImagesFromContext retrieves whether the model supports images from the context.
  42. func GetSupportsImagesFromContext(ctx context.Context) bool {
  43. return getContextValue(ctx, SupportsImagesContextKey, false)
  44. }
  45. // GetModelNameFromContext retrieves the model name from the context.
  46. func GetModelNameFromContext(ctx context.Context) string {
  47. return getContextValue(ctx, ModelNameContextKey, "")
  48. }