|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "strings" |
| 8 | + "unsafe" |
| 9 | + |
| 10 | + "github.com/envoyproxy/ai-gateway/internal/apischema/anthropic" |
| 11 | + cohereschema "github.com/envoyproxy/ai-gateway/internal/apischema/cohere" |
| 12 | + "github.com/envoyproxy/ai-gateway/internal/apischema/openai" |
| 13 | + "github.com/envoyproxy/ai-gateway/internal/dynamic_module/sdk" |
| 14 | + "github.com/envoyproxy/ai-gateway/internal/internalapi" |
| 15 | + openaisdk "github.com/openai/openai-go/v2" |
| 16 | +) |
| 17 | + |
| 18 | +const routerFilterPointerDynamicMetadataKey = "router_filter_pointer" |
| 19 | + |
| 20 | +type ( |
| 21 | + // routerFilterConfig implements [sdk.HTTPFilterConfig]. |
| 22 | + // |
| 23 | + // This is mostly for debugging purposes, it does not do anything except |
| 24 | + // setting a response header with the version of the dynamic module. |
| 25 | + routerFilterConfig struct { |
| 26 | + fcr *filterConfigReceiverImpl |
| 27 | + models openai.ModelList |
| 28 | + } |
| 29 | + // routerFilter implements [sdk.HTTPFilter]. |
| 30 | + routerFilter struct { |
| 31 | + fc *routerFilterConfig |
| 32 | + endpoint endpoint |
| 33 | + originalRequestBody interface{} |
| 34 | + originalRequestBodyRaw []byte |
| 35 | + } |
| 36 | + |
| 37 | + requestBodyParserFn func(body []byte) (parsed interface{}, modelName string, err error) |
| 38 | +) |
| 39 | + |
| 40 | +func newRouterFilterConfig(fcr *filterConfigReceiverImpl) *routerFilterConfig { |
| 41 | + config := fcr.fc |
| 42 | + models := openai.ModelList{ |
| 43 | + Object: "list", |
| 44 | + Data: make([]openai.Model, 0, len(config.DeclaredModels)), |
| 45 | + } |
| 46 | + for _, m := range config.DeclaredModels { |
| 47 | + models.Data = append(models.Data, openai.Model{ |
| 48 | + ID: m.Name, |
| 49 | + Object: "model", |
| 50 | + OwnedBy: m.OwnedBy, |
| 51 | + Created: openai.JSONUNIXTime(m.CreatedAt), |
| 52 | + }) |
| 53 | + } |
| 54 | + return &routerFilterConfig{fcr: fcr, models: models} |
| 55 | +} |
| 56 | + |
| 57 | +// NewFilter implements [sdk.HTTPFilterConfig]. |
| 58 | +func (f *routerFilterConfig) NewFilter() sdk.HTTPFilter { |
| 59 | + return &routerFilter{fc: f} |
| 60 | +} |
| 61 | + |
| 62 | +// RequestHeaders implements [sdk.HTTPFilter]. |
| 63 | +func (f *routerFilter) RequestHeaders(e sdk.EnvoyHTTPFilter, _ bool) sdk.RequestHeadersStatus { |
| 64 | + p, _ := e.GetRequestHeader(":path") // The :path pseudo header is always present. |
| 65 | + // Strip query parameters for processor lookup. |
| 66 | + if queryIndex := strings.Index(p, "?"); queryIndex != -1 { |
| 67 | + p = p[:queryIndex] |
| 68 | + } |
| 69 | + // TODO: prefix config. |
| 70 | + switch p { |
| 71 | + case "/v1/chat/completions": |
| 72 | + f.endpoint = chatCompletionsEndpoint |
| 73 | + return sdk.RequestHeadersStatusContinue |
| 74 | + case "/v1/completions": |
| 75 | + f.endpoint = completionsEndpoint |
| 76 | + return sdk.RequestHeadersStatusContinue |
| 77 | + case "/v1/embeddings": |
| 78 | + f.endpoint = embeddingsEndpoint |
| 79 | + return sdk.RequestHeadersStatusContinue |
| 80 | + case "/v1/images/generations": |
| 81 | + f.endpoint = imagesGenerationsEndpoint |
| 82 | + return sdk.RequestHeadersStatusContinue |
| 83 | + case "/cohere/v2/rerank": |
| 84 | + f.endpoint = rerankEndpoint |
| 85 | + return sdk.RequestHeadersStatusContinue |
| 86 | + case "/anthropic/v1/messages": |
| 87 | + f.endpoint = messagesEndpoint |
| 88 | + return sdk.RequestHeadersStatusContinue |
| 89 | + case "/v1/models": |
| 90 | + return f.handleModelsEndpoint(e) |
| 91 | + default: |
| 92 | + e.SendLocalReply(404, nil, []byte(fmt.Sprintf("unsupported path: %s", p))) |
| 93 | + return sdk.RequestHeadersStatusStopIteration |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +// RequestBody implements [sdk.HTTPFilter]. |
| 98 | +func (f *routerFilter) RequestBody(e sdk.EnvoyHTTPFilter, endOfStream bool) sdk.RequestBodyStatus { |
| 99 | + if !endOfStream { |
| 100 | + return sdk.RequestBodyStatusStopIterationAndBuffer |
| 101 | + } |
| 102 | + b, ok := e.GetRequestBody() |
| 103 | + if !ok { |
| 104 | + e.SendLocalReply(400, nil, []byte("failed to read request body")) |
| 105 | + return sdk.RequestBodyStatusStopIterationAndBuffer |
| 106 | + } |
| 107 | + raw, err := io.ReadAll(b) |
| 108 | + if err != nil { |
| 109 | + e.SendLocalReply(400, nil, []byte("failed to read request body: "+err.Error())) |
| 110 | + return sdk.RequestBodyStatusStopIterationAndBuffer |
| 111 | + } |
| 112 | + f.originalRequestBodyRaw = raw |
| 113 | + var parserFn requestBodyParserFn |
| 114 | + switch f.endpoint { |
| 115 | + case chatCompletionsEndpoint: |
| 116 | + parserFn = chatCompletionsBodyParser |
| 117 | + case completionsEndpoint: |
| 118 | + parserFn = completionsBodyParser |
| 119 | + case embeddingsEndpoint: |
| 120 | + parserFn = embeddingsBodyParser |
| 121 | + case imagesGenerationsEndpoint: |
| 122 | + parserFn = imagesGenerationsBodyParser |
| 123 | + case rerankEndpoint: |
| 124 | + parserFn = rerankBodyParser |
| 125 | + case messagesEndpoint: |
| 126 | + parserFn = messagesBodyParser |
| 127 | + default: |
| 128 | + e.SendLocalReply(500, nil, []byte("BUG: unsupported endpoint at body parsing: "+fmt.Sprintf("%d", f.endpoint))) |
| 129 | + } |
| 130 | + parsed, modelName, err := parserFn(raw) |
| 131 | + if err != nil { |
| 132 | + e.SendLocalReply(400, nil, []byte("failed to parse request body: "+err.Error())) |
| 133 | + return sdk.RequestBodyStatusStopIterationAndBuffer |
| 134 | + } |
| 135 | + f.originalRequestBody = parsed |
| 136 | + if !e.SetRequestHeader(internalapi.ModelNameHeaderKeyDefault, []byte(modelName)) { |
| 137 | + e.SendLocalReply(500, nil, []byte("failed to set model name header")) |
| 138 | + return sdk.RequestBodyStatusStopIterationAndBuffer |
| 139 | + } |
| 140 | + // Store the pointer to the filter in dynamic metadata for later retrieval in the upstream filter. |
| 141 | + e.SetDynamicMetadataString(internalapi.AIGatewayFilterMetadataNamespace, routerFilterPointerDynamicMetadataKey, |
| 142 | + fmt.Sprintf("%d", uintptr(unsafe.Pointer(f)))) |
| 143 | + return sdk.RequestBodyStatusContinue |
| 144 | +} |
| 145 | + |
| 146 | +// ResponseHeaders implements [sdk.HTTPFilter]. |
| 147 | +func (f *routerFilter) ResponseHeaders(sdk.EnvoyHTTPFilter, bool) sdk.ResponseHeadersStatus { |
| 148 | + return sdk.ResponseHeadersStatusContinue |
| 149 | +} |
| 150 | + |
| 151 | +// ResponseBody implements [sdk.HTTPFilter]. |
| 152 | +func (f *routerFilter) ResponseBody(sdk.EnvoyHTTPFilter, bool) sdk.ResponseBodyStatus { |
| 153 | + return sdk.ResponseBodyStatusContinue |
| 154 | +} |
| 155 | + |
| 156 | +// handleModelsEndpoint handles the /v1/models endpoint by returning the list of declared models in the filter configuration. |
| 157 | +// |
| 158 | +// This is called on request headers phase. |
| 159 | +func (f *routerFilter) handleModelsEndpoint(e sdk.EnvoyHTTPFilter) sdk.RequestHeadersStatus { |
| 160 | + body, _ := json.Marshal(f.fc.models) |
| 161 | + e.SendLocalReply(200, [][2]string{ |
| 162 | + {"content-type", "application/json"}, |
| 163 | + }, body) |
| 164 | + return sdk.RequestHeadersStatusStopIteration |
| 165 | +} |
| 166 | + |
| 167 | +func chatCompletionsBodyParser(body []byte) (interface{}, string, error) { |
| 168 | + var req openai.ChatCompletionRequest |
| 169 | + if err := json.Unmarshal(body, &req); err != nil { |
| 170 | + return nil, "", fmt.Errorf("failed to unmarshal body: %w", err) |
| 171 | + } |
| 172 | + return req, req.Model, nil |
| 173 | +} |
| 174 | + |
| 175 | +func completionsBodyParser(body []byte) (interface{}, string, error) { |
| 176 | + var req openai.CompletionRequest |
| 177 | + if err := json.Unmarshal(body, &req); err != nil { |
| 178 | + return nil, "", fmt.Errorf("failed to unmarshal body: %w", err) |
| 179 | + } |
| 180 | + return req, req.Model, nil |
| 181 | +} |
| 182 | + |
| 183 | +func embeddingsBodyParser(body []byte) (interface{}, string, error) { |
| 184 | + var req openai.EmbeddingRequest |
| 185 | + if err := json.Unmarshal(body, &req); err != nil { |
| 186 | + return nil, "", fmt.Errorf("failed to unmarshal body: %w", err) |
| 187 | + } |
| 188 | + return req, req.Model, nil |
| 189 | +} |
| 190 | + |
| 191 | +func imagesGenerationsBodyParser(body []byte) (interface{}, string, error) { |
| 192 | + var req openaisdk.ImageGenerateParams |
| 193 | + if err := json.Unmarshal(body, &req); err != nil { |
| 194 | + return nil, "", fmt.Errorf("failed to unmarshal body: %w", err) |
| 195 | + } |
| 196 | + return req, req.Model, nil |
| 197 | +} |
| 198 | + |
| 199 | +func rerankBodyParser(body []byte) (interface{}, string, error) { |
| 200 | + var req cohereschema.RerankV2Request |
| 201 | + if err := json.Unmarshal(body, &req); err != nil { |
| 202 | + return nil, "", fmt.Errorf("failed to unmarshal body: %w", err) |
| 203 | + } |
| 204 | + return req, req.Model, nil |
| 205 | +} |
| 206 | + |
| 207 | +func messagesBodyParser(body []byte) (interface{}, string, error) { |
| 208 | + var anthropicReq anthropic.MessagesRequest |
| 209 | + if err := json.Unmarshal(body, &anthropicReq); err != nil { |
| 210 | + return nil, "", fmt.Errorf("failed to unmarshal body: %w", err) |
| 211 | + } |
| 212 | + return anthropicReq, anthropicReq.GetModel(), nil |
| 213 | +} |
0 commit comments