tools.go

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