Skip to content

Commit

Permalink
feat 1.0.0 initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
iamorlando committed Dec 4, 2023
0 parents commit cd1f1b6
Show file tree
Hide file tree
Showing 33 changed files with 1,359 additions and 0 deletions.
31 changes: 31 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Node.js CI/CD

on:
push:
branches: [ main, dev ]

jobs:
build-and-publish:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
registry-url: 'https://registry.npmjs.org/'

- name: Install Dependencies
run: npm install

- name: Run Tests
id: tests
run: npm test


- name: Publish to Public NPM
if: github.ref == 'refs/heads/main'
run: npm publish
env:
NODE_AUTH_TOKEN: ${{secrets.PUBLISH}}
17 changes: 17 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
dist/
node_modules/
package-lock.json

.envrc
build.sh
react-nexbot*.tgz
runtest.sh
wipe.sh
.vscode/launch.json
react-nexbot-test/.*/
react-nexbot-test/.*
openapi.json
*/certs/*
update_api.sh

.vscode/settings.json
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
react-nexbot-test/
Empty file added .vscode/launch.json
Empty file.
209 changes: 209 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
# react-nexbot
## End-to-End RAG Implementation for React Applications
![Alt text](code.gif)

## Table of Contents
- [react-nexbot](#react-nexbot)
- [End-to-End RAG Implementation for React Applications](#end-to-end-rag-implementation-for-react-applications)
- [Table of Contents](#table-of-contents)
- [Getting Started](#getting-started)
- [How to Use react-nexbot](#how-to-use-react-nexbot)
- [Arguments](#arguments)
- [Return Value](#return-value)
- [sendMessage](#sendmessage)
- [MessageStream](#messagestream)
- [Installation](#installation)
- [Example Usage](#example-usage)
- [Sending a Message](#sending-a-message)
- [JavaScript](#javascript)
- [TypeScript](#typescript)
- [Invoking useChatStream](#invoking-usechatstream)
- [JavaScript](#javascript-1)
- [TypeScript](#typescript-1)
- [Nexbot Authentication Endpoint](#nexbot-authentication-endpoint)
- [JavaScript](#javascript-2)
- [TypeScript](#typescript-2)
- [Dependency Note](#dependency-note)

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](https://www.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](https://www.about.nexbot.io/signup-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

- **Arguments:**
- `message: string`: The message your bot will respond to.
- **Returns:**
- An RXJS Subject ([RXJS Subject Documentation](https://rxjs.dev/guide/subject)).

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
```shell
npm install react-nexbot
```

import
```
import { useChatStream } from "react-nexbot";
```


### Example Usage

#### Sending a Message

##### JavaScript
```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
```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);
};
```

#### Invoking useChatStream

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

##### TypeScript
```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);
```

### Nexbot Authentication Endpoint

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

```bash
curl -X GET \
-H "Authorization: Bearer YOUR_SERVER_SECRET" \
"https://apis.nexbot.io/web/v1/secrets/generate_single_use_token"
```


##### JavaScript
```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
```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.

### 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.

Binary file added code.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
51 changes: 51 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "react-nexbot",
"version": "1.0.0",
"description": "Hooks and utilities to chat with NEXBots from your project",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"build": "tsc && cp src/index.d.ts dist/index.d.ts"
},
"files": [
"./dist"
],
"keywords": [
"react",
"ai",
"generative",
"nexbot",
"chatbot",
"chat",
"bot",
"RAG",
"GPT",
"Retrieval",
"Augmented",
"Generation"
],
"author": "orlando@nexbot.io",
"homepage": "https://nexbot.io",
"license": "ISC",
"repository": {
"type": "git",
"url": "https://github.com/nexbotio/react-nexbot.git"
},
"peerDependencies": {
"react": "^18.2.0"
},
"dependencies": {
"axios": "^1.6.2",
"node-fetch": "^3.3.2",
"react-dom": "^18.2.0",
"react-query": "^3.39.3",
"react-use-websocket": "^4.5.0",
"rxjs": "^7.8.1",
"uuid": "^9.0.1"
},
"devDependencies": {
"@types/node": "^20.10.2",
"@types/react": "^18.2.40",
"@types/uuid": "^9.0.7"
}
}
70 changes: 70 additions & 0 deletions react-nexbot-test/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Getting Started with Create React App

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.

The page will reload when you make changes.\
You may also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can't go back!**

If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.

You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)

### Analyzing the Bundle Size

This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)

### Making a Progressive Web App

This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)

### Advanced Configuration

This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)

### Deployment

This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)

### `npm run build` fails to minify

This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
Loading

0 comments on commit cd1f1b6

Please sign in to comment.