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

unified-ai-sdk

v0.0.4

Published

统一 AI 模型 SDK - 支持多平台切换、多种生成能力(文本/图片/视频)

Readme

Unified AI SDK

生产级 TypeScript SDK - 统一接入多平台 AI 能力

TypeScript Node License

快速开始 · API 文档 · 使用示例 · 更新日志


概述

Unified AI SDK 是一个生产级别的 TypeScript SDK,旨在提供统一的 API 接口来访问多个 AI 平台的能力。通过创新的协议化架构,SDK 实现了高度的代码复用和可扩展性,让开发者能够轻松地在不同 AI 平台之间切换,而无需修改业务代码。

核心特性

  • 🔄 统一接口 - 一套 API 访问所有平台,无需学习各平台差异
  • 🏗️ 协议化架构 - Provider → Protocol → Model 三层抽象,新增平台只需配置
  • 🌐 多平台支持 - 支持 20+ 主流 AI 平台(OpenAI、DeepSeek、智谱、阿里云、Google 等)
  • 🤖 多模态能力 - 文本对话、视觉理解、图片生成、视频生成、语音合成/识别
  • 📡 流式输出 - 完整支持 SSE 流式响应,实时输出生成内容
  • ⚡ 异步任务 - 统一的异步任务管理,支持状态查询和进度追踪
  • 🔧 工具调用 - 内置工具注册与自动执行,支持 Function Calling
  • 🤝 Agent 支持 - 集成 PageAgent,支持浏览器自动化操作
  • 🧩 插件系统 - 灵活的插件机制,快速扩展新平台
  • 📦 零依赖 - 纯 TypeScript 实现,无第三方运行时依赖
  • 🛡️ 类型安全 - 完整的类型定义,优秀的 IDE 支持

支持的平台

| 平台 | 文本对话 | 视觉理解 | 图片生成 | 视频生成 | 语音合成 | 语音识别 | | ------------- | :------: | :------: | :------: | :------: | :------: | :------: | | OpenAI | ✅ | ✅ | ✅ | - | ✅ | ✅ | | Google Gemini | ✅ | ✅ | ✅ | - | - | - | | 智谱 AI | ✅ | ✅ | ✅ | ✅ | - | - | | 阿里云百炼 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | 腾讯混元 | ✅ | ✅ | - | - | - | - | | DeepSeek | ✅ | ✅ | - | - | - | - | | 豆包/字节跳动 | ✅ | ✅ | ✅ | ✅ | - | - | | 可灵 AI | - | - | - | ✅ | - | - | | 月之暗面 Kimi | ✅ | ✅ | - | - | - | - | | Claude | ✅ | ✅ | - | - | - | - | | Minimax | ✅ | ✅ | ✅ | ✅ | - | - | | 百度千帆 | ✅ | - | - | - | - | - | | 讯飞星火 | ✅ | - | - | - | - | - | | 华为云 | ✅ | - | - | - | - | - | | OpenRouter | ✅ | ✅ | - | - | - | - | | 小米 | ✅ | - | - | - | - | - | | 百川 | ✅ | - | - | - | - | - | | 澜舟科技 | ✅ | - | - | - | - | - | | 商汤科技 | ✅ | - | - | - | - | - | | 旷视 | ✅ | - | - | - | - | - |


安装

# npm
npm install unified-ai-sdk

# yarn
yarn add unified-ai-sdk

# pnpm
pnpm add unified-ai-sdk

环境要求

  • Node.js: 18.0 或更高版本
  • TypeScript: 5.0 或更高版本(推荐)

快速开始

1. 初始化 SDK

import { UnifiedAI } from 'unified-ai-sdk';

// 最简单的初始化
const ai = new UnifiedAI({
  providers: {
    openai: { apiKey: process.env.OPENAI_API_KEY },
  },
});

// 完整配置
const ai = new UnifiedAI({
  defaultProvider: 'openai',
  providers: {
    openai: {
      apiKey: process.env.OPENAI_API_KEY,
      timeout: 60000,
      maxRetries: 3,
    },
    deepseek: {
      apiKey: process.env.DEEPSEEK_API_KEY,
      enabled: true,
    },
    zhipu: {
      apiKey: process.env.ZHIPU_API_KEY,
      defaultModel: 'glm-4.7',
    },
  },
});

2. 文本对话

// 同步对话
const response = await ai.chat({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: '你好,请介绍一下自己' }],
});
console.log(response.content);

// 流式对话
await ai.chatStream({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: '写一首关于春天的诗' }],
  onChunk: (chunk) => {
    if (chunk.delta.content) {
      process.stdout.write(chunk.delta.content);
    }
  },
});

3. 视觉理解

const response = await ai.chat({
  model: 'gpt-4o',
  messages: [{
    role: 'user',
    content: [
      { type: 'text', text: '这张图片里有什么?' },
      { type: 'image_url', image_url: { url: 'https://example.com/image.jpg' } },
    ],
  }],
});
console.log(response.content);

4. 图片生成

// 同步生成(DALL-E)
const image = await ai.generateImage({
  model: 'dall-e-3',
  prompt: '一只可爱的橘猫在阳光下打盹',
  size: '1024x1024',
  quality: 'hd',
});
console.log('图片 URL:', image.images[0].data);

