Skip to content
Open
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
4 changes: 3 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,14 @@ const defaultConfig = {
allowReferrer: true,
},
],
}
},
};

// console.log(addonExtenders);
const config = addonExtenders.reduce(
(acc, extender) => extender.modify(acc),
defaultConfig,
);
// const config = defaultConfig;

module.exports = config;
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ videos
.env.test.local
.env.production.local
*~
.yalc
yalc.lock
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v20.9.0
1 change: 1 addition & 0 deletions chatbotlib/.nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v20.9.0
4 changes: 4 additions & 0 deletions chatbotlib/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# npm run build

all:
yalc publish
58 changes: 58 additions & 0 deletions chatbotlib/components/AutoResizeTextarea.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// import TextareaAutosize from 'react-textarea-autosize';
// import { Button } from 'semantic-ui-react';

const TextareaAutosize = (props) => <textarea {...props} />;

import React from "react";

import { default as SVGIcon } from "./SVGIcon";
import SendIcon from "./../icons/send.svg";

export default React.forwardRef(function AutoResizeTextarea(props, ref) {
const { onSubmit, isStreaming, ...rest } = props;
const [input, setInput] = React.useState("");

const handleSubmit = (e) => {
e.preventDefault();
if (input.trim()) {
onSubmit({ message: input });
setInput("");
}
};

return (
<>
<TextareaAutosize
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
handleSubmit(e);
} else if (e.key === "Enter" && e.shiftKey) {
e.preventDefault();
setInput(input + "\n");
}
}}
{...rest}
ref={ref}
/>

<button
className="submit-btn"
disabled={isStreaming}
type="submit"
aria-label="Send"
onKeyDown={(e) => {
handleSubmit(e);
}}
onClick={(e) => {
handleSubmit(e);
}}
>
<div className="btn-icon">
<SVGIcon name={SendIcon} size="28" />
</div>
</button>
</>
);
});
156 changes: 156 additions & 0 deletions chatbotlib/components/ChatMessageBubble.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import React from "react";

import { Citation } from "./Citation";
import { SourceDetails } from "./Source";
import { transformEmailsToLinks } from "../utils";
import { default as SVGIcon } from "./SVGIcon";

import BotIcon from "./../icons/bot.svg";
import UserIcon from "./../icons/user.svg";

const CITATION_MATCH = /\[\d+\](?![[(\])])/gm;

const Markdown = React.lazy(() => import("react-markdown"));

const components = (message) => {
return {
a: (props) => {
const { node, ...rest } = props;
const value = rest.children;

if (value?.toString().startsWith("*")) {
return (
<div className="flex-none bg-background-800 inline-block rounded-full h-3 w-3 ml-2" />
);
} else {
return (
<Citation link={rest?.href} value={value} message={message}>
{rest.children}
</Citation>
);
}
},
p: ({ node, ...props }) => {
const children = props.children;
const text = React.Children.map(children, (child) => {
if (typeof child === "string") {
return transformEmailsToLinks(child);
}
return child;
});

return (
<p {...props} className="text-default">
{text}
</p>
);
},
};
};

function addCitations(text) {
return text.replaceAll(CITATION_MATCH, (match) => {
const number = match.match(/\d+/)[0];
return `${match}(${number})`;
});
}

export function ToolCall({ tool_args, tool_name, tool_result }) {
if (tool_name === "run_search") {
return (
<div className="tool_info">
Searched for: <em>{tool_args?.query || ""}</em>
</div>
);
}
return null;
}

