@langwatch/server 3.1.0-beta.7 → 3.1.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/package.json +1 -6
  2. package/packages/server/dist/cli.cjs +23 -17
  3. package/cmd/service/main.go +0 -68
  4. package/go.mod +0 -117
  5. package/go.sum +0 -299
  6. package/pkg/breaker/breaker.go +0 -157
  7. package/pkg/breaker/breaker_test.go +0 -131
  8. package/pkg/clog/LICENSE +0 -26
  9. package/pkg/clog/clog.go +0 -90
  10. package/pkg/clog/clog_test.go +0 -56
  11. package/pkg/clog/panic.go +0 -39
  12. package/pkg/config/LICENSE +0 -26
  13. package/pkg/config/config.go +0 -86
  14. package/pkg/config/config_test.go +0 -70
  15. package/pkg/config/otel.go +0 -50
  16. package/pkg/config/server.go +0 -61
  17. package/pkg/config/validate.go +0 -80
  18. package/pkg/config/validate_test.go +0 -74
  19. package/pkg/contexts/contexts_test.go +0 -34
  20. package/pkg/contexts/request_id.go +0 -1
  21. package/pkg/contexts/service_info.go +0 -33
  22. package/pkg/errfuncs/errfuncs.go +0 -9
  23. package/pkg/errfuncs/errfuncs_test.go +0 -28
  24. package/pkg/forkedcontext/forkedcontext.go +0 -57
  25. package/pkg/health/health.go +0 -123
  26. package/pkg/health/health_test.go +0 -84
  27. package/pkg/herr/LICENSE +0 -26
  28. package/pkg/herr/code.go +0 -14
  29. package/pkg/herr/herr.go +0 -112
  30. package/pkg/herr/herr_test.go +0 -78
  31. package/pkg/herr/http.go +0 -133
  32. package/pkg/herr/http_test.go +0 -103
  33. package/pkg/herr/validate.go +0 -72
  34. package/pkg/herr/validate_test.go +0 -75
  35. package/pkg/httpmiddleware/bearer.go +0 -47
  36. package/pkg/httpmiddleware/httputil_test.go +0 -167
  37. package/pkg/httpmiddleware/inflight.go +0 -23
  38. package/pkg/httpmiddleware/maxbody.go +0 -30
  39. package/pkg/httpmiddleware/recover.go +0 -38
  40. package/pkg/httpmiddleware/requestid.go +0 -40
  41. package/pkg/httpmiddleware/telemetry.go +0 -96
  42. package/pkg/httpmiddleware/version.go +0 -16
  43. package/pkg/jwtverify/verifier.go +0 -72
  44. package/pkg/jwtverify/verifier_test.go +0 -134
  45. package/pkg/ksuid/LICENSE +0 -26
  46. package/pkg/ksuid/ksuid.go +0 -157
  47. package/pkg/ksuid/ksuid_test.go +0 -107
  48. package/pkg/ksuid/resources.go +0 -13
  49. package/pkg/lifecycle/group.go +0 -175
  50. package/pkg/lifecycle/group_test.go +0 -236
  51. package/pkg/lifecycle/service.go +0 -112
  52. package/pkg/netprobe/netprobe.go +0 -89
  53. package/pkg/netprobe/netprobe_test.go +0 -55
  54. package/pkg/otelsetup/otelsetup.go +0 -226
  55. package/pkg/otelsetup/otelsetup_test.go +0 -130
  56. package/pkg/ptr/LICENSE +0 -26
  57. package/pkg/ptr/ptr.go +0 -34
  58. package/pkg/ptr/ptr_test.go +0 -66
  59. package/pkg/retry/bench_test.go +0 -67
  60. package/pkg/retry/retry.go +0 -188
  61. package/pkg/retry/retry_test.go +0 -222
  62. package/pkg/slicefuncs/LICENSE +0 -26
  63. package/pkg/slicefuncs/slicefuncs.go +0 -10
  64. package/pkg/slicefuncs/slicefuncs_test.go +0 -29
  65. package/pkg/stacktrace/LICENSE +0 -26
  66. package/pkg/stacktrace/frames.go +0 -77
  67. package/pkg/stacktrace/frames_test.go +0 -73
  68. package/services/aigateway/BENCHMARKS.md +0 -110
  69. package/services/aigateway/README.md +0 -156
  70. package/services/aigateway/adapters/authresolver/bench_test.go +0 -13
  71. package/services/aigateway/adapters/authresolver/redis.go +0 -61
  72. package/services/aigateway/adapters/authresolver/service.go +0 -442
  73. package/services/aigateway/adapters/authresolver/service_test.go +0 -435
  74. package/services/aigateway/adapters/budget/bench_test.go +0 -50
  75. package/services/aigateway/adapters/budget/budget.go +0 -59
  76. package/services/aigateway/adapters/cacherules/evaluator.go +0 -134
  77. package/services/aigateway/adapters/cacherules/evaluator_test.go +0 -207
  78. package/services/aigateway/adapters/controlplane/bench_test.go +0 -40
  79. package/services/aigateway/adapters/controlplane/client.go +0 -213
  80. package/services/aigateway/adapters/controlplane/client_test.go +0 -73
  81. package/services/aigateway/adapters/controlplane/config_wire.go +0 -310
  82. package/services/aigateway/adapters/controlplane/guardrails.go +0 -88
  83. package/services/aigateway/adapters/controlplane/signer.go +0 -95
  84. package/services/aigateway/adapters/controlplane/signer_test.go +0 -64
  85. package/services/aigateway/adapters/customertracebridge/context.go +0 -48
  86. package/services/aigateway/adapters/customertracebridge/context_test.go +0 -24
  87. package/services/aigateway/adapters/customertracebridge/emitter.go +0 -329
  88. package/services/aigateway/adapters/customertracebridge/emitter_test.go +0 -93
  89. package/services/aigateway/adapters/customertracebridge/registry.go +0 -82
  90. package/services/aigateway/adapters/customertracebridge/transport.go +0 -122
  91. package/services/aigateway/adapters/gatewaytracer/attrs.go +0 -28
  92. package/services/aigateway/adapters/gatewaytracer/attrs_genai.go +0 -24
  93. package/services/aigateway/adapters/gatewaytracer/headers.go +0 -8
  94. package/services/aigateway/adapters/gatewaytracer/tracer.go +0 -101
  95. package/services/aigateway/adapters/httpapi/bench_test.go +0 -83
  96. package/services/aigateway/adapters/httpapi/middleware.go +0 -123
  97. package/services/aigateway/adapters/httpapi/router.go +0 -635
  98. package/services/aigateway/adapters/httpapi/router_test.go +0 -633
  99. package/services/aigateway/adapters/modelresolver/resolver.go +0 -107
  100. package/services/aigateway/adapters/modelresolver/resolver_test.go +0 -140
  101. package/services/aigateway/adapters/policy/matcher.go +0 -250
  102. package/services/aigateway/adapters/policy/matcher_test.go +0 -124
  103. package/services/aigateway/adapters/providers/bifrost.go +0 -798
  104. package/services/aigateway/adapters/providers/bifrost_parser.go +0 -201
  105. package/services/aigateway/adapters/providers/bifrost_test.go +0 -181
  106. package/services/aigateway/adapters/ratelimit/limiter.go +0 -122
  107. package/services/aigateway/adapters/ratelimit/limiter_test.go +0 -81
  108. package/services/aigateway/app/app.go +0 -104
  109. package/services/aigateway/app/dispatch.go +0 -89
  110. package/services/aigateway/app/dispatch_test.go +0 -475
  111. package/services/aigateway/app/handlers.go +0 -79
  112. package/services/aigateway/app/peek_bench_test.go +0 -21
  113. package/services/aigateway/app/pipeline/bench_test.go +0 -34
  114. package/services/aigateway/app/pipeline/budget.go +0 -55
  115. package/services/aigateway/app/pipeline/cache.go +0 -34
  116. package/services/aigateway/app/pipeline/cachecontrol.go +0 -86
  117. package/services/aigateway/app/pipeline/cachecontrol_test.go +0 -110
  118. package/services/aigateway/app/pipeline/guardrail.go +0 -121
  119. package/services/aigateway/app/pipeline/pipeline.go +0 -159
  120. package/services/aigateway/app/pipeline/policy.go +0 -23
  121. package/services/aigateway/app/pipeline/ratelimit.go +0 -21
  122. package/services/aigateway/app/pipeline/rawframing_test.go +0 -67
  123. package/services/aigateway/app/pipeline/resolve.go +0 -44
  124. package/services/aigateway/app/pipeline/trace.go +0 -129
  125. package/services/aigateway/app/ports.go +0 -61
  126. package/services/aigateway/cmd/root.go +0 -42
  127. package/services/aigateway/config.go +0 -86
  128. package/services/aigateway/deps.go +0 -177
  129. package/services/aigateway/domain/bundle.go +0 -203
  130. package/services/aigateway/domain/errors.go +0 -23
  131. package/services/aigateway/domain/model.go +0 -24
  132. package/services/aigateway/domain/provider.go +0 -38
  133. package/services/aigateway/domain/request.go +0 -65
  134. package/services/aigateway/domain/response.go +0 -56
  135. package/services/aigateway/domain/verdict.go +0 -55
  136. package/services/aigateway/serve.go +0 -45
  137. package/services/aigateway/tests/matrix/README.md +0 -71
  138. package/services/aigateway/tests/matrix/anthropic_test.go +0 -61
  139. package/services/aigateway/tests/matrix/azure_test.go +0 -52
  140. package/services/aigateway/tests/matrix/bedrock_test.go +0 -69
  141. package/services/aigateway/tests/matrix/gemini_test.go +0 -117
  142. package/services/aigateway/tests/matrix/matrix_test.go +0 -601
  143. package/services/aigateway/tests/matrix/openai_test.go +0 -66
  144. package/services/aigateway/tests/matrix/vertex_test.go +0 -160
