123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275 |
- import { useRef, useState, useEffect } from 'react';
- import Layout from '@/components/layout';
- import styles from '@/styles/Home.module.css';
- import { Message } from '@/types/chat';
- import Image from 'next/image';
- import ReactMarkdown from 'react-markdown';
- import LoadingDots from '@/components/ui/LoadingDots';
- import { Document } from 'langchain/document';
- import {
- Accordion,
- AccordionContent,
- AccordionItem,
- AccordionTrigger,
- } from '@/components/ui/accordion';
- // require('dotenv') .config()
- // import {run} from '@/scripts/ingest-data';
- export default function Home() {
- // run();
- //console.log(process.env.OPENAI_API_KEY)
- const [query, setQuery] = useState<string>('');
- const [loading, setLoading] = useState<boolean>(false);
- const [error, setError] = useState<string | null>(null);
- const [messageState, setMessageState] = useState<{
- messages: Message[];
- pending?: string;
- history: [string, string][];
- pendingSourceDocs?: Document[];
- }>({
- messages: [
- {
- message: 'Hi, what would you like to learn about this legal case?',
- type: 'apiMessage',
- },
- ],
- history: [],
- });
- const { messages, history } = messageState;
- const messageListRef = useRef<HTMLDivElement>(null);
- const textAreaRef = useRef<HTMLTextAreaElement>(null);
- useEffect(() => {
- textAreaRef.current?.focus();
- }, []);
- //handle form submission
- async function handleSubmit(e: any) {
- e.preventDefault();
- setError(null);
- if (!query) {
- alert('Please input a question');
- return;
- }
- const question = query.trim();
- setMessageState((state) => ({
- ...state,
- messages: [
- ...state.messages,
- {
- type: 'userMessage',
- message: question,
- },
- ],
- }));
- setLoading(true);
- setQuery('');
- try {
- const response = await fetch('/api/chat', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- question,
- history,
- }),
- });
- const data = await response.json();
- console.log('data', data);
- if (data.error) {
- setError(data.error);
- } else {
- setMessageState((state) => ({
- ...state,
- messages: [
- ...state.messages,
- {
- type: 'apiMessage',
- message: data.text,
- sourceDocs: data.sourceDocuments,
- },
- ],
- history: [...state.history, [question, data.text]],
- }));
- }
- console.log('messageState', messageState);
- setLoading(false);
- //scroll to bottom
- messageListRef.current?.scrollTo(0, messageListRef.current.scrollHeight);
- } catch (error) {
- setLoading(false);
- setError('An error occurred while fetching the data. Please try again.');
- console.log('error', error);
- }
- }
- //prevent empty submissions
- const handleEnter = (e: any) => {
- if (e.key === 'Enter' && query) {
- handleSubmit(e);
- } else if (e.key == 'Enter') {
- e.preventDefault();
- }
- };
- return (
- <>
- <Layout>
- <div className="mx-auto flex flex-col gap-4">
- <h1 className="text-2xl font-bold leading-[1.1] tracking-tighter text-center">
- Chat With Your Legal Docs
- </h1>
- <main className={styles.main}>
- <div className={styles.cloud}>
- <div ref={messageListRef} className={styles.messagelist}>
- {messages.map((message, index) => {
- let icon;
- let className;
- if (message.type === 'apiMessage') {
- icon = (
- <Image
- key={index}
- src="/bot-image.png"
- alt="AI"
- width="40"
- height="40"
- className={styles.boticon}
- priority
- />
- );
- className = styles.apimessage;
- } else {
- icon = (
- <Image
- key={index}
- src="/usericon.png"
- alt="Me"
- width="30"
- height="30"
- className={styles.usericon}
- priority
- />
- );
- // The latest message sent by the user will be animated while waiting for a response
- className =
- loading && index === messages.length - 1
- ? styles.usermessagewaiting
- : styles.usermessage;
- }
- return (
- <>
- <div key={`chatMessage-${index}`} className={className}>
- {icon}
- <div className={styles.markdownanswer}>
- <ReactMarkdown linkTarget="_blank">
- {message.message}
- </ReactMarkdown>
- </div>
- </div>
- {message.sourceDocs && (
- <div
- className="p-5"
- key={`sourceDocsAccordion-${index}`}
- >
- <Accordion
- type="single"
- collapsible
- className="flex-col"
- >
- {message.sourceDocs.map((doc, index) => (
- <div key={`messageSourceDocs-${index}`}>
- <AccordionItem value={`item-${index}`}>
- <AccordionTrigger>
- <h3>Source {index + 1}</h3>
- </AccordionTrigger>
- <AccordionContent>
- <ReactMarkdown linkTarget="_blank">
- {doc.pageContent}
- </ReactMarkdown>
- <p className="mt-2">
- <b>Source:</b> {doc.metadata.source}
- </p>
- </AccordionContent>
- </AccordionItem>
- </div>
- ))}
- </Accordion>
- </div>
- )}
- </>
- );
- })}
- </div>
- </div>
- <div className={styles.center}>
- <div className={styles.cloudform}>
- <form onSubmit={handleSubmit}>
- <textarea
- disabled={loading}
- onKeyDown={handleEnter}
- ref={textAreaRef}
- autoFocus={false}
- rows={1}
- maxLength={512}
- id="userInput"
- name="userInput"
- placeholder={
- loading
- ? 'Waiting for response...'
- : 'What is this legal case about?'
- }
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- className={styles.textarea}
- />
- <button
- type="submit"
- disabled={loading}
- className={styles.generatebutton}
- >
- {loading ? (
- <div className={styles.loadingwheel}>
- <LoadingDots color="#000" />
- </div>
- ) : (
- // Send icon SVG in input field
- <svg
- viewBox="0 0 20 20"
- className={styles.svgicon}
- xmlns="http://www.w3.org/2000/svg"
- >
- <path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z"></path>
- </svg>
- )}
- </button>
- </form>
- </div>
- </div>
- {error && (
- <div className="border border-red-400 rounded-md p-4">
- <p className="text-red-500">{error}</p>
- </div>
- )}
- </main>
- </div>
- <footer className="m-auto p-4">
- <a href="https://twitter.com/mayowaoshin">
- Powered by LangChainAI. Demo built by Mayo (Twitter: @mayowaoshin).
- </a>
- </footer>
- </Layout>
- </>
- );
- }
|