Skip to content
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

chore: updated rate -> Account Level model #85

Merged
merged 1 commit into from
Nov 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions src/api/clients/clients.api.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {
ClientAccountLevel,
ClientAvailabilityResponse,
ClientFeedbackResponse,
ClientMetadata,
ClientMetadataResponse,
ClientRate,
ClientResponse,
} from '@bot/api/clients/types';
import { fetchCachedData } from '@bot/common/utils';
Expand Down Expand Up @@ -42,6 +42,10 @@ export const createClient = async (
export const getClientAvailability = async (
telegramId: number,
): Promise<ClientAvailabilityResponse | null> => {
if (Number.isNaN(telegramId)) {
return null;
}

try {
const clientAvailability = await fetchCachedData(
`cached-client-availability-${telegramId}`,
Expand Down Expand Up @@ -95,20 +99,20 @@ export const giveClientFeedback = async (
}
};

export const updateClientRate = async (telegramId: number) => {
export const updateClientAccountLevel = async (telegramId: number) => {
try {
const response = await axios<ClientRate>({
const response = await axios<ClientAccountLevel>({
method: 'post',
data: {
telegramId,
},
url: `${config.CHAT_GPT_API_HOST}/v1/api/clients/rate`,
url: `${config.CHAT_GPT_API_HOST}/v1/api/clients/accountLevel`,
});

return response.data;
} catch (error) {
Logger.error({
context: 'src/api/clients/clients.api.ts::updateClientRate',
context: 'src/api/clients/clients.api.ts::updateClientAccountLevel',
message: error.message,
stack: JSON.stringify(error),
});
Expand Down
4 changes: 2 additions & 2 deletions src/api/clients/types/clients.types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ChatCompletionResponse } from '@bot/api/gpt/types';

export type ClientRate = {
export type ClientAccountLevel = {
expiresAt: number;
gptModels: string[];
gptTokens: number;
Expand All @@ -17,7 +17,7 @@ export type ClientMetadata = {
};

export type ClientAvailabilityResponse = {
rate: ClientRate;
accountLevel: ClientAccountLevel;
state: { blockReason: string; isApproved: string; isBlocked: string; updatedAt: number };
};

Expand Down
6 changes: 3 additions & 3 deletions src/api/gpt/types/gpt.types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MessageRolesGPT, TypeGPT } from '@bot/api/gpt/constants';
import { ClientRate } from 'api/clients/types';
import { ClientAccountLevel } from 'api/clients/types';

export type GptModelResponse = {
associated: string[];
Expand All @@ -12,7 +12,7 @@ export type GptModelResponse = {
};

export type ChatCompletionResponse = {
clientRate: ClientRate;
clientAccountLevel: ClientAccountLevel;
message: {
content: string;
role: `${MessageRolesGPT}`;
Expand All @@ -27,7 +27,7 @@ export type ChatCompletionResponse = {
export type TranscriptionResponse = { text: string };

export type GenerateImagesResponse = {
clientRate: ClientRate;
clientAccountLevel: ClientAccountLevel;
images: {
bytes: number | null;
height: number;
Expand Down
4 changes: 2 additions & 2 deletions src/app/types/bot.types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ClientMetadata, ClientRate } from '@bot/api/clients/types';
import { ClientAccountLevel, ClientMetadata } from '@bot/api/clients/types';
import { MessageRolesGPT } from '@bot/api/gpt/constants';
import { ConversationFlavor } from '@grammyjs/conversations';
import { HydrateFlavor } from '@grammyjs/hydrate';
Expand All @@ -12,7 +12,7 @@ export type SessionType = {
client: {
messages: SessionMessageType[];
metadata: ClientMetadata;
rate: ClientRate | null;
accountLevel: ClientAccountLevel | null;
selectedModel: {
speech: {
model: string;
Expand Down
10 changes: 5 additions & 5 deletions src/common/helpers/gpt.helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const getGptContent = async (ctx: BotContextType, text: string) => {
const messageId = Number(ctx.message?.message_id);

const { gpt: selectedGpt } = ctx.session.client.selectedModel;
const currentRateName = ctx.session.client.rate?.name;
const currentRateName = ctx.session.client.accountLevel?.name;

ctx.session.client.messages.push({
content: text,
Expand All @@ -29,20 +29,20 @@ export const getGptContent = async (ctx: BotContextType, text: string) => {
}

const content = chatCompletionResponse.message.content;
const clientRate = chatCompletionResponse.clientRate;
const clientAccountLevel = chatCompletionResponse.clientAccountLevel;

ctx.session.client.messages.push({
content,
role: MessageRolesGPT.ASSISTANT,
});

ctx.session.client.rate = clientRate;
ctx.session.client.accountLevel = clientAccountLevel;

if (!clientRate.gptModels.includes(selectedGpt.model)) {
if (!clientAccountLevel.gptModels.includes(selectedGpt.model)) {
ctx.session.client.selectedModel = resetSelectedModel();
}

if (clientRate.name !== currentRateName) {
if (clientAccountLevel.name !== currentRateName) {
removeValueFromMemoryCache('cached-gpt-models');
}

Expand Down
2 changes: 1 addition & 1 deletion src/common/helpers/session.helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const createInitialClientSession = (): SessionType['client'] => ({
lastname: '',
username: '',
},
rate: null,
accountLevel: null,
selectedModel: resetSelectedModel(),
});

Expand Down
12 changes: 8 additions & 4 deletions src/conversations/create-image.conversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,16 @@ export const generateImageConversation: ConversationType = async (conversation,
const locale = await conversation.external(() => ctx.i18n.getLocale());

const { image } = conversation.session.client.selectedModel;
const rate = conversation.session.client.rate;
const clientAccountLevel = conversation.session.client.accountLevel;

if (rate && !isExpiredDate(rate.expiresAt) && !rate.images) {
if (
clientAccountLevel &&
!isExpiredDate(clientAccountLevel.expiresAt) &&
!clientAccountLevel.images
) {
return await ctx.reply(
`${ctx.t('usage-image-limit', {
expiresIn: expiresInFormat(rate.expiresAt, locale),
expiresIn: expiresInFormat(clientAccountLevel.expiresAt, locale),
})} ${ctx.t('support-contact')}`,
{ reply_to_message_id: messageId },
);
Expand Down Expand Up @@ -73,7 +77,7 @@ export const generateImageConversation: ConversationType = async (conversation,
}`;

conversation.session.store.data = aiMessage;
conversation.session.client.rate = response.clientRate;
conversation.session.client.accountLevel = response.clientAccountLevel;

await ctx.replyWithMediaGroup(
response.images.map((img) => ({ type: 'photo', media: img.url })),
Expand Down
1 change: 0 additions & 1 deletion src/locales/en.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ gpt-model-change-title = Select an available GPT model.
# Profile
profile-client-initial-message = Hey 👋, { $firstname } { $lastname }!
profile-client-select-model = Selected GPT model:
profile-client-rate = Rate:
profile-client-available-messages = GPT tokens:
profile-client-available-images = GPT images:
profile-client-date-expires = Available tokens will be updated { $expiresIn }.
Expand Down
1 change: 0 additions & 1 deletion src/locales/ru.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ gpt-model-change-title = Выберете доступную GPT модель.
# Profile
profile-client-initial-message = Привет 👋, { $firstName } { $lastName }!
profile-client-select-model = Выбраная GPT модель:
profile-client-rate = Тариф:
profile-client-available-messages = GPT токены:
profile-client-available-images = GPT изображения:
profile-client-date-expires = Доступные токены будут обновлены { $expiresIn }.
Expand Down
10 changes: 5 additions & 5 deletions src/middlewares/normalize.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { updateClientRate } from '@bot/api/clients';
import { updateClientAccountLevel } from '@bot/api/clients';
import { BotContextType } from '@bot/app/types';
import { splitMessagesByTokenLimit } from '@bot/common/helpers/gpt.helpers';
import { isExpiredDate } from '@bot/common/utils';
Expand All @@ -9,7 +9,7 @@ export const normalize = (): GrammyMiddlewareFn<BotContextType> => async (ctx, n
const locale = await ctx.i18n.getLocale();

const sessionMessages = ctx.session.client.messages;
const rate = ctx.session.client.rate;
const clientAccountLevel = ctx.session.client.accountLevel;

ctx.session.client.metadata = {
firstname: ctx?.from?.first_name || '',
Expand All @@ -18,10 +18,10 @@ export const normalize = (): GrammyMiddlewareFn<BotContextType> => async (ctx, n
username: ctx?.from?.username || '',
};

if (rate && isExpiredDate(rate.expiresAt)) {
const updatedClientRate = await updateClientRate(telegramId);
if (clientAccountLevel && isExpiredDate(clientAccountLevel.expiresAt)) {
const updatedClientRate = await updateClientAccountLevel(telegramId);

ctx.session.client.rate = updatedClientRate;
ctx.session.client.accountLevel = updatedClientRate;
}

const [headSessionMessages, tailSessionMessages] = splitMessagesByTokenLimit(sessionMessages);
Expand Down
18 changes: 9 additions & 9 deletions src/modules/profile/profile.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ export const profileModule = (bot: BotType) =>
const messageId = Number(ctx.message?.message_id);
const locale = await ctx.i18n.getLocale();

if (!ctx.session.client.rate) {
if (!ctx.session.client.accountLevel) {
const availability = await getClientAvailability(telegramId);

ctx.session.client.rate = availability?.rate ?? null;
ctx.session.client.accountLevel = availability?.accountLevel ?? null;
}

const rate = ctx.session.client.rate;
const clientAccountLevel = ctx.session.client.accountLevel;
const metadata = ctx.session.client.metadata;

const profileMessageHtml = `<b>${ctx.t('profile-client-initial-message', {
Expand All @@ -26,17 +26,17 @@ export const profileModule = (bot: BotType) =>
})}</b>\n\r<a href="tg://user?id=${telegramId}">@${
metadata.username || 'username'
}</a>\n\r\n\r${
rate
? `${ctx.t('profile-client-rate')}<b> ${rate.name} ${rate.symbol}</b>\n\r\n\r${ctx.t(
clientAccountLevel
? `<b> ${clientAccountLevel.name} ${clientAccountLevel.symbol}</b>\n\r\n\r${ctx.t(
'profile-client-available-messages',
)}<b><tg-spoiler> ${rate.gptTokens}</tg-spoiler></b>\n\r${ctx.t(
)}<b><tg-spoiler> ${clientAccountLevel.gptTokens}</tg-spoiler></b>\n\r${ctx.t(
'profile-client-available-images',
)}<b><tg-spoiler> ${rate.images}</tg-spoiler></b>\n\r\n\r<b>${ctx.t(
rate.name === PROMO_RATE
)}<b><tg-spoiler> ${clientAccountLevel.images}</tg-spoiler></b>\n\r\n\r<b>${ctx.t(
clientAccountLevel.name === PROMO_RATE
? 'profile-client-promo-date-expires'
: 'profile-client-date-expires',
{
expiresIn: expiresInFormat(rate.expiresAt, locale),
expiresIn: expiresInFormat(clientAccountLevel.expiresAt, locale),
},
)}</b>`
: `<b>${ctx.t('profile-client-unavailable-info')}</b>`
Expand Down
10 changes: 7 additions & 3 deletions src/modules/text/text.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@ export const textModule = (bot: BotType) => {
const text = String(ctx.message?.text);
const locale = await ctx.i18n.getLocale();

const rate = ctx.session.client.rate;
const clientAccountLevel = ctx.session.client.accountLevel;

if (rate && !isExpiredDate(rate.expiresAt) && !rate.gptTokens) {
if (
clientAccountLevel &&
!isExpiredDate(clientAccountLevel.expiresAt) &&
!clientAccountLevel.gptTokens
) {
return await ctx.reply(
`${ctx.t('usage-token-limit', {
expiresIn: expiresInFormat(rate.expiresAt, locale),
expiresIn: expiresInFormat(clientAccountLevel.expiresAt, locale),
})} ${ctx.t('support-contact')}`,
{ reply_to_message_id: messageId },
);
Expand Down
10 changes: 7 additions & 3 deletions src/modules/voice/voice.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,16 @@ export const voiceModule = (bot: BotType) => {
const messageId = Number(ctx.message?.message_id);
const locale = await ctx.i18n.getLocale();

const rate = ctx.session.client.rate;
const clientAccountLevel = ctx.session.client.accountLevel;

if (rate && !isExpiredDate(rate.expiresAt) && !rate.gptTokens) {
if (
clientAccountLevel &&
!isExpiredDate(clientAccountLevel.expiresAt) &&
!clientAccountLevel.gptTokens
) {
return await ctx.reply(
`${ctx.t('usage-token-limit', {
expiresIn: expiresInFormat(rate.expiresAt, locale),
expiresIn: expiresInFormat(clientAccountLevel.expiresAt, locale),
})} ${ctx.t('support-contact')}`,
{ reply_to_message_id: messageId },
);
Expand Down
2 changes: 1 addition & 1 deletion src/services/payloads/client-error.payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const apiErrorPayload = (error: any) => {
text: {
type: 'mrkdwn',
text: `*Level:*\n${level.toUpperCase()}\n\n*Source:*\n${context}\n\n*Happened at:*\n${formatDate(
new Date(timestamp),
timestamp || new Date(),
DATE_FORMAT,
)}`,
},
Expand Down
Loading