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

mediachain

v1.2.0

Published

统一的AI模型调用调度层,支持多个第三方服务提供商

Downloads

612

Readme

MediaChain

MediaChain 是一个独立的模型调用调度层,封装了 Replicate、火山引擎、Tuzi、DreamAPI、OpenRouter 等第三方服务的输入输出逻辑,并且提供统一的运行与结果查询能力。通过依赖注入的方式,MediaChain 可以在任何项目中复用,并保持高内聚、低耦合的设计。

✨ 特性

  • 统一输入输出:所有 Provider 均遵守同一套 ModelRunParams 和返回结构。
  • 依赖注入:上传资源、对话历史、第三方客户端等全部通过依赖注入完成,MediaChain 内部不包含数据库或存储逻辑。
  • 可扩展架构:Provider、策略与上下文解耦,便于新增模型或替换实现。
  • TypeScript 友好:完整的类型定义,帮助调用方快速集成并获得 IDE 提示。

🚀 Getting Started

1. 安装

在 monorepo 中可直接通过工作区依赖引用:

pnpm add mediachain

如果作为独立 NPM 包使用:

npm install mediachain
# 或
pnpm add mediachain
yarn add mediachain

2. 创建实例

import { MediaChain, MediaChainDependencies, ModelRunParams } from 'mediachain'

const dependencies: MediaChainDependencies = {
  assets: {
    uploadImageFromUrl: async (url) => url,
    uploadVideoFromUrl: async (url) => url,
    uploadBase64Image: async (base64) => `data:image/png;base64,${base64}`
  }
}

const mediaChain = new MediaChain({
  modelResolver: async (modelId) => ({
    id: modelId,
    key: 'openai/gpt-4o-mini',
    provider: 'OPEN_ROUTER',
    modelType: 'CHAT_COMPLETION'
  }),
  dependencies
})

3. 运行模型

const params: ModelRunParams = {
  prompt: '帮我写一首关于春天的诗',
  conversationId: 'conv_1',
  userId: 'user_1'
}

const response = await mediaChain.run('model-id', params)

if (response.success && response.mode === 'sync') {
  console.log('输出结果:', response.output)
}

4. 查询异步任务

const result = await mediaChain.getResult('model-id', { jobId: 'task_123' })
if (result.success && result.status === 'COMPLETED') {
  console.log('生成结果:', result.output)
}

📦 输入输出结构

ModelRunParams

interface ModelRunParams {
  prompt: string
  input_images?: string[]
  size?: string
  duration?: string
  conversationId?: string
  userId?: string
  generationNum?: number
  historyMessages?: ConversationMessage[]
}
  • historyMessages:可直接注入对话上下文,或通过 conversationHistory 适配器按需加载。
  • 额外字段会原样透传给具体 Provider。

MediaChainRunResponse

interface MediaChainRunResponse {
  success: boolean
  jobId: string
  mode?: 'sync' | 'async'
  output?: string[]
  prediction?: unknown
  result?: unknown
  error?: string
}
  • modesync 代表同步返回结果,async 代表需要轮询 getResult
  • output:规范化后的结果列表(文本或已上传的资源 URL)。

GetResultResponse

interface GetResultResponse {
  success: boolean
  status: string
  output?: unknown
  error?: string | null
  prediction?: unknown
  result?: unknown
}
  • status 常见值:COMPLETEDGENERATINGFAILEDCANCELLED

🔌 依赖注入

通过 MediaChainDependencies 可以配置:

  • assets:处理图片、视频的上传逻辑(必须提供)。
  • replicate:自定义 Replicate 客户端,默认使用 REPLICATE_API_TOKEN
  • volcengine:注入火山引擎客户端。
  • notifier:接收 Provider 的警告(如余额不足)。
  • conversationHistory:按需读取对话历史,构建多轮上下文。

示例:

const mediaChain = new MediaChain({
  dependencies: {
    assets: myAssetAdapter,
    notifier: {
      onProviderWarning: ({ provider, message }) => console.warn(provider, message)
    }
  }
})

🧩 扩展 Provider

  1. 新建类继承 BaseProvider,实现 run/getResult 等方法。
  2. ProviderFactory 中注册。
  3. 根据需要扩展策略、上下文依赖。

🔧 开发指南

本地开发

# 安装依赖
cd packages/MediaChain
npm install

# 开发模式(监听文件变化)
npm run dev

# 构建
npm run build

# 清理构建文件
npm run clean

目录结构

packages/MediaChain/
├── src/                    # 源代码
│   ├── index.ts           # 入口文件
│   ├── mediachain.ts      # 主要调度逻辑
│   ├── types.ts           # TypeScript 类型定义
│   ├── providers/         # 服务提供商实现
│   ├── strategies/        # 参数处理策略
│   └── utils/             # 工具函数
├── dist/                  # 编译输出(发布时生成)
├── scripts/               # 发布脚本
└── README.md              # 项目文档

📦 发布到 NPM

前置条件

  1. NPM 登录:确保已登录到 NPM

    npm login
    npm whoami  # 验证登录状态
  2. 权限检查:确保有 mediachain 包的发布权限

发布流程

方式一:使用发布脚本(推荐)

# 进入 MediaChain 目录
cd packages/MediaChain

# Patch 版本发布(修复bug)
./scripts/publish.sh patch

# Minor 版本发布(新功能)
./scripts/publish.sh minor

# Major 版本发布(破坏性更改)
./scripts/publish.sh major

方式二:手动发布

# 1. 清理和构建
npm run clean
npm run build

# 2. 更新版本号
npm version patch  # 或 minor/major

# 3. 发布
npm publish

# 4. 推送标签到 Git
git push origin --tags

发布检查清单

发布前请确保:

  • [ ] 所有测试通过
  • [ ] 代码已提交到 Git
  • [ ] 版本号符合语义化版本规范
  • [ ] README 和文档已更新
  • [ ] 构建输出正确(检查 dist/ 目录)

版本管理

遵循 语义化版本 规范:

  • Patch (1.0.1):错误修复,向后兼容
  • Minor (1.1.0):新功能,向后兼容
  • Major (2.0.0):破坏性更改

发布后验证

# 验证包是否正确发布
npm view mediachain

# 在新项目中测试安装
npm install mediachain

NPM 脚本说明

| 脚本 | 功能 | 用途 | |------|------|------| | npm run build | TypeScript 编译 | 生成发布文件 | | npm run dev | 开发模式 | 监听文件变化自动编译 | | npm run clean | 清理构建文件 | 删除 dist/ 目录 | | npm run prepublishOnly | 发布前自动执行 | 自动清理和构建 | | npm run publish:patch | Patch 版本发布 | 自动版本号+发布 | | npm run publish:minor | Minor 版本发布 | 自动版本号+发布 | | npm run publish:major | Major 版本发布 | 自动版本号+发布 |

🤝 贡献

欢迎针对新的模型接入、依赖适配器和文档提出 Issue 或 PR。希望 MediaChain 能帮助你快速、稳定地整合多模型能力。

贡献流程

  1. Fork 项目
  2. 创建功能分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add amazing feature')
  4. 推送分支 (git push origin feature/amazing-feature)
  5. 创建 Pull Request