2dai-cloud-sdk

中文文档
3.2.0发布于 2026/11/03MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1838

2DAI生成API的已打入了JavaScript/TypeScript客户端——生成图像和视频,上传引用,并以API键下载结果.

中文使用文档
文档目录18 节
  1. 默认频道中的 Gen8
  2. 拿个钥匙
  3. 快速启动
  4. 正在生成
  5. 上传自己的媒体
  6. 下载
  7. 云盘驱动
  8. 浏览您的库
  9. 组织
  10. 账户历史( R)
  11. 状态
  12. 钱包数据( 只读)
  13. 处理错误
  14. 2DAI 堆栈
  15. 不是在JavaScript上吗? 使用 REST API
  16. 配置
  17. 许可证
  18. 社区链接( L)

2dai-cloud-sdk (英语)

npm

输入的 JavaScript/ TypeScript 客户端 2DAI (英语) 生成 API. 生成图像和视频、上传引用、浏览和组织您的云 驱动器和下载结果——都带有API键. 节点18+和现代浏览器. 零运行时间依赖关系.

不是在JavaScript上吗? 同一平台是一个简单的REST API——跳到 使用 REST API。 。 。 .

npm install 2dai-cloud-sdk

默认频道中的 Gen8

generate.image 财务报告和审定财务报表 generate.video 在其默认信道上运行GN8引擎; me().modelLabels 名称 每个频道后面的引擎( 今天) 第8.1类),一个频道的每一个规则都遵循该引擎:

  • 图像: 最多 6个 refCreationIds 在图片中保留了当地可辨认的文字, negativePrompt 在每个预设中应用.
  • 视频: 剪辑 有声音 24英尺,从第一个框架(inputCreationId+ 最多6个 refCreationIds (特征、道具、地点),可选 aspectRatio 和可选 音频参考 (单位:千美元)uploads.audio() a 一个 MP3,然后将其编号通过为 audioCreationId, (中文(简体) ), audioUse: 'music' 用于音轨或 'voice' 为了语音样本. 长度为精确秒 (1, 5, 8, 10, 12, 15, 17, 20, 按分级打开); 视频在 Explorer 打开.
  • 预设和长度取决于等级:已读 me().qualities 财务报告和审定财务报表 me().videoDurations 而不是猜测.

next 用于下一个引擎。 直到2026-11-17,它服务于默认通道的同一种引擎;之后是它 答复 400 VIDEO_MODEL_UNAVAILABLE 编号 : IMAGE_MODEL_UNAVAILABLE,未充电,直到引擎打开(见 me().modelChannels) (中文(简体) ). 离开 videoModel 编号 : imageModel 未设. 来源于3.1.x:见 变化。 。 。 .

拿个钥匙

签名于 第2代义奥 (任何活账户工程——无计划) 然后在仪表板上打开 集成 — API 密钥 — + 新密钥。 。 。 . 钥匙看起来像 2dai_sk_…,带宽(read, (中文(简体) ), generate,并且可以拥有 可选开支上限。 秘密一度被显示——存放在安全的地方. API 密码 几代人花你的账户信用 就像工作室。 完全通过 : 开始。 。 。 .

快速启动

import { Client } from '2dai-cloud-sdk';

const client = new Client({ apiKey: process.env.TWODAI_API_KEY! });

// Generates, waits for completion, and returns the finished creation.
const gen = await client.generate.image({ prompt: 'a red origami fox', aspectRatio: '1:1' });
console.log(gen.creationId, gen.downloadUrl);

// Save the actual bytes to disk (Node).
await client.download(gen, { savePath: './fox' }); // → ./fox.jpg

正在生成

generate.* 提交到同步队列 。 默认的 投票结束 财务报告和审定财务报表 返回已完成的 GenerationResult。通过 { wait: false } 获取队列 立即给自己投票.

// One-shot (default): resolves when the image is ready.
const img = await client.generate.image({
  prompt: 'a neon city street, rain',
  aspectRatio: '16:9', // or 'auto' — the server picks the best ratio from the prompt
  // style + quality default to 'auto' (the server picks by your tier);
  // me().qualities lists the presets open to your tier and flags the recommended one
});

// `enhanced` rewrites your prompt with TIXI, the 2DAI prompt agent, before it
// reaches the image model — it fills in camera, lighting, composition and style
// from a short brief. ~2s extra, no extra credit. Your text stays in `.prompt`;
// TIXI's version is in `.raw.finalPrompt`.
const rich = await client.generate.image({ prompt: 'a warrior', enhanced: true });

// Up to 6 references kept natively, legible text, long literal prompts honoured.
const poster = await client.generate.image({
  prompt: 'a concert poster titled "NEON TIDE": the singer with the red braids on the neon-lit festival stage, bold white typography',
  refCreationIds: [singerId, venueId],      // optional, ≤6 (each adds a surcharge)
  quality: 'auto',                          // or an allowed id of me().qualities.image ('max' opens at Holder)
});

// Non-blocking: get a ticket now, poll later.
const { queueId } = await client.generate.image({ prompt: '…' }, { wait: false });
const state = await client.queue.waitFor(queueId, { timeoutMs: 300_000 });

// Reference tools (character-ref / style-transfer / smart-edit), on the Gen8 image engine:
const ref = await client.generate.imageWithRefs({
  tool: 'character-ref',         // 1–6 shots of one character; face photos lock the exact same face
  prompt: 'as an astronaut',
  refCreationIds: [gen.creationId],
});

// Smart edit: refs[0] is the image to EDIT, the prompt is the instruction.
const edited = await client.generate.imageWithRefs({
  tool: 'smart-edit',
  prompt: 'replace the background with a rainy neon street',
  refCreationIds: [gen.creationId],
});

// Artist Painter: paint your subject as a new work in a curated
// artistic style. `artisticStyles.list()` gives the ids; omit `artisticStyleId` for 'auto'.
const styles = await client.artisticStyles.list();
const painting = await client.generate.artisticStyle({
  prompt: 'a lighthouse on a stormy coast',
  artisticStyleId: styles[0]?.artisticStyleId,          // or 'auto'
  refCreationIds: [gen.creationId],        // optional subject images (≤6)
});

// Video from an existing still, with sound. `duration` is one of me().videoDurations
// (exact seconds, tier lock resolved). Every video style except 'raw' runs TIXI on your
// prompt (the style's guidance only exists through that rewrite); 'raw' sends it
// verbatim unless enhanced: true. An empty prompt on 'raw' or 'auto' runs the 'action'
// style, exactly as if you had picked it.
const vid = await client.generate.video({
  prompt: 'gentle camera push-in',
  inputCreationId: gen.creationId,
  duration: 5,
  style: 'raw',        // verbatim — add `enhanced: true` to let TIXI write the brief
});

// A first frame plus up to 6 references, a ratio and a longer clip. Clips render for
// minutes: the SDK waits up to 20 min for a video (set timeoutMs, or wait: false).
const scene = await client.generate.video({
  prompt: 'the kite surfer lands, waves at the camera, the crowd cheers',
  inputCreationId: gen.creationId,          // first frame
  refCreationIds: [characterId, placeId],   // optional, ≤6 (each adds a surcharge)
  duration: 8,                              // one of me().videoDurations (8 s opens at Holder)
  aspectRatio: '16:9',                      // 'auto' = the first frame's ratio
  style: 'raw', enhanced: true,             // your idea → TIXI writes the brief (shots, pictures, sound)
});

// With an audio reference: your MP3 as the soundtrack ('music') or as a voice
// sample the speaking character follows ('voice'). Counts as one more reference
// for the price.
const track = await client.uploads.audio({ path: './theme.mp3' });
const scored = await client.generate.video({
  prompt: 'the band walks on stage as the intro swells',
  inputCreationId: gen.creationId,
  audioCreationId: track.creationId,
  audioUse: 'music',
  duration: 5,
});

// Wallpaper-resize: expand a creation into a wallpaper dimension. It runs on its own
// engine: quality is always Ultra, the dimension drives the price, up to 3 extra references.
const wall = await client.generate.wallpaper({
  inputCreationId: gen.creationId,
  dimension: 'widescreen',   // 'standard' | 'photo' | 'widescreen' | 'ultrawide'
});

每个工具都封住其参考文献(6个图像 6个字符-ref 6个样式-传输 6个智能编辑 6个艺术风格 ) 3个壁纸 · 视频: 第一张相框加6个相框 —— 超过封顶拒绝 TOO_MANY_REFS 在一切被起诉之前 还是一张票 待处理 能够被停止 与 client.queue.cancel(queueId);收费被退还. 细节 : 正在生成。 。 。 .

上传自己的媒体

带一幅图像/图像/图像/ mp4( a) .m4v 被作为 mp4 接受并存储到您的库中,以便用作参考或 动画,或成为视频片段音频参考的MP3. 这个 和工作室运行服务器一样温和.

const up = await client.uploads.image({ path: './portrait.jpg' });      // Node
const up2 = await client.uploads.image({ data: fileBlob });             // Browser
await client.generate.imageWithRefs({ tool: 'character-ref', prompt: 'in a suit', refCreationIds: [up.creationId] });

// An MP3 (5 min max, from Explorer, like video) as a clip's audio reference — see generate.video above.
const track = await client.uploads.audio({ path: './theme.mp3' });

// File it straight into a folder, and skip re-uploads with the md5 pre-flight:
const probe = await client.uploads.checkDuplicate(md5Hex, folder.folderId);
if (!probe.duplicate) {
  await client.uploads.image({ path: './portrait.jpg', targetFolderId: folder.folderId });
}

targetFolderId 文件上传到您可以写入的文件夹( 403) INVALID_FOLDER (否则). croppedFromCreationId 编号 : erasedFromCreationId 将上传记录为裁剪或删除您拥有的创建的编辑。 细节 : 上传。 。 。 .

下载

client.cdn 用你的钥匙认证,所以它也适用于私人创作. 接受 CDN 代码, a Creation页:1 QueueState,或者一代的结果.

await client.cdn.download(gen, { savePath: './out' });   // Node → './out.jpg' (ext inferred)
const asset = await client.cdn.fetch(gen);               // { bytes, contentType, ext }
const blob = await client.cdn.toBlob(gen);               // Browser
const dataUrl = await client.cdn.toDataUrl(gen);         // <img src={dataUrl} />

// The CDN can resize before it sends: `maxSide` scales the longest edge and
// keeps the aspect ratio, so one call covers portrait and landscape.
const preview = await client.cdn.toDataUrl(gen, { maxSide: 512 });   // 1164 kB → 132 kB
await client.cdn.download(gen, { maxSide: 256, savePath: './thumb' }); // composes with savePath

maxSide 是您想要的预览和缩略图; width 编号 : height 目标 一个轴,可以收割。 细节 : 下载。 。 。 .

云盘驱动

从代码组织您的库——文件夹,移动,垃圾,出版(镜片: manage 组织, publish 为大众取用).

const folder = await client.folders.create({ title: 'Brand assets' });
await client.creations.move(gen, folder.folderId);   // or move(gen, 'root')
await client.creations.publish(gen);                 // generated work only
await client.creations.trash(gen);                   // reversible
await client.creations.restore(gen);
await client.creations.trash(gen); await client.creations.delete(gen); // permanent (trash first)
await client.folders.delete(folder.folderId, { trashContents: true });

浏览您的库

creations.list 讲的镜头和过滤器都和工作室的云一样 驱动器 - 1 模式 每个呼叫(一个文件夹,一个活动视图,一个智能集, 或与你们共享的文件夹,加上由其中任何一种组成的过滤器.

await client.creations.list({ folderId: folder.folderId });   // or 'root', or { trashed: true }
await client.creations.list({ activity: 'uploaded' });        // all|history|uploaded|likes|public|trash|sdk|mcp|portfolio
await client.creations.list({ smart: 'faces' });              // faces|videos|crop|alpha|favorites

// Filters compose with any lens: whole-word search (trailing * = prefix),
// sort, aspect-ratio buckets, date range, the studio's Likes and Type filters…
await client.creations.list({ search: 'red fox*', sort: 'size-desc', ratioFilter: 'portrait' });
await client.creations.list({ folderId: folder.folderId, likeFilter: 'liked', mediaKind: 'video' });

// ONE uniformly-random creation from any lens (images and videos only), same filters:
const surprise = await client.creations.random({ smart: 'favorites', mediaKind: 'image', blockNsfw: true });

// The cross-user public feed:
const feed = await client.creations.feed({ limit: 48 });

贴上 nextBeforeDate (限值1.100)或基于1的 page。行随行 description, (中文(简体) ), folderId, (中文(简体) ), inTrash, (中文(简体) ), isPublicShared, (中文(简体) ), likes, (中文(简体) ), isLiked 还有更多 细节 : 云驱动。 。 。 .

组织

await client.creations.like(gen, true);              // idempotent SET, retry-safe
await client.creations.batch('trash', ids);          // bulk trash/untrash/delete, ≤1000 ids
await client.creations.reorder([id1, id2, id3]);     // stamp drag-reorder order

// Sidebar folder groups + folder metadata:
const group = await client.folders.groups.create('Client work');
await client.folders.update(folder.folderId, {
  groupId: group.groupId,            // null detaches
  posterCreationId: gen.creationId,  // null clears
  isFavorite: true,
});

删除一个组只会去除其文件夹——没有其它内容被删除.

账户历史( R)

const me = await client.me();
console.log(me.creditUsd, me.tier, me.key.scopes);
console.log(me.promptMaxChars, me.promptMaxCharsNext); // prompt cap for this tier (1,500 → 20,000), and the tier that raises it
console.log(me.modelLabels, me.videoDurations, me.qualities); // engine per channel, lengths and presets open to this tier

const page = await client.creations.list({ limit: 20 });
const one = await client.creations.get(page.creations[0].creationId);

const state = await client.queue.get(queueId);       // one-shot status read
const url = client.cdn.url(one);                      // raw CDN url (public creations)

状态

只读账户分析( 镜片) read:

const o = await client.stats.overview();               // storage, counters, streak, per-tool recents
const g = await client.stats.generations({ days: 30 }); // volume + spend by day / tool / source
const t = await client.stats.top();                    // most-used refs (with suggested config), styles, keywords

钱包数据( 只读)

这个 finance 名称空间读取您的钱包: 平衡, 分层, 接锁, 交易、余额/信贷历史。 它需要一把钥匙薄荷 选择进入 finance 范围 (默认关闭)——严格只读:不存押, 退出、互换或锁定操作存在于 API- key 表面, 因此 a finance 键可以看到数字,但永远不能移动资金.

const w = await client.finance.wallet();          // tokens, creditUsd, tier, pending flags
const tx = await client.finance.transactions({ limit: 20 });
const price = await client.finance.tokenPrice();  // cached $2DAI quote — only needs `read`

深度 : 标签( W)。 。 。 .

处理错误

每次失败都会丢出一个您可以分支的打出的错误 :

import { InsufficientCreditError, SpendLimitError, NsfwRejectedError, ApiError } from '2dai-cloud-sdk';

try {
  await client.generate.image({ prompt: '…' });
} catch (err) {
  if (err instanceof InsufficientCreditError) console.log('Top up:', err.deficitUsd);
  else if (err instanceof SpendLimitError) console.log('Key cap hit at', err.spendLimitUsd);
  else if (err instanceof NsfwRejectedError) console.log('Blocked by moderation');
  else if (err instanceof ApiError) console.log(err.code, err.httpStatus);
  else throw err;
}

其他错误 : AuthError, (中文(简体) ), ScopeError, (中文(简体) ), TierError, (中文(简体) ), QueueLimitError, (中文(简体) ), RateLimitError, (中文(简体) ), ValidationError (与 DurationError (400美元) INVALID_DURATION,其 allowed 列出频道长度, , NotFoundError, (中文(简体) ), GenerationFailedError, (中文(简体) ), TimeoutError, (中文(简体) ), GenerationPausedError (503个) GENERATION_PAUSED,简短的维护:稍后重试), KeyPolicyQualityError 编号 : KeyPolicyDurationError (403) 密钥自己的盖: maxQuality 财务报告和审定财务报表 kind, (中文(简体) ), maxVideoDurationSec) (中文(简体) ). 全部扩展 ApiError (单位:千美元).code, (中文(简体) ), .httpStatus, (中文(简体) ), .details) (中文(简体) ). A 类 GenerationFailedError (和失败) QueueState)还携带 errorCode 改为 分支运行( c)CAPACITY_FULL, (中文(简体) ), EXPIRED, (中文(简体) ), GENERATION_TIMEOUT,(......)和 errorMessage, (中文(简体) ), 一个可以读取的句子,你可以显示. A 类 TierError 命名打开所询问的分级(requiredTier, (中文(简体) ), requiredTierName(中文(简体) ) 和舰船 准备判决 message (例如:".在霍尔德开. 提升等级... ); 没有受到任何指控.

A 类 内容评级 结果不是一个错误:创建者 nsfwFlagged: true (单位:千美元)nsfwRate 0.8或0.99 完成并受到指控,但它在 所有者驱动器, 无法使用公共种子, 无法发布 (单位:千美元)NSFW_NOT_PUBLISHABLE) (中文(简体) ). 把用户交给你 viewUrl 而不是审查 重试中. 仅 NSFW_MAX_EXCEEDED (平面天花板) 丢弃输出——无为 充电 重写提示 细节 : 内容评级。 。 。 .

2DAI 堆栈

2DAI运行自己的模型,与其他人不同,我们不转售模型访问. 我们所有的模型都来自开源社区 或者我们自己的研发 然后拆解、修改、调整和优化,使之与我们的遗产相一致 财务报告和审定财务报表 2DAI❤️ART (英语) 线条。 他们也在我们的私人云层网络上运行.

me().modelChannels 编号 : me().modelLabels 命名每个频道后面的引擎 (单位:千美元)videoModel 编号 : imageModel));一个频道的每一个规则都跟随了引擎. 这个 next 为下一个引擎保留频道.

