-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathproxy-ollama.go
349 lines (300 loc) · 8.59 KB
/
proxy-ollama.go
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"github.com/joho/godotenv"
"golang.org/x/net/http2"
)
const (
ollamaEndpoint = "http://localhost:11434/api"
defaultModel = "llama2"
deepseekChatModel = "michaelneale/deepseek-r1-goose"
deepseekCoderModel = "deepseek-coder"
gpt4oModel = "gpt-4o"
)
// Configuration structure
type Config struct {
endpoint string
model string
}
var activeConfig Config
func init() {
// Load .env file
log.Printf("Variant: OLLAMA")
if err := godotenv.Load(); err != nil {
log.Printf("Warning: .env file not found or error loading it: %v", err)
}
// Get custom Ollama endpoint if specified
customEndpoint := os.Getenv("OLLAMA_API_ENDPOINT")
if customEndpoint != "" {
activeConfig.endpoint = customEndpoint
} else {
activeConfig.endpoint = ollamaEndpoint
}
// Get custom Ollama endpoint if specified
modelenv := os.Getenv("DEFAULT_MODEL")
if modelenv != "" {
activeConfig.model = modelenv
} else {
//no environment set so check for command line argument
modelFlag := defaultModel // default value
for i, arg := range os.Args {
if arg == "-model" && i+1 < len(os.Args) {
modelFlag = os.Args[i+1]
}
}
activeConfig.model = modelFlag
}
log.Printf("Initialized with model: %s using endpoint: %s", activeConfig.model, activeConfig.endpoint)
}
// OpenAI compatible structures
type ChatRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
Stream bool `json:"stream"`
Functions []Function `json:"functions,omitempty"`
Tools []Tool `json:"tools,omitempty"`
ToolChoice interface{} `json:"tool_choice,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
}
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
Name string `json:"name,omitempty"`
}
type Function struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters any `json:"parameters"`
}
type Tool struct {
Type string `json:"type"`
Function Function `json:"function"`
}
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
}
// Ollama specific structures
type OllamaRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
Stream bool `json:"stream"`
Temperature float64 `json:"temperature,omitempty"`
MaxTokens int `json:"max_tokens,omitempty"`
}
type OllamaResponse struct {
Model string `json:"model"`
CreatedAt string `json:"created_at"`
Message struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"message"`
Done bool `json:"done"`
}
func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
server := &http.Server{
Addr: ":9000",
Handler: http.HandlerFunc(proxyHandler),
}
// Enable HTTP/2 support
http2.ConfigureServer(server, &http2.Server{})
log.Printf("Starting Ollama proxy server on %s", server.Addr)
if err := server.ListenAndServe(); err != nil {
log.Fatalf("Server failed: %v", err)
}
}
func enableCors(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")
w.Header().Set("Access-Control-Expose-Headers", "Content-Length")
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
func proxyHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Received request: %s %s", r.Method, r.URL.Path)
if r.Method == "OPTIONS" {
enableCors(w)
return
}
enableCors(w)
switch r.URL.Path {
case "/v1/chat/completions":
handleChatCompletions(w, r)
case "/v1/models":
handleModelsRequest(w)
default:
http.Error(w, "Not found", http.StatusNotFound)
}
}
func handleChatCompletions(w http.ResponseWriter, r *http.Request) {
var chatReq ChatRequest
if err := json.NewDecoder(r.Body).Decode(&chatReq); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Store original model name for response
originalModel := chatReq.Model
if originalModel == "" {
originalModel = activeConfig.model
}
// Always use the configured model internally
chatReq.Model = activeConfig.model
log.Printf("Model converted to: %s (original: %s)", activeConfig.model, originalModel)
// Convert to Ollama request format
ollamaReq := OllamaRequest{
Model: activeConfig.model,
Messages: chatReq.Messages,
Stream: chatReq.Stream,
}
if chatReq.Temperature != nil {
ollamaReq.Temperature = *chatReq.Temperature
}
if chatReq.MaxTokens != nil {
ollamaReq.MaxTokens = *chatReq.MaxTokens
}
// Create Ollama request
ollamaReqBody, err := json.Marshal(ollamaReq)
if err != nil {
log.Printf("ERROR: failed to marshal ollama request: %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Send request to Ollama
ollamaResp, err := http.Post(
fmt.Sprintf("%s/chat", activeConfig.endpoint),
"application/json",
bytes.NewBuffer(ollamaReqBody),
)
if err != nil {
log.Printf("ERROR: POST failed: %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer ollamaResp.Body.Close()
if chatReq.Stream {
handleStreamingResponse(w, r, ollamaResp, originalModel)
} else {
handleRegularResponse(w, ollamaResp, originalModel)
}
}
func handleStreamingResponse(w http.ResponseWriter, r *http.Request, resp *http.Response, originalModel string) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
return
}
reader := bufio.NewReader(resp.Body)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
if err != io.EOF {
log.Printf("Error reading stream: %v", err)
}
break
}
var ollamaResp OllamaResponse
if err := json.Unmarshal(line, &ollamaResp); err != nil {
log.Printf("Error unmarshaling response: %v", err)
continue
}
// Convert to OpenAI format
openAIResp := map[string]interface{}{
"id": "chatcmpl-" + time.Now().Format("20060102150405"),
"object": "chat.completion.chunk",
"created": time.Now().Unix(),
"model": originalModel,
"choices": []map[string]interface{}{
{
"index": 0,
"delta": map[string]interface{}{
"role": "assistant",
"content": ollamaResp.Message.Content,
},
"finish_reason": nil,
},
},
}
if ollamaResp.Done {
openAIResp["choices"].([]map[string]interface{})[0]["finish_reason"] = "stop"
}
if data, err := json.Marshal(openAIResp); err == nil {
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
}
if ollamaResp.Done {
break
}
}
}
func handleRegularResponse(w http.ResponseWriter, resp *http.Response, originalModel string) {
var ollamaResp OllamaResponse
if err := json.NewDecoder(resp.Body).Decode(&ollamaResp); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Convert to OpenAI format
openAIResp := map[string]interface{}{
"id": "chatcmpl-" + time.Now().Format("20060102150405"),
"object": "chat.completion",
"created": time.Now().Unix(),
"model": originalModel,
"choices": []map[string]interface{}{
{
"index": 0,
"message": map[string]interface{}{
"role": "assistant",
"content": ollamaResp.Message.Content,
},
"finish_reason": "stop",
},
},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(openAIResp)
}
func handleModelsRequest(w http.ResponseWriter) {
log.Printf("Handling models request")
response := ModelsResponse{
Object: "list",
Data: []Model{
{
ID: activeConfig.model,
Object: "model",
Created: time.Now().Unix(),
OwnedBy: "ollama",
},
},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
log.Printf("Models response sent successfully")
}
type ModelsResponse struct {
Object string `json:"object"`
Data []Model `json:"data"`
}
type Model struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
OwnedBy string `json:"owned_by"`
}