-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathproxy.ts
More file actions
2984 lines (2798 loc) · 83.9 KB
/
proxy.ts
File metadata and controls
2984 lines (2798 loc) · 83.9 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
import { MessageParam } from "@anthropic-ai/sdk/resources";
import $RefParser from "@apidevtools/json-schema-ref-parser";
import { _urljoin, ExperimentLogPartialArgs, isArray } from "@braintrust/core";
import {
Message,
MessageRole,
responseFormatSchema,
} from "@braintrust/core/typespecs";
import { Meter, MeterProvider } from "@opentelemetry/api";
import {
APISecret,
AvailableModels,
AzureEntraSecretSchema,
DatabricksOAuthSecretSchema,
EndpointProviderToBaseURL,
MessageTypeToMessageType,
modelProviderHasReasoning,
ModelSpec,
translateParams,
VertexMetadataSchema,
} from "@schema";
import {
completionUsageSchema,
OpenAIChatCompletionChunk,
OpenAIReasoning,
} from "@types";
import cacheControlParse from "cache-control-parser";
import { differenceInSeconds } from "date-fns";
import {
createParser,
type EventSourceParser,
type ParsedEvent,
type ReconnectInterval,
} from "eventsource-parser";
import { importPKCS8, SignJWT } from "jose";
import { Buffer } from "node:buffer";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParams,
CompletionUsage,
CreateEmbeddingResponse,
ModerationCreateResponse,
} from "openai/resources";
import {
ChatCompletionContentPart,
ChatCompletionCreateParamsBase,
ChatCompletionMessage,
ChatCompletionMessageParam,
} from "openai/resources/chat/completions";
import {
Response as OpenAIResponse,
ResponseCreateParams,
ResponseInputContent,
ResponseInputItem,
ResponseOutputItem,
} from "openai/resources/responses/responses";
import {
getCurrentUnixTimestamp,
isTempCredential,
makeTempCredentials,
parseOpenAIStream,
verifyTempCredentials,
} from "utils";
import { z } from "zod";
import { NOOP_METER_PROVIDER, nowMs } from "./metrics";
import {
anthropicCompletionToOpenAICompletion,
anthropicEventToOpenAIEvent,
anthropicToolChoiceToOpenAIToolChoice,
DEFAULT_ANTHROPIC_MAX_TOKENS,
flattenAnthropicMessages,
openAIContentToAnthropicContent,
openAIToolCallsToAnthropicToolUse,
openAIToolMessageToAnthropicToolCall,
openAIToolsToAnthropicTools,
upgradeAnthropicContentMessage,
} from "./providers/anthropic";
import { getAzureEntraAccessToken } from "./providers/azure";
import {
fetchBedrockAnthropic,
fetchBedrockAnthropicMessages,
fetchConverse,
} from "./providers/bedrock";
import { getDatabricksOAuthAccessToken } from "./providers/databricks";
import {
googleCompletionToOpenAICompletion,
googleEventToOpenAIChatEvent,
openAIContentToGoogleContent,
openAIMessagesToGoogleMessages,
OpenAIParamsToGoogleParams,
} from "./providers/google";
import {
makeFakeOpenAIStreamTransformer,
normalizeOpenAIMessages,
} from "./providers/openai";
import {
flattenChunks,
flattenChunksArray,
getRandomInt,
isEmpty,
isObject,
ModelResponse,
parseAuthHeader,
parseNumericHeader,
ProxyBadRequestError,
writeToReadable,
} from "./util";
type CachedMetadata = {
cached_at: Date;
ttl: number;
};
type CachedData = {
headers: Record<string, string>;
// XXX make this a required field once deployed and cache data is cycled for 1 week (previous max cache TTL)
metadata?: CachedMetadata;
} & (
| {
// DEPRECATION_NOTICE: This can be removed in a couple weeks since writing (e.g. June 9 2024 onwards)
body: string;
}
| {
data: string;
}
);
const MAX_CACHE_TTL = 7 * 24 * 60 * 60; // 7 days
const DEFAULT_CACHE_TTL = 7 * 24 * 60 * 60; // 7 days
export const CACHE_HEADER = "x-bt-use-cache";
export const CACHE_TTL_HEADER = "x-bt-cache-ttl";
export const CREDS_CACHE_HEADER = "x-bt-use-creds-cache";
export const ORG_NAME_HEADER = "x-bt-org-name";
export const ENDPOINT_NAME_HEADER = "x-bt-endpoint-name";
export const FORMAT_HEADER = "x-bt-stream-fmt";
export const CACHED_HEADER = "x-bt-cached";
export const USED_ENDPOINT_HEADER = "x-bt-used-endpoint";
const CACHE_MODES = ["auto", "always", "never"] as const;
// The Anthropic SDK generates /v1/messages appended to the base URL, so we support both
const ANTHROPIC_MESSAGES = "/anthropic/messages";
const ANTHROPIC_V1_MESSAGES = "/anthropic/v1/messages";
// Options to control how the cache key is generated.
export interface CacheKeyOptions {
excludeAuthToken?: boolean;
excludeOrgName?: boolean;
}
export interface SpanLogger {
setName: (name: string) => void;
log: (args: ExperimentLogPartialArgs) => void;
end: () => void;
reportProgress: (progress: string) => void;
}
// This is an isomorphic implementation of proxyV1, which is used by both edge functions
// in CloudFlare and by the node proxy (locally and in lambda).
export async function proxyV1({
method,
url,
proxyHeaders,
body,
setHeader,
setStatusCode,
res,
getApiSecrets,
cacheGet,
cachePut,
digest,
meterProvider = NOOP_METER_PROVIDER,
cacheKeyOptions = {},
decompressFetch = false,
spanLogger,
}: {
method: "GET" | "POST";
url: string;
proxyHeaders: Record<string, string>;
body: string;
setHeader: (name: string, value: string) => void;
setStatusCode: (code: number) => void;
res: WritableStream<Uint8Array>;
getApiSecrets: (
useCache: boolean,
authToken: string,
model: string | null,
org_name?: string,
) => Promise<APISecret[]>;
cacheGet: (encryptionKey: string, key: string) => Promise<string | null>;
cachePut: (
encryptionKey: string,
key: string,
value: string,
ttl_seconds?: number,
) => Promise<void>;
digest: (message: string) => Promise<string>;
meterProvider?: MeterProvider;
cacheKeyOptions?: CacheKeyOptions;
decompressFetch?: boolean;
spanLogger?: SpanLogger;
}): Promise<void> {
const meter = meterProvider.getMeter("proxy-metrics");
const totalCalls = meter.createCounter("total_calls");
const cacheHits = meter.createCounter("results_cache_hits");
const cacheMisses = meter.createCounter("results_cache_misses");
const cacheSkips = meter.createCounter("results_cache_skips");
totalCalls.add(1);
proxyHeaders = Object.fromEntries(
Object.entries(proxyHeaders).map(([k, v]) => [k.toLowerCase(), v]),
);
const headers = Object.fromEntries(
Object.entries(proxyHeaders).filter(
([h, _]) =>
!(
h.startsWith("x-amzn") ||
h.startsWith("x-bt") ||
h.startsWith("sec-") ||
h === "content-length" ||
h === "origin" ||
h === "priority" ||
h === "referer" ||
h === "user-agent" ||
h === "cache-control"
),
),
);
const authToken = parseAuthHeader(proxyHeaders);
if (!authToken) {
throw new ProxyBadRequestError("Missing Authentication header");
}
// Caching is enabled by default, but let the user disable it
let useCacheMode = parseEnumHeader(
CACHE_HEADER,
CACHE_MODES,
proxyHeaders[CACHE_HEADER],
);
const cacheTTL = Math.min(
Math.max(
1,
parseNumericHeader(proxyHeaders, CACHE_TTL_HEADER) ?? DEFAULT_CACHE_TTL,
),
MAX_CACHE_TTL,
);
const cacheControl = cacheControlParse.parse(
proxyHeaders["cache-control"] || "",
);
const cacheMaxAge = cacheControl?.["max-age"];
const noCache = !!cacheControl?.["no-cache"] || cacheMaxAge === 0;
const noStore = !!cacheControl?.["no-store"];
const useCredentialsCacheMode = parseEnumHeader(
CACHE_HEADER,
CACHE_MODES,
proxyHeaders[CREDS_CACHE_HEADER],
);
const streamFormat = parseEnumHeader(
FORMAT_HEADER,
["openai", "vercel-ai"] as const,
proxyHeaders[FORMAT_HEADER],
);
let orgName: string | undefined = proxyHeaders[ORG_NAME_HEADER] ?? undefined;
const pieces = url
.split("/")
.filter((p) => p.trim() !== "")
.map((d) => decodeURIComponent(d));
if (pieces.length > 2 && pieces[0].toLowerCase() === "btorg") {
orgName = pieces[1];
url = "/" + pieces.slice(2).map(encodeURIComponent).join("/");
}
const isGoogleUrl = GOOGLE_URL_REGEX.test(url);
const cacheableEndpoint =
url === "/auto" ||
url === "/embeddings" ||
url === "/chat/completions" ||
url === "/responses" ||
url === "/completions" ||
url === "/moderations" ||
url === ANTHROPIC_MESSAGES ||
url === ANTHROPIC_V1_MESSAGES ||
isGoogleUrl;
let bodyData = null;
if (
url === "/auto" ||
url === "/chat/completions" ||
url === "/responses" ||
url === "/completions" ||
url === ANTHROPIC_MESSAGES ||
url === ANTHROPIC_V1_MESSAGES ||
isGoogleUrl
) {
try {
bodyData = JSON.parse(body);
} catch (e) {
console.warn("Failed to parse body. This doesn't really matter", e);
}
}
if (url === "/credentials") {
let readable: ReadableStream | null = null;
try {
const key = await makeTempCredentials({
authToken,
body: JSON.parse(body),
orgName,
cachePut,
});
setStatusCode(200);
readable = writeToReadable(JSON.stringify({ key }));
} catch (e) {
setStatusCode(400);
readable = writeToReadable(
e instanceof Error ? e.message : JSON.stringify(e),
);
} finally {
if (readable) {
readable.pipeTo(res).catch(console.error);
} else {
res.close().catch(console.error);
}
}
return;
}
// According to https://platform.openai.com/docs/api-reference, temperature is
// a parameter for audio completions and chat completions, and defaults to
// non-zero for completions, so unless it's set to zero, we can't cache it.
//
// OpenAI now allows you to set a seed, and if that is set, we should cache even
// if temperature is non-zero.
// TODO(sachin): Support caching for Google models.
const temperatureNonZero =
(url === "/chat/completions" ||
url === "/completions" ||
url === "/auto" ||
url === "/responses" ||
url === ANTHROPIC_MESSAGES ||
url === ANTHROPIC_V1_MESSAGES ||
isGoogleUrl) &&
bodyData &&
bodyData.temperature !== 0 &&
(bodyData.seed === undefined || bodyData.seed === null);
const readFromCache =
cacheableEndpoint &&
useCacheMode !== "never" &&
(useCacheMode === "always" || !temperatureNonZero) &&
!noCache;
const writeToCache =
cacheableEndpoint &&
useCacheMode !== "never" &&
(useCacheMode === "always" || !temperatureNonZero) &&
!noStore;
const endpointName = proxyHeaders[ENDPOINT_NAME_HEADER];
// Data key is computed from the input data and used for both the cache key and as an input to the encryption key.
const dataKey = await digest(
JSON.stringify({
url,
body,
authToken: cacheKeyOptions.excludeAuthToken || authToken,
orgName: cacheKeyOptions.excludeOrgName || orgName,
endpointName,
}),
);
// We must hash the data key again to get the cache key, so that the cache key is not reversible to the data key.
const cacheKey = `aiproxy/proxy/v2:${await digest(dataKey)}`;
// The data key is used as the encryption key, so unless you have the actual incoming data, you can't decrypt the cache.
const encryptionKey = await digest(`${dataKey}:${authToken}`);
let startTime = getCurrentUnixTimestamp();
let spanType: SpanType | undefined = undefined;
const isStreaming = !!bodyData?.stream;
let stream: ReadableStream<Uint8Array> | null = null;
if (readFromCache) {
const cached = await cacheGet(encryptionKey, cacheKey);
if (cached !== null) {
const cachedData: CachedData = JSON.parse(cached);
// XXX simplify once all cached data has a timestamp - assume existing data has age of 7 days
const responseMaxAge = cachedData.metadata?.ttl ?? DEFAULT_CACHE_TTL;
const age = cachedData.metadata
? differenceInSeconds(new Date(), cachedData.metadata.cached_at)
: DEFAULT_CACHE_TTL;
if (!cacheMaxAge || age <= cacheMaxAge) {
cacheHits.add(1);
for (const [name, value] of Object.entries(cachedData.headers)) {
setHeader(name, value);
}
setHeader(CACHED_HEADER, "HIT");
setHeader("cache-control", `max-age=${responseMaxAge}`);
setHeader("age", `${age}`);
spanType = guessSpanType(url, bodyData?.model);
if (spanLogger && spanType) {
spanLogger.setName(spanTypeToName(spanType));
logSpanInputs(bodyData, spanLogger, spanType);
spanLogger.log({
metrics: {
cached: 1,
},
});
}
stream = new ReadableStream<Uint8Array>({
start(controller) {
if ("body" in cachedData && cachedData.body) {
let splits = cachedData.body.split("\n");
for (let i = 0; i < splits.length; i++) {
controller.enqueue(
new TextEncoder().encode(
splits[i] + (i < splits.length - 1 ? "\n" : ""),
),
);
}
} else if ("data" in cachedData && cachedData.data) {
const data = Buffer.from(cachedData.data, "base64");
let start = 0;
for (let i = 0; i < data.length; i++) {
if (data[i] === 10) {
// 10 is ASCII/UTF-8 code for \n
controller.enqueue(
new Uint8Array(data.subarray(start, i + 1)),
);
start = i + 1;
}
}
if (start < data.length) {
controller.enqueue(new Uint8Array(data.subarray(start)));
}
}
controller.close();
},
});
} else {
cacheMisses.add(1);
}
} else {
cacheMisses.add(1);
}
} else {
cacheSkips.add(1);
}
let responseFailed = false;
let overridenHeaders: string[] = [];
const setOverriddenHeader = (name: string, value: string) => {
overridenHeaders.push(name);
setHeader(name, value);
};
if (stream === null) {
let bodyData = null;
try {
bodyData = JSON.parse(body);
} catch (e) {
console.warn(
"Failed to parse body. Will fall back to default (OpenAI)",
e,
);
}
if (streamFormat === "vercel-ai" && !isStreaming) {
throw new ProxyBadRequestError(
"Vercel AI format requires the stream parameter to be set to true",
);
}
const {
modelResponse: { response: proxyResponse, stream: proxyStream },
secretName,
} = await fetchModelLoop(
meter,
method,
url,
headers,
bodyData,
setOverriddenHeader,
async (model) => {
// First, try to use temp credentials, because then we'll get access
// to the model.
let cachedAuthToken: string | undefined;
if (
useCredentialsCacheMode !== "never" &&
isTempCredential(authToken)
) {
const { credentialCacheValue, jwtPayload } =
await verifyTempCredentials({
jwt: authToken,
cacheGet,
});
// Unwrap the API key here to avoid a duplicate call to
// `verifyTempCredentials` inside `getApiSecrets`. That call will
// use Redis which is not available in Cloudflare.
cachedAuthToken = credentialCacheValue.authToken;
if (jwtPayload.bt.logging) {
console.warn(
`Logging was requested, but not supported on ${method} ${url}`,
);
}
if (jwtPayload.bt.model && jwtPayload.bt.model !== model) {
console.warn(
`Temp credential allows model "${jwtPayload.bt.model}", but "${model}" was requested`,
);
return [];
}
}
const secrets = await getApiSecrets(
useCredentialsCacheMode !== "never",
cachedAuthToken || authToken,
model,
orgName,
);
if (endpointName) {
return secrets.filter((s) => s.name === endpointName);
} else {
return secrets;
}
},
spanLogger,
(st) => {
spanType = st;
},
digest,
cacheGet,
cachePut,
);
stream = proxyStream;
if (!proxyResponse.ok) {
setStatusCode(proxyResponse.status);
responseFailed = true;
}
const proxyResponseHeaders: Record<string, string> = {};
proxyResponse.headers.forEach((value, name) => {
const lowerName = name.toLowerCase();
if (
lowerName === "transfer-encoding" ||
lowerName === "connection" ||
lowerName === "keep-alive" ||
lowerName === "date" ||
lowerName === "server" ||
lowerName === "vary" ||
lowerName === "cache-control" ||
lowerName === "pragma" ||
lowerName === "expires" ||
lowerName === "access-control-allow-origin" ||
lowerName === "access-control-allow-credentials" ||
lowerName === "access-control-expose-headers" ||
lowerName === "access-control-max-age" ||
lowerName === "access-control-allow-methods" ||
lowerName === "access-control-allow-headers" ||
(decompressFetch && lowerName === "content-encoding") ||
overridenHeaders.includes(lowerName)
) {
return;
}
proxyResponseHeaders[name] = value;
});
if (secretName) {
setHeader(USED_ENDPOINT_HEADER, secretName);
proxyResponseHeaders[USED_ENDPOINT_HEADER] = secretName;
}
for (const [name, value] of Object.entries(proxyResponseHeaders)) {
setHeader(name, value);
}
setHeader(CACHED_HEADER, "MISS");
if (writeToCache) {
setHeader("cache-control", `max-age=${cacheTTL}`);
setHeader("age", "0");
}
if (stream && proxyResponse.ok && writeToCache) {
const allChunks: Uint8Array[] = [];
const cacheStream = new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
allChunks.push(chunk);
controller.enqueue(chunk);
},
async flush(controller) {
const data = flattenChunksArray(allChunks);
const dataB64 = Buffer.from(data).toString("base64");
await cachePut(
encryptionKey,
cacheKey,
JSON.stringify({
headers: proxyResponseHeaders,
metadata: {
cached_at: new Date(),
ttl: cacheTTL,
},
data: dataB64,
}),
cacheTTL,
);
},
});
stream = stream.pipeThrough(cacheStream);
}
}
if (spanLogger && stream) {
let first = true;
const allChunks: Uint8Array[] = [];
// These parameters are for the streaming case
let reasoning: OpenAIReasoning[] | undefined = undefined;
let role: string | undefined = undefined;
let content: string | undefined = undefined;
let tool_calls: ChatCompletionChunk.Choice.Delta.ToolCall[] | undefined =
undefined;
let finish_reason: string | undefined = undefined;
const eventSourceParser: EventSourceParser | undefined = !isStreaming
? undefined
: createParser((event: ParsedEvent | ReconnectInterval) => {
if (
("data" in event &&
event.type === "event" &&
event.data === "[DONE]") ||
// Replicate doesn't send [DONE] but does send a 'done' event
// @see https://replicate.com/docs/streaming
(event as any).event === "done"
) {
return;
}
try {
if ("data" in event) {
const result = JSON.parse(event.data) as
| OpenAIChatCompletionChunk
| undefined;
if (result) {
const extendedUsage = completionUsageSchema.safeParse(
result.usage,
);
if (extendedUsage.success) {
spanLogger.log({
// TODO: we should include the proxy meters metrics here
metrics: {
tokens: extendedUsage.data.total_tokens,
prompt_tokens: extendedUsage.data.prompt_tokens,
completion_tokens: extendedUsage.data.completion_tokens,
prompt_cached_tokens:
extendedUsage.data.prompt_tokens_details?.cached_tokens,
prompt_cache_creation_tokens:
extendedUsage.data.prompt_tokens_details
?.cache_creation_tokens,
completion_reasoning_tokens:
extendedUsage.data.completion_tokens_details
?.reasoning_tokens,
},
});
}
const choice = result.choices?.[0];
const delta = choice?.delta;
if (!choice || !delta) {
return;
}
if (!role && delta.role) {
role = delta.role;
}
if (choice.finish_reason) {
finish_reason = choice.finish_reason;
}
if (delta.content) {
content = (content || "") + delta.content;
}
if (delta.reasoning) {
if (!reasoning) {
reasoning = [
{
id: delta.reasoning.id || "",
content: delta.reasoning.content || "",
},
];
} else {
// TODO: could be multiple
reasoning[0].id = reasoning[0].id || delta.reasoning.id;
reasoning[0].content =
reasoning[0].content + (delta.reasoning.content || "");
}
}
if (delta.tool_calls) {
const lastTool = tool_calls
? tool_calls[tool_calls.length - 1]
: undefined;
const toolDelta = delta.tool_calls[0];
if (
!lastTool ||
(toolDelta.id && lastTool.id !== toolDelta.id)
) {
tool_calls = (tool_calls ?? []).concat([
{
index: 0,
id: toolDelta.id,
type: toolDelta.type,
function: toolDelta.function,
},
]);
} else if (lastTool.function) {
lastTool.function.arguments +=
toolDelta.function?.arguments ?? "";
} else {
lastTool.function = toolDelta.function;
}
}
}
}
} catch (e) {
spanLogger.log({
error: e,
});
}
});
const loggingStream = new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
if (
first &&
spanType &&
(["completion", "chat"] as SpanType[]).includes(spanType)
) {
first = false;
spanLogger.log({
metrics: {
time_to_first_token: getCurrentUnixTimestamp() - startTime,
},
});
}
if (isStreaming) {
eventSourceParser?.feed(new TextDecoder().decode(chunk));
} else {
allChunks.push(chunk);
}
controller.enqueue(chunk);
},
async flush(controller) {
if (isStreaming) {
spanLogger.log({
output: [
{
index: 0,
message: {
role,
content,
tool_calls,
reasoning,
},
logprobs: null,
finish_reason,
},
],
});
} else {
const dataRaw = JSON.parse(
new TextDecoder().decode(flattenChunksArray(allChunks)),
);
switch (spanType) {
case "chat":
case "completion": {
const data = dataRaw as ChatCompletion;
const extendedUsage = completionUsageSchema.safeParse(data.usage);
if (extendedUsage.success) {
spanLogger.log({
output: data.choices,
metrics: {
tokens: extendedUsage.data.total_tokens,
prompt_tokens: extendedUsage.data.prompt_tokens,
completion_tokens: extendedUsage.data.completion_tokens,
prompt_cached_tokens:
extendedUsage.data.prompt_tokens_details?.cached_tokens,
prompt_cache_creation_tokens:
extendedUsage.data.prompt_tokens_details
?.cache_creation_tokens,
completion_reasoning_tokens:
extendedUsage.data.completion_tokens_details
?.reasoning_tokens,
},
});
}
break;
}
case "embedding":
{
const data = dataRaw as CreateEmbeddingResponse;
spanLogger.log({
output: { embedding_length: data.data[0].embedding.length },
metrics: {
tokens: data.usage?.total_tokens,
prompt_tokens: data.usage?.prompt_tokens,
},
});
}
break;
case "moderation":
{
const data = dataRaw as ModerationCreateResponse;
spanLogger.log({
output: data.results,
});
}
break;
}
}
spanLogger.end();
controller.terminate();
},
});
stream = stream.pipeThrough(loggingStream);
}
if (stream && streamFormat === "vercel-ai" && !responseFailed) {
const textDecoder = new TextDecoder();
let eventSourceParser: EventSourceParser;
const parser = parseOpenAIStream();
const parseStream = new TransformStream({
async start(controller): Promise<void> {
eventSourceParser = createParser(
(event: ParsedEvent | ReconnectInterval) => {
if (
("data" in event &&
event.type === "event" &&
event.data === "[DONE]") ||
// Replicate doesn't send [DONE] but does send a 'done' event
// @see https://replicate.com/docs/streaming
(event as any).event === "done"
) {
return;
}
if ("data" in event) {
const parsedMessage = parser(event.data);
if (parsedMessage) {
controller.enqueue(new TextEncoder().encode(parsedMessage));
}
}
},
);
},
async flush(controller): Promise<void> {
controller.terminate();
},
transform(chunk, controller) {
eventSourceParser.feed(textDecoder.decode(chunk));
},
});
stream = stream.pipeThrough(parseStream);
}
if (stream) {
stream.pipeTo(res).catch((e) => {
console.error("Error piping stream to response", e);
});
} else {
res.close().catch((e) => {
console.error("Error closing response", e);
});
}
}
const RATE_LIMIT_ERROR_CODE = 429;
// Anthropic uses 529 for overloaded errors, while many providers use 503.
const OVERLOADED_ERROR_CODES = [503, 529];
const RATE_LIMIT_MAX_WAIT_MS = 45 * 1000; // Wait up to 45 seconds while retrying
const BACKOFF_EXPONENT = 2;
const TRY_ANOTHER_ENDPOINT_ERROR_CODES = [
// 404 means the model or endpoint doesn't exist. We may want to propagate these errors, or
// report them elsewhere, but for now round robin.
404,
// 429 is rate limiting. We may want to track stats about this and potentially handle more
// intelligently, eg if all APIs are rate limited, back off and try something else.
RATE_LIMIT_ERROR_CODE,
// 503 and 529 is overloaded. We may want to track stats about this and potentially handle more
// intelligently, eg if all APIs are overloaded, back off and try something else.
...OVERLOADED_ERROR_CODES,
];
const RATE_LIMITING_ERROR_CODES = [
RATE_LIMIT_ERROR_CODE,
...OVERLOADED_ERROR_CODES,
];
const GOOGLE_URL_REGEX =
/\/google\/(models\/[^:]+|publishers\/[^\/]+\/models\/[^:]+):([^\/]+)/;
let loopIndex = 0;
async function fetchModelLoop(
meter: Meter,
method: "GET" | "POST",
url: string,
headers: Record<string, string>,
bodyData: any | null,
setHeader: (name: string, value: string) => void,
getApiSecrets: (model: string | null) => Promise<APISecret[]>,
spanLogger: SpanLogger | undefined,
setSpanType: (spanType: SpanType) => void,
digest: (message: string) => Promise<string>,
cacheGet: (encryptionKey: string, key: string) => Promise<string | null>,
cachePut: (
encryptionKey: string,
key: string,
value: string,
ttl_seconds?: number,
) => Promise<void>,
): Promise<{ modelResponse: ModelResponse; secretName?: string | null }> {
const endpointCalls = meter.createCounter("endpoint_calls");
const endpointFailures = meter.createCounter("endpoint_failures");
const endpointRetryableErrors = meter.createCounter(
"endpoint_retryable_errors",
);
const retriesPerCall = meter.createHistogram("retries_per_call", {
advice: {
explicitBucketBoundaries: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
},
});
const llmTtft = meter.createHistogram("llm_ttft");
const llmLatency = meter.createHistogram("llm_latency");
let model: string | null = null;
if (
method === "POST" &&
(url === "/auto" ||
url === "/chat/completions" ||
url === "/completions" ||
url === "/responses" ||
url === ANTHROPIC_MESSAGES ||
url === ANTHROPIC_V1_MESSAGES) &&
isObject(bodyData) &&
bodyData?.model
) {
model = bodyData?.model;
} else if (method === "POST") {
const m = url.match(GOOGLE_URL_REGEX);
if (m) {
model = m[1];
// Hack since Gemini models are not registered with the models/ prefix.
model = model.replace(/^models\//, "");
}
}
// TODO: Make this smarter. For now, just pick a random one.
const secrets = await getApiSecrets(model);
const initialIdx = getRandomInt(secrets.length);
let proxyResponse: ModelResponse | null = null;
let secretName: string | null | undefined = null;
let lastException = null;
let loggableInfo: Record<string, any> = {};
let i = 0;
let delayMs = 50;
let totalWaitedTime = 0;
let retries = 0;
for (; i < secrets.length; i++) {
const idx = (initialIdx + i) % secrets.length;
const secret = secrets[idx];