forked from envoyproxy/ai-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendpointspec.go
More file actions
1063 lines (965 loc) · 46 KB
/
Copy pathendpointspec.go
File metadata and controls
1063 lines (965 loc) · 46 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
// Copyright Envoy AI Gateway Authors
// SPDX-License-Identifier: Apache-2.0
// The full text of the Apache license is available in the LICENSE file at
// the root of the repo.
// Package endpointspec defines the EndpointSpec which is to bundle the translator, tracing
// and most importantly request and response types for different API endpoints.
package endpointspec
import (
"bytes"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"strconv"
"strings"
"github.com/tidwall/sjson"
"github.com/envoyproxy/ai-gateway/internal/apischema/anthropic"
cohereschema "github.com/envoyproxy/ai-gateway/internal/apischema/cohere"
gcpschema "github.com/envoyproxy/ai-gateway/internal/apischema/gcp"
"github.com/envoyproxy/ai-gateway/internal/apischema/openai"
"github.com/envoyproxy/ai-gateway/internal/filterapi"
"github.com/envoyproxy/ai-gateway/internal/internalapi"
"github.com/envoyproxy/ai-gateway/internal/json"
"github.com/envoyproxy/ai-gateway/internal/redaction"
"github.com/envoyproxy/ai-gateway/internal/tracing/tracingapi"
"github.com/envoyproxy/ai-gateway/internal/translator"
)
type (
// Spec defines methods for parsing request bodies and selecting translators
// for different API endpoints.
//
// Type Parameters:
// * ReqT: The request type.
// * RespT: The response type.
// * RespChunkT: The chunk type for streaming responses.
//
// This must be implemented by specific endpoint handlers to provide
// custom logic for parsing and translation.
Spec[ReqT, RespT, RespChunkT any] interface {
// ParseBody parses the request body and returns the original model,
// the parsed request, whether the request is streaming, any mutated body,
// and an error if parsing fails.
//
// Parameters:
// * body: The raw request body as a byte slice.
// * costConfigured: A boolean indicating if cost metrics are configured.
//
// Returns:
// * originalModel: The original model specified in the request.
// * req: The parsed request of type ReqT.
// * stream: A boolean indicating if the request is for streaming responses.
// * mutatedBody: The possibly mutated request body as a byte slice. Or nil if no mutation is needed.
// * err: An error if parsing fails.
ParseBody(body []byte, costConfigured bool) (originalModel internalapi.OriginalModel, req *ReqT, stream bool, mutatedBody []byte, err error)
// GetTranslator selects the appropriate translator based on the output API schema
// and an optional model name override.
//
// Parameters:
// * out: The output API schema for which the translator is needed.
// * modelNameOverride: An optional model name to override the one specified in the request.
//
// Returns:
// * translator: The selected translator of type Translator[ReqT, RespT, RespChunkT].
// * err: An error if translator selection fails.
GetTranslator(schema filterapi.VersionedAPISchema, modelNameOverride string) (translator.Translator[ReqT, tracingapi.Span[RespT, RespChunkT]], error)
// RedactSensitiveInfoFromRequest creates a redacted copy of the request for safe debug logging.
// Sensitive content (messages, images, audio, tool parameters, etc.) is replaced with placeholders
// containing length and hash information to aid in debugging cache hits/misses and correlation.
//
// The returned request preserves the structure but removes actual sensitive data, making it
// safe to include in logs. It should NOT be used for actual AI provider requests.
//
// Parameters:
// * req: The original request to redact.
//
// Returns:
// * redactedReq: A copy with sensitive fields replaced by [REDACTED LENGTH=n HASH=xxxx] placeholders.
// * err: An error if redaction fails (implementation-specific).
RedactSensitiveInfoFromRequest(req *ReqT) (redactedReq *ReqT, err error)
// ParseMultipartBody parses a multipart/form-data request body.
// Endpoints that don't support multipart should return an error.
//
// Parameters:
// * body: The raw multipart request body.
// * contentType: The Content-Type header value (includes boundary parameter).
// * costConfigured: A boolean indicating if cost metrics are configured.
//
// Returns the same tuple as ParseBody.
ParseMultipartBody(body []byte, contentType string, costConfigured bool) (originalModel internalapi.OriginalModel, req *ReqT, stream bool, mutatedBody []byte, err error)
}
// ChatCompletionsEndpointSpec implements EndpointSpec for /v1/chat/completions.
ChatCompletionsEndpointSpec struct{}
// CompletionsEndpointSpec implements EndpointSpec for /v1/completions.
CompletionsEndpointSpec struct{}
// EmbeddingsEndpointSpec implements EndpointSpec for /v1/embeddings.
EmbeddingsEndpointSpec struct{}
// ImageGenerationEndpointSpec implements EndpointSpec for /v1/images/generations.
ImageGenerationEndpointSpec struct{}
// ImageEditsEndpointSpec implements EndpointSpec for /v1/images/edits.
// Requests are multipart/form-data; only the model and prompt fields are extracted for routing.
ImageEditsEndpointSpec struct{}
// ResponsesEndpointSpec implements EndpointSpec for /v1/responses.
ResponsesEndpointSpec struct{}
// MessagesEndpointSpec implements EndpointSpec for /v1/messages.
MessagesEndpointSpec struct{}
// RerankEndpointSpec implements EndpointSpec for /v2/rerank.
RerankEndpointSpec struct{}
// SpeechEndpointSpec implements EndpointSpec for /v1/audio/speech.
SpeechEndpointSpec struct{}
// GeminiGenerateContentEndpointSpec implements EndpointSpec for Gemini native API paths
// (/v1beta/models/{model}:generateContent, /v1beta/models/{model}:streamGenerateContent,
// and the equivalent Vertex AI paths /v1/projects/.../models/{model}:generateContent).
// Model and stream flag are extracted from the request path by the server and injected
// as synthetic headers; ParseBody returns empty model and stream=false intentionally.
GeminiGenerateContentEndpointSpec struct{}
// GeminiCachedContentsEndpointSpec implements EndpointSpec for Gemini cachedContents
// management API (/v1beta/cachedContents and /v1/projects/{p}/locations/{l}/cachedContents).
// Used for explicit context cache CRUD (POST/GET/PATCH/DELETE). The request body is parsed
// best-effort: POST/PATCH carry a CachedContentRequest, GET/DELETE carry no body.
GeminiCachedContentsEndpointSpec struct{}
// TranscriptionEndpointSpec implements EndpointSpec for /v1/audio/transcriptions.
TranscriptionEndpointSpec struct{}
// TranslationEndpointSpec implements EndpointSpec for /v1/audio/translations.
TranslationEndpointSpec struct{}
)
var errMultipartNotSupported = fmt.Errorf("%w: multipart body not supported for this endpoint", internalapi.ErrMalformedRequest)
// ParseBody implements [EndpointSpec.ParseBody].
func (ChatCompletionsEndpointSpec) ParseBody(
body []byte,
costConfigured bool,
) (internalapi.OriginalModel, *openai.ChatCompletionRequest, bool, []byte, error) {
var req openai.ChatCompletionRequest
if err := json.Unmarshal(body, &req); err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse JSON for /v1/chat/completions: %w", internalapi.ErrMalformedRequest, err)
}
var mutatedBody []byte
if req.Stream && costConfigured && (req.StreamOptions == nil || !req.StreamOptions.IncludeUsage) {
// If the request is a streaming request and cost metrics are configured, we need to include usage in the response
// to avoid the bypassing of the token usage calculation.
req.StreamOptions = &openai.StreamOptions{IncludeUsage: true}
// Rewrite the original bytes to include the stream_options.include_usage=true so that forcing the request body
// mutation, which uses this raw body, will also result in the stream_options.include_usage=true.
var err error
mutatedBody, err = sjson.SetBytesOptions(body, "stream_options.include_usage", true, &sjson.Options{
Optimistic: true,
// Note: it is safe to do in-place replacement since this route level processor is executed once per request,
// and the result can be safely shared among possible multiple retries.
ReplaceInPlace: true,
})
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to set stream_options.include_usage", internalapi.ErrMalformedRequest)
}
}
return req.Model, &req, req.Stream, mutatedBody, nil
}
// ParseMultipartBody implements [Spec.ParseMultipartBody].
func (ChatCompletionsEndpointSpec) ParseMultipartBody([]byte, string, bool) (internalapi.OriginalModel, *openai.ChatCompletionRequest, bool, []byte, error) {
return "", nil, false, nil, errMultipartNotSupported
}
// GetTranslator implements [EndpointSpec.GetTranslator].
func (ChatCompletionsEndpointSpec) GetTranslator(schema filterapi.VersionedAPISchema, modelNameOverride string) (translator.OpenAIChatCompletionTranslator, error) {
switch schema.Name {
case filterapi.APISchemaOpenAI:
return translator.NewChatCompletionOpenAIToOpenAITranslator(schema.OpenAIPrefix(), modelNameOverride), nil
case filterapi.APISchemaAWSBedrock:
return translator.NewChatCompletionOpenAIToAWSBedrockTranslator(modelNameOverride), nil
case filterapi.APISchemaAWSAnthropic:
return translator.NewChatCompletionOpenAIToAWSAnthropicTranslator(schema.Version, modelNameOverride), nil
case filterapi.APISchemaAzureOpenAI:
return translator.NewChatCompletionOpenAIToAzureOpenAITranslator(schema.Version, modelNameOverride), nil
case filterapi.APISchemaGCPVertexAI:
return translator.NewChatCompletionOpenAIToGCPVertexAITranslator(modelNameOverride), nil
case filterapi.APISchemaGCPAnthropic:
return translator.NewChatCompletionOpenAIToGCPAnthropicTranslator(schema.Version, modelNameOverride), nil
default:
return nil, fmt.Errorf("unsupported API schema: backend=%s", schema)
}
}
// RedactSensitiveInfoFromRequest implements [EndpointSpec.RedactSensitiveInfoFromRequest].
func (ChatCompletionsEndpointSpec) RedactSensitiveInfoFromRequest(req *openai.ChatCompletionRequest) (redactedReq *openai.ChatCompletionRequest, err error) {
// Create a shallow copy of the request
redacted := *req
// Redact all message content (user prompts, assistant responses, system messages, etc.)
redacted.Messages = make([]openai.ChatCompletionMessageParamUnion, len(req.Messages))
for i, msg := range req.Messages {
redacted.Messages[i] = redactMessage(msg)
}
// Redact prediction content if present (cached prompts, prefill content)
if req.PredictionContent != nil {
redactedPrediction := *req.PredictionContent
redactedPrediction.Content = redactContentUnion(req.PredictionContent.Content)
redacted.PredictionContent = &redactedPrediction
}
// Tool definitions (name, description, parameters) are developer-authored schema metadata,
// not user data — kept as-is.
// Response format schemas and guided_json are developer-authored — kept as-is.
return &redacted, nil
}
// ParseBody implements [EndpointSpec.ParseBody].
func (CompletionsEndpointSpec) ParseBody(
body []byte,
_ bool,
) (internalapi.OriginalModel, *openai.CompletionRequest, bool, []byte, error) {
var openAIReq openai.CompletionRequest
if err := json.Unmarshal(body, &openAIReq); err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse JSON for /v1/completions: %w", internalapi.ErrMalformedRequest, err)
}
return openAIReq.Model, &openAIReq, openAIReq.Stream, nil, nil
}
// ParseMultipartBody implements [Spec.ParseMultipartBody].
func (CompletionsEndpointSpec) ParseMultipartBody([]byte, string, bool) (internalapi.OriginalModel, *openai.CompletionRequest, bool, []byte, error) {
return "", nil, false, nil, errMultipartNotSupported
}
// GetTranslator implements [EndpointSpec.GetTranslator].
func (CompletionsEndpointSpec) GetTranslator(schema filterapi.VersionedAPISchema, modelNameOverride string) (translator.OpenAICompletionTranslator, error) {
switch schema.Name {
case filterapi.APISchemaOpenAI:
return translator.NewCompletionOpenAIToOpenAITranslator(schema.OpenAIPrefix(), modelNameOverride), nil
default:
return nil, fmt.Errorf("unsupported API schema: backend=%s", schema)
}
}
// RedactSensitiveInfoFromRequest implements [EndpointSpec.RedactSensitiveInfoFromRequest].
func (CompletionsEndpointSpec) RedactSensitiveInfoFromRequest(req *openai.CompletionRequest) (redactedReq *openai.CompletionRequest, err error) {
// Placeholder if redaction is required in future
return req, nil
}
// ParseBody implements [EndpointSpec.ParseBody].
func (EmbeddingsEndpointSpec) ParseBody(
body []byte,
_ bool,
) (internalapi.OriginalModel, *openai.EmbeddingRequest, bool, []byte, error) {
var openAIReq openai.EmbeddingRequest
if err := json.Unmarshal(body, &openAIReq); err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse JSON for /v1/embeddings: %w", internalapi.ErrMalformedRequest, err)
}
return openAIReq.Model, &openAIReq, false, nil, nil
}
// ParseMultipartBody implements [Spec.ParseMultipartBody].
func (EmbeddingsEndpointSpec) ParseMultipartBody([]byte, string, bool) (internalapi.OriginalModel, *openai.EmbeddingRequest, bool, []byte, error) {
return "", nil, false, nil, errMultipartNotSupported
}
// GetTranslator implements [EndpointSpec.GetTranslator].
func (EmbeddingsEndpointSpec) GetTranslator(schema filterapi.VersionedAPISchema, modelNameOverride string) (translator.OpenAIEmbeddingTranslator, error) {
switch schema.Name {
case filterapi.APISchemaOpenAI:
return translator.NewEmbeddingOpenAIToOpenAITranslator(schema.OpenAIPrefix(), modelNameOverride), nil
case filterapi.APISchemaAzureOpenAI:
return translator.NewEmbeddingOpenAIToAzureOpenAITranslator(schema.Version, modelNameOverride), nil
case filterapi.APISchemaGCPVertexAI:
return translator.NewEmbeddingOpenAIToGCPVertexAITranslator("", modelNameOverride), nil
case filterapi.APISchemaAWSBedrock:
return translator.NewEmbeddingOpenAIToAWSBedrockTranslator(modelNameOverride), nil
default:
return nil, fmt.Errorf("unsupported API schema: backend=%s", schema)
}
}
// RedactSensitiveInfoFromRequest implements [EndpointSpec.RedactSensitiveInfoFromRequest].
func (EmbeddingsEndpointSpec) RedactSensitiveInfoFromRequest(req *openai.EmbeddingRequest) (redactedReq *openai.EmbeddingRequest, err error) {
// Placeholder if redaction is required in future
return req, nil
}
func (ImageGenerationEndpointSpec) ParseBody(
body []byte,
_ bool,
) (internalapi.OriginalModel, *openai.ImageGenerationRequest, bool, []byte, error) {
var openAIReq openai.ImageGenerationRequest
if err := json.Unmarshal(body, &openAIReq); err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse JSON for /v1/images/generations: %w", internalapi.ErrMalformedRequest, err)
}
return openAIReq.Model, &openAIReq, false, nil, nil
}
// ParseMultipartBody implements [Spec.ParseMultipartBody].
func (ImageGenerationEndpointSpec) ParseMultipartBody([]byte, string, bool) (internalapi.OriginalModel, *openai.ImageGenerationRequest, bool, []byte, error) {
return "", nil, false, nil, errMultipartNotSupported
}
// GetTranslator implements [EndpointSpec.GetTranslator].
func (ImageGenerationEndpointSpec) GetTranslator(schema filterapi.VersionedAPISchema, modelNameOverride string) (translator.OpenAIImageGenerationTranslator, error) {
switch schema.Name {
case filterapi.APISchemaOpenAI:
return translator.NewImageGenerationOpenAIToOpenAITranslator(schema.OpenAIPrefix(), modelNameOverride), nil
default:
return nil, fmt.Errorf("unsupported API schema: backend=%s", schema)
}
}
// RedactSensitiveInfoFromRequest implements [EndpointSpec.RedactSensitiveInfoFromRequest].
func (ImageGenerationEndpointSpec) RedactSensitiveInfoFromRequest(req *openai.ImageGenerationRequest) (redactedReq *openai.ImageGenerationRequest, err error) {
// Placeholder if redaction is required in future
return req, nil
}
// ParseBody implements [Spec.ParseBody]. Image edits use multipart, so JSON body is not expected.
func (ImageEditsEndpointSpec) ParseBody(
_ []byte, _ bool,
) (internalapi.OriginalModel, *openai.ImageEditRequest, bool, []byte, error) {
return "", nil, false, nil, fmt.Errorf("%w: expected multipart/form-data content type for /v1/images/edits", internalapi.ErrMalformedRequest)
}
// ParseMultipartBody implements [Spec.ParseMultipartBody] for /v1/images/edits.
// It extracts the model and prompt from the multipart/form-data body without reading binary file parts.
func (ImageEditsEndpointSpec) ParseMultipartBody(
body []byte, _ string, _ bool,
) (internalapi.OriginalModel, *openai.ImageEditRequest, bool, []byte, error) {
req, err := parseImageEditRequest(body)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: %w", internalapi.ErrMalformedRequest, err)
}
return req.Model, req, false, nil, nil
}
// GetTranslator implements [EndpointSpec.GetTranslator].
func (ImageEditsEndpointSpec) GetTranslator(schema filterapi.VersionedAPISchema, modelNameOverride string) (translator.OpenAIImageEditsTranslator, error) {
switch schema.Name {
case filterapi.APISchemaOpenAI:
return translator.NewImageEditsOpenAIToOpenAITranslator(schema.OpenAIPrefix(), modelNameOverride), nil
default:
return nil, fmt.Errorf("unsupported API schema for image edits: backend=%s", schema)
}
}
// RedactSensitiveInfoFromRequest implements [EndpointSpec.RedactSensitiveInfoFromRequest].
func (ImageEditsEndpointSpec) RedactSensitiveInfoFromRequest(req *openai.ImageEditRequest) (redactedReq *openai.ImageEditRequest, err error) {
redacted := *req
redacted.Prompt = redaction.RedactString(req.Prompt)
return &redacted, nil
}
// parseImageEditRequest extracts metadata fields from a raw multipart/form-data body.
// Only text fields (model, prompt) are read; binary file parts are skipped.
func parseImageEditRequest(body []byte) (*openai.ImageEditRequest, error) {
eol := bytes.Index(body, []byte("\r\n"))
if eol < 3 || !bytes.HasPrefix(body, []byte("--")) {
return nil, fmt.Errorf("failed to parse multipart for /v1/images/edits: missing boundary marker")
}
boundary := string(body[2:eol])
mr := multipart.NewReader(bytes.NewReader(body), boundary)
req := &openai.ImageEditRequest{}
for {
part, err := mr.NextPart()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, fmt.Errorf("failed to parse multipart for /v1/images/edits: %w", err)
}
// Skip file upload parts (image, mask) to avoid reading large binary data.
if part.FileName() != "" {
continue
}
data, err := io.ReadAll(part)
if err != nil {
return nil, fmt.Errorf("failed to read multipart field %q: %w", part.FormName(), err)
}
switch part.FormName() {
case "model":
req.Model = string(data)
case "prompt":
req.Prompt = string(data)
}
}
return req, nil
}
// ParseBody implements [EndpointSpec.ParseBody].
func (ResponsesEndpointSpec) ParseBody(
body []byte,
_ bool,
) (internalapi.OriginalModel, *openai.ResponseRequest, bool, []byte, error) {
var openAIReq openai.ResponseRequest
if err := json.Unmarshal(body, &openAIReq); err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse JSON for /v1/responses: %w", internalapi.ErrMalformedRequest, err)
}
return openAIReq.Model, &openAIReq, openAIReq.Stream, nil, nil
}
// ParseMultipartBody implements [Spec.ParseMultipartBody].
func (ResponsesEndpointSpec) ParseMultipartBody([]byte, string, bool) (internalapi.OriginalModel, *openai.ResponseRequest, bool, []byte, error) {
return "", nil, false, nil, errMultipartNotSupported
}
// GetTranslator implements [EndpointSpec.GetTranslator].
func (ResponsesEndpointSpec) GetTranslator(schema filterapi.VersionedAPISchema, modelNameOverride string) (translator.OpenAIResponsesTranslator, error) {
switch schema.Name {
case filterapi.APISchemaOpenAI:
return translator.NewResponsesOpenAIToOpenAITranslator(schema.OpenAIPrefix(), modelNameOverride), nil
case filterapi.APISchemaAzureOpenAI:
return translator.NewResponsesOpenAIToAzureOpenAITranslator(schema.Version, modelNameOverride), nil
default:
return nil, fmt.Errorf("unsupported API schema: backend=%s", schema)
}
}
// RedactSensitiveInfoFromRequest implements [EndpointSpec.RedactSensitiveInfoFromRequest].
func (ResponsesEndpointSpec) RedactSensitiveInfoFromRequest(req *openai.ResponseRequest) (redactedReq *openai.ResponseRequest, err error) {
// Placeholder if redaction is required in future
return req, nil
}
// ParseBody implements [EndpointSpec.ParseBody].
func (MessagesEndpointSpec) ParseBody(
body []byte,
_ bool,
) (internalapi.OriginalModel, *anthropic.MessagesRequest, bool, []byte, error) {
var anthropicReq anthropic.MessagesRequest
if err := json.Unmarshal(body, &anthropicReq); err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse JSON for /v1/messages: %w", internalapi.ErrMalformedRequest, err)
}
model := anthropicReq.Model
if model == "" {
return "", nil, false, nil, fmt.Errorf("%w: model field is required", internalapi.ErrInvalidRequestBody)
}
stream := anthropicReq.Stream
return model, &anthropicReq, stream, nil, nil
}
// ParseMultipartBody implements [Spec.ParseMultipartBody].
func (MessagesEndpointSpec) ParseMultipartBody([]byte, string, bool) (internalapi.OriginalModel, *anthropic.MessagesRequest, bool, []byte, error) {
return "", nil, false, nil, errMultipartNotSupported
}
// GetTranslator implements [EndpointSpec.GetTranslator].
func (MessagesEndpointSpec) GetTranslator(schema filterapi.VersionedAPISchema, modelNameOverride string) (translator.AnthropicMessagesTranslator, error) {
// Messages processor only supports Anthropic-native translators.
switch schema.Name {
case filterapi.APISchemaGCPAnthropic:
return translator.NewAnthropicToGCPAnthropicTranslator(schema.Version, modelNameOverride), nil
case filterapi.APISchemaAWSAnthropic:
return translator.NewAnthropicToAWSAnthropicTranslator(schema.Version, modelNameOverride), nil
case filterapi.APISchemaAnthropic:
return translator.NewAnthropicToAnthropicTranslator(schema.AnthropicPrefix(), modelNameOverride), nil
case filterapi.APISchemaOpenAI:
return translator.NewAnthropicToChatCompletionOpenAITranslator(schema.OpenAIPrefix(), modelNameOverride), nil
case filterapi.APISchemaAWSBedrock:
return translator.NewAnthropicToAWSBedrockTranslator(modelNameOverride), nil
default:
return nil, fmt.Errorf("/v1/messages endpoint only supports backends that return native Anthropic format (Anthropic, GCPAnthropic, AWSAnthropic). OpenAI and AWSBedrock translation is also supported. Backend %s uses different model format", schema.Name)
}
}
// RedactSensitiveInfoFromRequest implements [EndpointSpec.RedactSensitiveInfoFromRequest].
func (MessagesEndpointSpec) RedactSensitiveInfoFromRequest(req *anthropic.MessagesRequest) (redactedReq *anthropic.MessagesRequest, err error) {
// Placeholder if redaction is required in future
return req, nil
}
// ParseBody implements [EndpointSpec.ParseBody].
func (RerankEndpointSpec) ParseBody(
body []byte,
_ bool,
) (internalapi.OriginalModel, *cohereschema.RerankV2Request, bool, []byte, error) {
var req cohereschema.RerankV2Request
if err := json.Unmarshal(body, &req); err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse JSON for /v2/rerank: %w", internalapi.ErrMalformedRequest, err)
}
return req.Model, &req, false, nil, nil
}
// ParseMultipartBody implements [Spec.ParseMultipartBody].
func (RerankEndpointSpec) ParseMultipartBody([]byte, string, bool) (internalapi.OriginalModel, *cohereschema.RerankV2Request, bool, []byte, error) {
return "", nil, false, nil, errMultipartNotSupported
}
// GetTranslator implements [EndpointSpec.GetTranslator].
func (RerankEndpointSpec) GetTranslator(schema filterapi.VersionedAPISchema, modelNameOverride string) (translator.CohereRerankTranslator, error) {
switch schema.Name {
case filterapi.APISchemaCohere:
return translator.NewRerankCohereToCohereTranslator(schema.Version, modelNameOverride), nil
default:
return nil, fmt.Errorf("unsupported API schema: backend=%s", schema)
}
}
// RedactSensitiveInfoFromRequest implements [EndpointSpec.RedactSensitiveInfoFromRequest].
func (RerankEndpointSpec) RedactSensitiveInfoFromRequest(req *cohereschema.RerankV2Request) (redactedReq *cohereschema.RerankV2Request, err error) {
// Placeholder if redaction is required in future
return req, nil
}
// ParseBody implements [EndpointSpec.ParseBody].
// Model and stream are intentionally left empty/false; they are filled in by the processor
// after reading the x-aigw-path-model and x-aigw-path-stream synthetic headers.
func (GeminiGenerateContentEndpointSpec) ParseBody(
body []byte,
_ bool,
) (internalapi.OriginalModel, *gcpschema.GenerateContentRequest, bool, []byte, error) {
var req gcpschema.GenerateContentRequest
if err := json.Unmarshal(body, &req); err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse JSON for Gemini generateContent: %w", internalapi.ErrMalformedRequest, err)
}
// Model and Stream are json:"-" fields populated by the processor from path-derived headers.
return req.Model, &req, req.Stream, nil, nil
}
// ParseMultipartBody implements [Spec.ParseMultipartBody]. Gemini generateContent is JSON-only.
func (GeminiGenerateContentEndpointSpec) ParseMultipartBody([]byte, string, bool) (internalapi.OriginalModel, *gcpschema.GenerateContentRequest, bool, []byte, error) {
return "", nil, false, nil, errMultipartNotSupported
}
// GetTranslator implements [EndpointSpec.GetTranslator].
func (GeminiGenerateContentEndpointSpec) GetTranslator(schema filterapi.VersionedAPISchema, modelNameOverride string) (translator.GeminiGenerateContentTranslator, error) {
switch schema.Name {
case filterapi.APISchemaGCPVertexAI:
return translator.NewGeminiToGCPVertexAITranslator(modelNameOverride), nil
default:
return nil, fmt.Errorf("unsupported API schema for Gemini generateContent: backend=%s", schema)
}
}
// RedactSensitiveInfoFromRequest implements [EndpointSpec.RedactSensitiveInfoFromRequest].
func (GeminiGenerateContentEndpointSpec) RedactSensitiveInfoFromRequest(req *gcpschema.GenerateContentRequest) (redactedReq *gcpschema.GenerateContentRequest, err error) {
return req, nil
}
// ParseBody implements [Spec.ParseBody] for cachedContents management requests.
// POST/PATCH carry a JSON CachedContentRequest body; GET/DELETE bodies are empty.
// Empty bodies parse to a zero-value request so the processor can still dispatch.
//
// The model returned as OriginalModel is normalised to its short name (e.g. "gemini-1.5-pro")
// even when the request body uses the full Vertex resource form
// "projects/.../publishers/google/models/{m}". AIGatewayRoute header matches and
// modelNameOverride mappings are written against the short form, so we have to expose the
// same shape ext_proc does for every other endpoint.
func (GeminiCachedContentsEndpointSpec) ParseBody(
body []byte,
_ bool,
) (internalapi.OriginalModel, *gcpschema.CachedContentRequest, bool, []byte, error) {
var req gcpschema.CachedContentRequest
if len(body) > 0 {
if err := json.Unmarshal(body, &req); err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse JSON for cachedContents: %w", internalapi.ErrMalformedRequest, err)
}
}
model := normalizeVertexModelName(req.Model)
// cachedContents is never streamed.
return model, &req, false, nil, nil
}
// normalizeVertexModelName trims any Vertex AI resource prefix from a model identifier and
// returns just the short model name (the segment after the last "/models/"). Returns the
// input unchanged when no prefix is present.
func normalizeVertexModelName(m string) string {
const seg = "/models/"
idx := strings.LastIndex(m, seg)
if idx == -1 {
return m
}
return m[idx+len(seg):]
}
// ParseMultipartBody implements [Spec.ParseMultipartBody]. cachedContents is JSON-only.
func (GeminiCachedContentsEndpointSpec) ParseMultipartBody([]byte, string, bool) (internalapi.OriginalModel, *gcpschema.CachedContentRequest, bool, []byte, error) {
return "", nil, false, nil, errMultipartNotSupported
}
// GetTranslator implements [EndpointSpec.GetTranslator]. The modelNameOverride is forwarded to
// the translator so cache-create bodies pick up the same model alias mapping as generateContent.
func (GeminiCachedContentsEndpointSpec) GetTranslator(schema filterapi.VersionedAPISchema, modelNameOverride string) (translator.GeminiCachedContentsTranslator, error) {
switch schema.Name {
case filterapi.APISchemaGCPVertexAI:
return translator.NewGeminiCachedContentsToGCPVertexAITranslator(modelNameOverride), nil
default:
return nil, fmt.Errorf("unsupported API schema for Gemini cachedContents: backend=%s", schema)
}
}
// RedactSensitiveInfoFromRequest implements [EndpointSpec.RedactSensitiveInfoFromRequest].
// Cached content is developer-supplied prompt material; not redacted for debug logs.
func (GeminiCachedContentsEndpointSpec) RedactSensitiveInfoFromRequest(req *gcpschema.CachedContentRequest) (redactedReq *gcpschema.CachedContentRequest, err error) {
return req, nil
}
// redactMessage redacts sensitive content from a chat message while preserving its type and structure.
// This dispatches to role-specific redaction functions based on the message type.
func redactMessage(msg openai.ChatCompletionMessageParamUnion) openai.ChatCompletionMessageParamUnion {
switch {
case msg.OfUser != nil:
return redactUserMessage(msg)
case msg.OfAssistant != nil:
return redactAssistantMessage(msg)
case msg.OfSystem != nil:
return redactSystemMessage(msg)
case msg.OfDeveloper != nil:
return redactDeveloperMessage(msg)
case msg.OfTool != nil:
return redactToolMessage(msg)
default:
return msg
}
}
// redactUserMessage redacts content from a user message, including text, images, audio, and files.
func redactUserMessage(msg openai.ChatCompletionMessageParamUnion) openai.ChatCompletionMessageParamUnion {
redactedMsg := *msg.OfUser
redactedMsg.Content = redactStringOrUserRoleContentUnion(msg.OfUser.Content)
return openai.ChatCompletionMessageParamUnion{OfUser: &redactedMsg}
}
// redactAssistantMessage redacts content from an assistant message, including message text and tool call arguments.
func redactAssistantMessage(msg openai.ChatCompletionMessageParamUnion) openai.ChatCompletionMessageParamUnion {
redactedMsg := *msg.OfAssistant
redactedMsg.Content = redactStringOrAssistantRoleContentUnion(msg.OfAssistant.Content)
// Redact tool call arguments (may contain data derived from user messages).
// Function name is kept — it is the tool API name, not user data.
if len(msg.OfAssistant.ToolCalls) > 0 {
redactedMsg.ToolCalls = make([]openai.ChatCompletionMessageToolCallParam, len(msg.OfAssistant.ToolCalls))
for i, tc := range msg.OfAssistant.ToolCalls {
redactedToolCall := tc
redactedToolCall.Function.Arguments = redaction.RedactString(tc.Function.Arguments)
redactedMsg.ToolCalls[i] = redactedToolCall
}
}
return openai.ChatCompletionMessageParamUnion{OfAssistant: &redactedMsg}
}
// redactSystemMessage redacts content from a system message.
func redactSystemMessage(msg openai.ChatCompletionMessageParamUnion) openai.ChatCompletionMessageParamUnion {
redactedMsg := *msg.OfSystem
redactedMsg.Content = redactContentUnion(msg.OfSystem.Content)
return openai.ChatCompletionMessageParamUnion{OfSystem: &redactedMsg}
}
// redactDeveloperMessage redacts content from a developer message.
func redactDeveloperMessage(msg openai.ChatCompletionMessageParamUnion) openai.ChatCompletionMessageParamUnion {
redactedMsg := *msg.OfDeveloper
redactedMsg.Content = redactContentUnion(msg.OfDeveloper.Content)
return openai.ChatCompletionMessageParamUnion{OfDeveloper: &redactedMsg}
}
// redactToolMessage redacts content from a tool message.
func redactToolMessage(msg openai.ChatCompletionMessageParamUnion) openai.ChatCompletionMessageParamUnion {
redactedMsg := *msg.OfTool
redactedMsg.Content = redactContentUnion(msg.OfTool.Content)
return openai.ChatCompletionMessageParamUnion{OfTool: &redactedMsg}
}
// redactContentUnion redacts content from a ContentUnion, handling both string and structured content parts.
func redactContentUnion(content openai.ContentUnion) openai.ContentUnion {
switch v := content.Value.(type) {
case string:
return openai.ContentUnion{Value: redaction.RedactString(v)}
case []openai.ChatCompletionContentPartTextParam:
redactedParts := make([]openai.ChatCompletionContentPartTextParam, len(v))
for i, part := range v {
redactedPart := part
redactedPart.Text = redaction.RedactString(part.Text)
redactedParts[i] = redactedPart
}
return openai.ContentUnion{Value: redactedParts}
default:
return content
}
}
// redactStringOrUserRoleContentUnion redacts content from a StringOrUserRoleContentUnion.
func redactStringOrUserRoleContentUnion(content openai.StringOrUserRoleContentUnion) openai.StringOrUserRoleContentUnion {
switch v := content.Value.(type) {
case string:
return openai.StringOrUserRoleContentUnion{Value: redaction.RedactString(v)}
case []openai.ChatCompletionContentPartUserUnionParam:
redactedParts := make([]openai.ChatCompletionContentPartUserUnionParam, len(v))
for i, part := range v {
redactedParts[i] = redactUserContentPart(part)
}
return openai.StringOrUserRoleContentUnion{Value: redactedParts}
default:
return content
}
}
// redactStringOrAssistantRoleContentUnion redacts content from a StringOrAssistantRoleContentUnion.
func redactStringOrAssistantRoleContentUnion(content openai.StringOrAssistantRoleContentUnion) openai.StringOrAssistantRoleContentUnion {
switch v := content.Value.(type) {
case string:
return openai.StringOrAssistantRoleContentUnion{Value: redaction.RedactString(v)}
case []openai.ChatCompletionAssistantMessageParamContent:
redactedParts := make([]openai.ChatCompletionAssistantMessageParamContent, len(v))
for i, part := range v {
redactedPart := part
if part.Text != nil {
redactedText := redaction.RedactString(*part.Text)
redactedPart.Text = &redactedText
}
if part.Refusal != nil {
redactedRefusal := redaction.RedactString(*part.Refusal)
redactedPart.Refusal = &redactedRefusal
}
redactedParts[i] = redactedPart
}
return openai.StringOrAssistantRoleContentUnion{Value: redactedParts}
case openai.ChatCompletionAssistantMessageParamContent:
redactedPart := v
if v.Text != nil {
redactedText := redaction.RedactString(*v.Text)
redactedPart.Text = &redactedText
}
if v.Refusal != nil {
redactedRefusal := redaction.RedactString(*v.Refusal)
redactedPart.Refusal = &redactedRefusal
}
return openai.StringOrAssistantRoleContentUnion{Value: redactedPart}
default:
return content
}
}
// redactUserContentPart redacts sensitive content from a user message content part.
// Handles multiple content types: text, images (URLs or base64), audio, and file attachments.
func redactUserContentPart(part openai.ChatCompletionContentPartUserUnionParam) openai.ChatCompletionContentPartUserUnionParam {
redacted := part
// Redact plain text content
if part.OfText != nil {
redactedText := *part.OfText
redactedText.Text = redaction.RedactString(part.OfText.Text)
redacted.OfText = &redactedText
}
// Redact image URLs (may be data URLs with embedded base64 image data)
if part.OfImageURL != nil {
redactedImage := *part.OfImageURL
redactedImage.ImageURL.URL = redaction.RedactString(part.OfImageURL.ImageURL.URL)
redacted.OfImageURL = &redactedImage
}
// Redact audio data (typically base64-encoded audio)
if part.OfInputAudio != nil {
redactedAudio := *part.OfInputAudio
redactedAudio.InputAudio.Data = redaction.RedactString(part.OfInputAudio.InputAudio.Data)
redacted.OfInputAudio = &redactedAudio
}
// Redact file attachments (may contain sensitive documents or data)
if part.OfFile != nil {
redactedFile := *part.OfFile
if part.OfFile.File.FileData != "" {
redactedFile.File.FileData = redaction.RedactString(part.OfFile.File.FileData)
}
redacted.OfFile = &redactedFile
}
return redacted
}
// ParseBody implements [EndpointSpec.ParseBody].
func (SpeechEndpointSpec) ParseBody(
body []byte,
_ bool,
) (internalapi.OriginalModel, *openai.SpeechRequest, bool, []byte, error) {
var req openai.SpeechRequest
if err := json.Unmarshal(body, &req); err != nil {
return "", nil, false, nil, fmt.Errorf("failed to unmarshal speech request: %w", err)
}
// Determine if streaming based on stream_format
stream := req.StreamFormat != nil && *req.StreamFormat == openai.StreamFormatSSE
return req.Model, &req, stream, nil, nil
}
// ParseMultipartBody implements [Spec.ParseMultipartBody].
func (SpeechEndpointSpec) ParseMultipartBody([]byte, string, bool) (internalapi.OriginalModel, *openai.SpeechRequest, bool, []byte, error) {
return "", nil, false, nil, errMultipartNotSupported
}
// GetTranslator implements [EndpointSpec.GetTranslator].
func (SpeechEndpointSpec) GetTranslator(
schema filterapi.VersionedAPISchema,
modelNameOverride string,
) (translator.OpenAISpeechTranslator, error) {
switch schema.Name {
case filterapi.APISchemaOpenAI:
return translator.NewSpeechOpenAIToOpenAITranslator(
schema.OpenAIPrefix(),
modelNameOverride,
), nil
case filterapi.APISchemaAlibabaDashScope:
return translator.NewSpeechOpenAIToDashScopeTranslator(modelNameOverride), nil
default:
return nil, fmt.Errorf("unsupported API schema for speech: backend=%s", schema)
}
}
// RedactSensitiveInfoFromRequest implements [EndpointSpec.RedactSensitiveInfoFromRequest].
func (SpeechEndpointSpec) RedactSensitiveInfoFromRequest(req *openai.SpeechRequest) (redactedReq *openai.SpeechRequest, err error) {
// Create a shallow copy of the request
redacted := *req
// Redact the input text (contains user-provided text to be synthesized)
redacted.Input = redaction.RedactString(req.Input)
// Redact instructions if present (may contain sensitive context)
if req.Instructions != nil {
redactedInstructions := redaction.RedactString(*req.Instructions)
redacted.Instructions = &redactedInstructions
}
return &redacted, nil
}
// ParseBody implements [Spec.ParseBody]. Transcription uses multipart, so JSON body is not expected.
func (TranscriptionEndpointSpec) ParseBody(
_ []byte, _ bool,
) (internalapi.OriginalModel, *openai.TranscriptionRequest, bool, []byte, error) {
return "", nil, false, nil, fmt.Errorf("%w: expected multipart/form-data content type for /v1/audio/transcriptions", internalapi.ErrMalformedRequest)
}
// ParseMultipartBody implements [Spec.ParseMultipartBody] for /v1/audio/transcriptions.
func (TranscriptionEndpointSpec) ParseMultipartBody(
body []byte, contentType string, _ bool,
) (internalapi.OriginalModel, *openai.TranscriptionRequest, bool, []byte, error) {
_, params, err := mime.ParseMediaType(contentType)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse multipart form data: %w", internalapi.ErrMalformedRequest, err)
}
boundary := params["boundary"]
if boundary == "" {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse multipart form data: missing boundary", internalapi.ErrMalformedRequest)
}
reader := multipart.NewReader(bytes.NewReader(body), boundary)
var req openai.TranscriptionRequest
var hasModel, hasFile bool
for {
part, err := reader.NextPart()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse multipart form data: %w", internalapi.ErrMalformedRequest, err)
}
switch part.FormName() {
case "model":
val, err := readFormField(part)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to read model field: %w", internalapi.ErrMalformedRequest, err)
}
req.Model = val
hasModel = true
case "file":
hasFile = true
req.FileName = part.FileName()
n, err := io.Copy(io.Discard, part)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to read file field: %w", internalapi.ErrMalformedRequest, err)
}
req.FileSize = n
case "language":
val, err := readFormField(part)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to read language field: %w", internalapi.ErrMalformedRequest, err)
}
req.Language = val
case "prompt":
val, err := readFormField(part)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to read prompt field: %w", internalapi.ErrMalformedRequest, err)
}
req.Prompt = val
case "response_format":
val, err := readFormField(part)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to read response_format field: %w", internalapi.ErrMalformedRequest, err)
}
req.ResponseFormat = val
case "temperature":
val, err := readFormField(part)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to read temperature field: %w", internalapi.ErrMalformedRequest, err)
}
t, parseErr := strconv.ParseFloat(val, 64)
if parseErr != nil {
return "", nil, false, nil, fmt.Errorf("%w: invalid temperature value %q: %w", internalapi.ErrMalformedRequest, val, parseErr)
}
req.Temperature = &t
case "stream":
val, err := readFormField(part)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to read stream field: %w", internalapi.ErrMalformedRequest, err)
}
req.Stream = strings.EqualFold(val, "true")
case "timestamp_granularities[]":
val, err := readFormField(part)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to read timestamp_granularities field: %w", internalapi.ErrMalformedRequest, err)
}
req.TimestampGranularities = append(req.TimestampGranularities, val)
}
}
if !hasModel {
return "", nil, false, nil, fmt.Errorf("%w: missing required field 'model'", internalapi.ErrMalformedRequest)
}
if !hasFile {
return "", nil, false, nil, fmt.Errorf("%w: missing required field 'file'", internalapi.ErrMalformedRequest)
}
return req.Model, &req, req.Stream, nil, nil
}
// GetTranslator implements [Spec.GetTranslator].
func (TranscriptionEndpointSpec) GetTranslator(
schema filterapi.VersionedAPISchema, modelNameOverride string,
) (translator.OpenAIAudioTranscriptionTranslator, error) {
switch schema.Name {
case filterapi.APISchemaOpenAI:
return translator.NewTranscriptionOpenAIToOpenAITranslator(schema.OpenAIPrefix(), modelNameOverride), nil
default:
return nil, fmt.Errorf("unsupported API schema for audio transcription: backend=%s", schema)
}
}
// RedactSensitiveInfoFromRequest implements [Spec.RedactSensitiveInfoFromRequest].
func (TranscriptionEndpointSpec) RedactSensitiveInfoFromRequest(req *openai.TranscriptionRequest) (*openai.TranscriptionRequest, error) {
redacted := *req
redacted.Prompt = redaction.RedactString(req.Prompt)
return &redacted, nil
}
// ParseBody implements [Spec.ParseBody]. Translation uses multipart, so JSON body is not expected.
func (TranslationEndpointSpec) ParseBody(
_ []byte, _ bool,
) (internalapi.OriginalModel, *openai.TranslationRequest, bool, []byte, error) {
return "", nil, false, nil, fmt.Errorf("%w: expected multipart/form-data content type for /v1/audio/translations", internalapi.ErrMalformedRequest)
}
// ParseMultipartBody implements [Spec.ParseMultipartBody] for /v1/audio/translations.
// OpenAI's translation endpoint does not support streaming, so the stream return value is
// always false.
func (TranslationEndpointSpec) ParseMultipartBody(
body []byte, contentType string, _ bool,
) (internalapi.OriginalModel, *openai.TranslationRequest, bool, []byte, error) {
_, params, err := mime.ParseMediaType(contentType)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse multipart form data: %w", internalapi.ErrMalformedRequest, err)
}
boundary := params["boundary"]
if boundary == "" {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse multipart form data: missing boundary", internalapi.ErrMalformedRequest)
}
reader := multipart.NewReader(bytes.NewReader(body), boundary)
var req openai.TranslationRequest
var hasModel, hasFile bool
for {
part, err := reader.NextPart()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to parse multipart form data: %w", internalapi.ErrMalformedRequest, err)
}
switch part.FormName() {
case "model":
val, err := readFormField(part)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to read model field: %w", internalapi.ErrMalformedRequest, err)
}
req.Model = val
hasModel = true
case "file":
hasFile = true
req.FileName = part.FileName()
n, err := io.Copy(io.Discard, part)
if err != nil {
return "", nil, false, nil, fmt.Errorf("%w: failed to read file field: %w", internalapi.ErrMalformedRequest, err)
}