({
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
})
| 126 | } |
| 127 | |
| 128 | export async function handleOpenRouterNonStream({ |
| 129 | body, |
| 130 | userId, |
| 131 | stripeCustomerId, |
| 132 | agentId, |
| 133 | openrouterApiKey, |
| 134 | fetch, |
| 135 | logger, |
| 136 | insertMessageBigquery, |
| 137 | }: { |
| 138 | body: ChatCompletionRequestBody |
| 139 | userId: string |
| 140 | stripeCustomerId?: string | null |
| 141 | agentId: string |
| 142 | openrouterApiKey: string | null |
| 143 | fetch: typeof globalThis.fetch |
| 144 | logger: Logger |
| 145 | insertMessageBigquery: InsertMessageBigqueryFn |
| 146 | }) { |
| 147 | // Ensure usage tracking is enabled |
| 148 | if (body.usage === undefined) { |
| 149 | body.usage = {} |
| 150 | } |
| 151 | body.usage.include = true |
| 152 | |
| 153 | const startTime = new Date() |
| 154 | const { clientId, clientRequestId, costMode, n } = extractRequestMetadataWithN({ |
| 155 | body, |
| 156 | logger, |
| 157 | }) |
| 158 | const auditRequest = createRequestAuditRecord(body) |
| 159 | const byok = openrouterApiKey !== null |
| 160 | |
| 161 | // If n > 1, make n parallel requests |
| 162 | if (n && n > 1) { |
| 163 | const requests = Array.from({ length: n }, () => |
| 164 | createOpenRouterRequest({ body, openrouterApiKey, fetch }), |
| 165 | ) |
| 166 | |
| 167 | const responses = await Promise.all(requests) |
| 168 | if (responses.every((r) => !r.ok)) { |
| 169 | // Return provider-specific error from the first failed response |
| 170 | const firstFailedResponse = responses[0] |
| 171 | throw await parseOpenRouterError(firstFailedResponse) |
| 172 | } |
| 173 | const allData = await Promise.all(responses.map((r) => r.json())) |
| 174 | |
| 175 | // Aggregate usage data from all responses |
| 176 | const responseContents: string[] = [] |
| 177 | const aggregatedUsage: UsageData = { |
| 178 | inputTokens: 0, |
| 179 | outputTokens: 0, |
| 180 | cacheReadInputTokens: 0, |
| 181 | reasoningTokens: 0, |
| 182 | cost: 0, |
| 183 | } |
| 184 | |
| 185 | for (const data of allData) { |
no test coverage detected