-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
345 lines (303 loc) · 10.5 KB
/
handler.go
File metadata and controls
345 lines (303 loc) · 10.5 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
package bedrockify
import (
"encoding/json"
"io"
"log"
"net/http"
"strings"
"time"
)
// maxRequestBodySize limits request body reads to 10MB to prevent OOM.
const maxRequestBodySize = 10 * 1024 * 1024
const defaultChatModel = "us.anthropic.claude-sonnet-4-6"
const defaultEmbedModel = "amazon.titan-embed-text-v2:0"
// Handler serves the OpenAI-compatible chat completions and embeddings API.
type Handler struct {
converser Converser
embedder Embedder
defaultModel string
embeddingModel string
region string
version string
}
// NewHandler creates a handler with the default model name.
func NewHandler(converser Converser) *Handler {
return &Handler{
converser: converser,
defaultModel: defaultChatModel,
region: "us-east-1",
}
}
// NewHandlerWithModel creates a handler with specific default model names and optional embedder.
func NewHandlerWithModel(converser Converser, model, version, region string) *Handler {
if region == "" {
region = "us-east-1"
}
return &Handler{
converser: converser,
defaultModel: model,
version: version,
region: region,
}
}
// NewHandlerFull creates a unified handler with both converser and embedder.
func NewHandlerFull(converser Converser, embedder Embedder, chatModel, embedModel, version, region string) *Handler {
if region == "" {
region = "us-east-1"
}
if embedModel == "" {
embedModel = defaultEmbedModel
}
return &Handler{
converser: converser,
embedder: embedder,
defaultModel: chatModel,
embeddingModel: embedModel,
version: version,
region: region,
}
}
// ServeHTTP dispatches requests to the appropriate handler.
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/chat/completions" && r.Method == http.MethodPost:
h.handleChatCompletions(w, r)
case path == "/v1/chat/completions":
h.writeError(w, http.StatusMethodNotAllowed, "method not allowed", "invalid_request_error")
case path == "/v1/embeddings" && r.Method == http.MethodPost:
h.handleEmbeddings(w, r)
case path == "/v1/embeddings" && r.Method == http.MethodOptions:
w.WriteHeader(http.StatusOK)
case path == "/v1/embeddings":
h.writeError(w, http.StatusMethodNotAllowed, "method not allowed", "invalid_request_error")
case path == "/v1/models" && r.Method == http.MethodGet:
h.handleModels(w, r)
case path == "/v1/models":
h.writeError(w, http.StatusMethodNotAllowed, "method not allowed", "invalid_request_error")
default:
h.writeError(w, http.StatusNotFound, "not found", "invalid_request_error")
}
}
// handleHealth returns a simple health check JSON.
func (h *Handler) handleHealth(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
resp := HealthResponse{
Status: "ok",
Model: h.defaultModel,
Version: h.version,
}
if h.embedder != nil {
resp.EmbedModel = h.embeddingModel
}
json.NewEncoder(w).Encode(resp)
}
// readBody reads and returns the request body with a size limit.
func readBody(r *http.Request) ([]byte, error) {
r.Body = http.MaxBytesReader(nil, r.Body, maxRequestBodySize)
return io.ReadAll(r.Body)
}
// handleChatCompletions handles POST /v1/chat/completions.
func (h *Handler) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
body, err := readBody(r)
if err != nil || len(body) == 0 {
h.writeError(w, http.StatusBadRequest, "empty or invalid request body", "invalid_request_error")
return
}
var req ChatRequest
if err := json.Unmarshal(body, &req); err != nil {
h.writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error(), "invalid_request_error")
return
}
if len(req.Messages) == 0 {
h.writeError(w, http.StatusBadRequest, "messages must not be empty", "invalid_request_error")
return
}
// Apply default model if not specified
if req.Model == "" {
req.Model = h.defaultModel
}
// Resolve model aliases (OpenRouter IDs, short names, etc.) to Bedrock IDs
req.Model, _ = ResolveModelAlias(req.Model, h.region)
start := time.Now()
if req.Stream {
h.handleStreaming(w, r, &req, start)
} else {
h.handleNonStreaming(w, r, &req, start)
}
}
// handleNonStreaming handles a regular (non-SSE) chat completion.
func (h *Handler) handleNonStreaming(w http.ResponseWriter, r *http.Request, req *ChatRequest, start time.Time) {
resp, err := h.converser.Converse(r.Context(), req)
if err != nil {
log.Printf("converse error model=%s latency=%s: %v", req.Model, time.Since(start).Round(time.Millisecond), err)
h.writeBedrockError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
// handleStreaming handles a streaming SSE chat completion.
func (h *Handler) handleStreaming(w http.ResponseWriter, r *http.Request, req *ChatRequest, start time.Time) {
ch, err := h.converser.ConverseStream(r.Context(), req)
if err != nil {
log.Printf("converse-stream error model=%s latency=%s: %v", req.Model, time.Since(start).Round(time.Millisecond), err)
h.writeBedrockError(w, err)
return
}
reqID := newRequestID()
includeUsage := req.StreamOptions != nil && req.StreamOptions.IncludeUsage
StreamWithOptions(w, ch, req.Model, reqID, includeUsage)
}
// handleEmbeddings handles POST /v1/embeddings.
func (h *Handler) handleEmbeddings(w http.ResponseWriter, r *http.Request) {
if h.embedder == nil {
h.writeError(w, http.StatusNotFound, "embeddings endpoint not configured; start with --embed-model to enable", "not_found_error")
return
}
body, err := readBody(r)
if err != nil || len(body) == 0 {
h.writeError(w, http.StatusBadRequest, "empty or invalid request body", "invalid_request_error")
return
}
inputs, model, err := parseEmbedInput(body)
if err != nil {
h.writeError(w, http.StatusBadRequest, err.Error(), "invalid_request_error")
return
}
// Resolve embedding model alias
if model != "" {
model, _ = ResolveEmbeddingAlias(model)
}
if model == "" {
model = h.embeddingModel
} else if model != h.embeddingModel {
h.writeError(w, http.StatusBadRequest,
"model '"+model+"' is not available; this server is configured with '"+h.embeddingModel+"'",
"invalid_request_error")
return
}
data := make([]EmbeddingData, 0, len(inputs))
promptTokens := 0
for i, text := range inputs {
embedding, err := h.embedder.Embed(r.Context(), text)
if err != nil {
log.Printf("embedding error: %v", err)
h.writeError(w, http.StatusInternalServerError, "embedding failed", "server_error")
return
}
data = append(data, EmbeddingData{
Object: "embedding",
Index: i,
Embedding: embedding,
})
promptTokens += len(text) / 4 // ~4 chars per BPE token
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(EmbeddingResponse{
Object: "list",
Data: data,
Model: model,
Usage: Usage{PromptTokens: promptTokens, TotalTokens: promptTokens},
})
}
// handleModels handles GET /v1/models.
func (h *Handler) handleModels(w http.ResponseWriter, r *http.Request) {
models, err := h.converser.ListModels(r.Context())
if err != nil {
log.Printf("list models error: %v", err)
h.writeError(w, http.StatusInternalServerError, "failed to list models: "+err.Error(), "server_error")
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ModelsResponse{
Object: "list",
Data: models,
})
}
// writeError writes a standard OpenAI error response.
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},
})
}
// writeBedrockError translates a Bedrock error into an OpenAI error response.
// Logs the full error server-side but returns a sanitized message to the client.
func (h *Handler) writeBedrockError(w http.ResponseWriter, err error) {
msg := err.Error()
status := http.StatusInternalServerError
errType := "server_error"
clientMsg := "internal server error"
lower := strings.ToLower(msg)
switch {
case strings.Contains(lower, "throttlingexception") || strings.Contains(lower, "too many requests"):
status = http.StatusTooManyRequests
errType = "rate_limit_error"
clientMsg = "rate limit exceeded — try again later"
case strings.Contains(lower, "validationexception") || strings.Contains(lower, "invalid"):
status = http.StatusBadRequest
errType = "invalid_request_error"
clientMsg = "invalid request — check model ID and parameters"
case strings.Contains(lower, "accessdenied") || strings.Contains(lower, "unauthorized"):
status = http.StatusUnauthorized
errType = "authentication_error"
clientMsg = "authentication failed"
case strings.Contains(lower, "resourcenotfound") || strings.Contains(lower, "not found"):
status = http.StatusNotFound
errType = "not_found_error"
clientMsg = "model not found"
}
h.writeError(w, status, clientMsg, errType)
}
// parseEmbedInput extracts text inputs and model from an OpenAI-format request body.
func parseEmbedInput(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"}
}
}