export function ChatMessageBubble(props) {
const { message, isLoading, isMostRecent, libs, onChoice, showToolCalls } =
props;
// const { remarkGfm } = libs; // , rehypePrism
const { citations = {}, documents, type } = message;
const isUser = type === "user";

const showLoader = isMostRecent && isLoading;

// TODO: these classes are not actually used, remove them
// const colorClassName = isUser ? 'bg-lime-300' : 'bg-slate-50';
// const alignmentClassName = isUser ? 'ml-auto' : 'mr-auto';

const icon = isUser ? (
<div className="circle user">
<SVGIcon name={UserIcon} size="20" color="white" />
</div>
) : (
<div className="circle assistant">
<SVGIcon name={BotIcon} size="20" color="white" />
</div>
);

// For some reason the list is shifted by one. It's all weird
// const sources = Object.keys(citations).map(
// (index) => documents[(parseInt(index) - 1).toString()],
// );

const sources = Object.values(citations).map((doc_id) =>
documents.find((doc) => doc.db_doc_id === doc_id),
);

const inverseMap = Object.entries(citations).reduce((acc, [k, v]) => {
return { ...acc, [v]: k };
}, {});

// remarkGfm

return (
<div>
<div className="comment">
{icon}

<div>
{showToolCalls &&
message.toolCalls?.map((info, index) => (
<ToolCall key={index} {...info} />
))}
<Markdown components={components(message)} remarkPlugins={[]}>
{addCitations(message.message)}
</Markdown>

{!showLoader && sources.length > 0 && (
<>
<h5>Sources:</h5>

<div className="sources">
{sources.map((source, i) => (
<SourceDetails
source={source}
key={i}
index={inverseMap[source.db_doc_id]}
/>
))}
</div>
</>
)}
{message.relatedQuestions?.length > 0 && (
<div className="chat-related-questions">
<h5>Related Questions:</h5>
{message.relatedQuestions?.map(({ question }) => (
<div
className="relatedQuestionButton"
role="button"
onClick={() => !isLoading && onChoice(question)}
onKeyDown={() => !isLoading && onChoice(question)}
tabIndex="-1"
>
{question}
</div>
))}
</div>
)}
</div>
</div>
</div>
);
}
149 changes: 149 additions & 0 deletions chatbotlib/components/ChatWindow.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import React, { Suspense } from "react";
// import { Button, Form, Icon, Segment } from 'semantic-ui-react';

import { useScrollonStream } from "../hooks/lib";
import { default as injectLazyLibs } from "../hooks/lazyLibs";
import { useBackendChat } from "./../hooks/useBackendChat";
import AutoResizeTextarea from "./AutoResizeTextarea";
import { ChatMessageBubble } from "./ChatMessageBubble";
import EmptyState from "./EmptyState";

function Button(props) {
return <button {...props} />;
}

function Form(props) {
return <div {...props} />;
}

function Icon(props) {
return <div {...props}></div>;
}

function Segment(props) {
return <div {...props}></div>;
}

function ChatWindow({
persona,
// rehypePrism,
// remarkGfm,
placeholderPrompt = "Ask a question",
isEditMode,
...data
}) {
const { height, qgenAsistantId, enableQgen, scrollToInput, showToolCalls } =
data;
const libs = {}; // rehypePrism, remarkGfm
const { onSubmit, messages, isStreaming, clearChat } = useBackendChat({
persona,
qgenAsistantId,
enableQgen,
});
const [showLandingPage, setShowLandingPage] = React.useState(false);

const textareaRef = React.useRef(null);
const conversationRef = React.useRef(null);
const endDivRef = React.useRef(null);
const scrollDist = React.useRef(0); // Keep track of scroll distance

React.useEffect(() => {
if (!textareaRef.current || isEditMode) return;

if (isStreaming || scrollToInput) {
textareaRef.current.focus();
}
}, [isStreaming, scrollToInput, isEditMode]);

const handleClearChat = () => {
clearChat();
setShowLandingPage(true);
};

React.useEffect(() => {
setShowLandingPage(messages.length === 0);
}, [messages]);

useScrollonStream({
isStreaming,
scrollableDivRef: conversationRef,
scrollDist,
endDivRef,
distance: 500, // distance that should "engage" the scroll
debounce: 100, // time for debouncing
});

return (
<div className="chat-window">
<div className="messages">
{showLandingPage ? (
<EmptyState
onChoice={(message) => {
onSubmit({ message });
setShowLandingPage(false);
}}
persona={persona}
{...data}
/>
) : (
<>
<Segment clearing basic>
<Button
disabled={isStreaming}
onClick={handleClearChat}
className="right floated"
>
<Icon name="edit outline" /> New chat
</Button>
</Segment>
<Suspense fallback={<div>Loading suspense</div>}>
<div
ref={conversationRef}
className={`conversation ${height ? "include-scrollbar" : ""}`}
style={{ maxHeight: height }}
>
{messages.map((m, index) => (
<ChatMessageBubble
key={m.messageId}
message={m}
isMostRecent={index === 0}
isLoading={isStreaming}
libs={libs}
onChoice={(message) => {
onSubmit({ message });
}}
showToolCalls={showToolCalls}
/>
))}
<div ref={endDivRef} /> {/* End div to mark the bottom */}
</div>
</Suspense>
</>
)}
{isStreaming && <div className="loader"></div>}
</div>

<div className="chat-form">
<Form>
<div className="textarea-wrapper">
<AutoResizeTextarea
maxRows={8}
minRows={1}
ref={textareaRef}
placeholder={
messages.length > 0 ? "Ask follow-up..." : placeholderPrompt
}
isStreaming={isStreaming}
onSubmit={onSubmit}
/>
</div>
</Form>
</div>
</div>
);
}

export default injectLazyLibs([
// "rehypePrism",
// "remarkGfm",
])(ChatWindow);
Loading