-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-helpers.ts
More file actions
380 lines (335 loc) · 10.8 KB
/
api-helpers.ts
File metadata and controls
380 lines (335 loc) · 10.8 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
/**
* Shared API helper functions for v1 endpoints
* Extracted from completions.ts, messages.ts, and responses.ts to reduce code duplication
*/
import type { InternalResponse, ModelWithProvider } from "@/adapters/types";
import type { ToolCallType } from "@/db/schema";
import { createLogger } from "@/utils/logger";
const logger = createLogger("api-helpers");
// =============================================================================
// Header Constants
// =============================================================================
/** Header prefix for NexusGate-specific headers (e.g., X-NexusGate-Provider) */
export const NEXUSGATE_HEADER_PREFIX = "x-nexusgate-";
/** Header name for provider selection */
export const PROVIDER_HEADER = "x-nexusgate-provider";
/** Headers that should NOT be forwarded to upstream */
export const EXCLUDED_HEADERS = new Set([
"host",
"connection",
"content-length",
"content-type",
"authorization",
"x-api-key",
"anthropic-version",
"accept",
"accept-encoding",
"accept-language",
"origin",
"referer",
"cookie",
"sec-fetch-dest",
"sec-fetch-mode",
"sec-fetch-site",
"sec-ch-ua",
"sec-ch-ua-mobile",
"sec-ch-ua-platform",
]);
// =============================================================================
// Header Extraction
// =============================================================================
/**
* Whether the client is requesting an SSE stream via the Accept header.
* Matches `text/event-stream` exactly (no structured-suffix matches like
* `text/event-stream+json`) and respects the RFC 7231 §5.3.1 quality
* factor — `q=0` means "do not accept" and is filtered out.
*/
export function acceptsEventStream(headers: Headers): boolean {
const accept = headers.get("accept");
if (!accept) {
return false;
}
return accept.split(",").some((part) => {
const [mediaType, ...params] = part
.split(";")
.map((segment) => segment.trim().toLowerCase());
if (mediaType !== "text/event-stream") {
return false;
}
for (const param of params) {
const eq = param.indexOf("=");
if (eq === -1) {
continue;
}
const name = param.slice(0, eq).trim();
if (name !== "q") {
continue;
}
const value = param.slice(eq + 1).trim();
const q = Number(value);
return Number.isFinite(q) && q > 0;
}
return true;
});
}
/**
* Extract headers to be forwarded to upstream
* All headers are forwarded EXCEPT:
* - Headers starting with "x-nexusgate-" (NexusGate-specific headers)
* - Standard HTTP headers (host, authorization, content-type, etc.)
*/
export function extractUpstreamHeaders(
headers: Headers,
): Record<string, string> | undefined {
const extra: Record<string, string> = {};
let hasExtra = false;
headers.forEach((value, key) => {
const lowerKey = key.toLowerCase();
// Skip NexusGate-specific headers and excluded standard headers
if (
lowerKey.startsWith(NEXUSGATE_HEADER_PREFIX) ||
EXCLUDED_HEADERS.has(lowerKey)
) {
return;
}
// Forward all other headers as-is
extra[key] = value;
hasExtra = true;
});
return hasExtra ? extra : undefined;
}
// =============================================================================
// Model Selection
// =============================================================================
/**
* Filter candidates by target provider if specified
* Returns all matching candidates (for use with failover)
*/
export function filterCandidates(
modelsWithProviders: ModelWithProvider[],
targetProvider?: string,
): ModelWithProvider[] {
if (modelsWithProviders.length === 0) {
return [];
}
if (!targetProvider) {
return modelsWithProviders;
}
const filtered = modelsWithProviders.filter(
(mp) => mp.provider.name === targetProvider,
);
if (filtered.length > 0) {
return filtered;
}
logger.warn(
`Provider '${targetProvider}' does not offer requested model, falling back to available providers`,
);
return modelsWithProviders;
}
/**
* Select the best model/provider combination based on target provider and weights
* Uses weighted random selection for load balancing across multiple providers
*/
export function selectModel(
modelsWithProviders: ModelWithProvider[],
targetProvider?: string,
): ModelWithProvider | null {
if (modelsWithProviders.length === 0) {
return null;
}
// Filter by target provider if specified
let candidates = modelsWithProviders;
if (targetProvider) {
const filtered = modelsWithProviders.filter(
(mp) => mp.provider.name === targetProvider,
);
if (filtered.length > 0) {
candidates = filtered;
} else {
logger.warn(
`Provider '${targetProvider}' does not offer requested model, falling back to available providers`,
);
}
}
// Single candidate, return directly
if (candidates.length === 1) {
// oxlint-disable-next-line no-unnecessary-type-assertion
return candidates[0]!; // TypeScript needs assertion here
}
// Weighted random selection for load balancing
const totalWeight = candidates.reduce((sum, c) => sum + c.model.weight, 0);
const random = Math.random() * totalWeight;
let cumulative = 0;
for (const candidate of candidates) {
cumulative += candidate.model.weight;
if (random < cumulative) {
logger.debug("Selected model via weighted random", {
modelId: candidate.model.id,
providerId: candidate.provider.id,
providerName: candidate.provider.name,
weight: candidate.model.weight,
totalWeight,
});
return candidate;
}
}
// Fallback (should not happen)
return candidates[0] ?? null;
}
// =============================================================================
// Content Extraction
// =============================================================================
/**
* Extract text content from internal response
* Combines thinking content (wrapped in <think> tags) and text content
*/
export function extractContentText(response: InternalResponse): string {
const parts: string[] = [];
const thinkingParts: string[] = [];
for (const block of response.content) {
if (block.type === "text") {
parts.push(block.text);
} else if (block.type === "thinking") {
thinkingParts.push(block.thinking);
}
}
let result = "";
if (thinkingParts.length > 0) {
result += `<think>${thinkingParts.join("")}</think>\n`;
}
result += parts.join("");
return result;
}
/**
* Extract tool calls from internal response
* Converts internal ToolUseContentBlock to OpenAI ToolCallType format
*/
export function extractToolCalls(
response: InternalResponse,
): ToolCallType[] | undefined {
const toolCalls: ToolCallType[] = [];
for (const block of response.content) {
if (block.type === "tool_use") {
toolCalls.push({
id: block.id,
type: "function",
function: {
name: block.name,
arguments: JSON.stringify(block.input),
},
});
}
}
return toolCalls.length > 0 ? toolCalls : undefined;
}
// =============================================================================
// Model Parsing
// =============================================================================
/**
* Parse model string with optional provider suffix (e.g., "gpt-4@openai")
* Returns the system name and optional target provider
*/
export function parseModelProvider(
model: string,
providerHeader: string | null,
): { systemName: string; targetProvider: string | undefined } {
// Parse model@provider format
const modelMatch = model.match(/^(\S+)@(\S+)$/);
// oxlint-disable-next-line no-unnecessary-type-assertion
const systemName = modelMatch ? modelMatch[1]! : model; // conflicting with tsc
// Determine target provider: header takes precedence over model@provider format
const targetProvider = providerHeader
? decodeURIComponent(providerHeader)
: modelMatch?.[2];
return { systemName, targetProvider };
}
// =============================================================================
// Failover Error Handling
// =============================================================================
import type { FailoverResult, FailoverError } from "@/services/failover";
import { addCompletions, type Completion } from "@/utils/completions";
/**
* Result of processing a failover error
*/
export type FailoverErrorResult =
| {
type: "upstream_error";
status: number;
body: string;
}
| {
type: "failover_exhausted";
status: 502;
};
/**
* Generate error summary from failover errors
*/
export function getErrorSummary(errors: FailoverError[]): string {
return errors.map((e) => `${e.providerName}: ${e.error}`).join("; ");
}
/**
* Process failover error and update completion record
* Returns structured result indicating error type and response data
*
* @param result - The failover result (must have success=false)
* @param completion - The completion record to update (will be mutated)
* @param bearer - API key for logging
* @param requestType - "streaming" or "non-streaming" for log messages
*/
export async function processFailoverError(
result: FailoverResult<Response>,
completion: Completion,
bearer: string,
requestType: "streaming" | "non-streaming",
): Promise<FailoverErrorResult> {
completion.status = "failed";
const errorSummary = getErrorSummary(result.errors);
// Non-retriable HTTP error from upstream - forward the response
if (result.response) {
logger.warn(`Non-retriable upstream error for ${requestType} request`, {
status: result.response.status,
provider: result.provider?.provider.name,
});
addCompletions(completion, bearer, {
level: "error",
message: `Upstream error (non-retriable): ${errorSummary}`,
details: {
type: "completionError",
data: {
type: "upstreamError",
msg: result.finalError,
},
},
}).catch(() => {
logger.error("Failed to log completion after upstream error");
});
const responseBody = await result.response.text();
return {
type: "upstream_error",
status: result.response.status,
body: responseBody,
};
}
// All providers failed with retriable errors or network errors
logger.error(`All providers failed for ${requestType} request`, {
errors: result.errors,
totalAttempts: result.totalAttempts,
});
addCompletions(completion, bearer, {
level: "error",
message: `All providers failed (${result.totalAttempts} attempts): ${errorSummary}`,
details: {
type: "completionError",
data: {
type: "failoverExhausted",
msg: result.finalError,
},
},
}).catch(() => {
logger.error("Failed to log completion after failover exhaustion");
});
return {
type: "failover_exhausted",
status: 502,
};
}