fashn
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFASHN API & SDKs
FASHN API 与 SDK
FASHN is an AI-first company specializing in human-centric generative image models tailored for fashion applications: virtual try-on, AI models, product photography, editing, and image-to-video. Everything runs through one prediction endpoint that takes a plus an object.
model_nameinputsThis skill helps you do two things:
- Integrate FASHN into a project: write production code against the REST API, the TypeScript SDK (on npm), or the Python SDK (
fashnon PyPI).fashn - Run a one-off generation inline: execute a single call and hand the result back to the user (see Inline quickstart).
When the user asks to add FASHN to their app / repo, integrate (write code into their project). When they ask to just do a try-on / generate an image now, run it inline.
Full per-endpoint parameter tables, the error catalog, webhooks, and credits live in reference.md. Load it when you need exactfor a giveninputs.model_name
FASHN是一家以AI为核心的公司,专注于打造以人为中心的生成式图像模型,专为时尚领域应用设计:包括虚拟试穿、AI模特、商品摄影、编辑以及图像转视频等。所有功能都通过一个预测端点实现,只需传入和对象即可。
model_nameinputs本技能可帮助你完成两类操作:
- 将FASHN集成到项目中:基于REST API、TypeScript SDK(npm上的包)或Python SDK(PyPI上的
fashn包)编写生产级代码。fashn - 直接在线运行单次生成任务:执行单次调用并将结果返回给用户(详见在线快速入门)。
当用户要求将FASHN添加到他们的应用/代码库时,执行集成操作(将代码写入他们的项目)。当用户要求立即进行试穿/生成图像时,执行在线运行操作。
完整的端点参数表、错误目录、Webhook说明以及积分相关信息请查看**reference.md**。当你需要特定对应的准确model_name参数时,请加载该文档。inputs
Authentication
身份验证
- Get an API key from the Developer API dashboard: https://app.fashn.ai/api
- All FASHN calls are server-side: never hard-code the key or expose it client-side.
- REST: send . Both SDKs read
Authorization: Bearer $FASHN_API_KEYfrom the environment by default.FASHN_API_KEY
Resolve the key (check in order; prompt only if all fail):
- env var (preferred, used by integration code, CI, and deploys). Check:
FASHN_API_KEY.echo "${FASHN_API_KEY:+set}" - Cache file . Load, then re-check:
~/.fashn/.env.set -a; [ -f ~/.fashn/.env ] && . ~/.fashn/.env; set +a - Otherwise, ask the user, then cache it (next bullet).
Caching (inline use only). When you had to ask the user for the key, save it to by default (right after you receive it) so later inline runs don't re-prompt, then tell the user it's cached there and that removes it. Only skip if they decline. Run:
~/.fashn/.envrm ~/.fashn/.envbash
umask 077; mkdir -p ~/.fashn; printf 'FASHN_API_KEY=%s\n' '<key>' > ~/.fashn/.env; chmod 600 ~/.fashn/.envNever echo the key back, write it to a shell profile, or commit it.
Integrations differ: pull the key from the project's own env (gitignored ) or secret manager, never or anywhere in the repo.
.env~/.fashn/.env- 从开发者API控制台获取API密钥:https://app.fashn.ai/api
- 所有FASHN调用均需在服务端执行:切勿硬编码密钥或在客户端暴露密钥。
- REST方式:请求头中携带。两个SDK默认会从环境变量中读取
Authorization: Bearer $FASHN_API_KEY。FASHN_API_KEY
密钥获取优先级(按顺序检查;仅当所有方式都失败时才询问用户):
- 环境变量(推荐,集成代码、CI流程和部署均使用此方式)。检查方式:
FASHN_API_KEY。echo "${FASHN_API_KEY:+set}" - 缓存文件。加载该文件后重新检查:
~/.fashn/.env。set -a; [ -f ~/.fashn/.env ] && . ~/.fashn/.env; set +a - 若以上方式均失败,则询问用户获取密钥,然后进行缓存(见下一点)。
缓存(仅在线运行时使用)。当你需要向用户询问密钥时,默认将其保存到(获取后立即执行),以便后续在线运行无需重复询问,然后告知用户密钥已缓存至该路径,执行可删除缓存。仅当用户拒绝时才跳过缓存。执行命令:
~/.fashn/.envrm ~/.fashn/.envbash
umask 077; mkdir -p ~/.fashn; printf 'FASHN_API_KEY=%s\n' '<key>' > ~/.fashn/.env; chmod 600 ~/.fashn/.env切勿回显密钥、写入shell配置文件或提交到代码仓库。
集成场景不同:从项目自身的环境变量(已加入git忽略的文件)或密钥管理工具中获取密钥,切勿使用或代码仓库中的任何路径。
.env~/.fashn/.envCore concepts (apply to every path)
核心概念(适用于所有使用方式)
One endpoint, many models. Every request is . Available s:
{ model_name, inputs }model_name| Category | | Required inputs |
|---|---|---|
| Virtual try-on (flagship) | | |
| Virtual try-on (legacy/fast) | | |
| Product → person wearing it | | |
| Generate a model from a prompt | | |
| Change a model's identity | | |
| Headshot → upper-body avatar | | |
| Freeform edit | | |
| Change aspect ratio (outpaint/crop) | | |
| Remove background → transparent PNG | | |
| Animate an image → video | | |
Prediction lifecycle. Two ways to get a result:
- (recommended): submit and auto-poll until a terminal state, then return the final result. Both SDKs expose this; for raw REST you implement the poll loop yourself.
subscribe - Manual +
run:statusreturns a predictionrunimmediately; polliduntilstatus(id)/completed. Use this for fire-and-forget, your own queue, or when pairing with webhooks.failed
Response envelope. A terminal prediction looks like:
json
{ "id": "...", "status": "completed", "output": ["https://cdn.fashn.ai/.../output_0.png"], "error": null }- :
status→starting→in_queue→processing|completed(SDKfailedmay also returnsubscribe/canceled).time_out - : array of CDN image URLs (or base64 if
output); MP4 URLs forreturn_base64: true.image-to-video - :
erroron success, elsenull.{ name, message }
Credits. Spend is returned in the response header (REST) and as (TS) / (Python) on the result. Failed predictions are not charged. Cost scales with and ; see reference.md. Check the balance with .
x-fashn-credits-usedcreditsUsedcredits_usedgeneration_moderesolutionGET /v1/creditsErrors (two kinds):
- API errors (HTTP 4xx/5xx, before the job runs): SDKs throw (subclasses); REST returns
APIError.{ "error": "<Code>", "message": "..." } - Runtime errors (job ran but failed): HTTP 200 with and
status: "failed", e.g.error: { name, message },ImageLoadError,ContentModerationError. Always branch onPoseErroreven when no exception is thrown.status
Limits: handle responses with backoff when batching.
429一个端点,多类模型。每个请求的格式均为。可用的如下:
{ model_name, inputs }model_name| 分类 | | 必填输入参数 |
|---|---|---|
| 虚拟试穿(旗舰版) | | |
| 虚拟试穿(旧版/快速版) | | |
| 商品转模特上身 | | |
| 通过提示词生成模特 | | |
| 更换模特身份 | | |
| 头像转上半身虚拟模特 | | |
| 自由编辑 | | |
| 修改宽高比(扩图/裁剪) | | |
| 移除背景生成透明PNG | | |
| 图像转视频 | | |
预测生命周期。获取结果有两种方式:
- (推荐):提交请求后自动轮询直至进入终态,然后返回最终结果。两个SDK均提供此方法;原生REST方式需自行实现轮询逻辑。
subscribe - 手动+
run:status会立即返回预测任务run;轮询id直至状态变为status(id)/completed。适用于无需等待结果的场景、自定义队列或搭配Webhook使用。failed
响应结构。终态预测结果示例:
json
{ "id": "...", "status": "completed", "output": ["https://cdn.fashn.ai/.../output_0.png"], "error": null }- :状态流转为
status→starting→in_queue→processing|completed(SDK的failed方法还可能返回subscribe/canceled)。time_out - :CDN图像URL数组(若设置
output则返回base64格式);return_base64: true模型返回MP4 URL。image-to-video - :成功时为
error,失败时为null。{ name, message }
积分。消耗的积分会在响应头(REST方式)中返回,SDK中则通过(TypeScript)/ (Python)字段返回。失败的预测任务不扣费。费用根据和有所不同;详见reference.md。可通过查询余额。
x-fashn-credits-usedcreditsUsedcredits_usedgeneration_moderesolutionGET /v1/credits错误类型(两类):
- API错误(HTTP 4xx/5xx,任务运行前发生):SDK会抛出异常(子类);REST方式返回
APIError。{ "error": "<Code>", "message": "..." } - 运行时错误(任务已执行但失败):HTTP状态码200,且
status: "failed",例如error: { name, message }、ImageLoadError、ContentModerationError。即使未抛出异常,也需始终根据PoseError分支处理。status
限制:批量处理时遇到响应需进行退避重试。
429Path A: TypeScript SDK (fashn
)
fashn方式A:TypeScript SDK(fashn
)
fashnInstall into the user's project:
npm install fashnts
import Fashn from 'fashn';
const client = new Fashn(); // reads FASHN_API_KEY from env
// Recommended: submit + auto-poll to completion
const result = await client.predictions.subscribe({
model_name: 'tryon-max',
inputs: {
model_image: 'https://example.com/person.jpg',
product_image: 'https://example.com/garment.jpg',
},
// optional: pollInterval (ms, default 1000), timeout (ms, default 300000),
onEnqueued: (id) => console.log('queued', id),
onQueueUpdate: (s) => console.log('status', s.status),
});
if (result.status === 'completed') {
console.log(result.output, 'credits:', result.creditsUsed);
} else {
console.error('failed:', result.status, result.error?.name, result.error?.message);
}Manual lifecycle:
ts
const { id } = await client.predictions.run({ model_name: 'tryon-max', inputs: { /* ... */ } });
const status = await client.predictions.status(id); // poll until terminalError handling (API vs runtime):
ts
try {
const r = await client.predictions.subscribe({ model_name: 'tryon-max', inputs: { /* ... */ } });
if (r.status !== 'completed') console.error('runtime error:', r.error?.name, r.error?.message);
} catch (err) {
if (err instanceof Fashn.APIError) console.error('API error:', err.status, err.message);
else throw err;
}安装到用户项目中:
npm install fashnts
import Fashn from 'fashn';
const client = new Fashn(); // 从环境变量读取FASHN_API_KEY
// 推荐方式:提交请求并自动轮询至完成
const result = await client.predictions.subscribe({
model_name: 'tryon-max',
inputs: {
model_image: 'https://example.com/person.jpg',
product_image: 'https://example.com/garment.jpg',
},
// 可选参数:pollInterval(毫秒,默认1000)、timeout(毫秒,默认300000),
onEnqueued: (id) => console.log('已加入队列', id),
onQueueUpdate: (s) => console.log('状态', s.status),
});
if (result.status === 'completed') {
console.log(result.output, '积分消耗:', result.creditsUsed);
} else {
console.error('失败:', result.status, result.error?.name, result.error?.message);
}手动生命周期管理:
ts
const { id } = await client.predictions.run({ model_name: 'tryon-max', inputs: { /* ... */ } });
const status = await client.predictions.status(id); // 轮询直至进入终态错误处理(API错误 vs 运行时错误):
ts
try {
const r = await client.predictions.subscribe({ model_name: 'tryon-max', inputs: { /* ... */ } });
if (r.status !== 'completed') console.error('运行时错误:', r.error?.name, r.error?.message);
} catch (err) {
if (err instanceof Fashn.APIError) console.error('API错误:', err.status, err.message);
else throw err;
}Path B: Python SDK (fashn
)
fashn方式B:Python SDK(fashn
)
fashnInstall into the user's project:
pip install fashnpython
import fashn
from fashn import Fashn
client = Fashn() # reads FASHN_API_KEY from env
result = client.predictions.subscribe(
model_name="tryon-max",
inputs={
"model_image": "https://example.com/person.jpg",
"product_image": "https://example.com/garment.jpg",
},
)
if result.status == "completed":
print(result.output, "credits:", result.credits_used)
else:
print("failed:", result.status, result.error)Manual lifecycle: → .
Async: use and .
API errors raise (, ); runtime failures arrive as with .
client.predictions.run(...)client.predictions.status(prediction_id)from fashn import AsyncFashnawait client.predictions.subscribe(...)fashn.APIErrore.status_codee.messageresult.status == "failed"result.error安装到用户项目中:
pip install fashnpython
import fashn
from fashn import Fashn
client = Fashn() # 从环境变量读取FASHN_API_KEY
result = client.predictions.subscribe(
model_name="tryon-max",
inputs={
"model_image": "https://example.com/person.jpg",
"product_image": "https://example.com/garment.jpg",
},
)
if result.status == "completed":
print(result.output, "积分消耗:", result.credits_used)
else:
print("失败:", result.status, result.error)手动生命周期管理: → 。
异步方式:使用并调用。
API错误会抛出(包含和);运行时失败会返回并附带。
client.predictions.run(...)client.predictions.status(prediction_id)from fashn import AsyncFashnawait client.predictions.subscribe(...)fashn.APIErrore.status_codee.messageresult.status == "failed"result.errorPath C: REST (any language)
方式C:REST(支持任意语言)
Base URL . Submit, then poll.
https://api.fashn.ai/v1bash
undefined基础URL为。提交请求后进行轮询。
https://api.fashn.ai/v1bash
undefinedSubmit → returns {"id": "...", "error": null}
提交请求 → 返回{"id": "...", "error": null}
curl -s -X POST https://api.fashn.ai/v1/run
-H "Authorization: Bearer $FASHN_API_KEY"
-H "Content-Type: application/json"
-d '{"model_name":"tryon-max","inputs":{ "model_image":"https://example.com/person.jpg", "product_image":"https://example.com/garment.jpg"}}'
-H "Authorization: Bearer $FASHN_API_KEY"
-H "Content-Type: application/json"
-d '{"model_name":"tryon-max","inputs":{ "model_image":"https://example.com/person.jpg", "product_image":"https://example.com/garment.jpg"}}'
curl -s -X POST https://api.fashn.ai/v1/run
-H "Authorization: Bearer $FASHN_API_KEY"
-H "Content-Type: application/json"
-d '{"model_name":"tryon-max","inputs":{ "model_image":"https://example.com/person.jpg", "product_image":"https://example.com/garment.jpg"}}'
-H "Authorization: Bearer $FASHN_API_KEY"
-H "Content-Type: application/json"
-d '{"model_name":"tryon-max","inputs":{ "model_image":"https://example.com/person.jpg", "product_image":"https://example.com/garment.jpg"}}'
Poll → repeat until status is "completed" or "failed"
轮询 → 重复调用直至状态变为"completed"或"failed"
curl -s https://api.fashn.ai/v1/status/<id> -H "Authorization: Bearer $FASHN_API_KEY" -i
curl -s https://api.fashn.ai/v1/status/<id> -H "Authorization: Bearer $FASHN_API_KEY" -i
read x-fashn-credits-used from the response headers
从响应头读取x-fashn-credits-used字段
Balance
查询余额
curl -s https://api.fashn.ai/v1/credits -H "Authorization: Bearer $FASHN_API_KEY"
**Webhooks** (skip polling): append `?webhook_url=` to `/run`. FASHN POSTs the terminal payload (`completed`/`failed`) to that URL, retrying up to 5 times over ~5 min. There's no signature header, so make the handler idempotent and respond 2xx fast. Details in reference.md.
---curl -s https://api.fashn.ai/v1/credits -H "Authorization: Bearer $FASHN_API_KEY"
**Webhook**(跳过轮询):在`/run`接口后追加`?webhook_url=`参数。FASHN会将终态结果(`completed`/`failed`)POST到该URL,在约5分钟内最多重试5次。该请求没有签名头,因此请确保处理接口具备幂等性并快速返回2xx状态码。详细说明见reference.md。
---Inline quickstart
在线快速入门
For a one-off generation (not an integration), run the TS SDK from so you don't touch the user's project:
~/.fashn- Install if needed:
ls ~/.fashn/node_modules/fashn 2>/dev/null || npm install --prefix ~/.fashn fashn - Resolve the key: . If still unset, see Authentication.
[ -z "$FASHN_API_KEY" ] && { set -a; . ~/.fashn/.env 2>/dev/null; set +a; } - Run it. Pipe the script via a single-quoted heredoc so the shell leaves backticks//quotes alone, and
$first so ESM resolves thecd ~/.fashnimport (it ignoresfashn):NODE_PATH
bash
[ -z "$FASHN_API_KEY" ] && { set -a; . ~/.fashn/.env 2>/dev/null; set +a; }
cd ~/.fashn && node --input-type=module <<'NODE'
import Fashn from 'fashn';
const r = await new Fashn().predictions.subscribe({
model_name: 'tryon-max',
inputs: {
model_image: 'https://example.com/person.jpg',
product_image: 'https://example.com/garment.jpg',
},
timeout: 120000, // ms
});
if (r.status !== 'completed') { console.error('Failed:', r.status, r.error); process.exit(1); }
console.log(JSON.stringify({ output: r.output, creditsUsed: r.creditsUsed }, null, 2));
NODE- Local image inputs: read the file as base64 (from
readFile(path, { encoding: 'base64' })) and pass it asnode:fs/promises. Save a result withproduct_image: 'data:image/jpeg;base64,' + b64.fetch(r.output[0]) - Don't write script files or put the key on the command line (use step 2's cache); back off on when batching.
429
对于单次生成任务(非集成场景),从目录运行TypeScript SDK,避免影响用户项目:
~/.fashn- 若未安装则执行安装:
ls ~/.fashn/node_modules/fashn 2>/dev/null || npm install --prefix ~/.fashn fashn - 获取密钥:。若仍未获取到密钥,请查看身份验证部分。
[ -z "$FASHN_API_KEY" ] && { set -a; . ~/.fashn/.env 2>/dev/null; set +a; } - 运行任务。通过单引号 heredoc 传递脚本,避免shell解析反引号//引号,并且**先执行
$**确保ESM能正确解析cd ~/.fashn导入(ESM会忽略fashn):NODE_PATH
bash
[ -z "$FASHN_API_KEY" ] && { set -a; . ~/.fashn/.env 2>/dev/null; set +a; }
cd ~/.fashn && node --input-type=module <<'NODE'
import Fashn from 'fashn';
const r = await new Fashn().predictions.subscribe({
model_name: 'tryon-max',
inputs: {
model_image: 'https://example.com/person.jpg',
product_image: 'https://example.com/garment.jpg',
},
timeout: 120000, // 毫秒
});
if (r.status !== 'completed') { console.error('失败:', r.status, r.error); process.exit(1); }
console.log(JSON.stringify({ output: r.output, creditsUsed: r.creditsUsed }, null, 2));
NODE- 本地图像输入:将文件读取为base64格式(使用中的
node:fs/promises),并以readFile(path, { encoding: 'base64' })的形式传入。可通过product_image: 'data:image/jpeg;base64,' + b64保存结果。fetch(r.output[0]) - 请勿编写脚本文件或在命令行中传入密钥(使用步骤2的缓存);批量处理时遇到响应需进行退避重试。
429
Reference
参考文档
See reference.md for every endpoint's full (types, allowed values, defaults), the complete error catalog, credit/pricing notes, webhook payloads, and rate limits.
inputs请查看**reference.md**获取所有端点的完整参数(类型、允许值、默认值)、完整错误目录、积分/定价说明、Webhook payload以及速率限制信息。
inputsUser's request
用户请求
$ARGUMENTS
$ARGUMENTS