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

Ai chat bot #126

Merged
merged 7 commits into from
May 28, 2024
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
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,11 @@
"dotenv": "^16.0.3",
"globby": "^13.1.3",
"jsdoc-api": "^7.1.1",
"lucide-react": "^0.379.0",
"nanostores": "^0.5.13",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-markdown": "^9.0.1",
"rehype-autolink-headings": "^6.1.1",
"rehype-slug": "^5.0.1",
"remark-copy-linked-files": "^1.5.0",
Expand Down
1 change: 1 addition & 0 deletions public/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,7 @@ th {
p code, li code, blockquote code, pre{
background-color: var(--theme-body-bg);
border: var(--theme-border);
border-radius: .65rem;
}

blockquote, aside.note {
Expand Down
134 changes: 134 additions & 0 deletions src/components/AiChatBot/AiChatBot.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import React, { useEffect, useRef, useState } from 'react';
import { Chat } from './Chat';
import { Modal } from './Modal';
import { Message } from './index';



const AiChatBot: React.FC = () => {
const [messages, setMessages] = useState<Message[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [isChatOpen, setIsChatOpen] = useState<boolean>(false);
const [hasSentMessage, setHasSentMessage] = useState<boolean>(false);
const messagesEndRef = useRef<HTMLDivElement>(null);

const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};

const handleSend = async (message: Message) => {
const updatedMessages = [...messages, message];
setMessages(updatedMessages);
setLoading(true);
setHasSentMessage(true);

const apiKey = process.env.DOCS_KEY;
const userQuestion = message.content;

try {
const response = await fetch('https://api.openreplay.com/ai/docs/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({
question: userQuestion,
n_references: 3,
}),
});

console.debug('API response status:', response.status);
if (!response.ok) {
setLoading(false);
throw new Error(`API response error: ${response.statusText}`);
}

const data = await response.json();
console.debug('API response data:', data);
if (!data) return;

setLoading(false);

// Format the response and references
const formattedResponse = `${data.response}\n\n**Related resources:**\n${data.references.map((ref: { url: string, title: string }) => `- [${ref.title}](${ref.url})`).join('\n')}`;

setMessages((messages) => [
...messages,
{ role: 'assistant', content: formattedResponse },
]);
} catch (error) {
console.error('Error fetching chat response:', error);
setLoading(false);
}
};




const handleReset = () => {
setMessages([
{
role: 'assistant',
content: 'Welcome to the OpenReplay Docs AI Assistant. What can I help you with?',
},
]);
setHasSentMessage(false);
};

useEffect(() => {
scrollToBottom();
}, [messages]);

useEffect(() => {
setMessages([
{
role: 'assistant',
content: 'Welcome to the OpenReplay Docs AI Assistant. What can I help you with?',
},
]);
}, []);

return (
<div>
<style>
{`
.bg-blue-500 {
background-color: rgb(57 77 255);
}
`}
</style>
<div className="flex flex-col h-screen">
<div className="flex-1 overflow-auto sm:px-10 pb-4 sm:pb-10">
<div className="max-w-[800px] mx-auto mt-4 sm:mt-12"></div>
</div>
</div>

<button
className="fixed bottom-4 right-4 bg-gradient-to-r from-teal-500 bg-indigo-600 hover:bg-blue-700 cursor-pointer rounded-full text-white font-bold py-2 px-4 rounded shadow-lg z-50 flex items-center gap-2 drop-shadow-sm"
onClick={() => {
setIsChatOpen(!isChatOpen);
console.debug(`Button, isChatOpen: ${!isChatOpen}`);
}}
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" className="lucide lucide-sparkles"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/><path d="M20 3v4"/><path d="M22 5h-4"/><path d="M4 17v2"/><path d="M5 18H3"/></svg>
Ask AI
</button>

{isChatOpen && (
<Modal isOpen={isChatOpen} onClose={() => setIsChatOpen(false)}>
<Chat
messages={messages}
loading={loading}
onSend={handleSend}
onReset={handleReset}
hasSentMessage={hasSentMessage} // Pass the state as a prop
/>
<div ref={messagesEndRef}></div>
</Modal>
)}
</div>
);
};

export default AiChatBot;
43 changes: 43 additions & 0 deletions src/components/AiChatBot/AiChatBotStyles.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
.textareaContainer {
position: relative;
display: inline-block;
border-radius: .75rem;
padding: 2px;
width: 100%;
background-color: #fff;
}

.textareaContainer::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: .75rem;
padding: 2px;
background: linear-gradient(-25deg, rgb(57, 78, 255), rgb(62, 170, 175), rgb(60, 207, 101));
-webkit-mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
-webkit-mask-composite: destination-out;
mask-composite: exclude; /* This property ensures that the background only appears as a border */
}

.textarea {
width: 100%;
height: 100px; /* Adjust height as needed */
border: none;
resize: none;
padding: 10px;
border-radius: .75rem; /* Apply border-radius to textarea */
position: relative;
z-index: 1;
background: white; /* Ensure textarea background color covers the content */
border-color: transparent;
}
.textarea:focus-visible, .textarea:focus, .textarea:active{
border-color: transparent;
outline: transparent;
}

