-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathschema.go
More file actions
194 lines (171 loc) · 5.04 KB
/
Copy pathschema.go
File metadata and controls
194 lines (171 loc) · 5.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package unstruct
import (
"crypto/md5"
"fmt"
"log/slog"
"reflect"
"sort"
"strings"
"time"
)
// hashParameters creates a deterministic hash of parameters for grouping
func hashParameters(params map[string]string) string {
if len(params) == 0 {
return ""
}
// Sort keys for deterministic hashing
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
// Create a sorted string representation
var parts []string
for _, k := range keys {
parts = append(parts, fmt.Sprintf("%s=%s", k, params[k]))
}
hashStr := strings.Join(parts, "&")
return fmt.Sprintf("%x", md5.Sum([]byte(hashStr)))[:8] // Use first 8 chars of hash
}
type promptKey struct {
prompt string // explicit label or ""
parentPath string // dotted path w/o the leaf field
model string // model name for this group
paramsHash string // hash of parameters for grouping
}
type promptGroup struct {
promptKey
parameters map[string]string // query parameters for this group
}
type fieldSpec struct {
jsonKey string
model string // may be ""
parameters map[string]string // query parameters for this field
index []int // reflect path
}
type schema struct {
group2keys map[promptKey][]string // batching groups (using comparable key)
group2specs map[promptKey]promptGroup // stores the full group info with parameters
json2field map[string]fieldSpec // merge map
}
func schemaOf[T any]() (*schema, error) {
return schemaOfWithOptions[T](nil, nil)
}
func schemaOfWithOptions[T any](opts *Options, log *slog.Logger) (*schema, error) {
var zero T
rt := reflect.TypeOf(zero)
if rt.Kind() != reflect.Struct {
return nil, fmt.Errorf("unstruct: T must be struct")
}
s := &schema{
group2keys: map[promptKey][]string{},
group2specs: map[promptKey]promptGroup{},
json2field: map[string]fieldSpec{},
}
// TODO: refactor
var walk func(t reflect.Type, parent, inheritedPrompt, inheritedModel string, inheritedParameters map[string]string, idx []int)
walk = func(t reflect.Type, parent, inheritedPrompt, inheritedModel string, inheritedParameters map[string]string, idx []int) {
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Anonymous || !f.IsExported() {
continue
}
jsonKey := strings.Split(f.Tag.Get("json"), ",")[0]
if jsonKey == "-" {
continue
}
if jsonKey == "" {
jsonKey = f.Name
}
fullKey := joinKey(parent, jsonKey)
tp := parseUnstructTag(f.Tag.Get("unstruct"), inheritedPrompt, log)
// Resolve group references
prompt := tp.prompt
model := tp.model
parameters := tp.parameters
// Inherit parameters if none specified in tag
if len(parameters) == 0 && len(inheritedParameters) > 0 {
parameters = inheritedParameters
}
if strings.HasPrefix(tp.prompt, "group:") {
groupName := strings.TrimPrefix(tp.prompt, "group:")
if opts != nil && opts.Groups != nil {
if groupDef, exists := opts.Groups[groupName]; exists {
prompt = groupDef.Prompt
model = groupDef.Model
// Group parameters could be merged here if needed
}
}
}
// Inherit model if not specified in the tag and not from group
if model == "" {
model = inheritedModel
}
// Check for field-specific model override from Options
if opts != nil && opts.FieldModels != nil {
typeName := t.Name()
fieldKey := typeName + "." + f.Name
if fieldModel, exists := opts.FieldModels[fieldKey]; exists {
model = fieldModel
}
}
nextIdx := append(idx, i)
if isPureStruct(f.Type) {
// Make the intermediate node addressable during patching
s.json2field[fullKey] = fieldSpec{
jsonKey: fullKey,
model: model,
parameters: parameters,
index: nextIdx,
}
walk(f.Type, fullKey, prompt, model, parameters, nextIdx)
continue
}
// Handle slices of structs
if f.Type.Kind() == reflect.Slice && isPureStruct(f.Type.Elem()) {
s.json2field[fullKey] = fieldSpec{
jsonKey: fullKey,
model: model,
parameters: parameters,
index: nextIdx,
}
walk(f.Type.Elem(), fullKey, prompt, model, parameters, nextIdx)
continue
}
// Create prompt key, optionally flattening groups
parentPathForGrouping := parent
if opts != nil && opts.FlattenGroups {
parentPathForGrouping = ""
}
pk := promptKey{
prompt: prompt,
parentPath: parentPathForGrouping,
model: model,
paramsHash: hashParameters(parameters),
}
s.group2keys[pk] = append(s.group2keys[pk], fullKey)
s.group2specs[pk] = promptGroup{
promptKey: pk,
parameters: parameters,
}
s.json2field[fullKey] = fieldSpec{
jsonKey: fullKey,
model: model,
parameters: parameters,
index: nextIdx,
}
}
}
walk(rt, "", "", "", nil, nil)
return s, nil
}
// helpers
func joinKey(parent, child string) string {
if parent == "" {
return child
}
return parent + "." + child
}
func isPureStruct(t reflect.Type) bool {
return t.Kind() == reflect.Struct && t != reflect.TypeOf(time.Time{})
}