({
body,
userId,
stripeCustomerId,
agentId,
openrouterApiKey,
fetch,
logger,
insertMessageBigquery,
}: {
body: ChatCompletionRequestBody
userId: string
stripeCustomerId?: string | null
agentId: string
openrouterApiKey: string | null
fetch: typeof globalThis.fetch
logger: Logger
insertMessageBigquery: InsertMessageBigqueryFn
})
| 313 | } |
| 314 | |
| 315 | export async function handleOpenRouterStream({ |
| 316 | body, |
| 317 | userId, |
| 318 | stripeCustomerId, |
| 319 | agentId, |
| 320 | openrouterApiKey, |
| 321 | fetch, |
| 322 | logger, |
| 323 | insertMessageBigquery, |
| 324 | }: { |
| 325 | body: ChatCompletionRequestBody |
| 326 | userId: string |
| 327 | stripeCustomerId?: string | null |
| 328 | agentId: string |
| 329 | openrouterApiKey: string | null |
| 330 | fetch: typeof globalThis.fetch |
| 331 | logger: Logger |
| 332 | insertMessageBigquery: InsertMessageBigqueryFn |
| 333 | }) { |
| 334 | // Ensure usage tracking is enabled |
| 335 | if (body.usage === undefined) { |
| 336 | body.usage = {} |
| 337 | } |
| 338 | body.usage.include = true |
| 339 | |
| 340 | const startTime = new Date() |
| 341 | const { clientId, clientRequestId, costMode } = extractRequestMetadata({ body, logger }) |
| 342 | const auditRequest = createRequestAuditRecord(body) |
| 343 | |
| 344 | const byok = openrouterApiKey !== null |
| 345 | const response = await createOpenRouterRequest({ |
| 346 | body, |
| 347 | openrouterApiKey, |
| 348 | fetch, |
| 349 | }) |
| 350 | |
| 351 | if (!response.ok) { |
| 352 | throw await parseOpenRouterError(response) |
| 353 | } |
| 354 | |
| 355 | const reader = response.body?.getReader() |
| 356 | if (!reader) { |
| 357 | throw new Error('Failed to get response reader') |
| 358 | } |
| 359 | |
| 360 | let heartbeatInterval: NodeJS.Timeout |
| 361 | let state: StreamState = { |
| 362 | responseText: '', |
| 363 | reasoningText: '', |
| 364 | ttftMs: null, |
| 365 | generationId: null, |
| 366 | model: null, |
| 367 | billed: false, |
| 368 | } |
| 369 | let clientDisconnected = false |
| 370 | let disconnectedStreamDrainTimeout: NodeJS.Timeout | null = null |
| 371 | |
| 372 | // Runs once on any stream-exit path. If we didn't bill through the normal |
no test coverage detected