// 异步生成(阿里云万相)- 自动等待完成
const asyncImage = await ai.generateImage({
  provider: 'aliyun',
  model: 'wan2.6-t2i',
  prompt: '一幅中国水墨画风格的山水画',
});

5. 视频生成

const video = await ai.generateVideo({
  model: 'kling-v1',
  prompt: '夕阳西下,海浪轻拍沙滩',
  duration: 5,
  aspectRatio: '16:9',
});
console.log('视频 URL:', video.video);

6. 语音合成/识别

// 文字转语音
const tts = await ai.textToSpeech({
  model: 'tts-1',
  text: '欢迎使用 Unified AI SDK',
  voice: 'alloy',
});

// 语音转文字
const asr = await ai.speechToText({
  model: 'whisper-1',
  audio: 'https://example.com/audio.mp3',
  language: 'zh',
});
console.log('转写结果:', asr.text);

7. 工具调用(Function Calling)

// 注册工具
ai.registerTool({
  name: 'get_weather',
  description: '获取指定城市的天气',
  parameters: {
    type: 'object',
    properties: {
      city: { type: 'string', description: '城市名称' },
    },
    required: ['city'],
  },
}, async (params) => {
  // 执行天气查询逻辑
  return { temperature: 25, weather: '晴天' };
});

// 自动工具调用循环
const result = await ai.chatWithTools({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: '北京今天天气怎么样?' }],
});
console.log(result.response.content);

核心概念

三层抽象模型

┌─────────────────────────────────────────────────────────────┐
│                      UnifiedAI                               │
│                    (统一 API 入口)                           │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐  │
│  │   Provider   │───▶│   Protocol   │───▶│    Model     │  │
│  │  (平台配置)   │    │  (协议定义)   │    │  (模型定义)   │  │
│  └──────────────┘    └──────────────┘    └──────────────┘  │
│                                                              │
│  Provider: 定义平台的连接信息(API Key、Base URL 等)          │
│  Protocol: 定义 API 的请求/响应格式(OpenAI、Bailian 等)       │
│  Model: 定义模型的能力和协议映射                               │
│                                                              │
└─────────────────────────────────────────────────────────────┘

Provider(平台)

平台配置定义了 AI 服务提供商的连接信息:

interface ProviderConfig {
  id: string;           // 平台唯一标识
  name: string;         // 平台名称
  apiKey?: string;      // API 密钥
  baseUrl?: string;     // API 基础 URL
  timeout?: number;     // 请求超时时间
  maxRetries?: number;  // 最大重试次数
  enabled?: boolean;    // 是否启用
}

Protocol(协议)

协议定义了 API 的请求和响应格式,实现协议复用:

interface ProtocolConfig {
  id: string;              // 协议唯一标识
  capability: Capability;  // 协议支持的能力
  requestFormatter: {      // 请求格式化器
    endpoint: string;
    method: 'GET' | 'POST';
    bodyBuilder: (ctx) => object;
    headersBuilder: (ctx) => object;
  };
  responseFormatter: {     // 响应格式化器
    parser: (response, ctx) => UnifiedResponse;
  };
}

Model(模型)

模型定义了具体的 AI 模型及其能力:

interface ModelConfig {
  id: string;              // 模型唯一标识
  provider: string;        // 所属平台
  capabilities: string[];  // 支持的能力列表
  protocols: {             // 能力到协议的映射
    [capability: string]: string;
  };
  contextLength?: number;  // 上下文长度
}

API 概览

文本对话

| 方法 | 说明 | | -------------------------------- | -------------------- | | chat(options) | 同步文本对话 | | chatStream(options) | 流式文本对话 | | chatWithTools(options) | 带工具调用循环的对话 | | chatStreamWithTools(options) | 流式 + 工具调用 |

多模态生成

| 方法 | 说明 | | -------------------------- | ----------------------------- | | generateImage(options) | 图片生成(自动判断同步/异步) | | generateVideo(options) | 视频生成 | | textToSpeech(options) | 文字转语音 | | speechToText(options) | 语音转文字 |

任务管理

| 方法 | 说明 | | ------------------------------------------ | ---------------- | | waitForTaskCompletion(taskId, options) | 等待异步任务完成 | | getTaskStatus(taskId) | 查询任务状态 | | getAllTasks() | 获取所有任务 | | getPendingTasks() | 获取待处理任务 |

工具管理

| 方法 | 说明 | | -------------------------------------- | ------------ | | registerTool(definition, executor) | 注册工具 | | registerTools(tools) | 批量注册工具 | | unregisterTool(name) | 注销工具 | | getToolDefinitions() | 获取工具定义 |

平台/模型管理

| 方法 | 说明 | | ---------------------------- | ---------------- | | registerProvider(config) | 注册平台 | | setProviderKey(id, key) | 设置平台 API Key | | getProviders() | 获取所有平台 | | registerModel(config) | 注册模型 | | getModels(providerId?) | 获取模型列表 |

事件监听

| 事件 | 说明 | | ------------------ | ---------- | | request:start | 请求开始 | | request:end | 请求完成 | | request:error | 请求错误 | | stream:start | 流式开始 | | stream:chunk | 流式数据块 | | stream:end | 流式结束 | | task:created | 任务创建 | | task:completed | 任务完成 |


