Skip to content

Commit

Permalink
ai chat session and history
Browse files Browse the repository at this point in the history
  • Loading branch information
farooqpk committed Oct 29, 2024
1 parent 277c197 commit 0ea5a66
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 17 deletions.
27 changes: 21 additions & 6 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ model User {
GroupAdmin GroupAdmin[]
ChatKey ChatKey[]
messageStatus MessageStatus[]
AiChatHistory AiChatHistory[]
}

model Chat {
Expand Down Expand Up @@ -74,12 +75,12 @@ model Group {
}

model GroupAdmin {
id String @id @default(auto()) @map("_id") @db.ObjectId
adminId String @db.ObjectId
groupId String @db.ObjectId
createdAt DateTime @db.Timestamp
admin User @relation(fields: [adminId], references: [userId])
group Group @relation(fields: [groupId], references: [groupId])
id String @id @default(auto()) @map("_id") @db.ObjectId
adminId String @db.ObjectId
groupId String @db.ObjectId
createdAt DateTime @db.Timestamp
admin User @relation(fields: [adminId], references: [userId])
group Group @relation(fields: [groupId], references: [groupId])
}

model ChatKey {
Expand All @@ -104,3 +105,17 @@ model MessageStatus {
@@unique([messageId, userId])
}

model AiChatHistory {
id String @id @default(auto()) @map("_id") @db.ObjectId
userId String @db.ObjectId
role AiChatRole
content String
createdAt DateTime @default(now()) @db.Timestamp
user User @relation(fields: [userId], references: [userId])
}

enum AiChatRole {
user
model
}
46 changes: 41 additions & 5 deletions src/controllers/ai/aiChat.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { Request, Response } from "express";
import { GoogleGenerativeAI } from "@google/generative-ai";
import { GEMINI_API_KEY } from "../../config";
import { prisma } from "../../utils/prisma";
import { AiChatRole } from "@prisma/client";

const genAI = new GoogleGenerativeAI(GEMINI_API_KEY!);

export const aiChat = async (req: Request, res: Response) => {
try {
const message = req.body?.message;
const userId = req.userId;

if (!message) {
return res.status(400).json({ message: "Message is required" });
Expand All @@ -16,13 +19,46 @@ export const aiChat = async (req: Request, res: Response) => {
model: "gemini-1.5-flash-latest",
});

const result = await model.generateContent(message);
const response = result.response;
const text = response.text();
const history = await prisma.aiChatHistory.findMany({
where: {
userId,
},
select: {
content: true,
role: true,
},
});

const chat = model.startChat({
history: history?.map((item) => {
return {
role: item.role,
parts: [{ text: item.content }],
};
}),
});

const result = await chat.sendMessage(message);

const response = result?.response.text();

if (!response) {
return res.status(500).json({
message: "Failed to get response from AI model",
});
}

const newHistories = [
{ role: AiChatRole.user, content: message, userId },
{ role: AiChatRole.model, content: response, userId },
];

await prisma.aiChatHistory.createMany({
data: newHistories,
});

return res.status(200).json({ message: text });
return res.status(200).json({ message: response });
} catch (error) {
console.log(error);
return res.status(500).json({
message: "An error occurred while processing your request",
});
Expand Down
22 changes: 22 additions & 0 deletions src/controllers/ai/getHistory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Request, Response } from "express";
import { prisma } from "../../utils/prisma";

export const getAiChatHistory = async (req: Request, res: Response) => {
const userId = req.userId;

try {
const data = await prisma.aiChatHistory.findMany({
where: {
userId,
},
select: {
content: true,
role: true,
},
});

res.status(200).json(data);
} catch (error) {
res.status(500).json({ error: "Internal Server Error" });
}
};
6 changes: 6 additions & 0 deletions src/controllers/user/deleteAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,12 @@ export const deleteAccount = async (req: Request, res: Response) => {
},
});

await tx.aiChatHistory.deleteMany({
where: {
userId,
},
});

await tx.user.delete({
where: {
userId,
Expand Down
3 changes: 3 additions & 0 deletions src/routes/ai.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import Express, { Router } from "express";
import { aiChat } from "../controllers/ai/aiChat";
import { verifyToken } from "../middlewares/verifyToken";
import { getAiChatHistory } from "../controllers/ai/getHistory";

export const aiRouter: Router = Express.Router();

aiRouter.post("/chat", verifyToken, aiChat);

aiRouter.get("/get-history", verifyToken, getAiChatHistory);
6 changes: 3 additions & 3 deletions src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ authRouter.post("/login", validateData(loginSchema), login);
// request for access and refresh token after login
authRouter.post("/login/token", loginToken);

authRouter.get("/verifyRoute", verifyRoute);

authRouter.post("/refresh", createAccessTokenFromRefreshToken);

authRouter.post(
Expand All @@ -33,4 +31,6 @@ authRouter.post(
updateUsername
);

authRouter.post("/logout",logout)
authRouter.post("/logout", logout);

authRouter.get("/verifyRoute", verifyRoute);
6 changes: 3 additions & 3 deletions src/routes/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ userRouter.get("/getUsersForSearch", verifyToken, searchUsers);

userRouter.get("/:userId", verifyToken, findUser);

userRouter.post("/get-public-keys", verifyToken, findPublicKeys);
userRouter.get("/is-any-group-admin/:userId", verifyToken, isAnyGroupAdmin);

userRouter.delete("/delete-account", verifyToken,deleteAccount);
userRouter.post("/get-public-keys", verifyToken, findPublicKeys);

userRouter.get("/is-any-group-admin/:userId", verifyToken, isAnyGroupAdmin);
userRouter.delete("/delete-account", verifyToken, deleteAccount);

0 comments on commit 0ea5a66

Please sign in to comment.