({
body,
userId,
stripeCustomerId,
agentId,
fetch,
logger,
insertMessageBigquery,
}: {
body: ChatCompletionRequestBody
userId: string
stripeCustomerId?: string | null
agentId: string
fetch: typeof globalThis.fetch
logger: Logger
insertMessageBigquery: InsertMessageBigqueryFn
})
| 374 | } |
| 375 | |
| 376 | export async function handleOpenAIStream({ |
| 377 | body, |
| 378 | userId, |
| 379 | stripeCustomerId, |
| 380 | agentId, |
| 381 | fetch, |
| 382 | logger, |
| 383 | insertMessageBigquery, |
| 384 | }: { |
| 385 | body: ChatCompletionRequestBody |
| 386 | userId: string |
| 387 | stripeCustomerId?: string | null |
| 388 | agentId: string |
| 389 | fetch: typeof globalThis.fetch |
| 390 | logger: Logger |
| 391 | insertMessageBigquery: InsertMessageBigqueryFn |
| 392 | }) { |
| 393 | const startTime = new Date() |
| 394 | const { clientId, clientRequestId, costMode } = extractRequestMetadata({ |
| 395 | body, |
| 396 | logger, |
| 397 | }) |
| 398 | const auditRequest = createRequestAuditRecord(body) |
| 399 | |
| 400 | const originalModel = body.model |
| 401 | const modelShortName = extractShortModelName(originalModel) |
| 402 | const openaiBody = buildOpenAIBody(body, modelShortName) |
| 403 | openaiBody.stream = true |
| 404 | openaiBody.stream_options = { include_usage: true } |
| 405 | |
| 406 | const response = await fetch('https://api.openai.com/v1/chat/completions', { |
| 407 | method: 'POST', |
| 408 | headers: { |
| 409 | Authorization: `Bearer ${env.OPENAI_API_KEY}`, |
| 410 | 'Content-Type': 'application/json', |
| 411 | }, |
| 412 | body: JSON.stringify(openaiBody), |
| 413 | // @ts-expect-error - dispatcher is a valid undici option not in fetch types |
| 414 | dispatcher: openaiAgent, |
| 415 | }) |
| 416 | |
| 417 | if (!response.ok) { |
| 418 | throw new OpenAIError( |
| 419 | response.status, |
| 420 | response.statusText, |
| 421 | await response.text(), |
| 422 | ) |
| 423 | } |
| 424 | |
| 425 | const reader = response.body?.getReader() |
| 426 | if (!reader) { |
| 427 | throw new Error('Failed to get response reader') |
| 428 | } |
| 429 | |
| 430 | let heartbeatInterval: NodeJS.Timeout |
| 431 | let responseText = '' |
| 432 | let reasoningText = '' |
| 433 | let ttftMs: number | null = null |
no test coverage detected