高级用法

平台切换

// 使用 OpenAI
const openaiResponse = await ai.chat({
  provider: 'openai',
  model: 'gpt-4o',
  messages: [{ role: 'user', content: '你好' }],
});

// 切换到 DeepSeek(更便宜)
const deepseekResponse = await ai.chat({
  provider: 'deepseek',
  model: 'deepseek-chat',
  messages: [{ role: 'user', content: '你好' }],
});

故障转移

async function chatWithFallback(messages: Message[]) {
  const providers = ['openai', 'deepseek', 'zhipu'];
  
  for (const provider of providers) {
    try {
      return await ai.chat({ provider, messages });
    } catch (error) {
      console.warn(`${provider} 失败,尝试下一个...`);
    }
  }
  
  throw new Error('所有平台都不可用');
}

Ollama 本地模型

// 快速使用 Ollama 本地模型
const response = await ai.ollama({
  baseUrl: 'http://localhost:11434/v1',
  model: 'llama3.2',
  messages: [{ role: 'user', content: '你好' }],
});

添加自定义平台

// 快速添加 OpenAI 兼容平台
ai.registerProvider({
  id: 'my-platform',
  name: 'My AI Platform',
  baseUrl: 'https://api.my-platform.com/v1',
  apiKey: 'your-api-key',
});

ai.registerModel({
  id: 'my-model',
  name: 'My Model',
  provider: 'my-platform',
  capabilities: ['chat', 'chat-stream'],
  protocols: {
    'chat': 'openai-chat',
    'chat-stream': 'openai-chat-stream',
  },
});

事件监听

ai.on('request:start', (event, data) => {
  console.log(`[${new Date().toISOString()}] 请求开始:`, data);
});

ai.on('request:error', (event, data) => {
  console.error('请求错误:', data);
});

ai.on('task:completed', (event, data) => {
  console.log('任务完成:', data);
});

使用示例文档

更多详细的使用示例请参阅:


Agent 智能代理

Agent 是 SDK 提供的高级功能,支持复杂任务的自动规划与执行。

核心特性

  • 🎯 智能路由 - AgentHub 自动识别用户意图,智能路由到合适的 Agent
  • 🤖 多种 Agent - 内置 ChatAgent、ToolAgent、PlanAgent、WebAgent、TravelAgent
  • 📋 自动规划 - 将复杂目标分解为可执行的子任务
  • 🔄 上下文传递 - 任务执行时携带完整上下文,确保任务协作
  • 🛠️ 工具集成 - 支持注册私有工具,与 AI 全局工具自动合并
  • 📊 事件监控 - 标准化的 Plan 事件格式,方便监控执行进度
  • 🔌 可扩展 - 支持动态注册自定义 Agent

Agent 类型

| Agent | 说明 | 适用场景 | | ------------ | ------------------------------------------- | -------------------------------- | | ChatAgent | 普通对话 Agent | 问答、闲聊、创意写作、分析推理 | | ToolAgent | 工具调用 Agent | 需要调用外部工具获取信息 | | PlanAgent | 规划执行 Agent | 复杂多步骤任务 | | WebAgent | Web 界面操作 Agent | 自动化 web 操作 | | TravelAgent | 旅游规划 Agent | 旅游行程规划、景点推荐 |

使用方式一:AgentHub(推荐)

AgentHub 是统一的 Agent 入口,支持自动意图识别和智能路由:

import { UnifiedAI, AgentHub } from 'unified-ai-sdk';

// 创建 AI 实例
const ai = new UnifiedAI({
  providers: {
    openai: { apiKey: process.env.OPENAI_API_KEY },
  },
});

// 创建 AgentHub
const hub = new AgentHub({
  ai,
  autoDetectIntent: true,  // 自动识别意图
  model: 'gpt-4o',
});

// 自动识别意图并选择合适的 Agent
const result = await hub.run('今天北京天气怎么样?');
console.log(result.output);
console.log('使用的 Agent:', result.usedAgent);  // 'tool'
console.log('使用的模式:', result.usedMode);    // 'tool'

AgentHub 流式运行

const result = await hub.runStream(
  '帮我写一首关于春天的诗',
  (chunk) => {
    if (chunk.delta.content) {
      process.stdout.write(chunk.delta.content);
    }
  },
  {
    onIntentDetected: (intentResult) => {
      console.log('意图识别结果:', intentResult.intent);
      console.log('推荐 Agent:', intentResult.recommendedAgent);
    },
  }
);

强制使用特定 Agent

// 强制使用 PlanAgent
const result = await hub.run('帮我规划一个学习计划', {
  forceAgent: 'plan',
});

// 强制使用 chat 模式
const result = await hub.run('你好', {
  forceMode: 'chat',
});

注册自定义 Agent

import { BaseAgent } from 'unified-ai-sdk';

// 创建自定义 Agent
class MyCustomAgent extends BaseAgent {
  protected getDefaultName() { return 'MyCustomAgent'; }
  protected getDefaultDescription() { return '自定义 Agent'; }
  
  async run(input: string, options?: any) {
    // 实现逻辑
  }
  
  async runStream(input: string, onChunk: any, options?: any) {
    // 实现逻辑
  }
}

