npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-nexbot

v1.2.0

Published

Hooks and utilities to chat with NEXBots from your project

Downloads

22

Readme

react-nexbot

End-to-End RAG Implementation for React Applications

Alt text

Table of Contents

React-nexbot is the quickest, cheapest, and fastest way to embed Retrieval Augmented Generation (RAG) functionality into your React applications. Utilize our web app at NEXBot.io to create, prompt, and add documents to your bots. This NPM package enables you to access and chat with your NEXBots from your apps.

Getting Started

Begin by signing up or logging in with your preferred authentication provider at Sign Up / Login.

You can generate your server secret by going to the developers settings, accessible from your profile menu.

Pricing: Pay-as-you-go model. Charges are based only on compute and storage usage. New accounts receive unlimited bots, 500 messages, and 300 pages of storage.

How to Use react-nexbot

The package exports a single client-side React hook: useChatStream().

Arguments

| Parameter | Type | Description | |----------------------|------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| | keyRetrievalCallback | () => Promise<string> | A callback that returns a promise resolving to a string. This should return an authentication token from an API call to our servers, containing your server-secret. | | botId | string | The ID corresponding to the bot you will be chatting with. | | conversationId | string \| undefined | Optional identifier. Use this to reference the conversation in chat. If omitted, each message will be independent of previous ones. | | user_display_name | string \| undefined | A name for your user. Defaults to “Guest” if not provided. |

Return Value

The hook returns a sendMessage function.

sendMessage

Subscribing to the subject and using next on the subscriber will retrieve the observer’s value.

MessageStream

  • Type: Object
  • Property: stream
  • Description: Contains a string with the token streamed by the server on each pull.

Installation

npm install react-nexbot

import

import { useChatStream }  from "react-nexbot";

Example Usage

Nexbot Authentication Endpoint

For Nexbot authentication, your endpoint should call the Nexbot API as follows:

curl -X GET \
     -H "Authorization: Bearer YOUR_SERVER_SECRET" \
     "https://apis.nexbot.io/web/v1/secrets/generate_single_use_token"
JavaScript
fetch("https://apis.nexbot.io/web/v1/secrets/generate_single_use_token", {
  method: "GET",
  headers: {
    "Authorization": "Bearer YOUR_SERVER_SECRET"
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
TypeScript
const getSingleUseToken = async (): Promise<any> => {
  try {
    const response = await fetch("https://apis.nexbot.io/web/v1/secrets/generate_single_use_token", {
      method: "GET",
      headers: {
        "Authorization": "Bearer YOUR_SERVER_SECRET"
      }
    });
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return await response.json();
  } catch (error) {
    console.error('Error:', error);
  }
};

The response will contain a JSON payload with the key access_token. Your callback must provide only this string.

The callback is initially used by the hook to cache a single-use token, which opens a websocket connection with our servers and is immediately invalidated. The hook refreshes the token every 25 minutes using the callback. While the callback does not have to be an API call, using one allows Nexbot to handle token refresh for you.

Invoking useChatStream

JavaScript
const { sendMessage } = useChatStream(() => {
  return axios.get("https://your.api/nexbot/authing/endpoint")
    .then((res) => {
      return res.data.token;
    });
}, botId);
TypeScript
const botId: string = 'your-bot-id'; // Replace with your actual bot ID

const { sendMessage } = useChatStream(() => {
  return axios.get("https://your.api/nexbot/authing/endpoint")
    .then((res) => {
      return res.data.token as string;
    });
}, botId);

Sending a Message

JavaScript
const onClick = () => {
  setWillStream(true);
}
const [text, setText] = useState("");
useEffect(() => {
  if (willStream) {
    setText("");
    const newObservable = sendMessage("Hello!");
    newObservable.subscribe({
      next: (data) => {
        setText(prev => prev ? prev + data.stream : data.stream);
      },
      complete: () => {
        setWillStream(false);
      },
    });
  }
}, [willStream]);
TypeScript
 const [willStream, setWillStream] = useState<boolean>(false);
  const [text, setText] = useState<string>('');
  const { sendMessage } = useChatStream(/* arguments here */);

  useEffect(() => {
    if (willStream) {
      setText('');
      const newObservable: Observable<any> = sendMessage('Hello!');
      newObservable.subscribe({
        next: (data) => {
          setText((prev: string) => prev ? `${prev}${data.stream}` : data.stream);
        },
        complete: () => {
          setWillStream(false);
        },
      });
    }
  }, [willStream, sendMessage]);

  const onClick = (): void => {
    setWillStream(true);
  };

Dependency Note

React-nexbot uses useQuery as a dependency. Ensure to wrap your component hierarchy with useQueryClientProvider at your desired level if not already doing so.