-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathmodels.go
More file actions
197 lines (171 loc) · 5.78 KB
/
Copy pathmodels.go
File metadata and controls
197 lines (171 loc) · 5.78 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
// gateway/routes/models.go
package routes
import (
"encoding/json"
"fmt"
"net/http"
"os"
"sync"
"time"
"github.com/gin-gonic/gin"
)
// ─── Ollama API types ─────────────────────────────────────────────────────────
type OllamaModel struct {
Name string `json:"name"`
ModifiedAt time.Time `json:"modified_at"`
Size int64 `json:"size"`
Digest string `json:"digest"`
}
type OllamaTagsResponse struct {
Models []OllamaModel `json:"models"`
}
// ─── In-process model override (session-scoped, non-persistent) ───────────────
var (
activeModelOverride string
modelMu sync.RWMutex
)
// GetActiveOllamaModel returns the in-memory override if set, else falls back
// to the OLLAMA_MODEL env var. Call this anywhere you need the current model.
func GetActiveOllamaModel() string {
modelMu.RLock()
defer modelMu.RUnlock()
if activeModelOverride != "" {
return activeModelOverride
}
return os.Getenv("OLLAMA_MODEL")
}
// ─── GET /api/models ──────────────────────────────────────────────────────────
// GetAvailableModels lists AI models available for the configured provider.
//
// - ollama → queries the local Ollama daemon at OLLAMA_URL/api/tags
// - openrouter → returns the currently configured OPENROUTER_MODEL only
// (full catalogue would require an OpenRouter API call; out of scope here)
func GetAvailableModels(c *gin.Context) {
provider := os.Getenv("AI_PROVIDER")
switch provider {
case "ollama":
handleOllamaModels(c)
case "openrouter":
handleOpenRouterModels(c)
default:
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Unknown AI_PROVIDER '%s'. Valid values: ollama, openrouter", provider),
"provider": provider,
"models": []gin.H{},
})
}
}
func handleOllamaModels(c *gin.Context) {
ollamaURL := os.Getenv("OLLAMA_URL")
if ollamaURL == "" {
ollamaURL = "http://localhost:11434"
}
// Use a short timeout — Ollama is local; if it doesn't respond in 3s it's down
client := &http.Client{Timeout: 3 * time.Second}
resp, err := client.Get(fmt.Sprintf("%s/api/tags", ollamaURL))
if err != nil {
c.JSON(http.StatusServiceUnavailable, gin.H{
"error": "Cannot connect to Ollama. Is Ollama running? (expected at: " + ollamaURL + ")",
"provider": "ollama",
"hint": "Run `ollama serve` or check OLLAMA_URL in your .env",
})
return
}
defer resp.Body.Close()
var ollamaResp OllamaTagsResponse
if err := json.NewDecoder(resp.Body).Decode(&ollamaResp); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to parse Ollama /api/tags response: " + err.Error(),
})
return
}
currentModel := GetActiveOllamaModel()
models := make([]gin.H, 0, len(ollamaResp.Models))
for _, m := range ollamaResp.Models {
models = append(models, gin.H{
"id": m.Name,
"name": m.Name,
"provider": "ollama",
// Convert bytes → GB, keep one decimal place
"sizeGB": fmt.Sprintf("%.1fGB", float64(m.Size)/1e9),
"isActive": m.Name == currentModel,
})
}
c.JSON(http.StatusOK, gin.H{
"provider": "ollama",
"currentModel": currentModel,
"models": models,
})
}
func handleOpenRouterModels(c *gin.Context) {
currentModel := os.Getenv("OPENROUTER_MODEL")
c.JSON(http.StatusOK, gin.H{
"provider": "openrouter",
"currentModel": currentModel,
"models": []gin.H{
{
"id": currentModel,
"name": currentModel,
"provider": "openrouter",
"isActive": true,
},
},
"note": "OpenRouter supports 300+ models. Update OPENROUTER_MODEL in .env to change the model.",
})
}
// ─── POST /api/models/switch ──────────────────────────────────────────────────
type SwitchModelRequest struct {
ModelID string `json:"modelId" binding:"required"`
}
// SwitchModel updates the active model for the current process lifetime.
// This does NOT persist across gateway restarts — users must update .env for
// permanent changes. Returns a confirmation with a clear session-only warning.
func SwitchModel(c *gin.Context) {
var req SwitchModelRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Request body must include a non-empty 'modelId' field",
})
return
}
// Validate: for ollama, ensure the model is actually installed
if os.Getenv("AI_PROVIDER") == "ollama" {
if err := validateOllamaModelExists(req.ModelID); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Model '%s' not found in Ollama. Run `ollama pull %s` first.", req.ModelID, req.ModelID),
})
return
}
}
modelMu.Lock()
activeModelOverride = req.ModelID
modelMu.Unlock()
c.JSON(http.StatusOK, gin.H{
"success": true,
"activeModel": req.ModelID,
"note": "Model switched for this session only. To persist, update OLLAMA_MODEL in your .env and restart.",
})
}
// validateOllamaModelExists checks the model actually exists before switching.
func validateOllamaModelExists(modelID string) error {
ollamaURL := os.Getenv("OLLAMA_URL")
if ollamaURL == "" {
ollamaURL = "http://localhost:11434"
}
client := &http.Client{Timeout: 3 * time.Second}
resp, err := client.Get(fmt.Sprintf("%s/api/tags", ollamaURL))
if err != nil {
return err
}
defer resp.Body.Close()
var ollamaResp OllamaTagsResponse
if err := json.NewDecoder(resp.Body).Decode(&ollamaResp); err != nil {
return err
}
for _, m := range ollamaResp.Models {
if m.Name == modelID {
return nil
}
}
return fmt.Errorf("model not found")
}