即时重写( 扩展了短提示的"TIXI" 的通过 ) ——同样的规则:不重新出售第三方 模式访问。 深度 : 关于模型。 。 。 .

不是在JavaScript上吗? 使用 REST API

下方的一切都是平地HTTP——SDK是一个方便层,而不是一个出入口. 基础 URL https://dapp.2dai.io:444/v1,无记名认证, JSON进出. 世代是同步的:提交,然后投票.

# 1 · submit → returns a queueId
curl -X POST https://dapp.2dai.io:444/v1/generate/image \
  -H "Authorization: Bearer $TWODAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"prompt":"a lighthouse at dusk"}'

# 2 · poll until status is completed, then fetch downloadUrl with the same bearer
curl https://dapp.2dai.io:444/v1/queue/$QUEUE_ID \
  -H "Authorization: Bearer $TWODAI_API_KEY"
方法终点范围什麽
获取/v1/meread账户、信贷、关键范围
邮政/v1/generate/imagegenerate文本 — 图像
邮政/v1/generate/image-with-refsgenerate面相/ 字符参考、 样式传输、 智能编辑
邮政/v1/generate/wallpapergenerate墙纸尺寸调整(按尺寸计价)
邮政/v1/generate/videogenerate仍然 ~ 视频
邮政/v1/uploadsgenerate上传媒体( 多部分)
获取/v1/uploads/check-duplicatereadmd5 飞行前脱发探测器
获取/v1/queue/:queueIdread传票一代人
邮政/v1/queue/:queueId/cancelgenerate取消待定的生成(退款)
获取/v1/creationsread列表 / 搜索您的驱动器( 机位+过滤器)
获取/v1/creations/:idread一个创造,一个细节
获取/v1/feedread交叉用户的公用饲料
邮政/v1/creations/:id/move | /trash | /restore | /likemanage组织
邮政/v1/creations/reorder | /batchmanage重排/批量动作
迪莱特/v1/creations/:idmanage永久删除( 先删除)
邮政/v1/creations/:id/publish | /unpublishpublish公共饲料
获得/部署/部署/部署/部署/v1/foldersread 编号 : manage文件夹
获得/部署/部署/部署/部署/v1/folder-groupsread 编号 : manage侧边栏文件夹组
获取/v1/stats/overview | /generations | /topread账户分析
获取/v1/wallet*, (中文(简体) ), /v1/account/tierfinance只读钱包数据
获取/v1/tiers, (中文(简体) ), /v1/token/priceread分级目录, 缓存的代号引用
获取/cdn/file/:cdnIdread下载字节( E)?s=512 用于预览)

