-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1126 lines (993 loc) · 29.8 KB
/
main.go
File metadata and controls
1126 lines (993 loc) · 29.8 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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"database/sql"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/joho/godotenv"
_ "github.com/mattn/go-sqlite3"
"golang.org/x/time/rate"
)
var (
db *sql.DB
apiBase string
apiKey string
model string
limiter *rate.Limiter
pricing map[string]ModelPricing
pricingFile string
host string
port int
rpm int
)
// ModelPricing represents pricing per 1M tokens for a model
type ModelPricing struct {
InputPrice float64 `json:"InputPrice"`
CachedPrice float64 `json:"CachedPrice"`
OutputPrice float64 `json:"OutputPrice"`
}
// RequestLog represents a log entry in the database
type RequestLog struct {
ID int `json:"id"`
Timestamp string `json:"timestamp"`
ClientIP string `json:"client_ip"`
UpstreamURL string `json:"upstream_url"`
Method string `json:"method"`
Path string `json:"path"`
StatusCode int `json:"status_code"`
LatencyMs int `json:"latency_ms"`
RequestBody string `json:"request_body"`
ResponseBody string `json:"response_body"`
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
TotalTokens int `json:"total_tokens"`
CachedTokens int `json:"cached_tokens"`
CostINR float64 `json:"cost_inr"`
Model string `json:"model"`
}
// Usage represents the usage field in responses (supports both formats)
type Usage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
TotalTokens int `json:"total_tokens"`
PromptTokens int `json:"prompt_tokens,omitempty"`
CompletionTokens int `json:"completion_tokens,omitempty"`
CachedTokens int `json:"cached_tokens,omitempty"`
PromptDetails TokenDetails `json:"prompt_tokens_details,omitempty"`
InputDetails TokenDetails `json:"input_tokens_details,omitempty"`
}
type TokenDetails struct {
CachedTokens int `json:"cached_tokens,omitempty"`
}
// Response represents a generic API response with usage
type Response struct {
Usage Usage `json:"usage"`
Model string `json:"model,omitempty"`
}
func init() {
// Load .env file
if err := godotenv.Load(); err != nil {
log.Printf("Warning: Error loading .env file: %v", err)
}
apiBase = os.Getenv("API_BASE")
apiKey = os.Getenv("API_KEY")
model = os.Getenv("MODEL")
if apiBase == "" {
log.Fatal("API_BASE is required")
}
if apiKey == "" {
log.Fatal("API_KEY is required")
}
if model == "" {
log.Fatal("MODEL is required")
}
// Define flags
flag.StringVar(&pricingFile, "pricing", "pricing.json", "Path to pricing JSON file")
flag.StringVar(&host, "host", "0.0.0.0", "Host to listen on")
flag.IntVar(&port, "port", 8080, "Port to listen on")
flag.IntVar(&rpm, "rpm", 60, "Maximum requests per minute")
flag.Parse()
// Initialize rate limiter
limiter = rate.NewLimiter(rate.Every(time.Minute/time.Duration(rpm)), rpm)
// Load pricing from JSON
loadPricing()
// Initialize SQLite database
var err error
db, err = sql.Open("sqlite3", "./tracer.db")
if err != nil {
log.Fatal("Failed to open database:", err)
}
// Create table if it doesn't exist
createTableSQL := `
CREATE TABLE IF NOT EXISTS request_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
client_ip TEXT,
upstream_url TEXT,
method TEXT,
path TEXT,
status_code INTEGER,
latency_ms INTEGER,
request_body TEXT,
response_body TEXT,
input_tokens INTEGER DEFAULT 0,
output_tokens INTEGER DEFAULT 0,
total_tokens INTEGER DEFAULT 0,
cached_tokens INTEGER DEFAULT 0,
cost_inr REAL DEFAULT 0,
model TEXT
);`
_, err = db.Exec(createTableSQL)
if err != nil {
log.Fatal("Failed to create table:", err)
}
createIndexesSQL := []string{
"CREATE INDEX IF NOT EXISTS idx_request_logs_timestamp ON request_logs(timestamp)",
"CREATE INDEX IF NOT EXISTS idx_request_logs_status_code ON request_logs(status_code)",
"CREATE INDEX IF NOT EXISTS idx_request_logs_model ON request_logs(model)",
}
for _, statement := range createIndexesSQL {
if _, err := db.Exec(statement); err != nil {
log.Fatal("Failed to create index:", err)
}
}
log.Printf("Loaded configuration:")
log.Printf(" Upstream URL: %s", apiBase)
log.Printf(" Model: %s", model)
log.Printf(" Listening on: %s:%d", host, port)
log.Printf(" Dashboard available at: http://%s:%d/dashboard", host, port)
log.Printf(" Rate limit: %d requests/minute", rpm)
}
func loadPricing() {
data, err := os.ReadFile(pricingFile)
if err != nil {
log.Printf("Warning: Could not read pricing file %s: %v. Starting with empty pricing.", pricingFile, err)
pricing = make(map[string]ModelPricing)
return
}
if err := json.Unmarshal(data, &pricing); err != nil {
log.Fatalf("Error parsing pricing JSON: %v", err)
}
log.Printf("Loaded pricing for %d models from %s", len(pricing), pricingFile)
}
func main() {
// Register handlers
http.HandleFunc("/api/logs", logsHandler)
http.HandleFunc("/api/logs/", logsHandler)
http.HandleFunc("/api/logs/last-updated", lastUpdatedHandler)
http.HandleFunc("/api/stats", statsHandler)
http.HandleFunc("/api/config", configHandler)
http.HandleFunc("/dashboard", dashboardHandler)
http.HandleFunc("/", rateLimitMiddleware(proxyHandler))
// Start server
addr := fmt.Sprintf("%s:%d", host, port)
log.Printf("\nProxy server starting on %s...", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}
// rateLimitMiddleware applies rate limiting to the handler
func rateLimitMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Ignore common browser requests
if r.URL.Path == "/favicon.ico" || r.URL.Path == "/robots.txt" {
w.WriteHeader(http.StatusNotFound)
return
}
// Skip rate limiting for dashboard and api routes
if r.URL.Path == "/dashboard" || r.URL.Path == "/api/logs" || r.URL.Path == "/api/stats" || r.URL.Path == "/api/config" || strings.HasPrefix(r.URL.Path, "/api/logs/") {
switch {
case r.URL.Path == "/dashboard":
dashboardHandler(w, r)
case strings.HasPrefix(r.URL.Path, "/api/logs/last-updated"):
lastUpdatedHandler(w, r)
case strings.HasPrefix(r.URL.Path, "/api/logs"):
logsHandler(w, r)
case r.URL.Path == "/api/stats":
statsHandler(w, r)
case r.URL.Path == "/api/config":
configHandler(w, r)
}
return
}
// Check rate limit
if !limiter.Allow() {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
errMsg := fmt.Sprintf(`{"error": "Rate limit exceeded. Maximum %d requests per minute."}`, rpm)
w.Write([]byte(errMsg))
log.Printf("Rate limit exceeded for %s", r.RemoteAddr)
return
}
next(w, r)
}
}
func proxyHandler(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
if r.URL.Path == "/.well-known/appspecific/com.chrome.devtools.json" {
w.WriteHeader(http.StatusNotFound)
return
}
// Capture client IP
clientIP := r.RemoteAddr
// Read request body
var requestBody []byte
if r.Body != nil {
requestBody, _ = io.ReadAll(r.Body)
r.Body.Close()
// Restore the body for forwarding
r.Body = io.NopCloser(bytes.NewReader(requestBody))
}
if responseBody, ok := localMetadataResponse(r.URL.Path); ok {
writeLocalResponse(w, r, startTime, clientIP, requestBody, responseBody)
return
}
forwardedBody := requestBody
if len(requestBody) > 0 {
if body, changed, err := prepareRequestBody(requestBody, r.URL.Path); err != nil {
log.Printf("Error preparing request body: %v", err)
} else if changed {
forwardedBody = body
}
}
// Build upstream URL
upstreamURL, err := url.Parse(apiBase)
if err != nil {
http.Error(w, "Invalid upstream URL", http.StatusInternalServerError)
log.Printf("Error parsing upstream URL: %v", err)
return
}
upstreamURL.Path = buildUpstreamPath(upstreamURL.Path, r.URL.Path)
upstreamURL.RawQuery = r.URL.RawQuery
upstreamFullPath := upstreamURL.String()
// Create new request to upstream
upstreamReq, err := http.NewRequest(r.Method, upstreamFullPath, bytes.NewReader(forwardedBody))
if err != nil {
http.Error(w, "Failed to create upstream request", http.StatusInternalServerError)
log.Printf("Error creating upstream request: %v", err)
return
}
// Copy headers from original request
for key, values := range r.Header {
if strings.EqualFold(key, "Authorization") ||
strings.EqualFold(key, "Content-Length") ||
strings.EqualFold(key, "Host") {
continue
}
for _, value := range values {
upstreamReq.Header.Add(key, value)
}
}
// Inject/overwrite Authorization header with upstream API key
upstreamReq.Header.Set("Authorization", "Bearer "+apiKey)
upstreamReq.ContentLength = int64(len(forwardedBody))
// Execute the upstream request
client := &http.Client{}
upstreamResp, err := client.Do(upstreamReq)
if err != nil {
http.Error(w, "Failed to reach upstream server", http.StatusBadGateway)
log.Printf("Error executing upstream request: %v", err)
return
}
defer upstreamResp.Body.Close()
// Read response body
responseBody, err := io.ReadAll(upstreamResp.Body)
if err != nil {
http.Error(w, "Failed to read upstream response", http.StatusInternalServerError)
log.Printf("Error reading response body: %v", err)
return
}
// Calculate latency
latency := int(time.Since(startTime).Milliseconds())
// Extract token usage and model from response
inputTokens, outputTokens, totalTokens, cachedTokens := extractTokens(responseBody)
responseModel := model
// Calculate cost
cost := calculateCost(responseModel, inputTokens, outputTokens, cachedTokens)
// Log to database
err = logToDatabase(RequestLog{
ClientIP: clientIP,
UpstreamURL: apiBase,
Method: r.Method,
Path: r.URL.Path,
StatusCode: upstreamResp.StatusCode,
LatencyMs: latency,
RequestBody: string(forwardedBody),
ResponseBody: string(responseBody),
InputTokens: inputTokens,
OutputTokens: outputTokens,
TotalTokens: totalTokens,
CachedTokens: cachedTokens,
CostINR: cost,
Model: responseModel,
})
if err != nil {
log.Printf("Error logging to database: %v", err)
}
// Console logging
log.Printf("\n========== REQUEST ==========")
log.Printf("Method: %s | Path: %s | Client: %s", r.Method, r.URL.Path, clientIP)
log.Printf("Upstream URL: %s", upstreamFullPath)
log.Printf("Configured Model: %s", model)
log.Printf("Path: %s", r.URL.Path)
log.Printf("Request Body: %s", truncateString(string(forwardedBody), 200))
log.Printf("========== RESPONSE ==========")
log.Printf("Status: %d | Latency: %dms", upstreamResp.StatusCode, latency)
log.Printf("Model: %s", responseModel)
log.Printf("Tokens - Input: %d | Cached: %d | Output: %d | Total: %d", inputTokens, cachedTokens, outputTokens, totalTokens)
log.Printf("Cost: $%.6f", cost)
log.Printf("Response Body: %s", truncateString(string(responseBody), 200))
log.Println("==============================")
// Copy response headers
for key, values := range upstreamResp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
// Write status code and body
w.WriteHeader(upstreamResp.StatusCode)
w.Write(responseBody)
}
func logsHandler(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/logs/") {
logDetailHandler(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
page := intFromQuery(r, "page", 1)
pageSize := intFromQuery(r, "page_size", 50)
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 50
}
if pageSize > 200 {
pageSize = 200
}
offset := (page - 1) * pageSize
var total int
if err := db.QueryRow(`SELECT COUNT(*) FROM request_logs`).Scan(&total); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
rows, err := db.Query(`
SELECT id, timestamp, client_ip, upstream_url, method, path,
status_code, latency_ms,
input_tokens, output_tokens, total_tokens, cached_tokens, cost_inr, model
FROM request_logs
ORDER BY id DESC
LIMIT ? OFFSET ?
`, pageSize, offset)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
var logs []RequestLog
for rows.Next() {
var reqLog RequestLog
err := rows.Scan(
&reqLog.ID, &reqLog.Timestamp, &reqLog.ClientIP, &reqLog.UpstreamURL,
&reqLog.Method, &reqLog.Path, &reqLog.StatusCode, &reqLog.LatencyMs,
&reqLog.InputTokens, &reqLog.OutputTokens, &reqLog.TotalTokens,
&reqLog.CachedTokens, &reqLog.CostINR, &reqLog.Model,
)
if err != nil {
log.Printf("Error scanning row: %v", err)
continue
}
logs = append(logs, reqLog)
}
response := map[string]interface{}{
"page": page,
"page_size": pageSize,
"total": total,
"total_pages": totalPages(total, pageSize),
"items": logs,
}
json.NewEncoder(w).Encode(response)
}
func logDetailHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/logs/"), "/")
if len(parts) == 0 || strings.TrimSpace(parts[0]) == "" {
http.Error(w, "Missing log id", http.StatusBadRequest)
return
}
id, err := strconv.Atoi(parts[0])
if err != nil || id < 1 {
http.Error(w, "Invalid log id", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
var reqLog RequestLog
if err := db.QueryRow(`
SELECT id, timestamp, client_ip, upstream_url, method, path,
status_code, latency_ms, request_body, response_body,
input_tokens, output_tokens, total_tokens, cached_tokens, cost_inr, model
FROM request_logs
WHERE id = ?
LIMIT 1
`, id).Scan(
&reqLog.ID, &reqLog.Timestamp, &reqLog.ClientIP, &reqLog.UpstreamURL,
&reqLog.Method, &reqLog.Path, &reqLog.StatusCode, &reqLog.LatencyMs,
&reqLog.RequestBody, &reqLog.ResponseBody,
&reqLog.InputTokens, &reqLog.OutputTokens, &reqLog.TotalTokens,
&reqLog.CachedTokens, &reqLog.CostINR, &reqLog.Model,
); err != nil {
if err == sql.ErrNoRows {
http.Error(w, "Log not found", http.StatusNotFound)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(reqLog)
}
func lastUpdatedHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
var lastID int
var lastTimestamp sql.NullString
if err := db.QueryRow(`
SELECT id, timestamp
FROM request_logs
ORDER BY id DESC
LIMIT 1
`).Scan(&lastID, &lastTimestamp); err != nil {
if err == sql.ErrNoRows {
json.NewEncoder(w).Encode(map[string]interface{}{
"last_id": 0,
"last_timestamp": "",
})
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(map[string]interface{}{
"last_id": lastID,
"last_timestamp": lastTimestamp.String,
})
}
func statsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var stats struct {
TotalRequests int `json:"total_requests"`
TotalTokens int `json:"total_tokens"`
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
CachedTokens int `json:"cached_tokens"`
TotalCost float64 `json:"total_cost_inr"`
}
err := db.QueryRow(`
SELECT
COUNT(*) as total_requests,
COALESCE(SUM(total_tokens), 0) as total_tokens,
COALESCE(SUM(input_tokens), 0) as input_tokens,
COALESCE(SUM(output_tokens), 0) as output_tokens,
COALESCE(SUM(cached_tokens), 0) as cached_tokens,
COALESCE(SUM(cost_inr), 0) as total_cost
FROM request_logs
`).Scan(
&stats.TotalRequests,
&stats.TotalTokens,
&stats.InputTokens,
&stats.OutputTokens,
&stats.CachedTokens,
&stats.TotalCost,
)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(stats)
}
func dashboardHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "dashboard.html")
}
type configResponse struct {
APIBase string `json:"api_base"`
Model string `json:"model"`
}
type configUpdate struct {
APIBase *string `json:"api_base"`
APIKey *string `json:"api_key"`
Model *string `json:"model"`
}
func configHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(configResponse{
APIBase: apiBase,
Model: model,
})
return
case http.MethodPost:
var update configUpdate
if err := json.NewDecoder(r.Body).Decode(&update); err != nil {
http.Error(w, "Invalid JSON payload", http.StatusBadRequest)
return
}
updates := make(map[string]string)
if update.APIBase != nil {
value := strings.TrimSpace(*update.APIBase)
if value == "" {
http.Error(w, "api_base cannot be empty", http.StatusBadRequest)
return
}
apiBase = value
os.Setenv("API_BASE", value)
updates["API_BASE"] = value
}
if update.Model != nil {
value := strings.TrimSpace(*update.Model)
if value == "" {
http.Error(w, "model cannot be empty", http.StatusBadRequest)
return
}
model = value
os.Setenv("MODEL", value)
updates["MODEL"] = value
}
if update.APIKey != nil {
value := strings.TrimSpace(*update.APIKey)
if value == "" {
http.Error(w, "api_key cannot be empty", http.StatusBadRequest)
return
}
apiKey = value
os.Setenv("API_KEY", value)
updates["API_KEY"] = value
}
if len(updates) == 0 {
http.Error(w, "No settings to update", http.StatusBadRequest)
return
}
if err := updateEnvFile(".env", updates); err != nil {
http.Error(w, "Failed to update .env", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(configResponse{
APIBase: apiBase,
Model: model,
})
return
default:
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
}
func localMetadataResponse(path string) ([]byte, bool) {
normalizedPath := normalizeRequestPath(path)
switch normalizedPath {
case "/models":
return mustJSON(map[string]interface{}{
"object": "list",
"data": []map[string]interface{}{
{
"id": model,
"object": "model",
"created": 0,
"owned_by": "llmproxy",
},
},
}), true
case "/api/tags":
return mustJSON(map[string]interface{}{
"models": []map[string]interface{}{
{
"name": model,
"model": model,
"modified_at": time.Now().UTC().Format(time.RFC3339Nano),
"size": 0,
"digest": "",
"details": map[string]interface{}{
"family": "openai",
"families": []string{"openai"},
"parameter_size": "",
"quantization_level": "",
},
},
},
}), true
case "/version":
return mustJSON(map[string]string{"version": "llmproxy"}), true
case "/props":
return mustJSON(map[string]interface{}{
"model": model,
"models": []string{
model,
},
}), true
default:
return nil, false
}
}
func writeLocalResponse(w http.ResponseWriter, r *http.Request, startTime time.Time, clientIP string, requestBody, responseBody []byte) {
latency := int(time.Since(startTime).Milliseconds())
if err := logToDatabase(RequestLog{
ClientIP: clientIP,
UpstreamURL: "local",
Method: r.Method,
Path: r.URL.Path,
StatusCode: http.StatusOK,
LatencyMs: latency,
RequestBody: string(requestBody),
ResponseBody: string(responseBody),
Model: model,
}); err != nil {
log.Printf("Error logging local response to database: %v", err)
}
log.Printf("\n========== REQUEST ==========")
log.Printf("Method: %s | Path: %s | Client: %s", r.Method, r.URL.Path, clientIP)
log.Printf("Upstream URL: local metadata response")
log.Printf("Configured Model: %s", model)
log.Printf("Request Body: %s", truncateString(string(requestBody), 200))
log.Printf("========== RESPONSE ==========")
log.Printf("Status: %d | Latency: %dms", http.StatusOK, latency)
log.Printf("Model: %s", model)
log.Printf("Tokens - Input: 0 | Cached: 0 | Output: 0 | Total: 0")
log.Printf("Cost: $0.000000")
log.Printf("Response Body: %s", truncateString(string(responseBody), 200))
log.Println("==============================")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if r.Method != http.MethodHead {
w.Write(responseBody)
}
}
func mustJSON(value interface{}) []byte {
body, err := json.Marshal(value)
if err != nil {
log.Fatalf("Failed to marshal local metadata response: %v", err)
}
return body
}
func buildUpstreamPath(basePath, requestPath string) string {
requestPath = normalizeRequestPath(requestPath)
if basePath == "" || basePath == "/" {
return requestPath
}
if requestPath == "" || requestPath == "/" {
return basePath
}
basePath = strings.TrimRight(basePath, "/")
if requestPath == basePath || strings.HasPrefix(requestPath, basePath+"/") {
return requestPath
}
return basePath + "/" + strings.TrimLeft(requestPath, "/")
}
func normalizeRequestPath(path string) string {
path = "/" + strings.TrimLeft(path, "/")
path = strings.TrimRight(path, "/")
if path == "" {
return "/"
}
switch {
case path == "/api/tags":
return path
case path == "/api/version":
return "/version"
case path == "/api/props":
return "/props"
case path == "/api/v1":
return "/"
case strings.HasPrefix(path, "/api/v1/"):
return "/" + strings.TrimPrefix(path, "/api/v1/")
case path == "/v1":
return "/"
case strings.HasPrefix(path, "/v1/"):
return "/" + strings.TrimPrefix(path, "/v1/")
default:
return path
}
}
func prepareRequestBody(requestBody []byte, path string) ([]byte, bool, error) {
var reqBody map[string]interface{}
if err := json.Unmarshal(requestBody, &reqBody); err != nil {
return nil, false, err
}
changed := false
if reqBody["model"] != model {
reqBody["model"] = model
changed = true
}
if isChatCompletionsPath(path) {
if stream, ok := reqBody["stream"].(bool); ok && stream {
streamOptions, _ := reqBody["stream_options"].(map[string]interface{})
if streamOptions == nil {
streamOptions = make(map[string]interface{})
reqBody["stream_options"] = streamOptions
changed = true
}
if streamOptions["include_usage"] != true {
streamOptions["include_usage"] = true
changed = true
}
}
}
if !changed {
return requestBody, false, nil
}
body, err := json.Marshal(reqBody)
if err != nil {
return nil, false, err
}
return body, true, nil
}
func isChatCompletionsPath(path string) bool {
return path == "/chat/completions" || strings.HasSuffix(path, "/chat/completions")
}
func extractTokens(responseBody []byte) (input, output, total, cached int) {
// Default to 0 if not found
input, output, total, cached = 0, 0, 0, 0
// Try to parse as Response API format (input_tokens/output_tokens)
var resp Response
if err := json.Unmarshal(responseBody, &resp); err == nil {
if usageHasTokens(resp.Usage) {
input, output, total, cached = tokensFromUsage(resp.Usage)
return
}
}
if input, output, total, cached, ok := extractTokensFromSSE(responseBody); ok {
return input, output, total, cached
}
// Try parsing as a generic map for flexibility
var wrappedResp map[string]interface{}
if err := json.Unmarshal(responseBody, &wrappedResp); err == nil {
if usage, ok := wrappedResp["usage"].(map[string]interface{}); ok {
input, output, total, cached = tokensFromUsageMap(usage)
return
}
}
return
}
func extractTokensFromSSE(responseBody []byte) (input, output, total, cached int, ok bool) {
lines := strings.Split(string(responseBody), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "data:") {
continue
}
payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
if payload == "" || payload == "[DONE]" {
continue
}
var chunk Response
if err := json.Unmarshal([]byte(payload), &chunk); err == nil && usageHasTokens(chunk.Usage) {
input, output, total, cached = tokensFromUsage(chunk.Usage)
ok = true
continue
}
var wrappedChunk map[string]interface{}
if err := json.Unmarshal([]byte(payload), &wrappedChunk); err == nil {
if usage, found := wrappedChunk["usage"].(map[string]interface{}); found {
input, output, total, cached = tokensFromUsageMap(usage)
if input > 0 || output > 0 || total > 0 || cached > 0 {
ok = true
}
}
}
}
return
}
func usageHasTokens(usage Usage) bool {
return usage.InputTokens > 0 ||
usage.OutputTokens > 0 ||
usage.PromptTokens > 0 ||
usage.CompletionTokens > 0 ||
usage.TotalTokens > 0 ||
usage.CachedTokens > 0 ||
usage.PromptDetails.CachedTokens > 0 ||
usage.InputDetails.CachedTokens > 0
}
func tokensFromUsage(usage Usage) (input, output, total, cached int) {
input = usage.InputTokens
output = usage.OutputTokens
if input == 0 {
input = usage.PromptTokens
}
if output == 0 {
output = usage.CompletionTokens
}
total = usage.TotalTokens
if total == 0 {
total = input + output
}
cached = usage.CachedTokens
if cached == 0 {
cached = usage.PromptDetails.CachedTokens
}
if cached == 0 {
cached = usage.InputDetails.CachedTokens
}
return
}
func tokensFromUsageMap(usage map[string]interface{}) (input, output, total, cached int) {
input = intFromMap(usage, "input_tokens")
output = intFromMap(usage, "output_tokens")
if input == 0 {
input = intFromMap(usage, "prompt_tokens")
}
if output == 0 {
output = intFromMap(usage, "completion_tokens")
}
total = intFromMap(usage, "total_tokens")
if total == 0 {
total = input + output
}
cached = intFromMap(usage, "cached_tokens")
if cached == 0 {
cached = cachedTokensFromDetails(usage, "prompt_tokens_details")
}
if cached == 0 {
cached = cachedTokensFromDetails(usage, "input_tokens_details")
}
return
}
func cachedTokensFromDetails(usage map[string]interface{}, key string) int {
details, ok := usage[key].(map[string]interface{})
if !ok {
return 0
}
return intFromMap(details, "cached_tokens")
}
func intFromMap(values map[string]interface{}, key string) int {
value, ok := values[key]
if !ok {
return 0
}
switch v := value.(type) {
case float64:
return int(v)
case int:
return v
case json.Number:
i, _ := v.Int64()
return int(i)
default:
return 0
}
}
func intFromQuery(r *http.Request, key string, fallback int) int {
value := strings.TrimSpace(r.URL.Query().Get(key))
if value == "" {
return fallback
}
parsed, err := strconv.Atoi(value)
if err != nil {
return fallback
}
return parsed
}
func totalPages(total, pageSize int) int {
if pageSize <= 0 {