-
Notifications
You must be signed in to change notification settings - Fork 7
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
Track credit consumption in AI bot #1809
Merged
+395
−13
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
cd957ac
Track credit consumption in AI bot
jurgenwerk 41b520a
AI bot saves credits usage for user in credits ledger
jurgenwerk 08255db
Save subscription cycle in extra credits ledger entries
jurgenwerk 111020a
Update pnpm lock
jurgenwerk 3e6f100
Merge branch 'main' into openrouter-ai-bot
jurgenwerk 6a17132
Fixes after upstream merge
jurgenwerk 3e89ac8
Fix query and comment
jurgenwerk bc5e24f
Revert default pg config, provide config with the start command
jurgenwerk 26e8ba0
Remove comment that is not relevant anymore
jurgenwerk d787401
Introduce CREDITS_PER_USD constant
jurgenwerk a34f106
Merge branch 'main' into openrouter-ai-bot
jurgenwerk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import { | ||
getCurrentActiveSubscription, | ||
getUserByMatrixUserId, | ||
spendCredits, | ||
} from '@cardstack/billing/billing-queries'; | ||
import { PgAdapter, TransactionManager } from '@cardstack/postgres'; | ||
import { logger, retry } from '@cardstack/runtime-common'; | ||
import * as Sentry from '@sentry/node'; | ||
|
||
let log = logger('ai-bot'); | ||
|
||
const CREDITS_PER_USD = 1000; | ||
|
||
export async function saveUsageCost( | ||
pgAdapter: PgAdapter, | ||
matrixUserId: string, | ||
generationId: string, | ||
) { | ||
try { | ||
// Generation data is sometimes not immediately available, so we retry a couple of times until we are able to get the cost | ||
let costInUsd = await retry(() => fetchGenerationCost(generationId), { | ||
retries: 10, | ||
delayMs: 500, | ||
}); | ||
|
||
let creditsConsumed = Math.round(costInUsd * CREDITS_PER_USD); | ||
|
||
let user = await getUserByMatrixUserId(pgAdapter, matrixUserId); | ||
|
||
// This check is for the transition period where we don't have subscriptions fully rolled out yet. | ||
// When we have assurance that all users who use the bot have subscriptions, we can remove this subscription check. | ||
let subscription = await getCurrentActiveSubscription(pgAdapter, user!.id); | ||
if (!subscription) { | ||
log.info( | ||
`user ${matrixUserId} has no subscription, skipping credit usage tracking`, | ||
); | ||
return Promise.resolve(); | ||
} | ||
|
||
if (!user) { | ||
throw new Error( | ||
`should not happen: user with matrix id ${matrixUserId} not found in the users table`, | ||
); | ||
} | ||
|
||
let txManager = new TransactionManager(pgAdapter); | ||
|
||
await txManager.withTransaction(async () => { | ||
await spendCredits(pgAdapter, user!.id, creditsConsumed); | ||
|
||
// TODO: send a signal to the host app to update credits balance displayed in the UI | ||
}); | ||
} catch (err) { | ||
log.error( | ||
`Failed to track AI usage (matrixUserId: ${matrixUserId}, generationId: ${generationId}):`, | ||
err, | ||
); | ||
Sentry.captureException(err); | ||
// Don't throw, because we don't want to crash the bot over this | ||
} | ||
} | ||
|
||
async function fetchGenerationCost(generationId: string) { | ||
let response = await ( | ||
await fetch(`https://openrouter.ai/api/v1/generation?id=${generationId}`, { | ||
headers: { | ||
Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`, | ||
}, | ||
}) | ||
).json(); | ||
|
||
if (response.error && response.error.includes('not found')) { | ||
return null; | ||
} | ||
|
||
return response.data.total_cost; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
I wonder if it would be worth tracking the generation ID.
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.
I think now with this simple variant this may not be necessary but later on when we introduce jobs and queues, we could save the generation id there (in the serialized job) and have it available for inspection if needed.