// 注册到 AgentHub
hub.registerAgent({
  name: 'custom',
  agent: new MyCustomAgent({ ai }),
  capabilities: {
    intents: ['custom_intent'],
    keywords: ['自定义关键词'],
    description: '自定义 Agent 描述',
    priority: 8,
  },
  mode: 'custom',
});

使用方式二:直接使用特定 Agent

可以直接创建和使用特定的 Agent:

import { 
  ChatAgent, 
  ToolAgent, 
  PlanAgent, 
  WebAgent, 
  TravelAgent 
} from 'unified-ai-sdk';

// 创建 ChatAgent - 普通对话
const chatAgent = new ChatAgent({
  ai,
  systemPrompt: '你是一个友好的助手',
  model: 'gpt-4o',
});
const chatResult = await chatAgent.run('你好,请介绍一下自己');

// 创建 ToolAgent - 工具调用
const toolAgent = new ToolAgent({
  ai,
  model: 'gpt-4o',
  tools: [
    {
      definition: {
        name: 'get_weather',
        description: '获取城市天气',
        parameters: {
          type: 'object',
          properties: {
            city: { type: 'string', description: '城市名称' },
          },
          required: ['city'],
        },
      },
      executor: async (params) => {
        return { city: params.city, temperature: 25, weather: '晴天' };
      },
    },
  ],
});
const toolResult = await toolAgent.run('北京今天天气怎么样?');

// 创建 PlanAgent - 规划执行
const planAgent = new PlanAgent({
  ai,
  model: 'gpt-4o',
});
const planResult = await planAgent.run('帮我完成一个市场调研报告');

// 创建 WebAgent - Web 操作
const webAgent = new WebAgent({
  ai,
  model: 'gpt-4o',
});

// 创建 TravelAgent - 旅游规划
const travelAgent = new TravelAgent({
  ai,
  model: 'gpt-4o',
});

便捷工厂函数

SDK 提供便捷的工厂函数来创建 Agent:

import { 
  createAgentHub,
  createChatAgent, 
  createToolAgent, 
  createPlanAgent,
  createWebAgent,
  createTravelAgent
} from 'unified-ai-sdk';

// 创建 AgentHub
const hub = createAgentHub(ai, { autoDetectIntent: true });

// 创建 ChatAgent
const chatAgent = createChatAgent(ai, { model: 'gpt-4o' });

// 创建 ToolAgent
const toolAgent = createToolAgent(ai, {
  tools: [
    {
      definition: { name: 'tool1', ... },
      executor: async () => { ... },
    },
  ],
});

// 创建 PlanAgent
const planAgent = createPlanAgent(ai, { model: 'gpt-4o' });

// 创建 WebAgent
const webAgent = createWebAgent(ai, { model: 'gpt-4o' });

// 创建 TravelAgent
const travelAgent = createTravelAgent(ai, { model: 'gpt-4o' });

注册工具

// 注册单个工具
agent.registerTool({
  name: 'get_weather',
  description: '获取指定城市的天气信息',
  parameters: {
    type: 'object',
    properties: {
      city: { type: 'string', description: '城市名称' },
    },
    required: ['city'],
  },
}, async (params) => {
  // 模拟天气查询
  return { city: params.city, temperature: 25, weather: '晴天' };
});

// 批量注册工具
agent.registerTools([
  {
    definition: {
      name: 'search_web',
      description: '搜索网页信息',
      parameters: { ... },
    },
    executor: async (params) => { ... },
  },
]);

Plan 模式事件监听

Plan 模式支持标准化的事件监听,方便监控任务执行进度:

const result = await planAgent.run('帮我完成一个市场调研报告', {
  onPlanEvent: (event) => {
    switch (event.type) {
      case 'plan_created':
        console.log(`📋 计划创建: ${event.data.totalTasks} 个任务`);
        event.data.tasks.forEach(t => console.log(`  - ${t.description}`));
        break;
      
      case 'task_started':
        console.log(`🔄 开始执行: ${event.data.task.description}`);
        break;
      
      case 'task_completed':
        console.log(`✅ 任务完成: ${event.data.task.description}`);
        console.log(`   进度: ${event.data.progress.completed}/${event.data.progress.total}`);
        break;
      
      case 'task_failed':
        console.log(`❌ 任务失败: ${event.data.task.error}`);
        break;
      
      case 'plan_completed':
        console.log(`🎉 计划完成! 总耗时: ${event.data.totalDuration}ms`);
        console.log(`   完成: ${event.data.completedTasks}, 失败: ${event.data.failedTasks}`);
        break;
      
      case 'plan_failed':
        console.log(`❌ 计划失败: ${event.data.reason}`);
        break;
    }
  },
});

进度回调

const result = await agent.run('分析并总结市场数据', {
  onProgress: (event) => {
    console.log(`阶段: ${event.phase}`);
    if (event.currentStep) {
      console.log(`步骤: ${event.currentStep}/${event.totalSteps}`);
    }
    if (event.message) {
      console.log(`消息: ${event.message}`);
    }
  },
});

Agent 运行结果

