2dai-cloud-sdk (英语)
输入的 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/me | read | 账户、信贷、关键范围 |
| 邮政 | /v1/generate/image | generate | 文本 — 图像 |
| 邮政 | /v1/generate/image-with-refs | generate | 面相/ 字符参考、 样式传输、 智能编辑 |
| 邮政 | /v1/generate/wallpaper | generate | 墙纸尺寸调整(按尺寸计价) |
| 邮政 | /v1/generate/video | generate | 仍然 ~ 视频 |
| 邮政 | /v1/uploads | generate | 上传媒体( 多部分) |
| 获取 | /v1/uploads/check-duplicate | read | md5 飞行前脱发探测器 |
| 获取 | /v1/queue/:queueId | read | 传票一代人 |
| 邮政 | /v1/queue/:queueId/cancel | generate | 取消待定的生成(退款) |
| 获取 | /v1/creations | read | 列表 / 搜索您的驱动器( 机位+过滤器) |
| 获取 | /v1/creations/:id | read | 一个创造,一个细节 |
| 获取 | /v1/feed | read | 交叉用户的公用饲料 |
| 邮政 | /v1/creations/:id/move | /trash | /restore | /like | manage | 组织 |
| 邮政 | /v1/creations/reorder | /batch | manage | 重排/批量动作 |
| 迪莱特 | /v1/creations/:id | manage | 永久删除( 先删除) |
| 邮政 | /v1/creations/:id/publish | /unpublish | publish | 公共饲料 |
| 获得/部署/部署/部署/部署 | /v1/folders | read 编号 : manage | 文件夹 |
| 获得/部署/部署/部署/部署 | /v1/folder-groups | read 编号 : manage | 侧边栏文件夹组 |
| 获取 | /v1/stats/overview | /generations | /top | read | 账户分析 |
| 获取 | /v1/wallet*, (中文(简体) ), /v1/account/tier | finance | 只读钱包数据 |
| 获取 | /v1/tiers, (中文(简体) ), /v1/token/price | read | 分级目录, 缓存的代号引用 |
| 获取 | /cdn/file/:cdnId | read | 下载字节( 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 你通过明确设置窗口.
许可证
麻省理工学院
社区链接( L)
- 网站 —— 说 页:1
- 页:1 —— 说 @ 2DAI 社区
- 电报 —— 说 t.me/Token2dAI (英语)
- 基地2美元 —— 说 dexscreener 上的图表 · 等级和每日信用空投的股份
- MCP 服务器 —— 说 2dai-mcp 服务器 将 Claude, Cursor, Cline & Windsurf 客户端变成 2DAI 客户端
- GitHub 图像 —— 说 2DAI 社区