Files
LLM-Proxy-Metrics/llmproxymetrics.go

106 lines
2.0 KiB
Go
Raw Normal View History

2025-04-20 13:47:17 +03:00
package main
import (
2025-04-22 19:31:34 +03:00
"bufio"
2025-04-20 13:47:17 +03:00
"encoding/json"
"fmt"
2025-04-23 14:46:49 +03:00
"io"
2025-04-20 13:47:17 +03:00
"log"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"github.com/caarlos0/env/v11"
)
var cfg config
type config struct {
BaseURL string `env:"BASE_URL"`
Port int `env:"PORT"`
}
func createProxy(target *url.URL) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
r.Host = target.Host
r.URL.Scheme = target.Scheme
r.URL.Host = target.Host
2025-04-23 14:46:49 +03:00
director := func(req *http.Request) {
2025-04-22 19:31:34 +03:00
req.Header.Set("X-Forwarded-For", r.RemoteAddr)
req.Host = target.Host
2025-04-23 14:46:49 +03:00
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
2025-04-22 19:31:34 +03:00
}
2025-04-20 13:47:17 +03:00
2025-04-23 14:46:49 +03:00
modifyResponse := func(response *http.Response) error {
pr, pw := io.Pipe()
body := response.Body
response.Body = pr
2025-04-22 19:31:34 +03:00
2025-04-23 14:46:49 +03:00
go func() {
defer pw.Close()
2025-04-22 19:31:34 +03:00
2025-04-23 14:46:49 +03:00
reader := bufio.NewReader(body)
for {
line, err := reader.ReadBytes('\n')
2025-04-22 19:31:34 +03:00
if err != nil {
2025-04-23 14:46:49 +03:00
if err == io.EOF {
handleJsonLine([]byte(string(line)))
pw.Write(line)
break
}
return
2025-04-22 19:31:34 +03:00
}
2025-04-23 14:46:49 +03:00
handleJsonLine(line)
pw.Write(line)
2025-04-22 19:31:34 +03:00
}
2025-04-20 13:47:17 +03:00
2025-04-23 14:46:49 +03:00
}()
2025-04-20 13:47:17 +03:00
2025-04-23 14:46:49 +03:00
return nil
}
2025-04-20 13:47:17 +03:00
2025-04-23 14:46:49 +03:00
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.Director = director
proxy.ModifyResponse = modifyResponse
2025-04-20 13:47:17 +03:00
2025-04-23 14:46:49 +03:00
proxy.ServeHTTP(w, r)
}
}
func handleJsonLine(line []byte) {
var jsonData map[string]interface{}
err := json.Unmarshal([]byte(line), &jsonData)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
if jsonData["done"].(bool) {
duration := jsonData["eval_duration"].(float64)
fmt.Printf("Duration: %.2f seconds\n", duration/1000000000.0)
2025-04-22 19:31:34 +03:00
}
2025-04-20 13:47:17 +03:00
}
func main() {
2025-04-22 19:31:34 +03:00
err := env.Parse(&cfg)
if err != nil {
log.Fatalf("Error parsing environment variables: %v", err)
}
2025-04-20 13:47:17 +03:00
targetURL, err := url.Parse(cfg.BaseURL)
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", createProxy(targetURL))
log.Printf("Starting proxy server on :%s", strconv.Itoa(cfg.Port))
2025-04-22 19:31:34 +03:00
err = http.ListenAndServe(fmt.Sprintf(":%d", cfg.Port), nil)
2025-04-20 13:47:17 +03:00
if err != nil {
log.Fatal(err)
}
}