-
Notifications
You must be signed in to change notification settings - Fork 12
refactor: use inline usage cost from OpenRouter instead of generation cost API #4328
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -40,7 +40,10 @@ import { | |||||||||||||||||||||||||
| import type { MatrixEvent as DiscreteMatrixEvent } from 'https://cardstack.com/base/matrix-event'; | ||||||||||||||||||||||||||
| import * as Sentry from '@sentry/node'; | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| import { saveUsageCost } from '@cardstack/billing/ai-billing'; | ||||||||||||||||||||||||||
| import { | ||||||||||||||||||||||||||
| spendUsageCost, | ||||||||||||||||||||||||||
| fetchGenerationCostWithBackoff, | ||||||||||||||||||||||||||
| } from '@cardstack/billing/ai-billing'; | ||||||||||||||||||||||||||
| import { PgAdapter } from '@cardstack/postgres'; | ||||||||||||||||||||||||||
| import type { ChatCompletionMessageParam } from 'openai/resources'; | ||||||||||||||||||||||||||
| import type { OpenAIError } from 'openai/error'; | ||||||||||||||||||||||||||
|
|
@@ -86,22 +89,41 @@ class Assistant { | |||||||||||||||||||||||||
| this.aiBotInstanceId = aiBotInstanceId; | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| async trackAiUsageCost(matrixUserId: string, generationId: string) { | ||||||||||||||||||||||||||
| async trackAiUsageCost( | ||||||||||||||||||||||||||
| matrixUserId: string, | ||||||||||||||||||||||||||
| opts: { costInUsd?: number; generationId?: string }, | ||||||||||||||||||||||||||
| ) { | ||||||||||||||||||||||||||
| if (trackAiUsageCostPromises.has(matrixUserId)) { | ||||||||||||||||||||||||||
| return; | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| // intentionally do not await saveUsageCost promise - it has a backoff mechanism to retry if the cost is not immediately available so we don't want to block the main thread | ||||||||||||||||||||||||||
| trackAiUsageCostPromises.set( | ||||||||||||||||||||||||||
| matrixUserId, | ||||||||||||||||||||||||||
| saveUsageCost( | ||||||||||||||||||||||||||
| this.pgAdapter, | ||||||||||||||||||||||||||
| matrixUserId, | ||||||||||||||||||||||||||
| generationId, | ||||||||||||||||||||||||||
| process.env.OPENROUTER_API_KEY!, | ||||||||||||||||||||||||||
| ).finally(() => { | ||||||||||||||||||||||||||
| trackAiUsageCostPromises.delete(matrixUserId); | ||||||||||||||||||||||||||
| }), | ||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||
| const promise = (async () => { | ||||||||||||||||||||||||||
| let { costInUsd, generationId } = opts; | ||||||||||||||||||||||||||
| if ( | ||||||||||||||||||||||||||
| typeof costInUsd === 'number' && | ||||||||||||||||||||||||||
| Number.isFinite(costInUsd) && | ||||||||||||||||||||||||||
| costInUsd > 0 | ||||||||||||||||||||||||||
| ) { | ||||||||||||||||||||||||||
| await spendUsageCost(this.pgAdapter, matrixUserId, costInUsd); | ||||||||||||||||||||||||||
| } else if (generationId) { | ||||||||||||||||||||||||||
| log.info( | ||||||||||||||||||||||||||
| `No inline cost for user ${matrixUserId}, falling back to generation cost API (generationId: ${generationId})`, | ||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||
| const fetchedCost = await fetchGenerationCostWithBackoff( | ||||||||||||||||||||||||||
| generationId, | ||||||||||||||||||||||||||
| process.env.OPENROUTER_API_KEY!, | ||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||
| if (fetchedCost !== null) { | ||||||||||||||||||||||||||
| await spendUsageCost(this.pgAdapter, matrixUserId, fetchedCost); | ||||||||||||||||||||||||||
|
||||||||||||||||||||||||||
| await spendUsageCost(this.pgAdapter, matrixUserId, fetchedCost); | |
| await spendUsageCost(this.pgAdapter, matrixUserId, fetchedCost); | |
| } else { | |
| let message = `Failed to fetch generation cost for user ${matrixUserId} (generationId: ${generationId}); credits were not deducted`; | |
| log.warn(message); | |
| Sentry.captureMessage(message, { | |
| level: 'warning', | |
| extra: { | |
| matrixUserId, | |
| generationId, | |
| }, | |
| }); |
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -57,33 +57,33 @@ async function handleStreamingRequest( | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (!reader) throw new Error('No readable stream available'); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| let generationId: string | undefined; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| let costInUsd: number | undefined; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| let lastPing = Date.now(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| await proxySSE( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| reader, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| async (data) => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Handle end of stream | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (data === '[DONE]') { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (generationId) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Save cost in the background so we don't block the stream on OpenRouter's generation cost API. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Chain per-user promises so costs are recorded sequentially. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const previousPromise = | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| pendingCostPromises.get(matrixUserId) ?? Promise.resolve(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const costPromise = previousPromise | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .then(() => | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| endpointConfig.creditStrategy.saveUsageCost( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| dbAdapter, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| matrixUserId, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| { id: generationId }, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .finally(() => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (pendingCostPromises.get(matrixUserId) === costPromise) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| pendingCostPromises.delete(matrixUserId); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| pendingCostPromises.set(matrixUserId, costPromise); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Deduct credits using the cost from the streaming response. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Chain per-user promises so costs are recorded sequentially. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const previousPromise = | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| pendingCostPromises.get(matrixUserId) ?? Promise.resolve(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const costPromise = previousPromise | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .then(() => | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| endpointConfig.creditStrategy.saveUsageCost( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| dbAdapter, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| matrixUserId, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| { id: generationId, usage: { cost: costInUsd } }, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| .finally(() => { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (pendingCostPromises.get(matrixUserId) === costPromise) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| pendingCostPromises.delete(matrixUserId); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| pendingCostPromises.set(matrixUserId, costPromise); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+68
to
+86
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Deduct credits using the cost from the streaming response. | |
| // Chain per-user promises so costs are recorded sequentially. | |
| const previousPromise = | |
| pendingCostPromises.get(matrixUserId) ?? Promise.resolve(); | |
| const costPromise = previousPromise | |
| .then(() => | |
| endpointConfig.creditStrategy.saveUsageCost( | |
| dbAdapter, | |
| matrixUserId, | |
| { id: generationId, usage: { cost: costInUsd } }, | |
| ), | |
| ) | |
| .finally(() => { | |
| if (pendingCostPromises.get(matrixUserId) === costPromise) { | |
| pendingCostPromises.delete(matrixUserId); | |
| } | |
| }); | |
| pendingCostPromises.set(matrixUserId, costPromise); | |
| // Deduct credits using the cost from the streaming response only | |
| // when we have enough metadata to save or resolve billing details. | |
| // Chain per-user promises so costs are recorded sequentially. | |
| const hasNumericCost = | |
| typeof costInUsd === 'number' && Number.isFinite(costInUsd); | |
| const hasBillingMetadata = hasNumericCost || generationId != null; | |
| if (hasBillingMetadata) { | |
| const previousPromise = | |
| pendingCostPromises.get(matrixUserId) ?? Promise.resolve(); | |
| const costPromise = previousPromise | |
| .then(() => | |
| endpointConfig.creditStrategy.saveUsageCost( | |
| dbAdapter, | |
| matrixUserId, | |
| { id: generationId, usage: { cost: costInUsd } }, | |
| ), | |
| ) | |
| .finally(() => { | |
| if (pendingCostPromises.get(matrixUserId) === costPromise) { | |
| pendingCostPromises.delete(matrixUserId); | |
| } | |
| }); | |
| pendingCostPromises.set(matrixUserId, costPromise); | |
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In which case there is no inline cost?