完整请求/响应形状,每个错误代码和限制都记录在 页:1 REST API 参考文献。 。 。 .

配置

new Client({
  apiKey: '2dai_sk_…',   // required
  baseUrl,               // default 'https://dapp.2dai.io:444'
  timeoutMs,             // per-request network timeout, default 60000
  maxRetries,            // idempotent GET retries on 429/5xx, default 2
  fetch,                 // inject a custom fetch
  integration,           // 'sdk' (default) | 'mcp' — official 2DAI integrations
  integrationVersion,    // that integration's own semver, e.g. '1.4.0'
});

integration 是一个关闭的集,而不是一个免费形式的用户代理,您应该 别管它了,每个创建的服务器邮票 source 从它,和 仪表板读取 source 以填充其 SDK / MCP 收藏并标记行 是从哪来的. 'mcp' 是为正式的 2DAI MCP 服务器预留的; 任何您 将报表构建为 sdk。 。 。 . integrationVersion 一定是真实的 1.2.3; 错误 值替换为 0.0.0 而不是省略, 所以符号仍然属性.

世代提交从不自动重审( 它们可能会充电); 服务器本身 在~5 s 内去除相同的提交件 (409 IDEMPOTENT_RETRY)和六分卫 clientToken 你通过明确设置窗口.