interface AgentRunResult {
  success: boolean;           // 是否成功
  output: string;             // 最终输出
  messages: Message[];        // 对话历史
  plan?: ExecutionPlan;       // 执行计划(plan 模式)
  steps?: StepResult[];       // 步骤结果(plan 模式)
  toolResults: ToolExecutionResult[];  // 工具调用结果
  tokenUsage: {               // Token 消耗
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
  };
  totalDuration: number;      // 总耗时
  reflection?: string;        // 反思总结
}

// AgentHub 运行结果扩展
interface AgentHubRunResult extends AgentRunResult {
  intentResult?: IntentRecognitionResult;  // 意图识别结果
  usedAgent: string;           // 实际使用的 Agent 名称
  usedMode: AgentMode;         // 实际使用的模式
}

AgentHub 配置选项

const hub = new AgentHub({
  ai,
  
  // 基础配置
  defaultMode: 'auto',           // 默认运行模式
  autoDetectIntent: true,        // 自动检测意图
  intentDetectionModel: 'gpt-4o-mini',  // 意图识别模型
  cacheIntentResults: true,      // 缓存意图识别结果
  model: 'gpt-4o',
  provider: 'openai',
  
  // 自定义意图识别器
  intentDetector: async (input, context) => {
    // 自定义意图识别逻辑
    return {
      intent: 'custom',
      recommendedAgent: 'custom',
      recommendedMode: 'tool',
      confidence: 0.9,
    };
  },
  
  // 内置 Agent 配置
  chatAgentOptions: { temperature: 0.7 },
  toolAgentOptions: { maxIterations: 10 },
  planAgentOptions: { enableReflection: true },
  
  // 全局工具
  toolRegistry: myToolRegistry,
  tools: [
    {
      definition: { name: 'tool1', ... },
      executor: async () => { ... },
    },
  ],
  
  // 额外的 Agent
  agents: [
    {
      name: 'custom',
      agent: customAgent,
      capabilities: { ... },
      mode: 'custom',
    },
  ],
});

Agent 完整示例

import { UnifiedAI, AgentHub } from 'unified-ai-sdk';

async function main() {
  // 1. 创建 AI 实例
  const ai = new UnifiedAI({
    providers: {
      openai: { apiKey: process.env.OPENAI_API_KEY },
    },
  });

  // 2. 创建 AgentHub
  const hub = new AgentHub({
    ai,
    autoDetectIntent: true,
    model: 'gpt-4o',
  });

  // 3. 注册全局工具
  hub.registerTool({
    name: 'search_market_data',
    description: '搜索市场数据',
    parameters: {
      type: 'object',
      properties: {
        keyword: { type: 'string', description: '搜索关键词' },
      },
      required: ['keyword'],
    },
  }, async (params) => {
    // 模拟数据搜索
    return { data: `${params.keyword} 相关市场数据...` };
  });

  // 4. 运行 AgentHub
  const result = await hub.run(
    '帮我完成一份人工智能行业的市场调研报告,包括市场规模、主要玩家、发展趋势',
    {
      showIntentDetection: true,
      onPlanEvent: (event) => {
        if (event.type === 'plan_created') {
          console.log(`📋 计划创建: ${event.data.totalTasks} 个任务`);
        } else if (event.type === 'task_completed') {
          console.log(`✅ 完成: ${event.data.task.description}`);
        }
      },
    }
  );

  // 5. 输出结果
  console.log('\n========== 最终报告 ==========\n');
  console.log(result.output);
  console.log('\n========== 执行统计 ==========');
  console.log(`使用的 Agent: ${result.usedAgent}`);
  console.log(`使用的模式: ${result.usedMode}`);
  console.log(`成功: ${result.success}`);
  console.log(`耗时: ${(result.totalDuration / 1000).toFixed(2)}s`);
  console.log(`Token: ${result.tokenUsage.totalTokens}`);
}

main();

+++++++ REPLACE</task_progress>


文档目录

| 文档 | 描述 | | -------------------------------------- | -------------------- | | 快速开始指南 | 安装、配置和基础用法 | | API 参考文档 | 完整的 API 接口说明 | | 平台配置 | 支持的平台和配置方式 | | 协议配置 | 内置协议和自定义协议 | | 模型配置 | 支持的模型列表和配置 | | 高级用法 | 扩展开发、最佳实践 | | Agent 文档 | Agent 功能说明 | | 更新日志 | 版本更新记录 |


目录结构

unified-ai-sdk/
├── src/
│   ├── index.ts              # 主入口,导出所有公共 API
│   ├── core.ts               # UnifiedAI 核心类实现
│   ├── types.ts              # 完整的 TypeScript 类型定义
│   ├── agent.ts              # Agent 功能
│   ├── tool.ts               # 工具调用系统
│   ├── task-manager.ts       # 异步任务管理器
│   ├── utils.ts              # 工具函数
│   ├── plugins/              # 平台插件目录
│   │   ├── index.ts          # 插件导出
│   │   ├── openai/           # OpenAI 插件
│   │   ├── deepseek/         # DeepSeek 插件
│   │   ├── zhipu/            # 智谱 AI 插件
│   │   ├── aliyun/           # 阿里云百炼插件
│   │   └── ...               # 更多平台插件
│   ├── tools/                # 内置工具目录
│   │   ├── index.ts          # 工具导出
│   │   ├── web_search.ts     # 网页搜索工具
│   │   └── get_current_time.ts # 获取当前时间工具
│   ├── skill-engine/         # 技能引擎
│   │   ├── index.ts
│   │   ├── core.ts
│   │   └── ...
│   └── web/                  # Web 相关功能
│       └── MediaController.ts
├── docs/                     # 文档目录
├── examples/                 # 示例代码
└── vue/                      # Vue 组件示例

