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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@simple-ai-chat-project/core-sdk

v1.0.1

Published

Lightweight core SDK for AI chat system (ESM)

Readme

@simple-ai-chat-project/core-sdk

轻量级 AI 聊天系统核心 SDK - 框架无关的纯 JavaScript 实现

特性

  • 🚀 框架无关 - 纯 JavaScript 实现,可在任何前端框架中使用
  • 📡 SSE 流式响应 - 基于 @microsoft/fetch-event-source 的增强型流式传输
  • 🎯 类型安全的事件系统 - 基于 EventEmitter3 的强大事件管理
  • 🔄 自动重连 - 内置智能重连机制
  • 💾 状态管理 - 完整的客户端状态管理
  • 🧪 完整测试 - 单元测试覆盖率 > 80%
  • 📦 小巧轻便 - 打包后体积小,性能优异

安装

npm install @simple-ai-chat-project/core-sdk
# 或
pnpm add @simple-ai-chat-project/core-sdk

快速开始

import { createChatClient } from '@simple-ai-chat-project/core-sdk';

// 创建客户端实例
const client = createChatClient({
  apiBaseUrl: 'http://localhost:8000',
  ai: {
    model: 'gpt-4',
    temperature: 0.7
  }
});

// 监听事件
client.on('stream:chunk', (data) => {
  console.log('接收到流式数据:', data.chunk);
});

client.on('message:new', (message) => {
  console.log('新消息:', message);
});

// 发送消息
await client.sendMessage({
  content: 'Hello, AI!',
  onStream: {
    onStart: () => console.log('流式响应开始'),
    onChunk: (data) => console.log('接收数据:', data.chunk),
    onComplete: (message) => console.log('响应完成:', message)
  }
});

核心 API

创建客户端

const client = createChatClient({
  // 必填配置
  apiBaseUrl: 'http://localhost:8000',

  // 可选配置
  auth: {
    type: 'jwt', // 'jwt' | 'apikey' | 'none'
    getToken: async () => localStorage.getItem('token')
  },

  sse: {
    reconnect: true,
    reconnectInterval: 3000,
    maxReconnectAttempts: 5
  },

  ai: {
    model: 'gpt-4',
    temperature: 0.7,
    maxTokens: 2000,
    streamResponse: true
  },

  logger: {
    level: 'info' // 'debug' | 'info' | 'warn' | 'error'
  }
});

发送消息

const message = await client.sendMessage({
  content: 'Hello, AI!',
  roomId: 'room-123', // 可选,不提供则创建新房间
  attachments: [], // 可选,附件数组

  // 流式响应回调
  onStream: {
    onStart: () => {},
    onChunk: (data) => {},
    onComplete: (message) => {},
    onError: (error) => {}
  },

  // AI 参数覆盖
  aiOptions: {
    temperature: 0.9
  }
});

房间管理

// 创建房间
const room = await client.createRoom({
  name: '新对话',
  metadata: { category: 'support' }
});

// 获取房间列表
const rooms = await client.getRooms();

// 切换房间
await client.switchRoom('room-123');

// 删除房间
await client.deleteRoom('room-123');

消息管理

// 获取房间消息
const messages = await client.getMessages('room-123', {
  page: 1,
  pageSize: 50
});

事件系统

// 消息事件
client.on('message:new', (message) => {});
client.on('message:update', (message) => {});

// 流式响应事件
client.on('stream:start', ({ roomId, messageId }) => {});
client.on('stream:chunk', ({ chunk, accumulated }) => {});
client.on('stream:end', ({ fullMessage }) => {});
client.on('stream:abort', () => {});

// 房间事件
client.on('room:created', (room) => {});
client.on('room:switched', (room) => {});
client.on('room:deleted', (roomId) => {});

// 状态变化事件
client.on('state:change', (state) => {});

// 错误事件
client.on('error', (error) => {});

// 连接状态事件
client.on('connection:change', (status) => {});

// 移除监听
const unsubscribe = client.on('message:new', handler);
unsubscribe(); // 或 client.off('message:new', handler)

流式响应控制

// 中止当前流式响应
client.abortStream();

工具方法

// 健康检查
const health = await client.healthCheck();

// 获取当前状态
const state = client.getState();

// 清理资源
client.destroy();

数据模型

Message

{
  id: 'msg_xxx',
  roomId: 'room_xxx',
  content: '消息内容',
  role: 'user' | 'assistant' | 'system',
  metadata: {},
  createdAt: '2024-01-01T00:00:00.000Z',
  updatedAt: '2024-01-01T00:00:00.000Z',
  isStreaming: false,
  isComplete: true,
  attachments: [],
  references: []
}

Room

{
  id: 'room_xxx',
  name: '对话名称',
  metadata: {},
  createdAt: '2024-01-01T00:00:00.000Z',
  updatedAt: '2024-01-01T00:00:00.000Z',
  config: {
    model: 'gpt-4',
    temperature: 0.7,
    maxTokens: 2000,
    systemPrompt: null
  },
  messageCount: 0,
  lastMessageAt: null
}

架构设计

@simple-ai-chat/core-sdk/
├── src/
│   ├── api/
│   │   ├── SSEClient.js      # SSE 流式客户端
│   │   └── RestClient.js     # REST API 客户端
│   ├── core/
│   │   └── ChatClient.js     # 核心客户端类
│   ├── models/
│   │   ├── Message.js        # 消息模型
│   │   └── Room.js           # 房间模型
│   └── index.js              # 主入口
├── tests/                    # 测试文件
└── dist/                     # 构建输出
    ├── index.esm.js          # ESM 格式
    └── index.cjs             # CommonJS 格式

开发

# 安装依赖
npm install

# 运行测试
npm test

# 构建
npm run build

# 开发模式(监听测试)
npm run dev

测试

本项目使用 Vitest 进行测试,测试覆盖率 > 80%。

# 运行所有测试
npm test

# 开发模式(监听)
npm run dev

# 查看覆盖率
npm test -- --coverage

浏览器兼容性

  • Chrome/Edge >= 90
  • Firefox >= 88
  • Safari >= 14
  • 支持 ES2022+ 特性

依赖

  • eventemitter3 - 事件系统
  • @microsoft/fetch-event-source - SSE 流式传输

许可证

MIT

相关项目

  • @simple-ai-chat-project/vue-ui - Vue 3 UI 组件包
  • @simple-ai-chat-project/web-component - Web Component 封装

更新日志

v1.0.1 (2024-10-29)

  • ✅ 实现 SSE 客户端
  • ✅ 实现核心 ChatClient 类
  • ✅ 实现数据模型 (Message, Room)
  • ✅ 实现事件系统
  • ✅ 实现流式响应控制
  • ✅ 完成单元测试 (27 tests passed)
  • ✅ 完成构建配置

贡献

欢迎提交 Issue 和 Pull Request!

支持

如有问题,请访问 GitHub Issues