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

@tmesoft/ai-request-sdk

v0.1.1

Published

AI Request SDK for streaming AI responses

Downloads

152

Readme

AI Request SDK

一个用于对接自研AI服务的TypeScript SDK,支持SSE流式响应、鉴权、消息处理等功能。

功能特点

  • 支持POST类型的SSE(Server-Sent Events)流式响应
  • 消息发送与接收
  • 事件驱动的消息处理
  • 支持回调事件和全局事件监听
  • 支持自定义超时处理
  • 错误处理与重试机制
  • 请求取消支持
  • TypeScript类型支持

安装

npm install @tmesoft/ai-request-sdk
# 或
yarn add @tmesoft/ai-request-sdk
# 或
pnpm add @tmesoft/ai-request-sdk

基本使用

创建SDK实例

import { AiService } from '@tmesoft/ai-request-sdk';

// 创建SDK实例
const aiService = new AiService({
  baseUrl: 'https://api.example.com', // 替换为实际的API地址
  token: 'your-auth-token',           // 替换为实际的认证令牌
  timeout: 30000,                     // 请求超时时间(毫秒)
  retryTimes: 3,                      // 失败后重试次数
  retryInterval: 1000,                // 重试间隔(毫秒)
});

方法1:使用消息处理器

import { AiService, MessageHandler } from '@tmesoft/ai-request-sdk';

// 创建消息处理器
const handler: MessageHandler = {
  onOpen: () => {
    console.log('连接已建立');
  },
  onMessage: (message) => {
    console.log('收到消息:', message.content);

    // 如果是最终消息
    if (message.done) {
      console.log('会话完成');
    }
  },
  onError: (error) => {
    console.error('发生错误:', error.type, error.message);
  },
  onClose: () => {
    console.log('会话已完成');
  },
  onDisconnect: () => {
    console.log('连接已断开');
  },
  onFinally: () => {
    console.log('请求已结束(无论成功失败)');
  },
};

// 发送消息
const requestId = aiService.sendMessage({
  content: '你好,AI助手',
  sessionId: 'user-session-123',
  // 可以添加其他自定义参数
  modelParams: {
    temperature: 0.7,
    maxTokens: 2000,
  },
}, handler);

方法2:使用事件监听

import { AiService, EventType } from '@tmesoft/ai-request-sdk';

// 注册事件监听器
aiService.on(EventType.OPEN, () => {
  console.log('连接已建立');
});

aiService.on(EventType.MESSAGE, (message) => {
  console.log('收到消息:', message.content);
});

aiService.on(EventType.ERROR, (error) => {
  console.error('发生错误:', error.type, error.message);
});

aiService.on(EventType.CLOSE, () => {
  console.log('会话已完成');
});

aiService.on(EventType.DISCONNECT, () => {
  console.log('连接已断开');
});

aiService.on(EventType.FINALLY, () => {
  console.log('请求已结束(无论成功失败)');
});

// 发送消息
const requestId = aiService.sendMessage({
  content: '请帮我总结一下这篇文章',
  sessionId: 'user-session-123',
});

取消请求

// 取消特定请求
aiService.cancelRequest(requestId);

// 取消所有活跃请求
aiService.cancelAllRequests();

API参考

AiService

主要的SDK类,提供与AI服务交互的接口。

构造函数

constructor(options: AiServiceOptions)

方法

| 方法名 | 参数 | 返回值 | 说明 | | ----------------- | ------------------------------------------------- | -------- | ------------------ | | setToken | token: string | void | 设置认证令牌 | | sendMessage | request: MessageRequest, handler?: MessageHandler | string | 发送消息,返回请求ID | | cancelRequest | requestId: string | boolean | 取消指定请求,返回是否成功取消 | | cancelAllRequests | - | void | 取消所有活跃请求 | | on | type: EventType, callback: Function | Function | 添加事件监听器,返回移除监听器的函数 | | off | type: EventType, callback: Function | void | 移除事件监听器 |

类型定义

AiServiceOptions

interface AiServiceOptions {
  /** API基础URL */
  baseUrl: string;
  /** 鉴权令牌 */
  token?: string;
  /** 请求超时时间(毫秒) */
  timeout?: number;
  /** 重试次数 */
  retryTimes?: number;
  /** 重试间隔(毫秒) */
  retryInterval?: number;
  /** 自定义请求头 */
  headers?: Record<string, string>;
}

MessageRequest

interface MessageRequest {
  /** 消息内容 */
  content?: string;
  /** 会话ID */
  sessionId?: string;
  /** 消息ID */
  messageId?: string;
  /** 模型参数 */
  modelParams?: Record<string, any>;
  /** 其他自定义参数 */
  [key: string]: any;
}

