({
body,
userId,
stripeCustomerId,
agentId,
fetch,
logger,
insertMessageBigquery,
}: {
body: ChatCompletionRequestBody
userId: string
stripeCustomerId?: string | null
agentId: string
fetch: typeof globalThis.fetch
logger: Logger
insertMessageBigquery: InsertMessageBigqueryFn
})
| 190 | } |
| 191 | |
| 192 | export async function handleSiliconFlowStream({ |
| 193 | body, |
| 194 | userId, |
| 195 | stripeCustomerId, |
| 196 | agentId, |
| 197 | fetch, |
| 198 | logger, |
| 199 | insertMessageBigquery, |
| 200 | }: { |
| 201 | body: ChatCompletionRequestBody |
| 202 | userId: string |
| 203 | stripeCustomerId?: string | null |
| 204 | agentId: string |
| 205 | fetch: typeof globalThis.fetch |
| 206 | logger: Logger |
| 207 | insertMessageBigquery: InsertMessageBigqueryFn |
| 208 | }) { |
| 209 | const originalModel = body.model |
| 210 | const startTime = new Date() |
| 211 | const { clientId, clientRequestId, costMode } = extractRequestMetadata({ body, logger }) |
| 212 | const auditRequest = createRequestAuditRecord(body) |
| 213 | |
| 214 | const response = await createSiliconFlowRequest({ body, originalModel, fetch }) |
| 215 | |
| 216 | if (!response.ok) { |
| 217 | throw await parseSiliconFlowError(response) |
| 218 | } |
| 219 | |
| 220 | const reader = response.body?.getReader() |
| 221 | if (!reader) { |
| 222 | throw new Error('Failed to get response reader') |
| 223 | } |
| 224 | |
| 225 | let heartbeatInterval: NodeJS.Timeout |
| 226 | let state: StreamState = { responseText: '', reasoningText: '', ttftMs: null, billedAlready: false } |
| 227 | let clientDisconnected = false |
| 228 | |
| 229 | const stream = new ReadableStream({ |
| 230 | async start(controller) { |
| 231 | const decoder = new TextDecoder() |
| 232 | let buffer = '' |
| 233 | |
| 234 | controller.enqueue( |
| 235 | new TextEncoder().encode(`: connected ${new Date().toISOString()}\n`), |
| 236 | ) |
| 237 | |
| 238 | heartbeatInterval = setInterval(() => { |
| 239 | if (!clientDisconnected) { |
| 240 | try { |
| 241 | controller.enqueue( |
| 242 | new TextEncoder().encode( |
| 243 | `: heartbeat ${new Date().toISOString()}\n\n`, |
| 244 | ), |
| 245 | ) |
| 246 | } catch { |
| 247 | // client disconnected |
| 248 | } |
| 249 | } |
no test coverage detected