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 🙏

© 2025 – Pkg Stats / Ryan Hefner

bf-chatbox

v1.2.6

Published

React AI Chat Box Component with Floating Icon Support

Readme

BF Chat Box

一个基于React和Ant Design X的AI聊天窗口组件,可以轻松集成到任何React项目中。

特性

  • 🎨 使用Ant Design X组件库构建,具有美观现代的UI
  • 🌊 支持流式响应和普通响应
  • 🔄 支持 Server-Sent Events (SSE) 格式的流数据
  • 🎯 高度可定制,支持自定义主题颜色
  • 🔊 支持语音输入功能
  • 📦 独立打包,避免与宿主项目的依赖冲突
  • 🔄 支持实时更新聊天内容
  • 🌐 支持与任何API后端集成
  • 🧩 提供可重用的hook,方便自定义UI实现
  • 💬 支持悬浮图标模式,点击展开聊天窗口

安装

yarn add bf-chatbox

或者

npm install bf-chatbox

使用方法

基本用法

// CommonJS 方式引入组件
const { AIChatBox } = require('bf-chatbox');
// 不需要额外引入CSS文件,样式已内联到JS中

function App() {
  const handleSendMessage = (message, params) => {
    console.log('发送消息:', message, params);
    // 在这里处理消息发送逻辑
  };

  return (
    <AIChatBox
      onSendMessage={handleSendMessage}
      baseUrl="https://api.example.com"
      placeholder="Ask me anything..."
      height="500px"
      width="100%"
      userId="user-123" // 设置用户ID,会在API请求中传递给后端
    />
  );
}

悬浮图标模式

使用 FloatingAIChat 组件可以在页面右下角显示一个悬浮图标,点击后展开聊天窗口:

// CommonJS 方式引入组件
const { FloatingAIChat } = require('bf-chatbox');
const { CommentOutlined } = require('@ant-design/icons'); // 可选,如需自定义图标
// 不需要额外引入CSS文件

function App() {
  return (
    <div className="App">
      {/* 你的应用内容 */}
      
      {/* 悬浮聊天图标 */}
      <FloatingAIChat
        baseUrl="https://api.example.com"
        useStream={true}
        themeColor="#10b981"
        // 设置用户ID
        userId="user-123"
        // 允许调整大小
        resizable={true}
        // 自定义初始位置
        initialPosition={{ right: 20, bottom: 100 }}
        // 自定义图标(可选)
        buttonIcon={<CommentOutlined style={{ fontSize: 24, color: 'white' }} />}
        // 自定义图标尺寸(可选)
        iconSize={50}  // 默认 50px
        // 自定义z-index(可选)
        zIndex={1000} // 默认 1000
      />
    </div>
  );
}

添加 GET 查询参数

You can add GET query parameters to the API URL:

// CommonJS 方式引入组件
const { AIChatBox } = require('bf-chatbox');

function App() {
  const handleSendMessage = (message, params) => {
    console.log('发送消息:', message, params);
    // 在这里处理消息发送逻辑
  };

  return (
    <AIChatBox
      onSendMessage={handleSendMessage}
      baseUrl="https://api.example.com"
      environmentParams={{
        urlParams: {
          model: 'gpt-4',
          temperature: 0.7,
          userId: 'user123'
        },
        sessionId: 'session-xyz',
        context: 'customer-support'
      }}
      useStream={true}
    />
  );
}

使用 useChatApi Hook

这个库也提供了一个可重用的 Hook useChatApi,允许您创建完全自定义的聊天界面:

// CommonJS 方式引入Hook
const React = require('react');
const { useState } = React;
const { useChatApi } = require('bf-chatbox');

