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

my-ai-chat-framework

v1.1.0

Published

A simple AI chat framework for managing chat messages and interactions with AI APIs with unified data format

Readme

🤖 My AI Chat Framework / 我的AI聊天框架

🎯 概述 / Overview

这是一个现代化的AI聊天框架,支持工具调用、流式传输和事件驱动架构。旨在帮助开发者构建功能丰富的AI聊天应用。

This is a modern AI chat framework with tool calling, streaming, and event-driven architecture. Designed to help developers build feature-rich AI chat applications.

✨ 新功能特性 / New Features

  • 🔧 工具调用系统 / Tool Calling System: 完整的OpenAI兼容工具调用支持,包括工具注册、执行和错误处理
  • 🌊 流式传输 / Streaming: 实时流式传输,支持工具调用和进度回调
  • ⚡ 事件驱动架构 / Event-Driven Architecture: 基于EventEmitter的丰富事件系统
  • 📦 模块化设计 / Modular Design: 清晰的关注点分离,易于扩展和维护

✅ 核心功能 / Core Features

  • 消息管理 / Message Management: 包含一个Messages类,用于处理聊天消息的存储和操作
  • 请求构建 / Request Building: RequestBuilder类构建发送到聊天API的请求体
  • API交互 / API Interaction: ApiClient类管理与聊天API的HTTP请求,支持标准和流式请求
  • 工具管理 / Tool Management: ToolManager类负责工具的注册、管理和执行
  • 事件系统 / Event System: EventEmitter类提供完整的事件驱动架构
  • 格式转换 / Format Conversion: MessageFormatter类负责消息格式转换

📁 项目结构 / Project Structure

my-ai-chat-framework/
├── dist/                          # 打包输出目录 / Build output
│   ├── my-ai-chat-framework.es.js    # ES模块 / ES Module
│   ├── my-ai-chat-framework.umd.js   # UMD模块(注册到window.AIChatFramework)/ UMD Module
│   └── my-ai-chat-framework.cjs.js   # CommonJS模块 / CommonJS Module
├── src/                           # 源代码 / Source code
│   ├── core/                      # 核心类 / Core classes
│   │   ├── EventEmitter.js        # 事件系统 / Event System
│   │   ├── Messages.js            # 消息状态管理 / Message State Management
│   │   ├── MessageFormatter.js    # 消息格式转换 / Message Format Conversion
│   │   ├── RequestBuilder.js      # 请求构建器 / Request Builder
│   │   ├── ApiClient.js           # API客户端(使用axios)/ API Client (axios)
│   │   └── ToolManager.js         # 工具管理器 / Tool Manager
│   ├── utils/                     # 工具函数 / Utility functions
│   └── index.js                   # 主入口文件 / Main entry point
├── test-*.html                    # 各种测试页面 / Various test pages
├── README_ZH.md                   # 详细中文文档 / Detailed Chinese documentation
├── FIX_SUMMARY.md                 # 修复总结 / Fix summary
├── vite.config.js                 # Vite配置 / Vite configuration
└── package.json                   # 项目配置 / Project configuration

🎯 统一数据格式 / Unified Data Format

从v1.1.0开始,框架使用统一的数据格式在所有组件之间传递消息,简化了使用体验。

核心消息格式

所有消息都遵循以下格式:

{
  // 必需字段 / Required fields
  role: 'user' | 'assistant' | 'system' | 'tool',
  content: string, // 允许空字符串 / Empty string allowed
  
  // 标准扩展字段 / Standard extension fields
  timestamp: string, // ISO格式时间戳,自动生成 / ISO timestamp, auto-generated
  metadata?: object, // 自定义元数据 / Custom metadata
  
  // 角色特定字段 / Role-specific fields
  reasoning_content?: string, // 助手消息的推理内容 / Reasoning content for assistant messages
  tool_calls?: array, // 助手消息的工具调用 / Tool calls for assistant messages
  tool_call_id?: string, // 工具消息的调用ID / Call ID for tool messages
  name?: string, // 工具消息的工具名称 / Tool name for tool messages
  
  // 自定义字段(任意)/ Custom fields (any)
  [key: string]: any // 所有自定义字段都会被保留 / All custom fields are preserved
}

