Track all requests to OpenAI in a database

this will be in future used to limit access to the bot
This commit is contained in:
Wroclaw 2023-05-02 17:55:48 +02:00
parent 05c50d25e4
commit a66115c3b8
5 changed files with 94 additions and 0 deletions

View file

@ -1,5 +1,6 @@
import DiscordApi from "discord.js";
import { Configuration as OpenAIApiConfiguration, OpenAIApi } from "openai";
import { PrismaClient } from "@prisma/client";
import config from "./config";
import toOpenAIMessages from "./toOpenAIMessages";
@ -17,6 +18,8 @@ export const openai = new OpenAIApi(new OpenAIApiConfiguration({
apiKey: config.tokens.OpenAI
}));
export const database = new PrismaClient();
discord.on("ready", async event => {
console.log(`Connected to Discord as ${event.user.tag} (${event.user.id})`);
});
@ -55,6 +58,20 @@ async function onMessage(channel: string) {
if (usage != undefined) {
const channelName: string = message.inGuild() ? `${message.channel.name} (${message.guild.name})` : `@${message.author.tag}`;
console.log(`Used ${usage.total_tokens} (${usage.prompt_tokens} + ${usage.completion_tokens}) tokens for ${message.author.tag} (${message.author.id}) in #${channelName}`);
database.usage.create({
data: {
timestamp: message.createdAt,
user: BigInt(message.author.id),
channel: BigInt(message.channelId),
guild: message.guildId ? BigInt(message.guildId) : null,
usageReguest: usage.prompt_tokens,
usageResponse: usage.completion_tokens
}
}).catch((e => {
console.error("Failed to push to a database");
console.error(e);
}));
}
const answerContent = answer.data.choices[0].message?.content;