MessageResponse

interface MessageResponse {
  /** 消息ID */
  messageId: string;
  /** 消息内容 */
  content: string;
  /** 是否是最终消息 */
  done: boolean;
  /** 错误信息 */
  error?: string;
  /** 其他自定义字段 */
  [key: string]: any;
}

EventType

enum EventType {
    OPEN = 'open',
    MESSAGE = 'message',
    ERROR = 'error',
    CLOSE = 'close',
    DISCONNECT = 'disconnect',
    FINALLY = 'finally',
}

事件调用顺序

以下是SDK中各种事件在不同情况下的触发顺序:

sequenceDiagram
    participant Client as 客户端
    participant SDK as AiService
    participant Server as 服务器

    Note over Client,Server: 正常流程
    Client->>SDK: sendMessage(request, handler)
    SDK->>Server: 建立SSE连接
    Server-->>SDK: 连接成功
    SDK->>Client: 触发 OPEN 事件/onOpen回调
    Note right of SDK: 连接建立成功

    loop 消息流
        Server-->>SDK: 发送消息片段
        SDK->>Client: 触发 MESSAGE 事件/onMessage回调
        Note right of SDK: 每收到一条消息
    end

    Server-->>SDK: 完成消息发送
    SDK->>Client: 触发 CLOSE 事件/onClose回调
    Note right of SDK: 服务器正常完成响应

    Note over Client,Server: 错误处理流程
    Client->>SDK: sendMessage(request, handler)
    SDK->>Server: 建立SSE连接

    alt 连接失败
        Server--xSDK: 连接失败 (HTTP错误)
        SDK->>Client: 触发 ERROR 事件/onError回调
        Note right of SDK: 连接无法建立
    else 连接中断
        Server-->>SDK: 连接成功
        SDK->>Client: 触发 OPEN 事件/onOpen回调
        Server-->>SDK: 发送部分消息
        SDK->>Client: 触发 MESSAGE 事件/onMessage回调
        Server--xSDK: 连接意外中断
        SDK->>Client: 触发 DISCONNECT 事件/onDisconnect回调
        Note right of SDK: 连接意外断开
    else 请求超时
        Server-->>SDK: 连接成功
        SDK->>Client: 触发 OPEN 事件/onOpen回调
        Note over SDK: 等待超时
        SDK-xServer: 中断连接
        SDK->>Client: 触发 ERROR 事件/onError回调 (TIMEOUT)
        SDK->>Client: 触发 DISCONNECT 事件/onDisconnect回调
        Note right of SDK: 请求超过设定时间
    end

    Note over Client,Server: 用户取消流程
    Client->>SDK: sendMessage(request, handler)
    SDK->>Server: 建立SSE连接
    Server-->>SDK: 连接成功
    SDK->>Client: 触发 OPEN 事件/onOpen回调
    Server-->>SDK: 发送部分消息
    SDK->>Client: 触发 MESSAGE 事件/onMessage回调
    Client->>SDK: cancelRequest(requestId)
    SDK-xServer: 中断连接
    SDK->>Client: 触发 DISCONNECT 事件/onDisconnect回调
    Note right of SDK: 用户主动取消请求

事件触发说明

  1. 正常流程

    • OPEN:连接成功建立时触发
    • MESSAGE:每收到服务器发送的一条消息时触发
    • CLOSE:服务器正常完成所有消息发送时触发
  2. 错误处理流程

    • 连接失败

      • ERROR:连接无法建立时触发(如HTTP错误、认证失败等)
    • 连接中断

      • OPEN:连接成功建立
      • MESSAGE:可能已收到部分消息
      • DISCONNECT:连接意外断开时触发
    • 请求超时

      • OPEN:连接成功建立
      • ERROR:请求超时时触发(带有TIMEOUT类型)
      • DISCONNECT:连接断开时触发
  3. 用户取消流程

    • OPEN:连接成功建立
    • MESSAGE:可能已收到部分消息
    • DISCONNECT:用户调用cancelRequest()取消请求时触发

事件应用场景

  • OPEN:显示连接状态指示器、开始计时器
  • MESSAGE:更新UI显示接收到的消息
  • ERROR:显示错误提示、记录错误日志
  • CLOSE:隐藏加载动画、启用输入框
  • DISCONNECT:显示断开连接提示、重置UI状态
  • FINALLY:无论请求成功或失败都执行的清理操作,如隐藏加载指示器、重置状态等

许可证

MIT