Skip to content

Commit

Permalink
Merge pull request #136 from openreplay/ai-chat-bot
Browse files Browse the repository at this point in the history
Add continue answer
  • Loading branch information
ghaidabouchaala authored Jun 18, 2024
2 parents 069e22a + ad8f2c7 commit 8310373
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 5 deletions.
89 changes: 88 additions & 1 deletion src/components/AiChatBot/AiChatBot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const AiChatBot: React.FC = () => {
const [hasSentMessage, setHasSentMessage] = useState<boolean>(false);
const [assistantHistory, setAssistantHistory] = useState<string[]>([]);
const [userHistory, setUserHistory] = useState<string[]>([]);
const [continuationMessageId, setContinuationMessageId] = useState<number | null>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);

const scrollToBottom = () => {
Expand Down Expand Up @@ -45,6 +46,7 @@ const AiChatBot: React.FC = () => {
assistant_history: assistantHistory,
user_history: userHistory,
n_references: 3,
resume: false,
});

console.debug('Request body:', body);
Expand All @@ -71,7 +73,7 @@ const AiChatBot: React.FC = () => {
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')}`;
const formattedResponse = `${data.response.join(' ')}\n\n**Related resources:**\n${data.references.map((ref: { url: string, title: string }) => `- [${ref.title}](${ref.url})`).join('\n')}`;

setMessages((messages) => [
...messages,
Expand All @@ -85,12 +87,90 @@ const AiChatBot: React.FC = () => {
} else {
console.error('Response is not a string:', data.response);
}

// Check endReason and set continuation message
if (data.endReason === "length") {
setContinuationMessageId(updatedMessages.length);
setMessages((messages) => [
...messages,
{ role: 'assistant', content: "Continue generating answer? Click here!", isContinuation: true },
]);
} else {
setContinuationMessageId(null);
}
} catch (error) {
console.error('Error fetching chat response:', error);
setLoading(false);
}
};

const handleContinue = async () => {
if (continuationMessageId === null) return;

setLoading(true);
const lastAssistantMessage = messages[continuationMessageId].content;
const apiKey = process.env.DOCS_KEY;

try {
const body = JSON.stringify({
question: lastAssistantMessage,
assistant_history: assistantHistory,
user_history: userHistory,
n_references: 3,
resume: true,
});

console.debug('Request body for continuation:', body);

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

console.debug('API response status for continuation:', 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 for continuation:', data);
if (!data) return;

setLoading(false);

// Check endReason and update continuation message id if needed
if (data.endReason === "length") {
setContinuationMessageId(messages.length);
} else {
setContinuationMessageId(null);
}

// Format the response and references
const formattedResponse = `${data.response.join(' ')}\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 },
]);

// Ensure data.response is a string before updating history
const responseContent = Array.isArray(data.response) ? data.response.join(' ') : data.response;
if (typeof responseContent === 'string') {
updateHistory('assistant', responseContent);
} else {
console.error('Response is not a string:', data.response);
}
} catch (error) {
console.error('Error fetching chat continuation response:', error);
setLoading(false);
}
};

const handleReset = () => {
setMessages([
{
Expand All @@ -116,6 +196,12 @@ const AiChatBot: React.FC = () => {
]);
}, []);

const handleAssistantMessageClick = (messageId: number) => {
if (messages[messageId].isContinuation) {
handleContinue();
}
};

return (
<div>
<style>
Expand Down Expand Up @@ -150,6 +236,7 @@ const AiChatBot: React.FC = () => {
onSend={handleSend}
onReset={handleReset}
hasSentMessage={hasSentMessage}
onMessageClick={handleAssistantMessageClick}
/>
<div ref={messagesEndRef}></div>
</Modal>
Expand Down
13 changes: 9 additions & 4 deletions src/components/AiChatBot/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,26 @@ 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
hasSentMessage: boolean;
onMessageClick: (index: number) => void;
}

export const Chat: FC<Props> = ({ messages, loading, onSend, onReset, hasSentMessage }) => {
export const Chat: FC<Props> = ({ messages, loading, onSend, onReset, hasSentMessage, onMessageClick }) => {
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">
<div
key={index}
className="my-1 sm:my-1.5"
onClick={() => message.isContinuation && onMessageClick(index)} // Add click handler for continuation messages
style={{ cursor: message.isContinuation ? 'pointer' : 'default' }} // Change cursor style for continuation messages
>
<ChatMessage message={message} />
</div>
))}
Expand Down
1 change: 1 addition & 0 deletions src/components/AiChatBot/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export interface Message {
role: Role;
content: string;
isContinuation?: boolean;
}

export type Role = "assistant" | "user";

0 comments on commit 8310373

Please sign in to comment.