关键特性

  1. 字段保留 / Field Preservation: 所有自定义字段都被保留,不再丢失
  2. 空内容处理 / Empty Content Handling: 允许空字符串内容,仅在API请求时过滤
  3. 工具消息特殊处理 / Tool Message Special Handling: tool消息可以没有content
  4. 事件数据统一 / Event Data Unification: 所有事件使用相同的数据结构
  5. 向后兼容 / Backward Compatibility: 现有API保持不变

使用示例

// 添加带自定义字段的消息 / Add message with custom fields
const msgIndex = chatService.messages.addUserMessage('Hello', {
  metadata: { userId: '123', priority: 'high' },
  customData: { session: 'test' }
});

// 获取完整消息 / Get complete message
const fullMessage = chatService.messages.getMessages()[msgIndex];
// 包含所有字段 / Contains all fields

// 监听事件获取统一格式数据 / Listen to events for unified data format
chatService.on('response', (data) => {
  console.log('收到响应 / Response received:', data.message);
  // data.message包含所有字段 / data.message contains all fields
});

📦 安装和使用 / Installation and Usage

浏览器中使用 / For Browser Usage

方式1:直接引入UMD版本(推荐)

<script src="https://unpkg.com/my-ai-chat-framework@latest/dist/my-ai-chat-framework.browser.umd.js"></script>
<script>
  // 全局变量 AIChatFramework 可用
  const { ChatService, Messages } = AIChatFramework;
  
  // 创建聊天服务
  const chat = new ChatService('your-api-key');
</script>

方式2:使用ES模块

<script type="module">
  import { ChatService, Messages } from 'https://unpkg.com/my-ai-chat-framework@latest/dist/my-ai-chat-framework.browser.es.js';
  
  const chat = new ChatService('your-api-key');
</script>

Node.js中使用 / For Node.js Usage

安装

npm install my-ai-chat-framework axios
# 或
yarn add my-ai-chat-framework axios
# 或
pnpm add my-ai-chat-framework axios

使用

// CommonJS
const { ChatService, Messages } = require('my-ai-chat-framework');

// ES模块
import { ChatService, Messages } from 'my-ai-chat-framework';

// 创建聊天服务
const chat = new ChatService('your-api-key');

本地开发 / Local Development

安装依赖

npm install

构建项目 / Build Project

npm run build

输出文件 / Output Files

构建后会在 dist/ 目录生成以下文件:

  • my-ai-chat-framework.es.js - ES模块格式(包含axios依赖)
  • my-ai-chat-framework.umd.js - UMD格式(包含axios依赖)
  • my-ai-chat-framework.cjs.js - CommonJS格式(包含axios依赖)

注意: axios已被打包进所有输出文件中,用户无需额外安装axios依赖。

预览构建结果 / Preview Build

npm run preview

在浏览器中使用 / Usage in Browser

传统浏览器(UMD模块)/ Traditional Browser (UMD Module)

<script src="./dist/my-ai-chat-framework.umd.js"></script>
<script>
// 使用全局变量 / Use global variable
const { Messages, ApiClient, ChatRequestBuilder, ChatService } = window.AIChatFramework;
const chat = new ChatService('your-api-key');
</script>

现代浏览器(ES模块)/ Modern Browser (ES Module)

<script type="module">
import { Messages, ChatService } from './dist/my-ai-chat-framework.es.js';
const chat = new ChatService('your-api-key');
</script>

在Node.js中使用 / Usage in Node.js

const { Messages, ChatService } = require('./dist/my-ai-chat-framework.cjs.js');
const chat = new ChatService('your-api-key');

核心类说明 / Core Classes Description

Messages 类

管理对话消息的核心类,支持:

  • 消息的推送、修改、撤回
  • 系统提示词管理
  • 工具定义管理
  • 数据导入/导出

ChatRequestBuilder 类

构建符合API规范的请求体,支持:

  • 自动格式化消息
  • 配置模型参数
  • 生成JSON请求体

