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: added multi sessions #29

Merged
merged 1 commit into from
May 15, 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
8 changes: 6 additions & 2 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,12 @@ export const createBot = async () => {

bot.use(
session({
initial: createInitialSessionData,
storage: mongo.sessionAdapter,
type: 'multi',
custom: {
storage: mongo.sessionAdapter,
initial: createInitialSessionData,
},
conversation: {},
}),
);

Expand Down
8 changes: 5 additions & 3 deletions src/helpers/gpt.helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,20 @@ export const convertGPTMessage = (

export const getGPTAnswer = async (ctx: BotContextType, text = '') => {
try {
ctx.session.messages.push({
ctx.session.custom.messages.push({
gptFormat: convertGPTMessage(text),
timestamp: Date.now(),
});

const response = await openAI.chat(ctx.session.messages.map(({ gptFormat }) => gptFormat));
const response = await openAI.chat(
ctx.session.custom.messages.map(({ gptFormat }) => gptFormat),
);

if (!response) {
return '';
}

ctx.session.messages.push({
ctx.session.custom.messages.push({
gptFormat: convertGPTMessage(response.content, MessageRoles.ASSISTANT),
timestamp: Date.now(),
});
Expand Down
3 changes: 1 addition & 2 deletions src/helpers/session.helpers.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { SessionCsvIds } from '@bot/constants';
import { SessionModelType, SessionType } from '@bot/types';

export const createInitialSessionData = (): SessionType => ({
export const createInitialSessionData = (): SessionType['custom'] => ({
username: null,
messages: [],
conversation: {},
});

export const mapUserSessionMessages = (userSession: SessionModelType) =>
Expand Down
7 changes: 3 additions & 4 deletions src/middlewares/normalize.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ import { BotContextType, GrammyMiddlewareFn } from '@bot/types';

export const normalize = (): GrammyMiddlewareFn<BotContextType> => async (ctx, next) => {
const username = ctx?.from?.username ?? '';
const sessionMessages = ctx.session.messages;
const sessionMessages = ctx.session.custom.messages;

ctx.session.username ??= username;
ctx.session.conversation ??= {};
ctx.session.custom.username ??= username;

if (sessionMessages.length >= MAX_SESSION_MESSAGES) {
ctx.session.messages = sessionMessages.slice(Math.floor(MAX_SESSION_MESSAGES / 2.5));
ctx.session.custom.messages = sessionMessages.slice(Math.floor(MAX_SESSION_MESSAGES / 2.5));
}

return next();
Expand Down
1 change: 0 additions & 1 deletion src/models/session.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const schema = new Schema<SessionModelType>({
value: {
username: { type: String },
messages: [],
conversation: { type: Object, default: {} },
},
});

Expand Down
4 changes: 2 additions & 2 deletions src/services/mongo.service.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { SessionModel, UserModel } from '@bot/models';
import { logger } from '@bot/services';
import { IMongo } from '@bot/types';
import { IMongo, SessionType } from '@bot/types';
import { fetchCachedData, removeValueFromMemoryCache, setValueToMemoryCache } from '@bot/utils';
import { ISession, MongoDBAdapter } from '@grammyjs/storage-mongodb';
import mongoose from 'mongoose';

export class MongoService implements IMongo {
sessions: mongoose.mongo.Collection<ISession>;

sessionAdapter: MongoDBAdapter<unknown>;
sessionAdapter: MongoDBAdapter<SessionType['custom']>;

constructor() {
const sessions = mongoose.connection.collection<ISession>('sessions');
Expand Down
13 changes: 7 additions & 6 deletions src/types/bot.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import { MenuFlavor } from '@grammyjs/menu';
import { Bot, Context, SessionFlavor } from 'grammy';

export type SessionType = {
username: string | null;
messages: {
gptFormat: { content: string; role: `${MessageRoles}` };
timestamp: number;
}[];
conversation: object;
custom: {
username: string | null;
messages: {
gptFormat: { content: string; role: `${MessageRoles}` };
timestamp: number;
}[];
};
};

export type BotContextType = Context &
Expand Down
3 changes: 1 addition & 2 deletions src/types/model.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ export type SessionModelType = {
key: string;
value: {
username: string;
messages: SessionType['messages'];
conversation: SessionType['conversation'];
messages: SessionType['custom']['messages'];
};
};