| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- package tools
- import (
- "context"
- "os"
- "strconv"
- "strings"
- "testing"
- )
- type (
- sessionIDContextKey string
- messageIDContextKey string
- supportsImagesKey string
- modelNameKey string
- )
- const (
- // SessionIDContextKey is the key for the session ID in the context.
- SessionIDContextKey sessionIDContextKey = "session_id"
- // MessageIDContextKey is the key for the message ID in the context.
- MessageIDContextKey messageIDContextKey = "message_id"
- // SupportsImagesContextKey is the key for the model's image support capability.
- SupportsImagesContextKey supportsImagesKey = "supports_images"
- // ModelNameContextKey is the key for the model name in the context.
- ModelNameContextKey modelNameKey = "model_name"
- )
- // getContextValue is a generic helper that retrieves a typed value from context.
- // If the value is not found or has the wrong type, it returns the default value.
- func getContextValue[T any](ctx context.Context, key any, defaultValue T) T {
- value := ctx.Value(key)
- if value == nil {
- return defaultValue
- }
- if typedValue, ok := value.(T); ok {
- return typedValue
- }
- return defaultValue
- }
- // GetSessionFromContext retrieves the session ID from the context.
- func GetSessionFromContext(ctx context.Context) string {
- return getContextValue(ctx, SessionIDContextKey, "")
- }
- // GetMessageFromContext retrieves the message ID from the context.
- func GetMessageFromContext(ctx context.Context) string {
- return getContextValue(ctx, MessageIDContextKey, "")
- }
- // GetSupportsImagesFromContext retrieves whether the model supports images from the context.
- func GetSupportsImagesFromContext(ctx context.Context) bool {
- return getContextValue(ctx, SupportsImagesContextKey, false)
- }
- // GetModelNameFromContext retrieves the model name from the context.
- func GetModelNameFromContext(ctx context.Context) string {
- return getContextValue(ctx, ModelNameContextKey, "")
- }
- // FirstLineDescription returns just the first non-empty line from the embedded
- // markdown description when CRUSH_SHORT_TOOL_DESCRIPTIONS is set, significantly
- // reducing token usage. Otherwise returns the full description.
- func FirstLineDescription(content []byte) string {
- if !testing.Testing() {
- if v, _ := strconv.ParseBool(os.Getenv("CRUSH_SHORT_TOOL_DESCRIPTIONS")); !v {
- return strings.TrimSpace(string(content))
- }
- }
- for line := range strings.SplitSeq(string(content), "\n") {
- line = strings.TrimSpace(line)
- if line != "" {
- return line
- }
- }
- return ""
- }
|