开发

安装依赖

pnpm install

构建

pnpm build

开发模式

pnpm dev

贡献指南

我们欢迎所有形式的贡献!

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 创建 Pull Request

许可证

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


联系方式


如果这个项目对你有帮助,请给我们一个 ⭐️ Star!

Made with ❤️ by the Unified AI SDK Team


使用示例文档

本文档提供 Unified AI SDK 的丰富使用示例,涵盖所有核心功能。


目录


基础用法

初始化 SDK

import { UnifiedAI } from 'unified-ai-sdk';

// 最简单的初始化
const ai = new UnifiedAI({
  providers: {
    openai: { apiKey: process.env.OPENAI_API_KEY },
  },
});

// 完整配置
const ai = new UnifiedAI({
  defaultProvider: 'openai',
  providers: {
    openai: {
      apiKey: process.env.OPENAI_API_KEY,
      timeout: 60000,
      maxRetries: 3,
    },
    deepseek: {
      apiKey: process.env.DEEPSEEK_API_KEY,
      enabled: true,
    },
    zhipu: {
      apiKey: process.env.ZHIPU_API_KEY,
      defaultModel: 'glm-4.7',
    },
  },
});

文本对话

多轮对话

import type { Message } from 'unified-ai-sdk';

const messages: Message[] = [
  { role: 'system', content: '你是一个专业的 AI 助手' },
  { role: 'user', content: '你好' },
  { role: 'assistant', content: '你好!有什么可以帮助你的吗?' },
  { role: 'user', content: '请解释一下什么是 TypeScript' },
];

const response = await ai.chat({
  model: 'gpt-4o',
  messages,
  temperature: 0.7,
  maxTokens: 1000,
});

console.log(response.content);
console.log(`Token 使用: ${response.usage.totalTokens}`);

流式对话

await ai.chatStream({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: '写一首关于春天的诗' }],
  onChunk: (chunk) => {
    if (chunk.delta.content) {
      process.stdout.write(chunk.delta.content);
    }
    if (chunk.finishReason) {
      console.log('\n完成原因:', chunk.finishReason);
    }
  },
});

带参数的对话

const response = await ai.chat({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: '给我一个 1-100 的随机数' }],
  temperature: 1.5,       // 更随机
  maxTokens: 100,
  seed: 42,               // 固定种子(可复现)
  responseFormat: { type: 'json_object' },  // JSON 格式输出
});

函数调用

const tools = [
  {
    type: 'function' as const,
    function: {
      name: 'get_weather',
      description: '获取指定城市的天气',
      parameters: {
        type: 'object',
        properties: {
          city: { type: 'string', description: '城市名称' },
        },
        required: ['city'],
      },
    },
  },
];

const response = await ai.chat({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: '北京今天天气怎么样?' }],
  tools,
  toolChoice: 'auto',
});

if (response.toolCalls) {
  for (const call of response.toolCalls) {
    console.log(`调用函数: ${call.function.name}`);
    console.log(`参数: ${call.function.arguments}`);
  }
}

JSON 模式

const response = await ai.chat({
  model: 'gpt-4o',
  messages: [
    { role: 'system', content: '你是一个数据分析助手,始终返回 JSON 格式' },
    { role: 'user', content: '分析"今天天气很好"的情感' },
  ],
  responseFormat: { type: 'json_object' },
});

const result = JSON.parse(response.content);
console.log(result);

视觉理解

分析单张图片

const response = await ai.chat({
  model: 'gpt-4o',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: '这张图片里有什么?请详细描述。' },
        {
          type: 'image_url',
          image_url: {
            url: 'https://example.com/image.jpg',
            detail: 'high',  // 'low' | 'high' | 'auto'
          },
        },
      ],
    },
  ],
});

console.log(response.content);

使用 Base64 图片

import fs from 'fs';

const imageBuffer = fs.readFileSync('./image.jpg');
const base64Image = imageBuffer.toString('base64');

const response = await ai.chat({
  model: 'gpt-4o',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: '描述这张图片' },
        {
          type: 'image_url',
          image_url: {
            url: `data:image/jpeg;base64,${base64Image}`,
          },
        },
      ],
    },
  ],
});

多图片比较

const response = await ai.chat({
  model: 'gpt-4o',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: '比较这两张图片的差异' },
        { type: 'image_url', image_url: { url: 'https://example.com/before.jpg' } },
        { type: 'image_url', image_url: { url: 'https://example.com/after.jpg' } },
      ],
    },
  ],
});

OCR 文字识别

const response = await ai.chat({
  model: 'glm-4.6v',  // 智谱视觉模型
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: '识别图片中的所有文字,保持原有格式' },
        { type: 'image_url', image_url: { url: 'https://example.com/document.png' } },
      ],
    },
  ],
});

使用阿里云视觉模型