ApiClient 类

HTTP客户端,支持:

  • 普通请求和流式请求
  • 请求中断
  • 错误处理
  • 前后端通用(使用axios)

ChatService 类

高级封装类,简化使用:

  • 集成所有核心功能
  • 提供简单API接口
  • 自动管理消息状态

示例代码 / Example Code

// 创建聊天服务 / Create chat service
const chat = new ChatService('your-api-key', 'deepseek-chat');

// 发送消息 / Send message
const response = await chat.send('你好,世界!');
console.log('AI回复:', response);

// 流式消息 / Stream message
await chat.stream('告诉我一个故事', 
  (chunk) => console.log('收到数据:', chunk),
  () => console.log('流式传输完成')
);

// 流式传输中的工具调用 / Tool calling in streaming
await chat.stream('查询北京天气', 
  (chunk) => console.log('实时数据:', chunk.content),
  (final) => console.log('最终结果:', final.content)
);

// 撤回消息 / Undo message
chat.undo();

// 导出对话 / Export conversation
const exportData = chat.export();

## 🤤 npm发布 / npm Publishing

### 发布准备
1. 确保已登录npm账号:
```bash
npm login
  1. 更新版本号(如果需要):
npm version patch  # 小版本更新
npm version minor  # 中版本更新  
npm version major  # 大版本更新
  1. 构建项目:
npm run build

发布到npm

npm publish

发布后验证

  1. 检查包是否发布成功:
npm view my-ai-chat-framework
  1. 测试安装:
npm install my-ai-chat-framework@latest

包信息

  • 包名: my-ai-chat-framework
  • 当前版本: 1.0.2
  • 许可证: MIT
  • 关键词: AI, chat, framework, messages, API, deepseek, openai, tool-calling

📄 许可证 / License

MIT License - 详见 LICENSE 文件

🤝 贡献 / Contributing

欢迎提交Issue和Pull Request!

📞 支持 / Support

如有问题,请提交Issue或联系作者。


✨ 感谢使用 My AI Chat Framework! ✨

// 导入对话 / Import conversation chat.import(exportData);


## 🌊 流式传输下的工具调用 / Tool Calling in Streaming

### 工作原理 / How It Works
框架自动处理流式传输中的工具调用:
1. **流式收集** / **Stream Collection**: 在流式传输过程中收集完整的工具调用信息
2. **工具执行** / **Tool Execution**: 执行所有请求的工具
3. **继续流式** / **Continue Streaming**: 将工具结果发送给AI并继续流式传输

### 代码示例 / Code Example
```javascript
// 注册工具 / Register tool
chat.registerTool('get_weather', toolDefinition, async (args) => {
  return { temperature: '25°C', condition: 'Sunny' };
});

// 流式传输会自动处理工具调用 / Streaming automatically handles tool calls
await chat.stream('What is the weather in Beijing?',
  (chunk) => {
    // 实时接收流式数据 / Receive streaming data in real-time
    if (chunk.content) console.log('Content:', chunk.content);
    if (chunk.tool_calls) console.log('Tool calls:', chunk.tool_calls);
  },
  (final) => {
    // 流式传输完成 / Streaming completed
    console.log('Final result:', final.content);
  }
);

📚 更多文档 / More Documentation

许可证 / License

本项目采用MIT许可证。详见LICENSE文件。

This project is licensed under the MIT License. See the LICENSE file for more details.

依赖库 / Dependencies


此文档由AI辅助生成,内容可能不完整或存在错误,请以实际代码为准。 This document is AI-assisted and may be incomplete or contain errors. Please refer to the actual code for accurate information.

配置系统章节

需要在两个 README 中都添加:

## 🔧 配置系统 / Configuration System

