Skip to content

Commit

Permalink
Merge pull request #23 from youngle316/dev
Browse files Browse the repository at this point in the history
feat: track conversation
  • Loading branch information
youngle316 authored Mar 5, 2023
2 parents d9095e4 + 801057b commit 985f247
Show file tree
Hide file tree
Showing 8 changed files with 45 additions and 24 deletions.
7 changes: 7 additions & 0 deletions lib/chatGPTApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { ChatGPTAPI } from 'chatgpt';

const api = new ChatGPTAPI({
apiKey: process.env.OPENAI_API_KEY as string
});

export { api };
17 changes: 5 additions & 12 deletions lib/queryApi.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
import { ChatGPTAPI } from 'chatgpt';

const chatgptQuery = async (prompt: string) => {
const api = new ChatGPTAPI({
apiKey: process.env.OPENAI_API_KEY || ''
});
import { api } from './chatGPTApi';

const chatgptQuery = async (prompt: string, parentMessageId: string) => {
const res = await api
.sendMessage(prompt)
.sendMessage(prompt, { parentMessageId: parentMessageId || undefined })
.then((res) => {
return res.text;
return res;
})
.catch(
() =>
`ChatGPT was unable to find an answer to your question. Please try again later.`
);
.catch();

return res;
};
Expand Down
11 changes: 11 additions & 0 deletions src/atom/AtomChat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { atom } from 'recoil';

/**
* This is the state for the parent message id. Track the conversation.
*/
const parentMessageIdState = atom({
key: 'parentMessageIdState',
default: ''
});

export { parentMessageIdState };
10 changes: 10 additions & 0 deletions src/components/Chat.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
'use client';

import { useEffect } from 'react';
import { useSetRecoilState } from 'recoil';
import { ArrowDownCircleIcon } from '@heroicons/react/24/outline';
import { collection, orderBy, query } from 'firebase/firestore';
import { useSession } from 'next-auth/react';
import { useCollection } from 'react-firebase-hooks/firestore';
import { db } from '../../firebase';
import Message from './Message';
import { parentMessageIdState } from '@/atom/AtomChat';

type ChatProps = {
chatId: string;
};

function Chat({ chatId }: ChatProps) {
const { data: session } = useSession();
const setParentMessageId = useSetRecoilState(parentMessageIdState);

const [messages] = useCollection(
session &&
Expand All @@ -29,6 +33,12 @@ function Chat({ chatId }: ChatProps) {
)
);

useEffect(() => {
const data = messages?.docs;
const lastData = data && data[data.length - 1];
setParentMessageId(lastData ? lastData.get('parentMessageId')! : '');
}, [messages]);

return (
<div className="flex-1 overflow-y-auto overflow-x-hidden">
{messages?.empty && (
Expand Down
12 changes: 5 additions & 7 deletions src/components/ChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import { addDoc, collection, serverTimestamp } from 'firebase/firestore';
import { useSession } from 'next-auth/react';
import { FormEvent, useState } from 'react';
import { toast } from 'react-hot-toast';
import useSWR from 'swr';
import { db } from '../../firebase';
import { useRecoilState } from 'recoil';
import { parentMessageIdState } from '@/atom/AtomChat';

type ChatProps = {
chatId: string;
Expand All @@ -15,10 +16,7 @@ type ChatProps = {
function ChatInput({ chatId }: ChatProps) {
const [prompt, setPrompt] = useState('');
const { data: session } = useSession();

const { data: model } = useSWR('model', {
fallbackData: 'text-davinci-003'
});
const [parentMessageId] = useRecoilState(parentMessageIdState);

const sendMessage = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
Expand Down Expand Up @@ -62,8 +60,8 @@ function ChatInput({ chatId }: ChatProps) {
body: JSON.stringify({
prompt: input,
chatId,
model,
session
session,
parentMessageId
})
}).then(() => {
toast.success('ChatGPT has responded!', {
Expand Down
1 change: 0 additions & 1 deletion src/components/ChatRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ function ChatRow({ id }: ChatRowProps) {
router.replace('/');
};

//
const linkToChat = () => {
openStateChange(false);
};
Expand Down
10 changes: 6 additions & 4 deletions src/pages/api/askQuestion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import { adminDb } from 'firebaseAdmin';

type Data = {
answer: string;
result?: any;
};

export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const { prompt, chatId, model, session } = req.body;
const { prompt, chatId, model, session, parentMessageId } = req.body;

if (!prompt) {
res.status(400).json({ answer: 'Please Provider A Prompt' });
Expand All @@ -21,11 +22,12 @@ export default async function handler(
res.status(400).json({ answer: 'Please Provider A Valid Chat ID' });
}

const response = await chatgptQuery(prompt);
const result = await chatgptQuery(prompt, parentMessageId);

const message: Message = {
parentMessageId: result.id,
text:
response ||
result.text ||
'ChatGPT was unable to find an answer to your question. Please try again later.',
createAt: admin.firestore.Timestamp.now(),
user: {
Expand All @@ -44,5 +46,5 @@ export default async function handler(
.collection('messages')
.add(message);

res.status(200).json({ answer: message.text });
res.status(200).json({ answer: message.text, result });
}
1 change: 1 addition & 0 deletions typing.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
interface Message {
parentMessageId?: string;
text: string;
createAt: admin.firestore.Timestamp;
user: {
Expand Down

0 comments on commit 985f247

Please sign in to comment.