-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathmain.go
More file actions
324 lines (286 loc) · 9.46 KB
/
Copy pathmain.go
File metadata and controls
324 lines (286 loc) · 9.46 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package main
import (
"encoding/json"
"fmt"
"os"
"reflect"
"strings"
"github.com/shopspring/decimal"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/codersdk"
)
// SchemaField describes a single form field in the generated schema.
type SchemaField struct {
JSONName string `json:"json_name"`
GoName string `json:"go_name"`
Type string `json:"type"`
Description string `json:"description,omitempty"`
Label string `json:"label,omitempty"`
Required bool `json:"required"`
Enum []string `json:"enum,omitempty"`
InputType string `json:"input_type"`
Hidden bool `json:"hidden,omitempty"`
VisibleWhen string `json:"visible_when,omitempty"`
ConflictsWith []string `json:"conflicts_with,omitempty"`
VisibleForProviders []string `json:"visible_for_providers,omitempty"`
}
// FieldGroup holds the fields for a struct or provider.
type FieldGroup struct {
Fields []SchemaField `json:"fields"`
}
// Schema is the top-level output structure.
type Schema struct {
General FieldGroup `json:"general"`
Providers map[string]FieldGroup `json:"providers"`
ProviderAliases map[string]string `json:"provider_aliases"`
}
func main() {
schema := Schema{
Providers: make(map[string]FieldGroup),
ProviderAliases: map[string]string{
"azure": "openai",
"bedrock": "anthropic",
},
}
// General options from ChatModelCallConfig, excluding
// the provider_options field which is handled separately.
schema.General = extractFields(
reflect.TypeOf(codersdk.ChatModelCallConfig{}),
"",
map[string]bool{"ProviderOptions": true},
nil,
)
if err := validateFieldReferences("general", schema.General); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// Provider-specific options. Each entry maps a provider key
// to the concrete options struct used for that provider.
providerTypes := []struct {
key string
typ reflect.Type
}{
{"openai", reflect.TypeOf(codersdk.ChatModelOpenAIProviderOptions{})},
{"anthropic", reflect.TypeOf(codersdk.ChatModelAnthropicProviderOptions{})},
{"google", reflect.TypeOf(codersdk.ChatModelGoogleProviderOptions{})},
{"openaicompat", reflect.TypeOf(codersdk.ChatModelOpenAICompatProviderOptions{})},
{"openrouter", reflect.TypeOf(codersdk.ChatModelOpenRouterProviderOptions{})},
{"vercel", reflect.TypeOf(codersdk.ChatModelVercelProviderOptions{})},
}
for _, p := range providerTypes {
schema.Providers[p.key] = extractFields(p.typ, "", nil, nil)
if err := validateFieldReferences(p.key, schema.Providers[p.key]); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
if err := validateProviderScopes(schema); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
out, err := json.MarshalIndent(schema, "", "\t")
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "marshal schema: %v\n", err)
os.Exit(1)
}
// Print the generated header and JSON body.
_, _ = fmt.Println("// Code generated by scripts/modeloptionsgen. DO NOT EDIT.")
_, _ = fmt.Println(string(out))
}
// validateProviderScopes rejects a providers tag naming something that is
// neither a canonical provider nor an alias, which would silently hide the
// field from every editor.
func validateProviderScopes(schema Schema) error {
for _, f := range schema.General.Fields {
for _, provider := range f.VisibleForProviders {
if _, ok := schema.Providers[provider]; ok {
continue
}
if _, ok := schema.ProviderAliases[provider]; ok {
continue
}
return xerrors.Errorf("field %q has providers entry %q referencing an unknown provider", f.JSONName, provider)
}
}
return nil
}
func validateFieldReferences(group string, fg FieldGroup) error {
names := make(map[string]bool, len(fg.Fields))
for _, f := range fg.Fields {
names[f.JSONName] = true
}
for _, f := range fg.Fields {
if f.VisibleWhen != "" && !names[f.VisibleWhen] {
return xerrors.Errorf("field %q in group %q has visible_when=%q referencing an unknown sibling field", f.JSONName, group, f.VisibleWhen)
}
for _, sibling := range f.ConflictsWith {
if !names[sibling] {
return xerrors.Errorf("field %q in group %q has conflicts_with entry %q referencing an unknown sibling field", f.JSONName, group, sibling)
}
}
}
return nil
}
// Nested fields inherit an enclosing provider scope unless they declare their
// own.
func extractFields(t reflect.Type, prefix string, skip map[string]bool, providers []string) FieldGroup {
var fields []SchemaField
for i := range t.NumField() {
f := t.Field(i)
if skip != nil && skip[f.Name] {
continue
}
jsonTag := f.Tag.Get("json")
if jsonTag == "" || jsonTag == "-" {
continue
}
jsonName := strings.Split(jsonTag, ",")[0]
if jsonName == "" {
continue
}
fullJSONName := jsonName
if prefix != "" {
fullJSONName = prefix + "." + jsonName
}
// Determine the underlying type, dereferencing pointers.
ft := f.Type
if ft.Kind() == reflect.Ptr {
ft = ft.Elem()
}
// Check the hidden tag before recursing into nested structs
// so that entire sub-objects can be marked hidden.
hidden := f.Tag.Get("hidden") == "true"
fieldProviders := providers
if tag := f.Tag.Get("providers"); tag != "" {
fieldProviders = strings.Split(tag, ",")
}
// decimal.Decimal is an opaque numeric type used for pricing
// precision; do not recurse into its internal struct fields.
isDecimal := ft == reflect.TypeOf(decimal.Decimal{})
// If the field is a struct (not a map), recurse to flatten
// its children using dot-separated names — unless the
// entire struct is marked hidden, in which case emit it
// as a single opaque field.
if ft.Kind() == reflect.Struct && !hidden && !isDecimal {
nested := extractFields(ft, fullJSONName, nil, fieldProviders)
fields = append(fields, nested.Fields...)
continue
}
typeName := goTypeToSchemaType(f.Type)
description := f.Tag.Get("description")
label := f.Tag.Get("label")
enumTag := f.Tag.Get("enum")
visibleWhen := f.Tag.Get("visible_when")
var conflictsWith []string
if conflictsTag := f.Tag.Get("conflicts_with"); conflictsTag != "" {
conflictsWith = strings.Split(conflictsTag, ",")
}
var enumValues []string
if enumTag != "" {
enumValues = strings.Split(enumTag, ",")
}
required := !strings.Contains(jsonTag, "omitempty")
inputType := inferInputType(typeName, enumValues)
fields = append(fields, SchemaField{
JSONName: fullJSONName,
GoName: goFieldPath(prefix, f.Name, t, fullJSONName),
Type: typeName,
Description: description,
Label: label,
Required: required,
Enum: enumValues,
InputType: inputType,
Hidden: hidden,
VisibleWhen: visibleWhen,
ConflictsWith: conflictsWith,
VisibleForProviders: fieldProviders,
})
}
return FieldGroup{Fields: fields}
}
// goFieldPath builds a dot-separated Go field name for nested fields.
// For top-level fields it returns just the field name. For nested
// fields it reconstructs the parent struct field name from the prefix
// by looking at the enclosing type's fields.
func goFieldPath(prefix, name string, _ reflect.Type, fullJSONName string) string {
if prefix == "" {
return name
}
// Build the Go path by walking the JSON name segments. Each
// segment maps to a struct field that we already traversed
// during recursion, so we reconstruct the path from the JSON
// parts. The parent extractFields call sets the prefix to the
// parent json name, so we can derive the Go path from the
// json segments by title-casing each part.
parts := strings.Split(fullJSONName, ".")
goNames := make([]string, 0, len(parts))
for _, p := range parts {
goNames = append(goNames, jsonSegmentToGoName(p))
}
return strings.Join(goNames, ".")
}
// jsonSegmentToGoName converts a snake_case JSON segment to a
// PascalCase Go field name using common conventions.
func jsonSegmentToGoName(seg string) string {
words := strings.Split(seg, "_")
var b strings.Builder
for _, w := range words {
if w == "" {
continue
}
// Handle common acronyms.
upper := strings.ToUpper(w)
switch upper {
case "ID", "URL", "IP", "HTTP", "JSON", "API", "UI":
_, _ = b.WriteString(upper)
default:
_, _ = b.WriteString(strings.ToUpper(w[:1]))
_, _ = b.WriteString(w[1:])
}
}
return b.String()
}
// goTypeToSchemaType maps a Go reflect.Type to a JSON schema type
// string.
func goTypeToSchemaType(t reflect.Type) string {
// Dereference pointers.
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
// decimal.Decimal represents a precise numeric value and should
// map to the "number" schema type.
if t == reflect.TypeOf(decimal.Decimal{}) {
return "number"
}
switch t.Kind() {
case reflect.String:
return "string"
case reflect.Bool:
return "boolean"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return "integer"
case reflect.Float32, reflect.Float64:
return "number"
case reflect.Slice:
return "array"
case reflect.Map:
return "object"
default:
return "string"
}
}
// inferInputType decides the appropriate frontend input widget for
// a field based on its schema type and enum values.
func inferInputType(typeName string, enum []string) string {
if len(enum) > 0 {
return "select"
}
switch typeName {
case "boolean":
return "select"
case "array", "object":
return "json"
default:
return "input"
}
}