diff --git a/README.md b/README.md index c60ea6f..f68b1ac 100644 --- a/README.md +++ b/README.md @@ -21,10 +21,30 @@ React-Chatbot is a UI widget for adding [Vectara](https://vectara.com/)-powered ## UI -_Screenshots coming soon!_ +React-Chatbot adds a button to the lower right corner of your application: + +Chatbot toggle button + +When the button is clicked, a chat window opens, where your users can start a conversation with your data: + +Initial chat window state + +The Vectara platform responds to user messages and presents a list of references that support its answer: + +Chat message answer + +When the chat API returns an error, the UI allows the user to retry sending the message: + +Retry message + +React-Chatbot is also ready for use on mobile sites, taking the fullscreen when the chat window is opened: + +Mobile-friendly chat window ## Use it in your application +### Use the chatbot directly + Install React-Chatbot: ```shell @@ -40,53 +60,140 @@ import { ReactChatbot } from "@vectara/react-chatbot"; } isInitiallyOpen={false} + zIndex={ /* (optional) number representing the z-index the component should have */ } />; ``` -### Configuration options +#### Configuration Options -#### `customerId` (required) +##### `customerId` (required) Every Vectara account is associated with a customer ID. You can find your customer ID by logging into the [Vectara Console](https://console.vectara.com/) and opening your account dropdown in the top-right corner. -#### `corpusIds` (required) +##### `corpusIds` (required) After you [create a corpus](https://docs.vectara.com/docs/console-ui/creating-a-corpus), you can find its ID by navigating to the corpus and looking in the top-left corner, next to the corpus name. -#### `apiKey` (required) +##### `apiKey` (required) API keys enable applications to access data inside of corpora. Learn how to [create a **QueryService** API key](https://docs.vectara.com/docs/console-ui/manage-api-access#create-an-api-key). -#### `title` (optional) +##### `title` (optional) Configure the title in the header of the chatbot window. -#### `placeholder` (optional) +##### `placeholder` (optional) Configure the placeholder text in the chatbot's input. -#### `emptyStateDisplay` (optional) +##### `emptyStateDisplay` (optional) Configure JSX content to render in the messages window when there are no messages to display. -#### `isInitiallyOpen` (optional) +##### `isInitiallyOpen` (optional) Set the chat window to be opened on initial render. -#### `inputSize` (optional) +##### `inputSize` (optional) + +Control the size of the input - either "large" (18px) or "medium" (14px) + +##### `zIndex` (optional) + +Customize the z-index of the chatbot widget + +### Use your own views with the useChat hook + +Install React-Chatbot: + +```shell +npm install --save @vectara/react-chatbot +``` + +Then use the `useChat` hook in your application like this: + +```js +import { useChat } from "@vectara/react-chatbot/lib"; + +/* snip */ + +const { sendMessage, messageHistory, isLoading, hasError } = useChat( + "CUSTOMER_ID", + ["CORPUS_ID_1", "CORPUS_ID_2", "CORPUS_ID_N"], + "API_KEY" +); +``` + +The values returned by the hook can be passed on to your custom components as props or used in any way you wish. + +#### Hook Values + +##### sendMessage: `async ({ query: string; isRetry?: boolean }) => void;` + +This is used to send a message to the chat API. Send `true` for the optional `isRetry` flag to if this is retrying a previously failed message. This allows the internal logic to correctly link the next successful answer to the failed query. + +##### messageHistory: `ChatTurn[]` + +This is an array of objects representing question and answer pairs from the entire conversation. Each pair is a `ChatTurn` object. More information on types can be found [here](src/types.ts). + +##### isLoading: `boolean` + +A boolean value indicating whether or not a chat API request is still pending -Used to control the size of the input - either "large" (18px) or "medium" (14px) +##### hasError: `boolean` + +A boolean value indicating whether or not the most recent chat API request encountered an error + +### Usage with SSR Frameworks + +Using React-Chatbot with SSR frameworks may require additional infrastucture. Here are some common gotchas: + +#### Next.js + +Since React-Chatbot requires a few browser-only features to function, we need to defer the rendering of the component to the client. In order to do this, you will need to: + +1. Use the `"use client"` directive in the file that imports ReactChatbot. +2. Use a one-time `useEffect` call in ReactChatbot's consumer. The useEffect callback should set the rendered widget as a state on the consumer component. +3. Include the rendered widget state value in the rendered consumer component. + +Example: + +``` +"use client"; +export const App = (props: Props): ReactNode => { + const [chatWidget, setChatWidget] = useState(null); + + /* the rest of your code */ + + useEffect(() => { + setChatWidget( + + ); + }, []); + + return ( + <> + { /* other content */ } + + ) +}; + +``` ### Set up your data -React-Chat uses the data in your Vectara corpus to provide factual responses. To set this up: +React-Chatbot uses the data in your Vectara corpus to provide factual responses. To set this up: 1. [Create a free Vectara account](https://console.vectara.com/signup). 2. [Create a corpus and add data to it](https://docs.vectara.com/docs/console-ui/creating-a-corpus). @@ -94,7 +201,7 @@ React-Chat uses the data in your Vectara corpus to provide factual responses. To **Pro-tip:** After you create an API key, navigate to your corpus and click on the "Access control" tab. Find your API key on the bottom and select the "Copy all" option to copy your customer ID, corpus ID, and API key. This gives you all the data you need to configure your `` instance. -![Copy all option](https://raw.githubusercontent.com/vectara/react-chat/main/images/copyAll.jpg) +![Copy all option](https://raw.githubusercontent.com/vectara/react-chatbot/main/images/copyAll.jpg) ## Maintenance diff --git a/docs/src/index.tsx b/docs/src/index.tsx index d7a68a3..341e922 100644 --- a/docs/src/index.tsx +++ b/docs/src/index.tsx @@ -220,7 +220,7 @@ const App = () => {

For help,{" "} - + read the docs.

@@ -236,6 +236,65 @@ const App = () => { {generateCodeSnippet(customerId, corpusIds, apiKey, title, placeholder, inputSize, emptyStateJsx)} + + + +

Create your own view

+
+ + + + +

+ React-Chatbot also exposes a useChat hook that sends and receives data to/from the chat API. This is + perfect for rolling your own components that are powered by Vectara's chat functionality. +

+

Check out the example below.

+
+ + + + + {` +import { useChat } from "@vectara/react-chatbot/lib"; + +export const App = () => { + const { sendMessage, messageHistory, isLoading, hasError } = useChat( + DEFAULT_CUSTOMER_ID, + DEFAULT_CORPUS_IDS, + DEFAULT_API_KEY + ); + + /* You can pass the values returned by the hook to your custom components as props, or use them + however you wish. */ +}; +`} + + + + + +

+

The hook returns:

+
    +
  • sendMessage - a function that sends a string to the Chat API endpoint
  • +
  • messageHistory - an array of objects representing messages from the entire conversation
  • +
  • isLoading - a boolean value indicating whether or not a chat message request is pending
  • +
  • + hasError - a boolean value indicating whether or not the previous message request returned an error +
  • +
+
+ + + + + For more details, including return value types,{" "} + + read the docs. + + + setIsConfigurationDrawerOpen(false)} diff --git a/images/answerWithReferences.png b/images/answerWithReferences.png new file mode 100644 index 0000000..aee27b0 Binary files /dev/null and b/images/answerWithReferences.png differ diff --git a/images/emptyMessagesState.png b/images/emptyMessagesState.png new file mode 100644 index 0000000..d7ad890 Binary files /dev/null and b/images/emptyMessagesState.png differ diff --git a/images/messageWithError.png b/images/messageWithError.png new file mode 100644 index 0000000..26137bc Binary files /dev/null and b/images/messageWithError.png differ diff --git a/images/responsiveDemo.gif b/images/responsiveDemo.gif new file mode 100644 index 0000000..a976339 Binary files /dev/null and b/images/responsiveDemo.gif differ diff --git a/images/toggleButton.png b/images/toggleButton.png new file mode 100644 index 0000000..1c7f3af Binary files /dev/null and b/images/toggleButton.png differ diff --git a/src/components/ChatItem.tsx b/src/components/ChatItem.tsx index 4d8a615..07bb727 100644 --- a/src/components/ChatItem.tsx +++ b/src/components/ChatItem.tsx @@ -54,12 +54,11 @@ export const ChatItem = ({ question, answer, searchResults, onRetry }: Props) => content = (
- + - Message not sent. {onRetry && ( diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx index 84e0456..360524e 100644 --- a/src/components/ChatView.tsx +++ b/src/components/ChatView.tsx @@ -54,7 +54,7 @@ export const ChatView = ({ }: Props) => { const [isOpen, setIsOpen] = useState(isInitiallyOpen ?? false); const [query, setQuery] = useState(""); - const { sendMessage, messageHistory, isLoading, error } = useChat(customerId, corpusIds, apiKey); + const { sendMessage, messageHistory, isLoading, hasError } = useChat(customerId, corpusIds, apiKey); const appLayoutRef = useRef(null); const isScrolledToBottomRef = useRef(true); @@ -98,7 +98,9 @@ export const ChatView = ({ const chatItems = messageHistory.map((turn, index) => { const { question, answer, results } = turn; const onRetry = - error && index === messageHistory.length - 1 ? () => sendMessage({ query: question, isRetry: true }) : undefined; + hasError && index === messageHistory.length - 1 + ? () => sendMessage({ query: question, isRetry: true }) + : undefined; return ; }); diff --git a/src/useChat.ts b/src/useChat.ts index dae2647..14ac27a 100644 --- a/src/useChat.ts +++ b/src/useChat.ts @@ -12,7 +12,7 @@ export const useChat = (customerId: string, corpusIds: string[], apiKey: string) const [recentAnswer, setRecentAnswer] = useState(); const [isLoading, setIsLoading] = useState(false); const [conversationId, setConversationId] = useState(); - const [error, setError] = useState(false); + const [hasError, setHasError] = useState(false); const getLanguage = (languageValue?: string): SummaryLanguage => (languageValue ?? "eng") as SummaryLanguage; const sendMessage = async ({ query, isRetry = false }: { query: string; isRetry?: boolean }) => { @@ -34,7 +34,7 @@ export const useChat = (customerId: string, corpusIds: string[], apiKey: string) ]; }); } else { - setError(false); + setHasError(false); } const baseSearchRequestParams = { @@ -60,7 +60,7 @@ export const useChat = (customerId: string, corpusIds: string[], apiKey: string) try { initialSearchResponse = await sendSearchRequest(baseSearchRequestParams); } catch (error) { - setError(true); + setHasError(true); setIsLoading(false); return []; } @@ -109,6 +109,6 @@ export const useChat = (customerId: string, corpusIds: string[], apiKey: string) sendMessage, messageHistory, isLoading, - error + hasError }; };