function CustomChatInterface() {
  const [inputValue, setInputValue] = useState('');
  
  const {
    messages,      // 消息列表
    setMessages,   // 设置消息列表的函数
    isLoading,     // 是否正在加载
    sendMessage,   // 发送消息的函数
    clearMessages  // 清空消息列表的函数
  } = useChatApi({
    baseUrl: 'https://api.example.com',
    useStream: true,
    streamResponseField: 'answer',
    responseField: 'message',
    headers: {
      'Authorization': 'Bearer your-token-here'
    },
    environmentParams: {
      urlParams: {
        model: 'gpt-4'
      }
    },
    onSendMessage: (message, params) => {
      console.log('发送消息:', message, params);
    },
    userId: 'user-123' // 设置用户ID
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    if (inputValue.trim()) {
      sendMessage(inputValue);
      setInputValue('');
    }
  };

  return (
    <div className="custom-chat">
      <div className="messages">
        {messages.map(msg => (
          <div key={msg.id} className={`message ${msg.role}`}>
            {msg.type === 'loading' ? (
              <div className="loading">思考中...</div>
            ) : (
              <div className="content">{msg.content}</div>
            )}
          </div>
        ))}
      </div>
      
      <form onSubmit={handleSubmit}>
        <input
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          placeholder="输入消息..."
          disabled={isLoading}
        />
        <button type="submit" disabled={isLoading || !inputValue.trim()}>
          发送
        </button>
        <button type="button" onClick={clearMessages}>
          清空消息
        </button>
      </form>
    </div>
  );
}

处理 JSON 流式响应

如果您的 API 返回 JSON 格式的流式响应,可以指定应该从哪个字段提取文本内容:

// CommonJS 方式引入组件
const { AIChatBox } = require('bf-chatbox');

function App() {
  return (
    <AIChatBox
      baseUrl="https://api.example.com"
      useStream={true}
      streamResponseField="answer" // 从 JSON 中的 answer 字段提取内容
      responseField="message" // 从非流式响应中的 message 字段提取内容
    />
  );
}

组件支持两种流式数据格式:

  1. 纯 JSON 格式
{"event":"message","answer":"AI 生成的回复内容在这里"}
  1. Server-Sent Events (SSE) 格式
data:{"event":"node_started","answer":""}
data:{"event":"message","answer":"AI 生成的回复内容在这里"}

组件会自动检测并处理两种格式。对于 SSE 格式,它会自动移除 data: 前缀并解析后面的 JSON 数据。

对于具有 event 字段的 JSON 对象,组件有特殊处理:

  • node_started:标记流开始,但不显示内容
  • messagenode_donestream_data:这些事件会显示其中的内容
  • 其他事件类型:如果包含内容也会尝试显示

组件支持多种流式数据接收模式:

  1. 单个完整的 JSON 对象
  2. 多个 JSON 对象(按行分隔)
  3. 部分 JSON 对象(会累积直到收到完整对象)

调整聊天窗口大小

通过设置 resizable={true} 属性,可以启用悬浮聊天窗口的拖拽调整大小功能。启用后,聊天窗口的右下角会出现一个调整大小的手柄,用户可以通过拖拽该手柄来调整窗口的宽度和高度。

注意:调整大小功能仅在使用 FloatingAIChat 组件(悬浮聊天窗口)时可用。

// CommonJS 方式引入组件
const { FloatingAIChat } = require('bf-chatbox');

function App() {
  return (
    <FloatingAIChat
      baseUrl="https://api.example.com"
      // 启用调整大小功能
      resizable={true}
    />
  );
}

启用后,用户可以通过拖拽窗口右下角的调整大小手柄来自由调整聊天窗口的大小,以适应不同的内容或屏幕布局需求。

参数

AIChatBox 组件参数

| 参数名 | 类型 | 默认值 | 描述 | |--------|------|--------|------| | messages | ChatMessage[] | [] | 聊天历史记录 | | loading | boolean | false | 是否处于加载状态 | | useStream | boolean | false | 是否使用流式响应 | | onSendMessage | (message: string, customParams?: Record<string, any>) => void | - | 发送消息时的回调函数 | | onInitialize | (customParams?: Record<string, any>) => void | - | 组件初始化时的回调函数 | | baseUrl | string | - | API的基础URL,用于构建完整API请求地址 | | headers | Record<string, string> | - | 自定义请求头 | | environmentParams | object | - | 环境参数,会传递给回调函数或API请求 | | environmentParams.urlParams | object | - | GET查询参数,添加到URL | | streamResponseField | string | 'answer' | 从流式JSON响应中提取内容的字段名 | | responseField | string | 'message' | 从普通JSON响应中提取内容的字段名 | | width | string | number | '100%' | 组件宽度 | | height | string | number | '500px' | 组件高度 | | placeholder | string | 'Type something...' | 输入框的占位符文本 | | themeColor | string | '#6d28d9' | 主题颜色 | | allowVoiceMessages | boolean | false | 是否允许语音消息输入 | | userId | string | 'guest' | 用户ID,用于在请求时传递给后端 |

FloatingAIChat 组件参数

FloatingAIChat 组件继承了 AIChatBox 的所有参数,并添加了以下特有参数:

| 参数名 | 类型 | 默认值 | 描述 | |--------|------|--------|------| | visible | boolean | false | 是否显示浮动聊天窗口 | | onClose | () => void | - | 关闭按钮点击时的回调函数 | | buttonIcon | ReactNode | - | 自定义触发按钮图标 | | closeIcon | ReactNode | - | 自定义关闭按钮图标 | | resizable | boolean | true | 是否允许通过拖拽调整聊天窗口大小(右下角) | | initialPosition | { right: number, bottom: number } | { right: 20, bottom: 20 } | 初始位置 | | iconSize | number | 50 | 触发按钮大小 | | zIndex | number | 1000 | 组件的z-index值 |

useChatApi Hook 参数

| 参数名 | 类型 | 默认值 | 描述 | |--------|------|--------|------| | baseUrl | string | - | API的基础URL,用于构建完整API请求地址 | | useStream | boolean | false | 是否使用流式响应 | | headers | Record<string, string> | - | 自定义请求头 | | environmentParams | object | - | 环境参数,会传递给回调函数或API请求 | | environmentParams.urlParams | object | - | GET查询参数,添加到URL | | streamResponseField | string | 'answer' | 从流式JSON响应中提取内容的字段名 | | responseField | string | 'message' | 从普通JSON响应中提取内容的字段名 | | onSendMessage | (message: string, customParams?: Record<string, any>) => void | - | 发送消息时的回调函数 | | userId | string | 'guest' | 用户ID,用于在请求时传递给后端 |

useChatApi Hook 返回值

| 名称 | 类型 | 描述 | |------|------|------| | messages | ChatMessage[] | 当前消息列表 | | setMessages | React.Dispatch<React.SetStateAction<ChatMessage[]>> | 设置消息列表的函数 | | isLoading | boolean | 是否正在加载 | | sendMessage | (text: string) => Promise | 发送消息的函数 | | clearMessages | () => void | 清空消息列表的函数 |

本地开发

  1. 克隆仓库:

    git clone ssh://[email protected]:7001/front-end/ai-chat-box.git
    cd ai-chat-box
  2. 安装依赖:

    yarn install
  3. 构建库:

    yarn build
  4. 运行示例:

    yarn start-example

通过局域网访问示例项目

示例项目已配置为支持局域网访问,您可以从同一网络中的其他设备访问开发服务器。步骤如下:

  1. 启动示例项目:

    yarn start-example
  2. 找到您电脑的局域网 IP 地址:

    • Windows:打开命令提示符并输入 ipconfig
    • macOS:打开系统偏好设置 > 网络,或在终端输入 ifconfig
    • Linux:在终端输入 ip addrifconfig
  3. 在同一网络的其他设备上,使用浏览器访问:

    http://您的IP地址:5173

    例如:http://192.168.1.100:5173

  4. 如果您需要更改默认端口或其他配置,请修改 example/vite.config.ts 文件中的 server 部分:

    server: {
      host: '0.0.0.0',
      port: 5173, // 修改这里以更改端口
      open: true,
      strictPort: false,
      cors: true,
    }

注意:确保您的防火墙允许通过 5173 端口(或您设置的其他端口)的连接。

许可证

MIT