39 changes: 39 additions & 0 deletions src/components/AiChatBot/Chat.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Message } from ".";
import { FC } from "react";
import { ChatInput } from "./ChatInput";
import { ChatLoader } from "./ChatLoader";
import { ChatMessage } from "./ChatMessage";
import React from 'react';


interface Props {
messages: Message[];
loading: boolean;
onSend: (message: Message) => void;
onReset: () => void;
hasSentMessage: boolean; // Add this prop
}

export const Chat: FC<Props> = ({ messages, loading, onSend, onReset, hasSentMessage }) => {
return (
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto sm:border border-neutral-300">
{messages.map((message, index) => (
<div key={index} className="my-1 sm:my-1.5">
<ChatMessage message={message} />
</div>
))}

{loading && (
<div className="my-1 sm:my-1.5">
<ChatLoader />
</div>
)}
</div>

<div className="mt-4 sm:mt-8 bottom-[56px] left-0 w-full">
<ChatInput onSend={onSend} hasSentMessage={hasSentMessage} /> {/* Pass the prop here */}
</div>
</div>
);
};
103 changes: 103 additions & 0 deletions src/components/AiChatBot/ChatInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import React, { FC, KeyboardEvent, useEffect, useRef, useState } from "react";
import { Message } from ".";
import { CornerDownLeft } from 'lucide-react';
import styles from './AiChatBotStyles.module.css';

interface Props {
onSend: (message: Message) => void;
hasSentMessage: boolean;
}

export const ChatInput: FC<Props> = ({ onSend, hasSentMessage }) => {
const [content, setContent] = useState<string>("");
const [remainingChars, setRemainingChars] = useState<number>(300);

const textareaRef = useRef<HTMLTextAreaElement>(null);

const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value;
if (value.length <= 300) {
setContent(value);
setRemainingChars(300 - value.length);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can be simply calculated property

const remainingChars = React.useMemo(() => 300 - content.length, [content])

}
};

const handleSend = () => {
if (!content.trim()) {
alert("Please enter a message");
return;
}
onSend({ role: "user", content });
setContent("");
setRemainingChars(300);
};

const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
}
};

useEffect(() => {
if (textareaRef.current) {
textareaRef.current.focus();
}
}, []);

useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = "inherit";
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
}
}, [content]);

const suggestedPrompts = [
"Get Started with OpenReplay",
"How can I deploy OpenReplay on Docker",
"How can I troubleshoot session replays"
];

return (
<div className="relative">
{!hasSentMessage && (
<div className="mb-4">
<h3 className="text-lg font-semibold">Suggested Prompts</h3>
<div className="flex flex-col gap-2 mt-2">
{suggestedPrompts.map((prompt, index) => (
<button
key={index}
className="bg-white hover:border-blue-500 text-gray-700 py-1 px-2 rounded-xl border border-transparent text-left shadow-sm transition-colors w-fit"
onClick={() => onSend({ role: "user", content: prompt })}
>
{prompt}
</button>
))}
</div>
</div>
)}

<div className={`${styles.textareaContainer} w-100`}>
<textarea
ref={textareaRef}
className={`${styles.textarea} font-sans text-base w-100`}
placeholder="Ask OpenReplay AI a question"
value={content}
rows={1}
onChange={handleChange}
onKeyDown={handleKeyDown}
maxLength={300}
/>
<button
onClick={handleSend}
className="absolute z-10 right-2 bottom-3 h-8 w-8 flex items-center justify-center rounded p-1 bg-transparent text-indigo-500 hover:opacity-80"
>
<CornerDownLeft />
</button>
</div>
<div className="text-sm text-gray-500 mt-1">
{remainingChars} characters remaining
</div>
</div>
);
};
19 changes: 19 additions & 0 deletions src/components/AiChatBot/ChatLoader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { FC } from "react";
import React from 'react';

interface Props {}

export const ChatLoader: FC<Props> = () => {
return (
<div className="flex flex-col flex-start">
<div
className={`flex items-center bg-gradient-to-r from-teal-50 bg-indgo-50 text-neutral-900 rounded-xl px-4 py-2 w-fit`}
style={{ overflowWrap: "anywhere" }}
>
<span className="loading-text flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader"><path d="M12 2v4"/><path d="m16.2 7.8 2.9-2.9"/><path d="M18 12h4"/><path d="m16.2 16.2 2.9 2.9"/><path d="M12 18v4"/><path d="m4.9 19.1 2.9-2.9"/><path d="M2 12h4"/><path d="m4.9 4.9 2.9 2.9"/><animateTransform attributeName="transform" type="rotate" from="0 0 0" to="360 0 0" dur=".75s" repeatCount="indefinite"/></svg>
Hang tight, getting your answer right away...</span>
</div>
</div>
);
};
Loading
Loading