@@ -1,201 +0,0 @@
1
- package providers
2
-
3
- import (
4
- "context"
5
- "encoding/json"
6
- "fmt"
7
-
8
- bfschemas "github.com/maximhq/bifrost/core/schemas"
9
-
10
- "github.com/bytedance/sonic"
11
- "github.com/tidwall/gjson"
12
- "github.com/tidwall/sjson"
13
-
14
- "github.com/langwatch/langwatch/services/aigateway/domain"
15
- )
16
-
17
- // buildChatRequest constructs a BifrostChatRequest appropriate for the
18
- // inbound request type. RequestTypeChat expects an OpenAI-shape body and
19
- // goes through the parser (Bifrost then translates per-provider).
20
- // RequestTypeMessages expects an Anthropic-shape body and is forwarded
21
- // raw (Bifrost's own adapter decodes it natively).
22
- //
23
- // Returned context is enriched with the raw-forward flag when required;
24
- // callers should use it to derive the BifrostContext.
25
- func buildChatRequest(
26
- ctx context.Context,
27
- req *domain.Request,
28
- provider bfschemas.ModelProvider,
29
- model string,
30
- ) (*bfschemas.BifrostChatRequest, context.Context, error) {
31
- if req.Type == domain.RequestTypeMessages {
32
- return &bfschemas.BifrostChatRequest{
33
- Provider: provider,
34
- Model: model,
35
- RawRequestBody: req.Body,
36
- Input: []bfschemas.ChatMessage{},
37
- },
38
- rawForwardCtx(ctx),
39
- nil
40
- }
41
-
42
- // OpenAI-family providers accept the OpenAI wire format natively, so
43
- // there is nothing to translate. Running the body through
44
- // parse+re-marshal still subtly changes bytes (JSON key ordering,
45
- // whitespace, number formatting) which breaks OpenAI's prefix-hash
46
- // auto-cache between two otherwise-identical calls. Raw-forward
47
- // preserves byte-for-byte identity and keeps cache hits working.
48
- // Translation earns its keep only when the target wire format
49
- // differs from the inbound (Anthropic / Gemini / Bedrock / Vertex).
50
- if isOpenAICompatibleProvider(provider) {
51
- return &bfschemas.BifrostChatRequest{
52
- Provider: provider,
53
- Model: model,
54
- RawRequestBody: req.Body,
55
- Input: []bfschemas.ChatMessage{},
56
- },
57
- rawForwardCtx(ctx),
58
- nil
59
- }
60
-
61
- messages, params, err := parseOpenAIChatRequest(req.Body)
62
- if err != nil {
63
- return nil, ctx, err
64
- }
65
- return &bfschemas.BifrostChatRequest{
66
- Provider: provider,
67
- Model: model,
68
- Input: messages,
69
- Params: params,
70
- }, ctx, nil
71
- }
72
-
73
- // isOpenAICompatibleProvider reports whether the destination provider
74
- // natively speaks OpenAI chat-completions wire format. When true, the
75
- // gateway raw-forwards the inbound body rather than parse+re-marshal,
76
- // preserving byte-for-byte identity so OpenAI prompt-prefix auto-cache
77
- // continues to hit between repeated calls.
78
- func isOpenAICompatibleProvider(p bfschemas.ModelProvider) bool {
79
- switch p {
80
- case bfschemas.OpenAI, bfschemas.Azure:
81
- return true
82
- default:
83
- return false
84
- }
85
- }
86
-
87
- // parseOpenAIChatRequest decodes an OpenAI-shape /v1/chat/completions body
88
- // into Bifrost's normalized request structures. Bifrost's own ChatMessage +
89
- // ChatParameters types carry OpenAI-compatible JSON tags, so each provider
90
- // family translates from this neutral shape downstream (OpenAI → pass-through,
91
- // Anthropic → Messages API, Gemini → generateContent, etc.).
92
- //
93
- // The input []ChatMessage is read off the `messages` key; everything else
94
- // (temperature, tools, response_format, stream_options, seed, logprobs,
95
- // max_completion_tokens, ...) unmarshals onto ChatParameters via its json
96
- // tags. `stream` is not part of ChatParameters — the caller decides the
97
- // streaming dispatch path, so we simply discard it here.
98
- //
99
- // Provider-specific extension fields (e.g. Gemini's `cached_content` for
100
- // referencing a pre-created CachedContent resource) live in
101
- // ChatParameters.ExtraParams. The Bifrost gemini translator at
102
- // providers/gemini/chat.go:50-54 reads the "cached_content" key off
103
- // ExtraParams and lifts it onto geminiReq.CachedContent — but ExtraParams
104
- // is `json:"-"`, so a stock json.Unmarshal can't populate it. We lift
105
- // supported extension keys explicitly here so callers can drive
106
- // gemini/vertex prompt caching via the standard chat-completions
107
- // endpoint without needing a native gemini route.
108
- func parseOpenAIChatRequest(body []byte) ([]bfschemas.ChatMessage, *bfschemas.ChatParameters, error) {
109
- if len(body) == 0 {
110
- return nil, nil, nil
111
- }
112
-
113
- var messagesWrap struct {
114
- Messages []bfschemas.ChatMessage `json:"messages"`
115
- }
116
- if err := sonic.Unmarshal(body, &messagesWrap); err != nil {
117
- return nil, nil, fmt.Errorf("parse messages: %w", err)
118
- }
119
-
120
- var params bfschemas.ChatParameters
121
- if err := sonic.Unmarshal(body, &params); err != nil {
122
- return nil, nil, fmt.Errorf("parse params: %w", err)
123
- }
124
-
125
- liftExtensionParams(body, &params)
126
-
127
- return messagesWrap.Messages, &params, nil
128
- }
129
-
130
- // chatExtensionKeys enumerates the provider-extension fields the gateway
131
- // recognizes on the inbound /v1/chat/completions body and forwards via
132
- // ChatParameters.ExtraParams. Bifrost's per-provider translators read these
133
- // off ExtraParams and lift them onto the provider-native request shape.
134
- //
135
- // Currently:
136
- // - cached_content: Gemini/Vertex CachedContent reference
137
- // (see providers/gemini/chat.go:50-54). Required to read prompt cache
138
- // hits on accounts where implicit caching isn't enabled.
139
- // - safety_settings: Gemini SafetySettings array
140
- // (providers/gemini/chat.go:43-48).
141
- // - labels: Gemini per-request labels (providers/gemini/chat.go:57-62).
142
- //
143
- // Add new keys here only when a Bifrost translator reads them from
144
- // ExtraParams — silently lifting an unrecognized field leaks vendor
145
- // jargon into providers that won't recognize it.
146
- var chatExtensionKeys = []string{
147
- "cached_content",
148
- "safety_settings",
149
- "labels",
150
- }
151
-
152
- // ensureStreamIncludeUsage injects stream_options.include_usage=true on an
153
- // OpenAI-shape /v1/chat/completions body when the caller asked for streaming
154
- // but didn't opt in to the final usage SSE chunk. Without include_usage,
155
- // OpenAI streams finish with zero prompt/completion tokens — cost-enrichment
156
- // then has nothing to fold and the trace shows tokens=0 + success_no_usage.
157
- //
158
- // The function is a no-op when:
159
- // - the body has no "stream":true (non-stream dispatch),
160
- // - the body already carries stream_options.include_usage (caller decided).
161
- //
162
- // Only call on raw-forward paths for OpenAI / Azure. Anthropic / Gemini /
163
- // Vertex / Bedrock emit usage natively in their stream deltas and this flag
164
- // is meaningless on their wire formats.
165
- func ensureStreamIncludeUsage(body []byte) []byte {
166
- if len(body) == 0 {
167
- return body
168
- }
169
- if !gjson.GetBytes(body, "stream").Bool() {
170
- return body
171
- }
172
- if gjson.GetBytes(body, "stream_options.include_usage").Exists() {
173
- return body
174
- }
175
- out, err := sjson.SetBytes(body, "stream_options.include_usage", true)
176
- if err != nil {
177
- return body
178
- }
179
- return out
180
- }
181
-
182
- func liftExtensionParams(body []byte, params *bfschemas.ChatParameters) {
183
- var raw map[string]json.RawMessage
184
- if err := sonic.Unmarshal(body, &raw); err != nil {
185
- return
186
- }
187
- for _, key := range chatExtensionKeys {
188
- v, ok := raw[key]
189
- if !ok {
190
- continue
191
- }
192
- var decoded interface{}
193
- if err := sonic.Unmarshal(v, &decoded); err != nil {
194
- continue
195
- }
196
- if params.ExtraParams == nil {
197
- params.ExtraParams = make(map[string]interface{})
198
- }
199
- params.ExtraParams[key] = decoded
200
- }
201
- }
@@ -1,181 +0,0 @@
1
- package providers
2
-
3
- import (
4
- "bytes"
5
- "encoding/json"
6
- "testing"
7
-
8
- bfschemas "github.com/maximhq/bifrost/core/schemas"
9
- "github.com/tidwall/gjson"
10
- )
11
-
12
- // Regression: Bifrost's providers/utils EnrichError stores raw provider
13
- // response bytes as json.RawMessage. json.RawMessage is `type RawMessage []byte`
14
- // but Go's type switch does NOT match []byte for RawMessage — they are
15
- // distinct named types. An explicit case is required, otherwise the raw
16
- // bytes fall through to sonic.Marshal which double-encodes or fails,
17
- // and codex / opencode 504s mask the upstream OpenAI error shape.
18
- func TestExtractRawResponseBytes_RawMessage(t *testing.T) {
19
- jsonBytes := []byte(`{"error":{"message":"oops","code":"rate_limit"}}`)
20
- raw := json.RawMessage(jsonBytes)
21
-
22
- got, ok := extractRawResponseBytes(raw)
23
- if !ok {
24
- t.Fatalf("extractRawResponseBytes returned ok=false for non-empty json.RawMessage")
25
- }
26
- if !bytes.Equal(got, jsonBytes) {
27
- t.Fatalf("byte mismatch: got %q, want %q", got, jsonBytes)
28
- }
29
- }
30
-
31
- func TestExtractRawResponseBytes_EmptyRawMessage(t *testing.T) {
32
- raw := json.RawMessage(nil)
33
- if _, ok := extractRawResponseBytes(raw); ok {
34
- t.Fatalf("empty json.RawMessage should return ok=false")
35
- }
36
- }
37
-
38
- func TestRawResponseFromBifrostError_UnmarshalFailure(t *testing.T) {
39
- status := 502
40
- berr := &bfschemas.BifrostError{
41
- StatusCode: &status,
42
- Error: &bfschemas.ErrorField{
43
- Message: "failed to unmarshal response from provider API",
44
- },
45
- ExtraFields: bfschemas.BifrostErrorExtraFields{
46
- // Shape populated by providerUtils.EnrichError on raw-forward paths
47
- // when BifrostContextKeySendBackRawResponse=true.
48
- RawResponse: json.RawMessage(`{"id":"resp_abc","object":"response"}`),
49
- },
50
- }
51
-
52
- body, gotStatus, ok := rawResponseFromBifrostError(berr)
53
- if !ok {
54
- t.Fatalf("rawResponseFromBifrostError returned ok=false despite populated RawResponse")
55
- }
56
- if gotStatus != status {
57
- t.Fatalf("status mismatch: got %d, want %d", gotStatus, status)
58
- }
59
- if string(body) != `{"id":"resp_abc","object":"response"}` {
60
- t.Fatalf("body mismatch: got %q", body)
61
- }
62
- }
63
-
64
- // TestEnsureStreamIncludeUsage covers the stream_options.include_usage
65
- // auto-injection path (spec: streaming.feature → "Streaming usage capture").
66
- // OpenAI streams only emit a final usage chunk when the request body
67
- // carries this flag, so without it the gateway sees tokens=0 and the
68
- // trace's cost-enrichment has nothing to fold.
69
- func TestEnsureStreamIncludeUsage(t *testing.T) {
70
- cases := []struct {
71
- name string
72
- in string
73
- wantInclude bool // true = body must have stream_options.include_usage=true
74
- wantChanged bool // true = body bytes must differ from input
75
- assertExtra func(t *testing.T, out []byte)
76
- }{
77
- {
78
- name: "stream true, no stream_options → injected",
79
- in: `{"model":"gpt-5-mini","stream":true,"messages":[{"role":"user","content":"hi"}]}`,
80
- wantInclude: true,
81
- wantChanged: true,
82
- },
83
- {
84
- name: "stream true, caller include_usage=true → unchanged",
85
- in: `{"model":"gpt-5-mini","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"hi"}]}`,
86
- wantInclude: true,
87
- wantChanged: false,
88
- },
89
- {
90
- name: "stream true, caller include_usage=false → left alone",
91
- in: `{"model":"gpt-5-mini","stream":true,"stream_options":{"include_usage":false},"messages":[{"role":"user","content":"hi"}]}`,
92
- wantInclude: false,
93
- wantChanged: false,
94
- assertExtra: func(t *testing.T, out []byte) {
95
- t.Helper()
96
- if gjson.GetBytes(out, "stream_options.include_usage").Bool() {
97
- t.Fatalf("caller opted OUT of usage; gateway must not overwrite")
98
- }
99
- },
100
- },
101
- {
102
- name: "stream false → not mutated",
103
- in: `{"model":"gpt-5-mini","stream":false,"messages":[{"role":"user","content":"hi"}]}`,
104
- wantInclude: false,
105
- wantChanged: false,
106
- assertExtra: func(t *testing.T, out []byte) {
107
- t.Helper()
108
- if gjson.GetBytes(out, "stream_options").Exists() {
109
- t.Fatalf("stream=false must not grow a stream_options field")
110
- }
111
- },
112
- },
113
- {
114
- name: "stream absent → not mutated",
115
- in: `{"model":"gpt-5-mini","messages":[{"role":"user","content":"hi"}]}`,
116
- wantInclude: false,
117
- wantChanged: false,
118
- assertExtra: func(t *testing.T, out []byte) {
119
- t.Helper()
120
- if gjson.GetBytes(out, "stream_options").Exists() {
121
- t.Fatalf("no stream flag must not grow a stream_options field")
122
- }
123
- },
124
- },
125
- {
126
- name: "empty body → returned as-is",
127
- in: ``,
128
- wantInclude: false,
129
- wantChanged: false,
130
- },
131
- }
132
-
133
- for _, tc := range cases {
134
- t.Run(tc.name, func(t *testing.T) {
135
- in := []byte(tc.in)
136
- out := ensureStreamIncludeUsage(in)
137
-
138
- if tc.wantChanged && bytes.Equal(out, in) {
139
- t.Fatalf("expected body to be rewritten, but bytes are identical:\n%s", string(out))
140
- }
141
- if !tc.wantChanged && !bytes.Equal(out, in) {
142
- t.Fatalf("expected body to be unchanged, got:\nin=%s\nout=%s", string(in), string(out))
143
- }
144
- if tc.wantInclude && !gjson.GetBytes(out, "stream_options.include_usage").Bool() {
145
- t.Fatalf("expected stream_options.include_usage=true on output:\n%s", string(out))
146
- }
147
- if tc.assertExtra != nil {
148
- tc.assertExtra(t, out)
149
- }
150
- })
151
- }
152
- }
153
-
154
- // TestEnsureStreamIncludeUsage_PreservesMessages guards the
155
- // "byte-equivalent except for the injected key" contract on the BDD spec.
156
- // The injection must NOT re-order messages, drop other keys, or change
157
- // number formatting on existing fields — those would invalidate OpenAI's
158
- // prompt-prefix auto-cache between two otherwise-identical calls.
159
- func TestEnsureStreamIncludeUsage_PreservesMessages(t *testing.T) {
160
- in := []byte(`{"model":"gpt-5-mini","stream":true,"temperature":0.7,"messages":[{"role":"system","content":"be concise"},{"role":"user","content":"hi"}],"max_completion_tokens":16}`)
161
- out := ensureStreamIncludeUsage(in)
162
-
163
- // Everything except the injected key should round-trip.
164
- for _, path := range []string{
165
- "model",
166
- "stream",
167
- "temperature",
168
- "messages",
169
- "max_completion_tokens",
170
- } {
171
- gotIn := gjson.GetBytes(in, path).Raw
172
- gotOut := gjson.GetBytes(out, path).Raw
173
- if gotIn != gotOut {
174
- t.Fatalf("field %q mutated: in=%q out=%q", path, gotIn, gotOut)
175
- }
176
- }
177
-
178
- if !gjson.GetBytes(out, "stream_options.include_usage").Bool() {
179
- t.Fatalf("expected stream_options.include_usage=true on output")
180
- }
181
- }
@@ -1,122 +0,0 @@
1
- // Package ratelimit enforces per-VK request-rate ceilings (RPM/RPD).
2
- // In-memory token bucket per VK with LRU eviction.
3
- package ratelimit
4
-
5
- import (
6
- "context"
7
- "fmt"
8
- "sync"
9
- "time"
10
-
11
- lru "github.com/hashicorp/golang-lru/v2"
12
- "golang.org/x/time/rate"
13
-
14
- "github.com/langwatch/langwatch/services/aigateway/domain"
15
- )
16
-
17
- // Limiter enforces per-VK rate limits. Implements app.RateLimiter.
18
- type Limiter struct {
19
- cache *lru.Cache[string, *buckets]
20
- mu sync.Mutex
21
- }
22
-
23
- // Options configures the limiter.
24
- type Options struct {
25
- MaxVKs int // LRU size (default 50000)
26
- }
27
-
28
- // New creates a Limiter.
29
- func New(opts Options) (*Limiter, error) {
30
- if opts.MaxVKs <= 0 {
31
- opts.MaxVKs = 50_000
32
- }
33
- c, err := lru.New[string, *buckets](opts.MaxVKs)
34
- if err != nil {
35
- return nil, err
36
- }
37
- return &Limiter{cache: c}, nil
38
- }
39
-
40
- // Allow returns nil if the request is permitted, or an error if the VK's
41
- // rate limit has been exceeded.
42
- func (l *Limiter) Allow(_ context.Context, vkID string, limits domain.RateLimits) error {
43
- if vkID == "" || (limits.RPM <= 0 && limits.RPD <= 0) {
44
- return nil
45
- }
46
-
47
- b := l.bucketsFor(vkID, limits)
48
- now := time.Now()
49
-
50
- // Reserve RPM
51
- var rpmRes *rate.Reservation
52
- if b.rpm != nil {
53
- r := b.rpm.ReserveN(now, 1)
54
- rpmRes = r
55
- if !r.OK() || r.DelayFrom(now) > 0 {
56
- r.CancelAt(now)
57
- return fmt.Errorf("rpm %d exceeded", limits.RPM)
58
- }
59
- }
60
-
61
- // Reserve RPD
62
- if b.rpd != nil {
63
- r := b.rpd.ReserveN(now, 1)
64
- if !r.OK() || r.DelayFrom(now) > 0 {
65
- r.CancelAt(now)
66
- if rpmRes != nil {
67
- rpmRes.CancelAt(now)
68
- }
69
- return fmt.Errorf("rpd %d exceeded", limits.RPD)
70
- }
71
- }
72
-
73
- return nil
74
- }
75
-
76
- // Invalidate drops cached buckets so next Allow() rebuilds with fresh ceilings.
77
- func (l *Limiter) Invalidate(vkID string) {
78
- l.cache.Remove(vkID)
79
- }
80
-
81
- func (l *Limiter) bucketsFor(vkID string, limits domain.RateLimits) *buckets {
82
- if existing, ok := l.cache.Get(vkID); ok {
83
- if sameCeilings(existing, limits) {
84
- return existing
85
- }
86
- }
87
- l.mu.Lock()
88
- defer l.mu.Unlock()
89
- if existing, ok := l.cache.Get(vkID); ok && sameCeilings(existing, limits) {
90
- return existing
91
- }
92
- b := &buckets{}
93
- if limits.RPM > 0 {
94
- b.rpm = rate.NewLimiter(rate.Limit(float64(limits.RPM)/60.0), limits.RPM)
95
- }
96
- if limits.RPD > 0 {
97
- b.rpd = rate.NewLimiter(rate.Limit(float64(limits.RPD)/86400.0), limits.RPD)
98
- }
99
- l.cache.Add(vkID, b)
100
- return b
101
- }
102
-
103
- type buckets struct {
104
- rpm *rate.Limiter
105
- rpd *rate.Limiter
106
- }
107
-
108
- func sameCeilings(b *buckets, limits domain.RateLimits) bool {
109
- if (limits.RPM > 0) != (b.rpm != nil) {
110
- return false
111
- }
112
- if b.rpm != nil && b.rpm.Burst() != limits.RPM {
113
- return false
114
- }
115
- if (limits.RPD > 0) != (b.rpd != nil) {
116
- return false
117
- }
118
- if b.rpd != nil && b.rpd.Burst() != limits.RPD {
119
- return false
120
- }
121
- return true
122
- }
@@ -1,81 +0,0 @@
1
- package ratelimit
2
-
3
- import (
4
- "context"
5
- "testing"
6
-
7
- "github.com/stretchr/testify/assert"
8
- "github.com/stretchr/testify/require"
9
-
10
- "github.com/langwatch/langwatch/services/aigateway/domain"
11
- )
12
-
13
- func newLimiter(t *testing.T) *Limiter {
14
- t.Helper()
15
- l, err := New(Options{MaxVKs: 100})
16
- require.NoError(t, err)
17
- return l
18
- }
19
-
20
- func TestAllow_NoLimits(t *testing.T) {
21
- l := newLimiter(t)
22
- err := l.Allow(context.Background(), "vk_1", domain.RateLimits{RPM: 0, RPD: 0})
23
- require.NoError(t, err)
24
- }
25
-
26
- func TestAllow_EmptyVKID(t *testing.T) {
27
- l := newLimiter(t)
28
- err := l.Allow(context.Background(), "", domain.RateLimits{RPM: 100, RPD: 1000})
29
- require.NoError(t, err)
30
- }
31
-
32
- func TestAllow_WithinRPM(t *testing.T) {
33
- l := newLimiter(t)
34
- err := l.Allow(context.Background(), "vk_1", domain.RateLimits{RPM: 100})
35
- require.NoError(t, err)
36
- }
37
-
38
- func TestAllow_RPMExceeded(t *testing.T) {
39
- l := newLimiter(t)
40
- limits := domain.RateLimits{RPM: 1}
41
-
42
- // First request allowed (burst = 1)
43
- err := l.Allow(context.Background(), "vk_1", limits)
44
- require.NoError(t, err)
45
-
46
- // Second request blocked immediately (no tokens left, rate is 1/60s)
47
- err = l.Allow(context.Background(), "vk_1", limits)
48
- assert.Error(t, err)
49
- }
50
-
51
- func TestAllow_RPDExceeded(t *testing.T) {
52
- l := newLimiter(t)
53
- limits := domain.RateLimits{RPD: 1}
54
-
55
- // First request allowed (burst = 1)
56
- err := l.Allow(context.Background(), "vk_1", limits)
57
- require.NoError(t, err)
58
-
59
- // Second request blocked immediately (burst exhausted, rate is 1/86400s)
60
- err = l.Allow(context.Background(), "vk_1", limits)
61
- assert.Error(t, err)
62
- }
63
-
64
- func TestInvalidate(t *testing.T) {
65
- l := newLimiter(t)
66
- limits := domain.RateLimits{RPM: 1}
67
-
68
- // Exhaust the bucket
69
- err := l.Allow(context.Background(), "vk_1", limits)
70
- require.NoError(t, err)
71
-
72
- err = l.Allow(context.Background(), "vk_1", limits)
73
- require.Error(t, err)
74
-
75
- // Invalidate rebuilds buckets
76
- l.Invalidate("vk_1")
77
-
78
- // Now the first request should be allowed again (fresh bucket)
79
- err = l.Allow(context.Background(), "vk_1", limits)
80
- require.NoError(t, err)
81
- }
@@ -1,104 +0,0 @@
1
- // Package app is the application layer for the AI Gateway service.
2
- // It orchestrates domain logic via consumer-defined interfaces (ports.go).
3
- package app
4
-
5
- import (
6
- "context"
7
-
8
- "go.uber.org/zap"
9
-
10
- "github.com/langwatch/langwatch/services/aigateway/app/pipeline"
11
- "github.com/langwatch/langwatch/services/aigateway/domain"
12
- )
13
-
14
- // App is the application orchestrator. All dependencies are interfaces
15
- // defined in ports.go, making the app trivially testable.
16
- type App struct {
17
- auth AuthResolver
18
- providers ProviderRouter
19
- budget BudgetChecker
20
- guardrails GuardrailEvaluator
21
- ratelimit RateLimiter
22
- policy PolicyMatcher
23
- cache CacheEvaluator
24
- models ModelResolver
25
- traces AITraceEmitter
26
- logger *zap.Logger
27
-
28
- pipeline pipeline.Pipeline
29
- }
30
-
31
- // Option configures the App.
32
- type Option func(*App)
33
-
34
- func WithAuth(a AuthResolver) Option { return func(app *App) { app.auth = a } }
35
- func WithProviders(p ProviderRouter) Option { return func(app *App) { app.providers = p } }
36
- func WithBudget(b BudgetChecker) Option { return func(app *App) { app.budget = b } }
37
- func WithGuardrails(g GuardrailEvaluator) Option { return func(app *App) { app.guardrails = g } }
38
- func WithRateLimiter(r RateLimiter) Option { return func(app *App) { app.ratelimit = r } }
39
- func WithPolicy(p PolicyMatcher) Option { return func(app *App) { app.policy = p } }
40
- func WithCache(c CacheEvaluator) Option { return func(app *App) { app.cache = c } }
41
- func WithModels(m ModelResolver) Option { return func(app *App) { app.models = m } }
42
- func WithTraces(t AITraceEmitter) Option { return func(app *App) { app.traces = t } }
43
- func WithLogger(l *zap.Logger) Option { return func(app *App) { app.logger = l } }
44
-
45
- // New creates an App with the given options and builds the dispatch pipeline.
46
- func New(opts ...Option) *App {
47
- app := &App{}
48
- for _, opt := range opts {
49
- opt(app)
50
- }
51
- if app.logger == nil {
52
- app.logger, _ = zap.NewProduction()
53
- }
54
-
55
- app.pipeline = pipeline.Build(
56
- app.buildInterceptors(),
57
- app.coreDispatch,
58
- app.coreDispatchStream,
59
- )
60
-
61
- return app
62
- }
63
-
64
- func (a *App) buildInterceptors() []pipeline.Interceptor {
65
- var chain []pipeline.Interceptor
66
- if a.ratelimit != nil {
67
- chain = append(chain, pipeline.RateLimit(a.ratelimit.Allow))
68
- }
69
- if a.policy != nil {
70
- chain = append(chain, pipeline.Policy(a.policy.Check))
71
- }
72
- if a.models != nil {
73
- chain = append(chain, pipeline.ModelResolve(a.models.Resolve))
74
- }
75
- if a.cache != nil {
76
- chain = append(chain, pipeline.Cache(a.cache.Evaluate))
77
- }
78
- if a.budget != nil {
79
- chain = append(chain, pipeline.Budget(a.budget.Precheck, a.logger))
80
- }
81
- if a.guardrails != nil {
82
- chain = append(chain, pipeline.Guardrail(
83
- a.guardrails.EvaluatePre,
84
- a.guardrails.EvaluatePost,
85
- a.guardrails.EvaluateChunk,
86
- a.logger,
87
- ))
88
- }
89
- if a.traces != nil {
90
- chain = append(chain, pipeline.Trace(a.traces.BeginSpan, a.traces.EndSpan))
91
- }
92
- return chain
93
- }
94
-
95
- // Auth returns the auth resolver (for use by transport middleware).
96
- func (a *App) Auth() AuthResolver { return a.auth }
97
-
98
- // ListModels returns models available to the bundle's virtual key.
99
- func (a *App) ListModels(ctx context.Context, bundle *domain.Bundle) ([]domain.Model, error) {
100
- if a.providers == nil {
101
- return nil, nil
102
- }
103
- return a.providers.ListModels(ctx, bundle.Credentials)
104
- }