-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
151 lines (131 loc) · 4.25 KB
/
handler.go
File metadata and controls
151 lines (131 loc) · 4.25 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
package embedrock
import (
"encoding/json"
"io"
"net/http"
"strings"
)
const defaultModel = "amazon.titan-embed-text-v2:0"
// Handler serves the OpenAI-compatible embedding API.
type Handler struct {
embedder Embedder
defaultModel string
}
// NewHandler creates a handler with the default model name.
func NewHandler(embedder Embedder) *Handler {
return &Handler{embedder: embedder, defaultModel: defaultModel}
}
// NewHandlerWithModel creates a handler with a specific default model name.
// The model name appears in health checks and responses when the client omits it.
func NewHandlerWithModel(embedder Embedder, model string) *Handler {
return &Handler{embedder: embedder, defaultModel: model}
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
path := strings.TrimSuffix(r.URL.Path, "/")
switch {
case r.Method == http.MethodGet && (path == "" || path == "/"):
h.handleHealth(w)
case path == "/v1/embeddings" && r.Method == http.MethodPost:
h.handleEmbeddings(w, r)
case path == "/v1/embeddings":
h.writeError(w, http.StatusMethodNotAllowed, "method not allowed", "invalid_request")
default:
h.writeError(w, http.StatusNotFound, "not found", "invalid_request")
}
}
func (h *Handler) handleHealth(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(HealthResponse{Status: "ok", Model: h.defaultModel})
}
func (h *Handler) handleEmbeddings(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil || len(body) == 0 {
h.writeError(w, http.StatusBadRequest, "empty or invalid request body", "invalid_request")
return
}
inputs, model, err := parseInput(body)
if err != nil {
h.writeError(w, http.StatusBadRequest, err.Error(), "invalid_request")
return
}
if model == "" {
model = h.defaultModel
}
data := make([]EmbeddingData, 0, len(inputs))
promptTokens := 0
for i, text := range inputs {
embedding, err := h.embedder.Embed(text)
if err != nil {
h.writeError(w, http.StatusInternalServerError, err.Error(), "server_error")
return
}
data = append(data, EmbeddingData{
Object: "embedding",
Index: i,
Embedding: embedding,
})
promptTokens += len(text)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(EmbeddingResponse{
Object: "list",
Data: data,
Model: model,
Usage: Usage{PromptTokens: promptTokens, TotalTokens: promptTokens},
})
}
// parseInput extracts text inputs and model from an OpenAI-format request body.
func parseInput(body []byte) ([]string, string, error) {
// Try batch (array input)
var batch EmbeddingRequestBatch
if err := json.Unmarshal(body, &batch); err == nil && len(batch.Input) > 0 {
return batch.Input, batch.Model, nil
}
// Try single string input
var single EmbeddingRequest
if err := json.Unmarshal(body, &single); err == nil && single.Input != "" {
return []string{single.Input}, single.Model, nil
}
// Fallback: raw JSON with generic input field
var raw map[string]interface{}
if err := json.Unmarshal(body, &raw); err != nil {
return nil, "", err
}
model, _ := raw["model"].(string)
switch v := raw["input"].(type) {
case string:
if v == "" {
return nil, "", &EmbedError{Message: "input is empty"}
}
return []string{v}, model, nil
case []interface{}:
inputs := make([]string, 0, len(v))
for _, item := range v {
s, ok := item.(string)
if !ok {
return nil, "", &EmbedError{Message: "input array must contain strings"}
}
inputs = append(inputs, s)
}
if len(inputs) == 0 {
return nil, "", &EmbedError{Message: "input array is empty"}
}
return inputs, model, nil
default:
return nil, "", &EmbedError{Message: "input must be a string or array of strings"}
}
}
func (h *Handler) writeError(w http.ResponseWriter, status int, message, errType string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(ErrorResponse{
Error: ErrorDetail{Message: message, Type: errType},
})
}