许可证

麻省理工学院

版本与发布记录

2dai-cloud-sdk 共发布 48 个版本,首次发布于 2026/01/07;过去 12 个月发布了 48 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.2.0latest2026/11/034 天前
3.1.32026/11/017 天前
3.1.22026/10/309 天前
3.1.12026/10/299 天前
3.1.02026/10/2117 天前
3.0.02026/10/1524 天前

关于 2dai-cloud-sdk 的常见问题

2dai-cloud-sdk 是什么?

2DAI生成API的已打入了JavaScript/TypeScript客户端——生成图像和视频,上传引用,并以API键下载结果.

如何安装 2dai-cloud-sdk?

在项目目录运行 npm install 2dai-cloud-sdk,或使用 pnpm add / yarn add / bun add。

2dai-cloud-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

2dai-cloud-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

2dai-cloud-sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

2dai-cloud-sdk 可以商用吗?

2dai-cloud-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

2dai-cloud-sdk 的下载量有多少?

根据 npm 官方下载统计,2dai-cloud-sdk 在 2026/10/04 – 2026/11/02 这 30 天内被下载 1,838 次,日均约 61 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

2dai-cloud-sdk 还在维护吗?

最新版本 3.2.0 发布于 2026/11/03(4 天前);至今共发布 48 个版本,其中过去 12 个月发布了 48 个;首次发布于 2026/01/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。