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

@unif/react-native-chat-sdk

v0.4.2

Published

UNIF React Native Chat SDK — 流式通信、Provider、状态管理

Downloads

686

Readme

@unif/react-native-chat-sdk

AI 聊天 SDK — 流式通信、Provider 模式、状态管理。

安装

yarn add @unif/react-native-chat-sdk

peerDependencies

yarn add react react-native react-native-sse

架构

┌──────────────────────────────────────────┐
│            useXChat (Hook)               │
│  组合 Provider + store,输出 messages    │
├──────────────────────────────────────────┤
│           ChatProvider 层                │
│  AbstractChatProvider → OpenAI/DeepSeek  │
├──────────────────────────────────────────┤
│              工具层                      │
│  XRequest + XStream + SSEParser          │
└──────────────────────────────────────────┘

快速开始

方式一:ChatProvider 全局模式

import {
  ChatProvider,
  useChatContext,
  OpenAIChatProvider,
  XRequest,
} from '@unif/react-native-chat-sdk';
import AsyncStorage from '@react-native-async-storage/async-storage';

const request = new XRequest({
  baseURL: 'https://api.openai.com',
  getToken: async () => 'sk-...',
});
const provider = new OpenAIChatProvider({request, model: 'gpt-4o'});

function App() {
  return (
    <ChatProvider provider={provider} storage={AsyncStorage}>
      <ChatScreen />
    </ChatProvider>
  );
}

function ChatScreen() {
  const {messages, onRequest, requesting, abort} = useChatContext();
  // 使用 messages 渲染列表,onRequest 发送消息...
}

方式二:直接使用 Hooks

import {useXChat, useXConversations, useXModel} from '@unif/react-native-chat-sdk';

function ChatScreen() {
  const {messages, onRequest, abort, requesting} = useXChat({provider});
  const {sessions, switchSession, newSession} = useXConversations({storage: AsyncStorage});
  const {selectedModel, setSelectedModel} = useXModel({models: MODELS});
}

API

Hooks

useXChat

聊天操作核心 hook,消费 Provider 输出可渲染 messages。

const {
  messages,      // MessageInfo[] — 可渲染消息列表
  requesting,    // boolean — 是否请求中
  suggestions,   // SuggestionItem[] — 建议提示
  error,         // string | null — 错误信息
  onRequest,     // (input) => void — 发起请求
  abort,         // () => void — 中止请求
  resetChat,     // () => void — 重置聊天
  loadSession,   // (messages) => void — 加载历史会话
  clearError,    // () => void — 清除错误
} = useXChat({provider});

useXConversations

会话管理 hook,组合 session + history。

const {
  sessions,        // SessionSummary[]
  activeId,        // string
  switchSession,   // (id) => Promise<ChatMessage[]>
  newSession,      // () => void
  deleteSession,   // (id) => Promise<void>
  archiveSession,  // (id, title, messages) => Promise<void>
} = useXConversations({storage: AsyncStorage});

useXModel

模型选择 hook。

const {
  selectedModel,     // string
  models,            // ModelInfo[]
  setSelectedModel,  // (id) => void
} = useXModel({models: AVAILABLE_MODELS, defaultModel: 'gpt-4o'});

Providers

AbstractChatProvider

抽象基类,自定义 Provider 需继承并实现 3 个方法:

class MyProvider extends AbstractChatProvider {
  // 将 useXChat.onRequest() 参数转为 HTTP 请求体
  transformParams(input: RequestParams): Record<string, unknown>;

  // 创建用户本地消息(立即显示在列表中)
  transformLocalMessage(input: RequestParams): ChatMessage;

  // 将 SSE 流数据转为 assistant 消息(流式累积)
  transformMessage(output: SSEOutput, current?: ChatMessage): ChatMessage;
}

OpenAIChatProvider

OpenAI 兼容 Provider,支持所有 OpenAI 标准 API。

const provider = new OpenAIChatProvider({
  baseURL: 'https://api.openai.com',
  model: 'gpt-4o',
  getToken: async () => apiKey,
});

DeepSeekChatProvider

DeepSeek Provider,继承 OpenAI,额外处理 reasoning_content

const provider = new DeepSeekChatProvider({
  model: 'deepseek-chat',
  getToken: async () => apiKey,
});

Tools

XStream

SSE 流适配器,基于 react-native-sse 的 RN 原生实现。

const stream = new XStream({
  url: 'https://api.example.com/stream',
  method: 'POST',
  body: {message: 'hello'},
  timeout: 120000,
});

stream.connect({
  onMessage: (output) => console.log(output.data),
  onError: (err) => console.error(err),
  onComplete: () => console.log('done'),
});

XRequest

面向 LLM 的 HTTP 请求工具,组合 XStream + SSEParser。

const request = new XRequest({
  baseURL: 'https://api.example.com',
  endpoint: '/v1/chat/completions',
  getToken: async () => token,
});

await request.create(params, {
  onStream: (chunk) => handleChunk(chunk),
  onSuccess: () => handleDone(),
  onError: (err) => handleError(err),
});

SSEParser

SSE 解析器,event_id 幂等去重 + seq 严格排序。

const parser = new SSEParser();
parser.reset(); // 每轮对话重置

const envelopes = parser.process(rawData); // 返回排序后的事件数组

Types

// 消息类型
interface ChatMessage {
  id: string;
  text: string;
  role: 'user' | 'assistant' | 'system';
  status: 'local' | 'loading' | 'updating' | 'success' | 'error' | 'abort';
  messageType: 'text' | 'card' | 'system';
  createdAt: Date;
  turnId: string;
  cardType?: string;
  cardData?: { data: Record<string, unknown>; actions: string[] };
  extra?: Record<string, unknown>;
}

// 存储抽象
interface ChatStorage {
  getItem: (key: string) => Promise<string | null>;
  setItem: (key: string, value: string) => Promise<void>;
  removeItem: (key: string) => Promise<void>;
}

兼容性

| @unif/react-native-chat-sdk | React Native | React | 状态 | |-----------------------------|-------------|-------|------| | >= 0.3.x | >= 0.71 | >= 18 | ✅ |

许可证

MIT