({
apiKey,
endpointId,
requestId,
}: {
apiKey: string
endpointId: string
requestId: string
})
| 158 | } |
| 159 | |
| 160 | export async function getFalAICostMetadata({ |
| 161 | apiKey, |
| 162 | endpointId, |
| 163 | requestId, |
| 164 | }: { |
| 165 | apiKey: string |
| 166 | endpointId: string |
| 167 | requestId: string |
| 168 | }): Promise<FalAICostMetadata> { |
| 169 | for (let attempt = 0; attempt < FALAI_BILLING_EVENT_ATTEMPTS; attempt++) { |
| 170 | const event = await fetchFalAIBillingEvent(apiKey, requestId) |
| 171 | if (event) { |
| 172 | return { |
| 173 | endpointId: event.endpoint_id, |
| 174 | requestId: event.request_id, |
| 175 | costDollars: event.cost_estimate_nano_usd / 1_000_000_000, |
| 176 | source: 'billing_events', |
| 177 | outputUnits: event.output_units, |
| 178 | unitPrice: event.unit_price, |
| 179 | percentDiscount: event.percent_discount, |
| 180 | currency: 'USD', |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | if (attempt < FALAI_BILLING_EVENT_ATTEMPTS - 1) { |
| 185 | await sleep(FALAI_BILLING_EVENT_RETRY_MS) |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | const estimate = await estimateFalAICallCost(apiKey, endpointId) |
| 190 | if (estimate.costDollars !== undefined) { |
| 191 | return { |
| 192 | endpointId, |
| 193 | requestId, |
| 194 | costDollars: estimate.costDollars, |
| 195 | source: 'historical_estimate', |
| 196 | currency: 'USD', |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | logger.warn('Fal.ai cost metadata unavailable after generation completed', { |
| 201 | endpointId, |
| 202 | requestId, |
| 203 | error: estimate.error, |
| 204 | }) |
| 205 | |
| 206 | return { |
| 207 | endpointId, |
| 208 | requestId, |
| 209 | costDollars: getFalAIFallbackProviderCostDollars(endpointId), |
| 210 | source: 'fallback_floor', |
| 211 | currency: 'USD', |
| 212 | error: estimate.error, |
| 213 | } |
| 214 | } |
no test coverage detected