-
Notifications
You must be signed in to change notification settings - Fork 21
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
Ai chat bot #126
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
0db9413
Add AI chat bot
ghaidabouchaala 56bd5ac
Updated AIChatBot styles.
sudheer-salavadi 74f3bc8
Minor UI udpate
sudheer-salavadi da51e81
add user input limit
ghaidabouchaala e306bec
update chat behavior
ghaidabouchaala 3ac8858
update key definition
ghaidabouchaala 435df27
update debug data
ghaidabouchaala File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
}; | ||
|
||
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> | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | ||
); | ||
}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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])