({
body,
userId,
stripeCustomerId,
agentId,
fetch,
logger,
insertMessageBigquery,
}: {
body: ChatCompletionRequestBody
userId: string
stripeCustomerId?: string | null
agentId: string
fetch: typeof globalThis.fetch
logger: Logger
insertMessageBigquery: InsertMessageBigqueryFn
})
| 348 | } |
| 349 | |
| 350 | export async function handleMoonshotStream({ |
| 351 | body, |
| 352 | userId, |
| 353 | stripeCustomerId, |
| 354 | agentId, |
| 355 | fetch, |
| 356 | logger, |
| 357 | insertMessageBigquery, |
| 358 | }: { |
| 359 | body: ChatCompletionRequestBody |
| 360 | userId: string |
| 361 | stripeCustomerId?: string | null |
| 362 | agentId: string |
| 363 | fetch: typeof globalThis.fetch |
| 364 | logger: Logger |
| 365 | insertMessageBigquery: InsertMessageBigqueryFn |
| 366 | }) { |
| 367 | const originalModel = body.model |
| 368 | const startTime = new Date() |
| 369 | const { clientId, clientRequestId, costMode } = extractRequestMetadata({ |
| 370 | body, |
| 371 | logger, |
| 372 | }) |
| 373 | const auditRequest = createRequestAuditRecord(body) |
| 374 | |
| 375 | const response = await createMoonshotRequest({ body, originalModel, fetch }) |
| 376 | if (!response.ok) { |
| 377 | throw await parseMoonshotError(response) |
| 378 | } |
| 379 | |
| 380 | const reader = response.body?.getReader() |
| 381 | if (!reader) { |
| 382 | throw new Error('Failed to get response reader') |
| 383 | } |
| 384 | |
| 385 | let heartbeatInterval: NodeJS.Timeout |
| 386 | let state: StreamState = { |
| 387 | responseText: '', |
| 388 | reasoningText: '', |
| 389 | ttftMs: null, |
| 390 | billedAlready: false, |
| 391 | } |
| 392 | let clientDisconnected = false |
| 393 | |
| 394 | const stream = new ReadableStream({ |
| 395 | async start(controller) { |
| 396 | const decoder = new TextDecoder() |
| 397 | let buffer = '' |
| 398 | |
| 399 | controller.enqueue( |
| 400 | new TextEncoder().encode(`: connected ${new Date().toISOString()}\n`), |
| 401 | ) |
| 402 | |
| 403 | heartbeatInterval = setInterval(() => { |
| 404 | if (!clientDisconnected) { |
| 405 | try { |
| 406 | controller.enqueue( |
| 407 | new TextEncoder().encode( |
no test coverage detected