### 配置结构
```javascript
{
  api: {
    key: '',                    // API密钥
    url: 'https://api.deepseek.com/v1/chat/completions',
    timeout: 30000
  },
  model: {
    name: 'deepseek-chat',
    temperature: 0.7,
    maxTokens: 2000,
    stream: false,
    reasoningEffort: 'medium'
  }
  // ...
}

This is the code block that represents the suggested code change:

## 🔧 配置系统 / Configuration System

### 配置结构 / Configuration Structure
```javascript
// 完整配置结构 / Complete configuration structure
{
  api: {
    key: '',                    // API密钥(必填)/ API Key (required)
    url: 'https://api.deepseek.com/v1/chat/completions',
    timeout: 30000              // 请求超时(毫秒)/ Request timeout (ms)
  },
  model: {
    name: 'deepseek-chat',      // 模型名称 / Model name
    temperature: 0.7,           // 温度(0-2)/ Temperature (0-2)
    maxTokens: 2000,            // 最大token数 / Max tokens
    stream: false,              // 是否流式传输 / Whether to use streaming
    reasoningEffort: 'medium'   // 推理强度(仅DeepSeek)/ Reasoning effort (DeepSeek only)
  },
  conversation: {
    baseRounds: 10,             // 基础对话轮次 / Base conversation rounds
    cycleRounds: 5              // 循环对话轮次 / Cycle conversation rounds
  },
  debug: false                  // 调试模式 / Debug mode
}
```

### 使用方式 / Usage

#### 方式1:基本使用 / Basic Usage
```javascript
import { ChatService } from './src/index.js';

// 最小配置 / Minimal configuration
const chat = new ChatService({
  api: { key: 'your-api-key' }
});

// 完整配置 / Complete configuration
const chat = new ChatService({
  api: {
    key: 'your-api-key',
    url: 'https://api.openai.com/v1/chat/completions'
  },
  model: {
    name: 'gpt-4',
    temperature: 0.8,
    stream: true
  }
});
```

#### 方式2:动态配置更新 / Dynamic Configuration Updates
```javascript
// 创建服务后更新配置 / Update configuration after creating service
const chat = new ChatService({ api: { key: 'initial-key' } });

// 方法1:直接修改配置(自动同步)/ Method 1: Direct modification (auto-sync)
chat.configManager.config.api.key = 'new-key';
chat.configManager.config.model.temperature = 0.9;

// 方法2:批量更新 / Method 2: Batch update
chat.configManager.update({
  api: { url: 'https://custom-api.com/v1/chat/completions' },
  model: { name: 'custom-model' }
});

// 方法3:便捷方法 / Method 3: Convenience methods
chat.setApi('new-key', 'https://api.openai.com/v1/chat/completions');
chat.setModel('gpt-4', 0.8);
```

#### 方式3:配置事件监听 / Configuration Event Listening
```javascript
// 监听配置变更 / Listen to configuration changes
chat.configManager.on('config-changed', (data) => {
  console.log(`配置 ${data.path} 已更新:`, data.oldValue, '→', data.newValue);
  console.log(`Configuration ${data.path} updated:`, data.oldValue, '→', data.newValue);
});

// 监听特定配置变更 / Listen to specific configuration changes
chat.configManager.on('config-changed:model.temperature', (data) => {
  console.log('温度已更新:', data.newValue);
  console.log('Temperature updated:', data.newValue);
});
```

### 配置验证 / Configuration Validation
框架会自动验证配置 / The framework automatically validates configuration:
- ✅ API Key 格式检查 / API Key format check
- ✅ URL 格式验证 / URL format validation
- ✅ 数值范围检查(temperature: 0-2)/ Value range check (temperature: 0-2)
- ✅ 枚举值验证(reasoningEffort: 'low'/'medium'/'high')/ Enum value validation

发现无效配置时会发出警告,但不会阻止执行 / Warnings are issued for invalid configurations, but execution is not blocked.

### 最佳实践 / Best Practices
1. **环境变量** / **Environment Variables**: 在生产环境中使用环境变量存储API Key / Use environment variables to store API keys in production
2. **配置分离** / **Configuration Separation**: 将配置提取到单独的文件中 / Extract configuration to separate files
3. **类型检查** / **Type Checking**: 使用TypeScript获得更好的类型安全 / Use TypeScript for better type safety
4. **版本控制** / **Version Control**: 不要将敏感配置提交到版本控制系统 / Do not commit sensitive configurations to version control