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

kanas-chatbot

v0.0.7

Published

This library provides a React client-side component for Chating with Baidu Qianfan LLM.

Downloads

27

Readme

Kanas Chatbot

This library provides a React client-side component for Chating with Baidu Qianfan LLM.

Frontend

install dependency

npm install kanas-chatbot

use the component in your react project

import { ChatWindow } from 'kanas-chatbot'
import 'kanas-chatbot/dist/style.css'

const MyComponent = () => {
  // the url here should be your ai-chat api, which will be explained in "Backend" part below
  const url = '<YOUR_CHAT_API>'
  const handleClose = () => {
    console.log('close chat window')
  }
  const containerStyle = { width: 500, height: 900 }
  const windowStyle = { borderRadius: 5, boxShadow: 'rgba(0, 0, 0, 0.1) 0 4px 16px' }

  return (
    <div style={containerStyle}>
      <ChatWindow
        url={url}
        title="How can I help you?"
        onClose={handleClose}
        style={windowStyle}
      />
    </div>
  )
}

Backend

To access LLM service, you have to prepare your api key first. This api key must not be public to your clients, so that you need a backend server to store it. The backend server will communicate between your clients and LLM.

This instruction will show how to write your own chat api in NodeJS.

Get your own Baidu Qianfan API key

Follow the instructions of Baidu Cloud Page to get your Access Key and Secret Key.

Create an Express.js server

  1. We will start by setting up a new Node.js and TypeScript project, and install the dependencies. Create a new directory for your project, navigate to it, and run the following commands:
npm init --yes
npm install --dev typescript ts-node @types/node @types/express @types/cors
npm install express cors dotenv @baiducloud/qianfan
npx tsc --init
  1. Create a file called .env and save your Access Key and Secret Key in it.
QIANFAN_ACCESS_KEY='<YOUR_ACCESS_KEY>'
QIANFAN_SECRET_KEY='<YOUR_SECRET_KEY>'
  1. Create a file called index.ts and add the following code:
import { ChatCompletion } from "@baiducloud/qianfan";
import express, { Express, Request, Response } from 'express';
import cors from 'cors';

// load environment variables
import 'dotenv/config'

const qianfanClient = new ChatCompletion({
  QIANFAN_ACCESS_KEY: process.env.QIANFAN_ACCESS_KEY,
  QIANFAN_SECRET_KEY: process.env.QIANFAN_SECRET_KEY,
});

const app: Express = express();
const port = 8080;

app.use(cors());
app.use(express.json());

app.listen(port, () => {
  console.log(`[server]: Server is running at http://localhost:${port}`);
});
  1. Then Modify index.ts file to add a new endpoint:
// It's important to note that the new API is created with post method.
// This is a requirement for integration.
app.post('/chat', async (req: Request, res: Response) => {
  const { messages } = req.body;

  if (!messages) {
    res.status(400).send({ error: 'messages is required' });
    return
  }

  try {
    const stream = await qianfanClient.chat(
      {
        messages,
        stream: true,
      },
      'ERNIE-Tiny-8K'   // you can change to other models
    );
    res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');

    // respond in stream
    for await (const chunk of stream) {
      res.write(`data: ${JSON.stringify(chunk)}\n\n`)
    }
    res.end()

  } catch (error) {
    // Error communicating with Baidu Qianfan AI
    res.status(500).send({ error });
  }
})
  1. Run your Express.js application using the following command:
npx ts-node index.ts

This will run your development server on http://localhost:8080 and you will have a new endpoint at POST http://localhost:8080/chat that is powered by Qianfan LLM model.

  1. Now you can go back to your client-side React component, and change the url prop of ChatWindow to your new endpoint - http://localhost:8080/chat. If everything is configured correctly, it should work as expected.