const response = await ai.chat({
  provider: 'aliyun',
  model: 'qwen-vl-max',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: '分析这张图表' },
        { type: 'image_url', image_url: { url: 'https://example.com/chart.png' } },
      ],
    },
  ],
});

图片生成

同步生成(DALL-E)

const result = await ai.generateImage({
  model: 'dall-e-3',
  prompt: '一只可爱的橘猫在阳光下打盹,水彩画风格',
  size: '1024x1024',
  quality: 'hd',
  style: 'vivid',
});

console.log('生成的图片:');
result.images.forEach((img, i) => {
  console.log(`图片 ${i + 1}: ${img.type === 'url' ? img.data : 'base64数据'}`);
  if (img.revisedPrompt) {
    console.log(`优化后的提示词: ${img.revisedPrompt}`);
  }
});

异步生成(阿里云万相)

// 提交生成任务
const result = await ai.generateImage({
  provider: 'aliyun',
  model: 'wan2.6-t2i',
  prompt: '一幅中国水墨画风格的山水画',
  size: '1024x1024',
});

console.log(`任务已提交,ID: ${result.taskId}`);

// 等待完成
const finalStatus = await ai.waitForTaskCompletion(result.taskId!, {
  pollInterval: 3000,
  timeout: 300000,
  onProgress: (status) => {
    console.log(`进度: ${status.progress || 0}%`);
  },
});

if (finalStatus.status === 'completed' && finalStatus.result) {
  const images = (finalStatus.result as any).images;
  console.log('生成的图片:', images);
}

使用智谱 CogView

const result = await ai.generateImage({
  provider: 'zhipu',
  model: 'cogview-3-flash',  // 免费模型
  prompt: '一个未来感的城市景观',
  size: '1024x1024',
});

带负面提示词

const result = await ai.generateImage({
  model: 'wan2.6-t2i',
  prompt: '一个美丽的花园',
  negativePrompt: '模糊, 低质量, 变形',
  size: '1024x1024',
});

视频生成

文本生成视频

// 提交视频生成任务
const result = await ai.generateVideo({
  model: 'kling-v1',
  prompt: '夕阳西下,海浪轻拍沙滩,远处的帆船缓缓驶过',
  duration: 5,
  aspectRatio: '16:9',
});

console.log(`任务 ID: ${result.taskId}`);
console.log(`预计时间: ${result.estimatedTime} 秒`);

// 等待完成
const finalStatus = await ai.waitForTaskCompletion(result.taskId!, {
  pollInterval: 5000,
  timeout: 600000,
  onProgress: (status) => {
    console.log(`状态: ${status.status}, 进度: ${status.progress || 0}%`);
  },
});

if (finalStatus.status === 'completed' && finalStatus.result) {
  const videos = (finalStatus.result as any).videos;
  console.log('生成的视频:', videos);
}

图片生成视频

const result = await ai.generateVideo({
  model: 'kling-v1',
  prompt: '让这张图片动起来',
  referenceImage: 'https://example.com/image.jpg',
  duration: 5,
  aspectRatio: '16:9',
});

使用豆包 Seedance

const result = await ai.generateVideo({
  provider: 'doubao',
  model: 'doubao-seedance-1-5-pro-251215',
  prompt: '一只蝴蝶在花丛中翩翩起舞',
  duration: 5,
  aspectRatio: '16:9',
});

语音功能

文字转语音(TTS)

const result = await ai.textToSpeech({
  model: 'tts-1',
  text: '欢迎使用统一 AI SDK,这是一个强大的多平台整合工具。',
  voice: 'alloy',
  speed: 1.0,
  outputFormat: 'mp3',
});

console.log(`音频格式: ${result.audio.format}`);
// result.audio.data 包含 base64 编码的音频数据

// 保存音频文件
import fs from 'fs';
const audioBuffer = Buffer.from(result.audio.data, 'base64');
fs.writeFileSync('output.mp3', audioBuffer);

使用 ElevenLabs 高质量语音

const result = await ai.textToSpeech({
  provider: 'elevenlabs',
  model: 'eleven_multilingual_v2',
  text: 'Hello, this is a test.',
  voice: '21m00Tcm4TlvDq8ikWAM',
});

语音识别(ASR)

const result = await ai.speechToText({
  model: 'whisper-1',
  audio: 'https://example.com/audio.mp3',
  language: 'zh',
  returnTimestamps: true,
});

console.log(`转写文本: ${result.text}`);

if (result.segments) {
  console.log('时间戳信息:');
  result.segments.forEach((seg) => {
    console.log(`[${seg.start}s - ${seg.end}s] ${seg.text}`);
  });
}

使用本地音频文件

import fs from 'fs';

const audioBuffer = fs.readFileSync('./audio.mp3');
const base64Audio = audioBuffer.toString('base64');

const result = await ai.speechToText({
  model: 'whisper-1',
  audio: `data:audio/mp3;base64,${base64Audio}`,
  language: 'zh',
});

高级用法

多平台故障转移

