-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmodels.go
More file actions
256 lines (230 loc) · 7.39 KB
/
Copy pathmodels.go
File metadata and controls
256 lines (230 loc) · 7.39 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
// Package internal provides model-related logic for github-copilot-svcs.
package internal
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/privapps/github-copilot-svcs/pkg/transform"
)
var (
cachedModels *transform.ModelList
modelsMutex sync.RWMutex
modelsLoaded bool
)
// ModelsDevResponse represents the structure from models.dev API
type ModelsDevResponse map[string]struct {
ID string `json:"id"`
Models map[string]struct {
ID string `json:"id"`
Name string `json:"name"`
ReleaseDate string `json:"release_date"`
OwnedBy string `json:"owned_by,omitempty"`
} `json:"models"`
}
// FetchFromModelsDev fetches models from models.dev API as fallback
func FetchFromModelsDev(httpClient *http.Client) (*transform.ModelList, error) {
resp, err := httpClient.Get("https://models.dev/api.json")
if err != nil {
return nil, err
}
defer func() {
if err := resp.Body.Close(); err != nil {
Warn("Error closing response body", "error", err)
}
}()
if resp.StatusCode != http.StatusOK {
return nil, NewNetworkError("fetch_models", "https://models.dev/api.json", fmt.Sprintf("API returned HTTP %d", resp.StatusCode), nil)
}
var providers ModelsDevResponse
if err := json.NewDecoder(resp.Body).Decode(&providers); err != nil {
return nil, err
}
// Extract GitHub Copilot models
copilotProvider, exists := providers["github-copilot"]
if !exists {
return nil, NewValidationError("provider", "github-copilot", "provider not found in models.dev response", nil)
}
var models []transform.Model
for modelID, modelInfo := range copilotProvider.Models {
ownedBy := modelInfo.OwnedBy
if ownedBy == "" {
// Determine owner based on model name
switch {
case containsAny(modelInfo.Name, []string{"claude", "anthropic"}):
ownedBy = "anthropic"
case containsAny(modelInfo.Name, []string{"gpt", "o1", "o3", "o4", "openai"}):
ownedBy = "openai"
case containsAny(modelInfo.Name, []string{"gemini", "google"}):
ownedBy = "google"
default:
ownedBy = "github-copilot"
}
}
models = append(models, transform.Model{
ID: modelID,
Object: "model",
Created: time.Now().Unix(),
OwnedBy: ownedBy,
APIType: apiTypeForModel(modelID),
})
}
return &transform.ModelList{
Object: "list",
Data: models,
}, nil
}
// apiTypeForModel returns the API endpoint type for a model.
// Models are divided into two categories based on testing:
// - "chat_completions": Use /v1/chat/completions (OpenAI Chat Completions API)
// - "responses": Use /v1/responses (OpenAI Responses API)
func apiTypeForModel(modelID string) string {
responsesModels := map[string]bool{
"gpt-5.3-codex": true,
"gpt-5.4-mini": true,
"gpt-5.6-luna": true,
"gpt-5.6-sol": true,
"gpt-5.6-terra": true,
}
if responsesModels[modelID] {
return "responses"
}
return "chat_completions"
}
// GetDefault returns a default list of models based on actual GitHub Copilot entries.
func GetDefault() []transform.Model {
now := time.Now().Unix()
entries := []struct {
id string
ownedBy string
apiType string
}{
// Chat Completions models
{"gpt-4o", "openai", "chat_completions"},
{"gpt-4.1", "openai", "chat_completions"},
{"claude-haiku-4.5", "anthropic", "chat_completions"},
{"claude-sonnet-5", "anthropic", "chat_completions"},
{"claude-opus-4.8", "anthropic", "chat_completions"},
{"gemini-3.5-flash", "google", "chat_completions"},
{"gemini-3.1-pro-preview", "google", "chat_completions"},
// Responses API models
{"gpt-5.3-codex", "openai", "responses"},
{"gpt-5.4-mini", "openai", "responses"},
{"gpt-5.6-luna", "openai", "responses"},
{"gpt-5.6-sol", "openai", "responses"},
{"gpt-5.6-terra", "openai", "responses"},
}
models := make([]transform.Model, len(entries))
for i, e := range entries {
models[i] = transform.Model{
ID: e.id,
Object: "model",
Created: now,
OwnedBy: e.ownedBy,
APIType: e.apiType,
}
}
return models
}
// containsAny checks if text contains any of the substrings
func containsAny(text string, substrings []string) bool {
textLower := strings.ToLower(text)
for _, substr := range substrings {
if strings.Contains(textLower, strings.ToLower(substr)) {
return true
}
}
return false
}
// ModelsService provides model operations
type ModelsService struct {
coalescingCache CoalescingCacheInterface
httpClient *http.Client
}
// NewModelsService creates a new models service
func NewModelsService(cache CoalescingCacheInterface, httpClient *http.Client) *ModelsService {
return &ModelsService{
coalescingCache: cache,
httpClient: httpClient,
}
}
// CoalescingCacheInterface interface for request coalescing
type CoalescingCacheInterface interface {
GetRequestKey(method, path string, body interface{}) string
CoalesceRequest(key string, fn func() interface{}) interface{}
} // Handler returns an HTTP handler for the models endpoint.
// Handler returns an HTTP handler for the models endpoint.
func (s *ModelsService) Handler() http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
// Use request coalescing for identical concurrent requests
requestKey := s.coalescingCache.GetRequestKey("GET", "/v1/models", nil)
result := s.coalescingCache.CoalesceRequest(requestKey, func() interface{} {
// Check cache first
modelsMutex.RLock()
if modelsLoaded && cachedModels != nil {
modelsMutex.RUnlock()
return cachedModels
}
modelsMutex.RUnlock()
// Load models if not cached
modelsMutex.Lock()
defer modelsMutex.Unlock()
// Double-check in case another goroutine loaded while we waited
if modelsLoaded && cachedModels != nil {
return cachedModels
}
Info("Loading models for the first time...")
// Try models.dev API first (don't hit GitHub Copilot for models list)
modelList, err := FetchFromModelsDev(s.httpClient)
if err != nil {
Warn("Failed to fetch from models.dev, using default models", "error", err)
// Ultimate fallback to hardcoded models
modelList = &transform.ModelList{
Object: "list",
Data: GetDefault(),
}
}
// Cache the results
cachedModels = modelList
modelsLoaded = true
Info("Loaded and cached models", "count", len(modelList.Data))
return modelList
})
modelList := result.(*transform.ModelList)
// Filter if allowed_models is set in config
cfg, cfgErr := LoadConfig(true)
filtered := modelList.Data
filteredMsg := ""
if cfgErr == nil && cfg.AllowedModels != nil && len(cfg.AllowedModels) > 0 {
allowedSet := make(map[string]struct{}, len(cfg.AllowedModels))
for _, name := range cfg.AllowedModels {
allowedSet[name] = struct{}{}
}
var modelsFiltered []transform.Model
for _, m := range filtered {
if _, ok := allowedSet[m.ID]; ok {
modelsFiltered = append(modelsFiltered, m)
}
}
filtered = modelsFiltered
filteredMsg = "(filtered by allowed_models from config)"
}
resp := struct {
Object string `json:"object"`
Data []transform.Model `json:"data"`
Filtered string `json:"note,omitempty"`
}{
Object: "list",
Data: filtered,
Filtered: filteredMsg,
}
Debug("Returning models", "count", len(filtered))
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(resp); err != nil {
Error("Error encoding models response", "error", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
}