Skip to content

Commit

Permalink
feat(save-chat): Persist chat logs to DB
Browse files Browse the repository at this point in the history
  • Loading branch information
Subham-Maity committed May 30, 2024
1 parent 4370d3d commit df46a2d
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 9 deletions.
3 changes: 3 additions & 0 deletions client/.evn.local.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_OUT_URL=/

PINECONE_API_KEY=
OPENAI_API_KEY=
19 changes: 16 additions & 3 deletions client/src/app/api/chat-with-user/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,6 @@ export async function POST(req: Request) {
// console.log(
// "API HIT ************* Chat Completion" + JSON.stringify(prompt),
// );

// Dubbugging Purpose
// console.log(context + "context-data");

const response = await openai.createChatCompletion({
Expand All @@ -66,7 +64,22 @@ export async function POST(req: Request) {
],
stream: true,
});
const stream = OpenAIStream(response);
const stream = OpenAIStream(response, {
onStart: async () => {
// Call the NestJS backend to save the user message
await axios.post(`/chat/saveUserMessage`, {
chatId,
content: lastMessage.content,
});
},
onCompletion: async (completion) => {
// Call the NestJS backend to save the AI message
await axios.post(`/chat/saveAIMessage`, {
chatId,
content: completion,
});
},
});
return new StreamingTextResponse(stream);
} catch (error) {}
}
17 changes: 16 additions & 1 deletion client/src/components/chat/chat/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,28 @@ import MessageList from "@/components/chat/chat/list/message-list";
import { HoverBorderGradient } from "@/components/ui/aceternity/hover-border-gradient";
import { useChat } from "ai/react";
import { Textarea } from "@/components/ui/shadcn/textarea";
import { useQuery } from "react-query";
import { Message } from "ai";
import createAxiosInstance from "@/hook/axios/axios";
const Chat = ({ chatId }: { chatId: string }) => {
const axios = createAxiosInstance(0);
const { data, isLoading } = useQuery({
queryKey: ["chat", chatId],
queryFn: async () => {
const response = await axios.post<Message[]>("/chat/getChat/", {
chatId,
});
return response.data;
},
});
const { input, handleInputChange, handleSubmit, messages } = useChat({
api: "/api/chat-with-user",
body: {
chatId,
},
initialMessages: data || [],
});

React.useEffect(() => {
const messageContainer = document.getElementById("message-container");
if (messageContainer) {
Expand All @@ -22,7 +37,7 @@ const Chat = ({ chatId }: { chatId: string }) => {
}, [messages]);
return (
<div id="message-container">
<MessageList messages={messages} />
<MessageList messages={messages} isLoading={isLoading} />

<form onSubmit={handleSubmit}>
<div className="grid mx-6 gap-2">
Expand Down
11 changes: 10 additions & 1 deletion client/src/components/chat/chat/list/message-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,21 @@ import { cn } from "@/lib/utils";
import { Message } from "ai/react";
import React from "react";
import { Card, CardContent } from "@/components/ui/shadcn/card";
import { Loader2 } from "lucide-react";

type Props = {
messages: Message[];
isLoading: boolean;
};

const MessageList = ({ messages }: Props) => {
const MessageList = ({ messages, isLoading }: Props) => {
if (isLoading) {
return (
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
<Loader2 className="w-6 h-6 animate-spin" />
</div>
);
}
if (!messages) return <></>;
return (
<Card className="mx-6 mb-1 dark:bg-stone-700 bg-white">
Expand Down
12 changes: 8 additions & 4 deletions server/src/chat/chat.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,26 @@ export class ChatController {
}
@Post('saveUserMessage')
async saveUserMessage(
@Body('chatId') chatId: number,
@Body('chatId') chatId: string,
@Body('content') content: string,
) {
return this.chatService.saveUserMessage(chatId, content);
return this.chatService.saveUserMessage(parseInt(chatId), content);
}

@Post('saveAIMessage')
async saveAIMessage(
@Body('chatId') chatId: number,
@Body('chatId') chatId: string,
@Body('content') content: string,
) {
return this.chatService.saveAIMessage(chatId, content);
return this.chatService.saveAIMessage(parseInt(chatId), content);
}

@Get(':chatId')
async getChatById(@Param('chatId') chatId: string) {
return this.chatService.getChatByChatId(parseInt(chatId));
}
@Post('getChat')
async getChatMessages(@Body('chatId') chatId: string) {
return this.chatService.getChatMessages(parseInt(chatId));
}
}
12 changes: 12 additions & 0 deletions server/src/chat/chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,16 @@ export class ChatService {

return chat;
}
async getChatMessages(chatId: number) {
const chat = await this.prisma.chat.findUnique({
where: { id: chatId },
include: { messages: true },
});

if (!chat) {
throw new Error('Chat not found');
}

return chat.messages;
}
}

0 comments on commit df46a2d

Please sign in to comment.