async function chatWithFallback(messages: Message[]): Promise<string> {
  const providers = [
    { name: 'openai', model: 'gpt-4o' },
    { name: 'deepseek', model: 'deepseek-chat' },
    { name: 'zhipu', model: 'glm-4.7' },
  ];

  for (const { name, model } of providers) {
    try {
      const response = await ai.chat({
        provider: name,
        model,
        messages,
      });
      return response.content;
    } catch (error) {
      console.warn(`${name} 失败,尝试下一个...`);
    }
  }

  throw new Error('所有平台都不可用');
}

负载均衡

class LoadBalancer {
  private providers: string[];
  private currentIndex = 0;

  constructor(providers: string[]) {
    this.providers = providers;
  }

  getNext(): string {
    const provider = this.providers[this.currentIndex];
    this.currentIndex = (this.currentIndex + 1) % this.providers.length;
    return provider;
  }
}

const balancer = new LoadBalancer(['openai', 'deepseek', 'zhipu']);

async function balancedChat(messages: Message[]) {
  const provider = balancer.getNext();
  return ai.chat({ provider, messages });
}

事件监听

// 监听所有事件
ai.on('request:start', (event, data) => {
  console.log(`[${new Date().toISOString()}] 请求开始:`, data);
});

ai.on('request:end', (event, data) => {
  console.log(`[${new Date().toISOString()}] 请求完成`);
});

ai.on('request:error', (event, data) => {
  console.error(`[${new Date().toISOString()}] 请求错误:`, data);
});

ai.on('stream:chunk', (event, data) => {
  // 可以在这里记录日志或做其他处理
});

ai.on('task:created', (event, data) => {
  console.log(`异步任务创建: ${(data as any).taskId}`);
});

ai.on('task:completed', (event, data) => {
  console.log(`异步任务完成: ${(data as any).taskId}`);
});

批量处理

async function batchProcess(prompts: string[]): Promise<string[]> {
  const results = await Promise.all(
    prompts.map((prompt) =>
      ai.simpleChat(prompt, { model: 'gpt-4o-mini' })
    )
  );
  return results;
}

const answers = await batchProcess([
  '什么是 TypeScript?',
  '什么是 React?',
  '什么是 Node.js?',
]);

流式输出到客户端

import { Response } from 'express';

async function streamToClient(res: Response, prompt: string) {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  await ai.chatStream({
    model: 'gpt-4o',
    messages: [{ role: 'user', content: prompt }],
    onChunk: (chunk) => {
      if (chunk.delta.content) {
        res.write(`data: ${JSON.stringify({ content: chunk.delta.content })}\n\n`);
      }
    },
  });

  res.write('data: [DONE]\n\n');
  res.end();
}

完整工作流示例

async function fullWorkflow() {
  // 1. 文本对话生成创意
  const storyResponse = await ai.chat({
    model: 'gpt-4o',
    messages: [{
      role: 'user',
      content: '请写一个关于外星人来地球的简短故事(100字以内)',
    }],
  });
  const story = storyResponse.content;
  console.log('生成的故事:', story);

  // 2. 为故事生成配图
  const imageResult = await ai.generateImage({
    model: 'dall-e-3',
    prompt: `科幻风格插画:${story.substring(0, 50)}`,
    size: '1024x1024',
  });
  console.log('配图 URL:', imageResult.images[0]?.data);

  // 3. 生成语音朗读
  const ttsResult = await ai.textToSpeech({
    model: 'tts-1',
    text: story,
    voice: 'onyx',
  });
  console.log('语音已生成');

  // 4. 生成视频
  const videoResult = await ai.generateVideo({
    model: 'kling-v1',
    prompt: story,
    duration: 5,
  });

  const finalVideo = await ai.waitForTaskCompletion(videoResult.taskId!);
  console.log('视频生成完成:', finalVideo.status);
}

添加自定义平台

// 使用 Builder 添加自定义平台
import { ProviderBuilder, ModelBuilder } from 'unified-ai-sdk';

const customProvider = new ProviderBuilder('my-ai')
  .name('My AI Platform')
  .baseUrl('https://api.my-ai.com/v1')
  .apiKey('your-api-key')
  .timeout(120000)
  .build();

ai.registerProvider(customProvider);

const customModel = new ModelBuilder('my-model')
  .name('My Model')
  .provider('my-ai')
  .capabilities(['chat', 'chat-stream'])
  .protocol('chat', 'openai-chat')
  .protocol('chat-stream', 'openai-chat-stream')
  .contextWindow(32000)
  .build();

ai.registerModel(customModel);

// 使用自定义平台
const response = await ai.chat({
  provider: 'my-ai',
  model: 'my-model',
  messages: [{ role: 'user', content: '你好' }],
});

错误处理最佳实践

async function safeChat(messages: Message[]): Promise<string> {
  try {
    const response = await ai.chat({
      model: 'gpt-4o',
      messages,
    });
    return response.content;
  } catch (error: any) {
    // 检查是否是可重试的错误
    if (error.statusCode === 429) {
      console.log('触发限流,等待后重试...');
      await new Promise((r) => setTimeout(r, 5000));
      return safeChat(messages);  // 重试
    }

    if (error.statusCode === 401) {
      throw new Error('API Key 无效');
    }

    if (error.statusCode >= 500) {
      console.log('服务端错误,切换平台');
      // 故障转移
      return ai.simpleChat(messages[messages.length - 1].content as string, {
        provider: 'deepseek',
      });
    }

    throw error;
  }
}