开发者文档
通过 REST API 和 Python SDK 0.3.0,在自己的代码中运行商品页测试、UI A/B 测试和智能助手。
- API 基础地址
https://qyzkdesign.com/api/v1
快速开始
1. 创建 API 密钥
注册(我们会发送验证码到你的邮箱)后,在控制台的 API 密钥页面创建密钥。密钥以 fl_ 开头;以 Authorization: Bearer fl_... 发送,并妥善保管。密钥只显示一次:如果没有复制,请撤销并重新创建。
2. 安装 Python SDK
SDK(包名 facetlab,版本 0.3.0,需要 Python 3.8 或更高版本)尚未发布到 PyPI。请从 GitHub 安装或升级:
pip install -U git+https://github.com/qyzk/facetlab-sdk-public.git3. 运行商品页测试
estimate 检查是否可以开始、人群规模和所需额度,不会创建任何内容。create 检查图片、创建测试、为每个方案上传一张图片并开始测试。wait 会一直轮询,直到测试状态变为 completed、failed 或 cancelled。
from facetlab import FacetLabClient
client = FacetLabClient(api_key="fl_...") # create a key at https://qyzkdesign.com/dashboard/api-keys
spec = {
"name": "Shoe cabinet page test",
"market": "tiktok_us", # <platform>_<us|uk|jp> (uk = Europe, jp = Asia). Platforms: tiktok, amazon, temu, shein,
# walmart, shopee, etsy, own_site, other (other needs platform_label)
"product": {"name": "White 3-Tier Foldable Shoe Cabinet",
"use": "Entryway shoe storage",
"dimensions": "17.3 x 13.8 x 20.87 in"},
"pricing": {"current_price": 37.69, "shipping": "Free shipping shown"},
"scenario": {"shopper_intent": "browsing"},
"question": {"primary": "Would you buy this shoe cabinet at the shown price?"},
"arms": [{"id": "A", "label": "Original page"}, # A is the control
{"id": "B", "label": "Adjusted layout"}],
"persona_count": 25,
"sessions_per_arm": 5,
}
estimate = client.product_tests.estimate(spec) # creates nothing
print(estimate["ready"], estimate["credits"], estimate["data_gaps"])
test = client.product_tests.create(spec, images={"A": "a.png", "B": "b.png"}) # uploads and starts
done = client.product_tests.wait(test["id"])
if done["status"] == "completed":
results = done["results"]
for arm_id, arm in results["arms"].items():
print(arm_id, arm["buy_rate"]["value"], arm["buy_rate"]["ci95"])
for c in results["comparisons"]:
print(c["arm"], "vs A:", c["difference"], c["stability"])
print(done["report_urls"]["en"]) # signed HTML report, valid for 1 hour
else:
print(done["status"], done["error_message"])除非你的流量本身就有购买意向,否则请把 scenario.shopper_intent 设为 "browsing"。API 默认值 "in_market" 假设每位消费者都已经想买这类商品,购买率会偏高,方案之间的差异也可能看不出来。
默认情况下,所有方案共用同一组商品信息,只有截图不同。虚拟消费者根据每张截图判断价格、运费和卖点。pricing.current_price 仍为必填,会写入报告;proposed_price、key_features 和 shopper_problem 仅作记录,不会展示给虚拟消费者。要比较不同的商品而不只是页面设计(例如两层和三层鞋架),请用 arms[].product 和 arms[].pricing 为每个方案填写各自的信息,例如名称、尺寸、材质和价格,让每个方案的 AI 消费者看到正确的商品信息。
AI 模拟,用于上线前预测试,不是销量预测。
client.product_tests 方法
| 方法 | 作用 |
|---|---|
| estimate(spec) | 返回是否可以开始、数据缺口、符合条件的虚拟消费者数、所需额度和预计时长,不会创建测试。 |
| create(spec, images, idempotency_key=None) | 创建测试、为每个方案上传一张图片并开始。传入 idempotency_key 可以安全重试;不传时 SDK 会自动生成。 |
| wait(test_id, poll_interval=20, timeout=1800) | 轮询直到测试结束:默认每 20 秒一次,最多 30 分钟。 |
| get(test_id, include_personas=False) | 获取单个测试。include_personas=True 返回全部虚拟消费者,而不只是代表性的几个。 |
| list(partner_product_id=None, limit=20, cursor=None) | 列出你的测试,最新的在前,支持游标分页,可按 partner_product_id 筛选。 |
| clone(test_id, overrides, images=None, idempotency_key=None) | 修改后再测一次。没有提供新图片的方案沿用上一轮测试的图片。 |
| cancel(test_id) | 取消尚未结束的测试。 |
| markets_audience(market) | 获取某个市场可用的人群筛选项及对应人数。 |
UI A/B 测试、余额和智能助手
查询余额
client.account()(REST:GET /api/v1/account)返回剩余免费测试、以美元计的预付余额、按每个虚拟消费者每个方案计的费率、下一个测试的费率,以及最大测试规模(max_personas)。run_experiment 和 product_tests.create 会在上传前检查余额,余额不足时抛出 InsufficientFundsError;测试开始时服务器会再次按准确费用检查。
acct = client.account()
print(acct["free_tests"]) # {"used": 1, "limit": 2, "remaining": 1} (None on a plan)
print(acct["balance"]) # 25.0 (US dollars)
print(acct["next_test_rate"]) # 0.8 (US dollars per persona per variant, without a plan)
print(acct["max_personas"]) # 100 (largest test: 500 on Base, 2,000 on Pro)运行 UI A/B 测试
同一页面的两张截图:对照版和实验版。run_experiment 会检查余额、上传两张截图、开始测试并等待结果。两张截图合计需小于约 3 MB。
result = client.run_experiment(
control_image="control.png",
treatment_image="treatment.png",
locale="usa", # "usa", "europe" or "asia"
persona_count=25, # up to 100 without a plan, 500 on Base, 2,000 on Pro; billed as persona_count x 2
context="Sign-up page: bigger free-trial banner",
positive_decision="Start the free trial",
negative_decision="Leave the page",
)
print(result.winner, result.lift, result.confidence)使用智能助手
用自然语言描述测试。智能助手会询问缺少的信息并起草计划;reply.draft() 会告诉你需要上传哪些图片。调用 start 之前不会运行任何测试,开始后与其他测试一样计费。当助手询问测试类型时,用 send(conv, "", workflow="product_test") 或 "ui_ab_test" 回答。
conv = client.agent.start_conversation()
reply = client.agent.send(conv, "Compare my original shoe cabinet page with a "
"benefit-led version on TikTok Shop US, 25 personas, $37.69.")
print(reply.text)
draft = reply.draft() # None until the Assistant has what it needs: reply with send()
if draft:
client.agent.upload(conv, draft, {"A": "original.png", "B": "benefit.png"})
client.agent.start(draft) # paid like any test
print(client.product_tests.wait(draft.draft_id)["status"])UI A/B 测试、余额和智能助手的 REST 接口
| 方法 | 作用 |
|---|---|
| GET /api/v1/account | 剩余免费测试、余额和下一个测试的费率。 |
| POST /api/sdk/experiments/create | 用两张 base64 截图(control_image、treatment_image、locale、persona_count、context)创建并开始 UI A/B 测试。 |
| GET /api/sdk/experiments/{id} | 状态,以及 completed 后的结果。 |
| POST /api/sdk/experiments/{id}/start | 在上传截图后,开始智能助手准备好的 UI A/B 草稿。 |
| POST /api/agent/conversations | 开始与智能助手的对话,返回 {"id"}。 |
| POST /api/agent/conversations/{id}/messages | 发送 {"text"}(可附带 "workflow")。回复以服务器推送事件流返回:text、card(计划、上传请求、结果)以及最后的 done。 |
| POST /api/agent/conversations/{id}/uploads | 草稿的上传地址:{"draft_id", "workflow", "content_types"}。用对应的 Content-Type 将每张图片 PUT 到其地址。 |
Product Tests API v1
SDK 所封装的 REST API 的完整参考。任何语言都可以用 API 密钥直接调用。
API 参考文档仅提供英文版。
A Product Test compares 2-6 versions ("arms") of a product page, listing image or creative on a given market. Virtual consumers (personas) from that market's audience pool each run several simulated shopping sessions per arm and decide whether to buy. You get buy rates, arm-vs-control comparisons, concerns and persona-level detail.
Base URL: https://qyzkdesign.com/api/v1/product-tests
This is an intent simulation, not a sales forecast. Results come from AI virtual consumers. Use them to form hypotheses and plan real validation. They do not predict real orders or sales. Every
resultsobject carries anis_simulation: trueflag and a bilingualdisclaimer; please keep it visible wherever you show results.
1. Authentication
Authorization: Bearer fl_...- User keys are created at
/dashboard/api-keys. Requests act as that user and see only that user's tests. - Partner keys (issued by FacetLab to integration partners) act as the partner. Two optional headers scope requests:
X-Team-Id: when sent, create/list/get only see tests created with the same team id.X-End-User-Id: records the partner's end user.- Both: 1-128 characters from
A-Z a-z 0-9 _ . : @ -. A present but invalid header returns400 invalid_team_id/400 invalid_end_user_id. When absent, the partner-wide view applies.
- Missing, malformed or revoked key:
401 unauthorized. A test that is not yours is indistinguishable from a missing one (404 not_found).
All bodies are JSON; errors use the shape in section 10.
2. Flow
POST /estimate: check readiness, audience size, credits and quota. Free, no side effects.POST /with anIdempotency-Key: creates the test (awaiting_upload) and returnsupload_urls.PUTeach arm's image to itsupload_urls[arm].urlwith exactly the listedContent-Type.POST /{id}/start: reserves credits and queues the run.- Poll
GET /{id}untilstatusiscompleted,failedorcancelled(typically 5-15 minutes; seeeta_minutes). Every 15-30 s is plenty. - Read
results(andreport_urls) from the completed test.
BASE=https://qyzkdesign.com/api/v1/product-tests
AUTH="Authorization: Bearer $FACETLAB_KEY"
curl -s -X POST $BASE -H "$AUTH" -H "Idempotency-Key: my-shop-2026-10-13-0001" \
-H "Content-Type: application/json" -d @spec.json # -> id, upload_urls
curl -s -X PUT "<upload_urls.A.url>" -H "Content-Type: image/png" --data-binary @a.png
curl -s -X PUT "<upload_urls.B.url>" -H "Content-Type: image/png" --data-binary @b.png
curl -s -X POST $BASE/pt_.../start -H "$AUTH"
curl -s $BASE/pt_... -H "$AUTH"The Python SDK (facetlab >= 0.2.0, FacetLabClient(...).product_tests) wraps this whole flow, including upload validation, start and polling.
3. Request body (the test spec)
Canonical example (POST /estimate and POST / take the same body):
{
"name": "TikTok US shoe cabinet - page layout",
"market": "tiktok_us",
"product": {
"name": "White 3-Tier Foldable Shoe Cabinet",
"url": "https://www.tiktok.com/view/product/1731093726010380869",
"platform_product_id": "1731093726010380869",
"variant": "White, 3 tiers",
"use": "Enclosed shoe storage for entryways",
"dimensions": "17.3 x 13.8 x 20.87 in (outer W x D x H)",
"key_features": ["Foldable", "3 enclosed tiers"],
"limitations": []
},
"pricing": {
"current_price": 37.69,
"proposed_price": null,
"shipping": "Free shipping shown",
"tax": "unknown",
"delivery": "unknown"
},
"scenario": {
"shopper_problem": "Shoes cluttering a small entryway",
"entry_point": "feed_content",
"usage_context": "Apartment entryway",
"shopper_intent": "browsing"
},
"audience": {
"description": "US adults who shop on TikTok Shop",
"filters": {
"gender": ["female"],
"urbanicity": ["urban", "suburban"],
"average_purchase_price": { "min": 10, "max": 60 }
}
},
"question": {
"primary": "Would you buy this shoe cabinet at the shown price?",
"follow_ups": ["Did you notice whether shipping is free?"]
},
"arms": [
{ "id": "A", "label": "Original page", "change_summary": null, "content_type": "image/png" },
{ "id": "B", "label": "Adjusted layout", "change_summary": "Price area and spec grouping reorganized", "content_type": "image/png" }
],
"persona_count": 25,
"sessions_per_arm": 5,
"external_ref": { "partner_product_id": "sku-1042", "opportunity_id": null }
}What shoppers see. By default every arm shares one set of product facts and only the screenshot differs. Shoppers judge the price, shipping, name and features from what is visible in each arm's screenshot, plus the seller details variant, dimensions, inner_dimensions, material and limitations. Fields marked informational below are kept for the report but are not shown to shoppers. To compare different products rather than page designs (for example a 2-tier and a 3-tier shoe rack), give each arm its own facts with arms[].product and arms[].pricing; see "Comparing different products" below.
Unknown top-level keys are ignored; unknown keys inside audience.filters are rejected (the error suggests the closest field name).
| Field | Rules |
|---|---|
name | required, 1-200 chars |
market | required, see section 4 |
currency | optional; if given must equal the market's currency (currency_mismatch). Derived from the market otherwise. |
material_language | optional, up to 20 chars; defaults to the market's locale (en-US, en-GB, ja-JP) |
product.name | required, up to 300 chars |
product.* (optional text, up to 300; url 500) | url, platform_product_id, asin, variant, use, material, dimensions, inner_dimensions |
product.key_features, product.limitations | up to 10 strings each, up to 200 chars each. key_features is informational (shoppers read features from the screenshot); limitations is shown to shoppers. |
pricing.current_price | positive number in the market currency. Required to start (blocking gap). Used for the report; shoppers judge the price shown in each screenshot. |
pricing.proposed_price | optional positive number. Informational: not shown to shoppers. |
pricing.shipping, tax, delivery | free text, default "unknown" |
scenario.entry_point | feed_content, search, comparison, product_page (default). Informational: recorded for the report, does not yet change decisions (same for shopper_problem and usage_context) |
scenario.shopper_intent | browsing (recommended: the shopper lands on the page without a plan to buy) or in_market (API default: every persona is assumed to already want this kind of product, so buy rates run high and variant differences can disappear; use only for purchase-intent traffic) |
scenario.shopper_problem, usage_context | optional text, informational. At least one of product.use / scenario.shopper_problem is required (blocking gap otherwise). |
audience.description | optional, up to 500 chars (informational) |
audience.filters | see section 5 |
question.primary | required, up to 300 chars; follow_ups: up to 3 |
arms | 2-6 entries, ids exactly A, B, C... in order. A is the control; every other arm is compared against A. Each: label (1-120), change_summary (optional, up to 300), content_type (image/png default, image/jpeg, image/webp). |
arms[].product | optional per-arm product facts, any of name, variant, use, material, dimensions, inner_dimensions (text, up to 300 chars) and key_features, limitations (1-10 strings, up to 200 chars each). Other keys are rejected (invalid_spec). |
arms[].pricing | optional per-arm pricing, any of current_price (positive number), shipping and delivery (text, up to 200 chars). Other keys (proposed_price, tax) are rejected. |
persona_count | integer, at least 10, default 25; at most the owner's plan size (100 without a plan, 500 on Base, 2,000 on Pro; partner keys by the tier on the key), else 403 tier_limit |
sessions_per_arm | integer 3-10, default 5 |
external_ref | partner_product_id and opportunity_id (up to 128 chars). partner_product_id is returned as partner_product_id and can filter the list. |
Missing optional facts such as dimensions, material, inner dimensions, shipping or delivery produce non-blocking (limiting) data_gaps; results are then reported with narrower conclusions.
Comparing different products
Each arm can describe its own product, so a test can compare different products, not just page designs. Each arm's AI shoppers see that arm's facts.
- Merge, field by field. An arm's facts are the shared
productandpricingwith that arm'sproduct/pricingapplied per field. A provided value wins; an omitted,nullor blank one falls back to the shared value. Lists (key_features,limitations) replace the shared list when provided; they are not appended. - Send only what differs. Omit any field you don't want to override. Don't send placeholders such as
"unknown": a provided value is used as is. Keys outside the lists above are rejected. - The control. The shared
productandpricingare the control's facts. Arm A may carry overrides too, but keeping A's facts at the top level is clearest. - Different products. An arm is a different product when any of its merged
productvalues or itspricing.current_pricediffers from arm A's. If any arm is,scope_warningsaddsdifferent_products: "Variants are different products; differences reflect the product, its price and its page together." Read those comparisons as product + price + page together, not as a page-design effect. - Readiness per arm. Data gaps are computed on each arm's merged facts. A gap every arm has keeps its plain field (
product.dimensions). A gap only some arms have is reported once per affected arm asarms.<ID>.<field>(for examplearms.B.product.material), its message prefixed with the arm id and label ("B · 2-tier bamboo rack: Material unknown: ..."). Severity is unchanged, so an arm whose merged facts have nocurrent_priceis a blocking gap. - Unchanged. Credits, quota, statistics (every arm is still compared against A), audience and market are the same as for a page-design test. Without
arms[].product/arms[].pricing, a test behaves exactly as before.
Example: a 3-tier plastic rack (the control, shared facts) against a 2-tier bamboo rack.
{
"name": "Shoe rack: 3-tier plastic vs 2-tier bamboo",
"market": "tiktok_us",
"product": {
"name": "3-Tier Plastic Shoe Rack",
"variant": "Black, 3 tiers",
"use": "Entryway shoe storage",
"material": "Plastic",
"dimensions": "20.9 in tall"
},
"pricing": { "current_price": 37.69, "shipping": "Free shipping shown" },
"scenario": { "shopper_intent": "browsing" },
"question": { "primary": "Would you buy this shoe rack at the shown price?" },
"arms": [
{ "id": "A", "label": "3-tier plastic rack" },
{ "id": "B", "label": "2-tier bamboo rack",
"product": { "name": "2-Tier Bamboo Shoe Rack", "variant": "Natural, 2 tiers",
"material": "Bamboo", "dimensions": "14 in tall" },
"pricing": { "current_price": 29.99 } }
]
}Arm B's shoppers see the bamboo rack's name, variant, material, height and $29.99, and inherit use and shipping from the shared facts. POST /estimate returns the different_products scope warning, and results.test.arms[] echoes each arm's product / pricing overrides.
4. Markets
| Platform | Markets | Audience pool |
|---|---|---|
| TikTok Shop | tiktok_us (US), tiktok_uk (UK), tiktok_jp (Asia) | new, non-Prime shoppers |
| Amazon | amazon_us (US), amazon_uk (UK), amazon_jp (Asia) | new Prime + veteran Prime shoppers |
Currencies: US USD, UK GBP, Asia JPY. Any other value returns 422 market_not_supported (details list the supported codes).
5. Audience filters
audience.filters narrows the market's pool. Fields combine with AND. Empty lists, null bounds and empty ranges are ignored.
- Categorical (a non-empty list of allowed values; any listed value matches):
age,gender,income,education,industry,home_ownership,pet_ownership,parental_status,relationship_status,urbanicity,cohort. - Numeric ranges (
{"min": n, "max": n}, inclusive, either bound optional,min <= max; personas lacking the field never match):income_min,average_purchase_price,median_purchase_price,max_purchase_price,average_monthly_spending,avg_purchases_per_month,total_purchases. Money fields are in the market currency.
The valid categorical values and numeric distributions are discoverable through GET /audience. If fewer eligible personas than persona_count remain, creation fails with 422 audience_too_small.
6. Endpoints
GET /audience?market=tiktok_us
Filter menu for a market (de-duplicated pool).
{
"market": "tiktok_us", "currency": "USD",
"fields": { "age": [["0-10", "10-20"], ["20-30"], ["30-40"]], "urbanicity": [["Suburban"], ["Urban"], ["Rural"]] },
"numeric": { "average_purchase_price": { "count": 3000, "min": 3.2, "p10": 9.5, "p50": 24, "p90": 61, "max": 410 } }
}fields maps each offered categorical field to its options; each option is a list of raw values to send together in audience.filters (e.g. "age": ["0-10", "10-20"]). Values are grouped so every option covers at least 50 personas (adjacent ranges are merged, small categories combined); fields with a single option are omitted. industry and cohort are not offered. numeric gives count/min/p10/p50/p90/max per numeric field (nulls when empty).
POST /estimate
Body: the spec. Never creates anything and needs no Idempotency-Key.
{
"ready": true,
"data_gaps": [
{ "field": "product.inner_dimensions", "severity": "limiting",
"message_en": "Inner dimensions unknown: we can see whether shoppers ask, but cannot conclude what fits inside.",
"message_zh": "..." }
],
"scope_warnings": [{ "code": "overall_variant", "message_en": "Differences reflect each page variant as a whole, not any single element.", "message_zh": "..." }],
"audience": { "pool_size": 3120, "eligible": 812, "enough": true },
"credits": 50,
"eta_minutes": { "typical": 6, "max": 15 },
"quota": { "used": 0, "limit": 150, "remaining": 150 }
}ready is true only when there is no blocking gap (including free-tier limit gaps) and audience.enough. It does not check the quota; compare credits with quota.remaining.
POST /
Headers: Idempotency-Key (required, 8-128 chars of A-Za-z0-9_.:-). Body: the spec. Does not charge credits. 201:
{
"id": "pt_0b8f3f0e-5f0a-4a8c-9a55-3f2f6f1c2b11",
"status": "awaiting_upload",
"credits": 50,
"eta_minutes": { "typical": 6, "max": 15 },
"data_gaps": [],
"scope_warnings": [{ "code": "overall_variant", "message_en": "...", "message_zh": "..." }],
"upload_urls": {
"A": { "url": "https://...presigned...", "content_type": "image/png" },
"B": { "url": "https://...presigned...", "content_type": "image/png" }
}
}Failure modes: 403 tier_limit, 422 needs_info (blocking gaps in details.data_gaps), 422 audience_too_small, 422 invalid_spec / invalid_arms / market_not_supported / currency_mismatch, 400 idempotency_key_required. Rejected requests (4xx) do not store the key.
Upload images
PUT the file bytes to upload_urls[arm].url. URLs are valid for 1 hour and the Content-Type header must exactly equal the content_type returned for that arm (the signature binds it; a mismatch is rejected by storage). To get fresh URLs for a test still in awaiting_upload, repeat the create call with the same Idempotency-Key and body (see section 8).
Limits per image:
- Formats: PNG, JPEG, WebP. At most 5 MB.
- Pixel caps: JPEG 80 MP, opaque PNG 45 MP, PNG with transparency 25 MP, WebP 12 MP (any WebP).
- The file's real format should match the declared
content_type.
POST /{id}/start
No body. Requires every arm image to be uploaded and valid; for a free-plan user's key, also requires a free test left (403 free_tier_limit, nothing reserved). Then it reserves credits against the monthly quota and queues the run (and counts one free test for a free-plan user): { "id": "pt_...", "status": "queued" }. Calling it again on a test that has already started returns its current status (safe to retry).
Errors: 409 images_missing (details.missing lists arm ids), 409 images_invalid (details.invalid: over 5 MB or wrong content type), 402 quota_exceeded, 404 not_found. Pixel-cap violations are detected by the pipeline and surface as a failed test with error_message, so validate dimensions before uploading.
GET /{id}
Returns the summary below plus spec, arm_images (signed image URLs, valid 1 hour) and, once completed, results and report_urls (en, zh HTML reports, signed, valid 1 hour). Add ?include=personas to get all personas in results.personas; by default only the up-to-6 representative ones are included.
{
"id": "pt_0b8f...", "name": "TikTok US shoe cabinet - page layout", "status": "completed",
"market": "tiktok_us", "platform_name": "TikTok Shop", "country_name": "United States",
"arm_count": 2, "progress": { "finished": 25, "total": 25 },
"credits": 50, "billable": true,
"parent_test_id": null, "partner_product_id": "sku-1042",
"buy_rate_a": 0.42, "best_arm": "B",
"error_message": null, "warning_message": null,
"created_at": "2026-10-13T08:00:00.000Z", "completed_at": "2026-10-13T08:06:10.000Z",
"spec": { "...": "stored spec incl. data_gaps, scope_warnings, parent_test_id" },
"arm_images": { "A": "https://...", "B": "https://..." },
"results": { "...": "see section 7" },
"report_urls": { "en": "https://...", "zh": "https://..." }
}progress is null until the run has a shard count; total is the number of personas. billable says whether credits stay spent (see section 9). Error text is scrubbed of internal storage paths.
GET /
Lists your tests, newest first. Query: partner_product_id, limit (1-100, default 20), cursor. Returns { "data": [ <summary>, ... ], "next_cursor": "..." | null } (no spec or results). A bad cursor returns 400 invalid_cursor.
POST /{id}/clone
Creates a follow-up round from an existing test (re-test). Headers: Idempotency-Key (required). Body: optional partial spec. Objects product, pricing, scenario, audience, question and external_ref are merged key-by-key over the parent's spec; other fields (and arms, if given) replace it. If arms is omitted, all parent arms are reused with reuse_parent_image: true (including any arms[].product / arms[].pricing), so you do not upload those images again. For a new arm image set reuse_parent_image: false (and upload it); reuse_parent_image: true is only valid for arm ids that exist in the parent. Response is the same as create (upload_urls only lists arms that need an upload; if none does, call start directly). The new test records parent_test_id and may add scope warnings (market_changed, price_changed, variant_changed). Errors add 409 parent_images_missing when the parent's image is no longer available. If you change market, currency and material language are re-derived.
POST /{id}/cancel
Allowed in awaiting_upload, queued or processing. Returns { "id": "pt_...", "status": "cancelled", "billable": false }. Finished tests return 409 not_cancellable. Refund rules in section 9.
7. Status values
status | Meaning |
|---|---|
awaiting_upload | Created; waiting for images and start. Nothing is charged. |
queued | Started; credits reserved. |
processing | Personas are being simulated (progress advances). |
completed | results and report_urls available. |
failed | The run failed; see error_message. |
cancelled | Cancelled by you. |
completed, failed and cancelled are terminal. Personas that fail individually are counted in results.sample.personas_failed; warning_message may carry a notice.
8. Idempotency
- Required on
POST /andPOST /{id}/clone; 8-128 chars fromA-Za-z0-9_.:-. Use a fresh unique key per logical test. - Scope: your owner identity (and
X-Team-Idfor partners) plus the key. Keys expire after 7 days. - Same key + same body: no new test; the original is returned with
"idempotent_replay": true(summary shape; plus freshupload_urlswhile it is stillawaiting_upload). Safe to retry after timeouts or to refresh expired upload URLs. For clone the "body" is the parent id plus overrides. - Same key + different body:
409 idempotency_conflict. - Same key while the first request is still being processed:
409 idempotency_in_progress; retry shortly. - If creation itself fails after the key was claimed, the key is released so you can retry.
9. Pricing, quota and refunds
- 1 credit = 5 sessions x 1 persona x 1 arm.
credits = persona_count x number_of_arms x ceil(sessions_per_arm / 5). Example: 25 personas, 2 arms, 5 sessions = 50 credits; with 10 sessions = 100. - Free tests: 2 free tests in total, shared by the web app, the API and the Assistant. A key created in the dashboard acts as its user, so each successful
startcounts one free test like a start in the app (a retried or concurrent start of the same test is not counted again). A free test covers up to 100 personas, 2 arms and 5 sessions per arm; a larger test, and every test after the free ones, is paid from the prepaid balance (402 insufficient_fundswith the cost indetails.required), or403 free_tier_limitwhile billing is off. Partner keys are not counted. - Prepaid price: billed per persona per arm (5 sessions): units =
persona_count x number_of_arms x sessions_per_arm / 5, rounded up, times the rate on the pricing page ($0.80 without a plan; lower on Base and Pro). - Sizes: at most 100 personas per test without a plan, 500 on Base and 2,000 on Pro (
403 tier_limiton create, a blockingdata_gapsentry on estimate); 3-10 sessions per arm and 2-6 arms on every plan. Credits remain a monthly guard (400 for free-tier users by default) for tests not paid from the balance; partner keys use the tier on the key. - The monthly quota is per owner and per UTC calendar month. Credits are reserved on
start, not on create. A single test larger than the monthly limit can never start. - Cancel: cancelling in
awaiting_uploadcosts nothing. Cancelling a started test before any persona has finished refunds the credits (billable: false). If at least one persona had finished, credits are kept (billable: true). - Failure: a test that fails after starting with no completed personas is refunded automatically, exactly once (
billable: falseon the next read). A failed test where some personas completed remains billable. GETfieldscreditsandbillablealways show the current position.
10. Errors
{ "error": { "code": "audience_too_small", "message": "Only 7 personas match the audience filters",
"message_zh": "...", "details": { "pool_size": 3120, "eligible": 7, "enough": false } } }| HTTP | code | Meaning |
|---|---|---|
| 400 | invalid_json | Body is empty, malformed or not a JSON object |
| 400 | idempotency_key_required | Missing or malformed Idempotency-Key |
| 400 | invalid_cursor | Bad list cursor |
| 400 | invalid_team_id, invalid_end_user_id | Malformed partner header |
| 401 | unauthorized | Missing, invalid or revoked key |
| 402 | quota_exceeded | Monthly credits would be exceeded on start |
| 403 | tier_limit | More personas than the plan allows (details.data_gaps) |
| 403 | free_tier_limit | All 2 free tests are used (details.limit), on start |
| 404 | not_found | Test does not exist or is not yours |
| 409 | idempotency_conflict | Key reused with a different body |
| 409 | idempotency_in_progress | First request with this key still running |
| 409 | images_missing / images_invalid | Arm images not uploaded, over 5 MB, or wrong type |
| 409 | parent_images_missing | Re-test cannot reuse the parent's image |
| 409 | not_cancellable | Test already finished |
| 422 | invalid_spec | Schema violation; details.fieldErrors / formErrors list them |
| 422 | invalid_arms | Arm ids not A,B,... in order; reuse_parent_image misuse |
| 422 | market_not_supported, currency_mismatch | Bad market / currency |
| 422 | needs_info | Blocking data gaps (details.data_gaps) |
| 422 | audience_too_small | Fewer eligible personas than persona_count |
| 500 | internal_error | Unexpected; retry later |
| 503 | feature_disabled | Product Tests are not enabled for this deployment; every endpoint returns this until they are |
11. results.json reference
Returned as results in GET /{id} when completed. All rates are 0-1.
| Field | Description |
|---|---|
schema_version | "1" |
test_id | Test id |
is_simulation | Always true |
disclaimer | {en, zh} simulation notice (not a sales forecast) |
test | Echo of the spec: name, market, platform_name, country_name, currency, product, pricing, question, audience, arms[] (spec arm, including any product / pricing overrides, plus is_control), parent_test_id |
sample.personas_planned / personas_completed / personas_failed | Persona counts |
sample.sessions_per_arm | Sessions per persona per arm |
sample.sessions_unparsed | Sessions whose answer could not be read; excluded from all rates |
sample.models_used | Model ids that produced valid sessions |
arms.<id>.buy_rate | {value, ci95:[lo,hi]}: mean over personas of each persona's buy share; 95% persona-level bootstrap interval |
arms.<id>.buy_sessions / valid_sessions | Counts of buy decisions / parsed sessions |
arms.<id>.personas_majority_buy | Personas who bought in more than half of their sessions |
arms.<id>.top_concerns[] | Up to 5 {category, sessions, share_of_non_buy} from non-buy sessions |
arms.<id>.top_buy_reasons[] | Up to 3 {category, sessions, share_of_buy} |
arms.<id>.common_questions[] | Up to 5 questions shoppers asked most |
comparisons[] | One per non-control arm: arm, vs: "A", difference (arm minus A, mean of per-persona differences), ci ([lo,hi]), ci_level (95%, Bonferroni-adjusted when there are several treatments), stability, scope: "overall_variant" |
comparisons[].stability | clear (CI excludes 0), directional (CI includes 0 but difference >= 0.05), no_difference, insufficient (fewer than 10 personas) |
segments[] | Buy rate per demographic group with at least 3 personas: {dimension, value, personas, buy_rate:{<arm>: rate or null}}. Dimensions: cohort, age, gender, income, home_ownership, pet_ownership, parental_status, relationship_status, urbanicity |
personas[] | {persona_id, profile, representative, arms:{<id>:{buy_rate, decisions[], primary_reason, primary_concern, questions[]}}}. Without ?include=personas, only entries with representative: true (up to 6, mixing control buyers and non-buyers) |
data_gaps, scope_warnings | From the spec: read conclusions within them |
definitions | {en, zh} text for buy_rate, ci, stability, sessions_unparsed |
narrative | {en, zh} reserved; currently null |
GET /{id} also returns buy_rate_a (control buy rate) and best_arm at top level for convenience.
Interpretation notes: differences describe each page variant as a whole, not a single element; a directional result is a lean, not a finding; always carry the disclaimer and data_gaps along.
限制与错误
- 商品页测试:2–6 个方案(
A为对照),至少 10 个虚拟消费者(最多为您套餐的上限),每个方案模拟 3–10 次。 - 免费测试:共 2 次,App、API 和智能助手共用(通过 API 开始的测试与在 App 中开始的一样计数)。一次免费测试可运行最多 100 个虚拟消费者、2 个方案、每个方案最多模拟 5 次的 UI A/B 测试或商品页测试。更大规模的测试(虚拟消费者、方案或模拟次数更多)以及免费测试用完后的所有测试,都从预付余额扣费,即使还有免费测试也是如此;余额不足时开始测试会返回
insufficient_funds(402)。订阅基础版或专业版时不使用免费测试。 - 预付余额:API 密钥代表您的账号,用
client.run_experiment或client.product_tests发起的测试在开始时从余额扣费,按每个虚拟消费者每个方案计费:用量 =persona_count × 方案数 × sessions_per_arm ÷ 5,向上取整;UI A/B 测试有 2 个方案,用量 =persona_count × 2。单价:未订阅套餐时 $0.80,每月最多 50 个测试;基础版每月前 10 个测试 $0.50,之后 $0.55,最多 50 个;专业版前 50 个 $0.35,之后 $0.40,最多 1,000 个(超出后返回plan_limit(403))。例如:100 个虚拟消费者的 UI A/B 测试计 200 个“虚拟消费者 × 方案”。余额不足时返回insufficient_funds(402),并附上所需金额(required)和当前余额;请在账单页面充值。最大测试规模:未订阅套餐时 100 个虚拟消费者,基础版 500 个,专业版 2,000 个,网页应用、API、SDK 和智能助手相同。通过 API 时,UI A/B 测试超出的persona_count会自动降到上限;商品页测试超出时返回tier_limit(403)。 - 额度:
persona_count × 方案数 × ceil(sessions_per_arm ÷ 5)。25 个虚拟消费者、2 个方案、每个方案模拟 5 次需要 50 额度。额度在测试开始时预留;从余额付费的测试受余额和套餐测试数量限制,不受额度限制。 - 测试如果在任何虚拟消费者完成前失败或被取消,会退回:包括额度,以及从余额扣除的费用。一旦有虚拟消费者完成,该测试即正常计费。
- 图片:PNG、JPEG 或 WebP,每张不超过 5 MB;JPEG 最多 8000 万像素,PNG 4500 万,透明 PNG 2500 万,WebP 1200 万。SDK 会在上传前检查。
- 商品页测试通常需要 5–15 分钟(见
eta_minutes),每 15–30 秒轮询一次就足够了。
错误
API 以 {"error": {"code", "message", "message_zh", "details"}} 返回错误。SDK 会抛出 FacetLabError(或其子类:InsufficientFundsError、LimitError、AuthenticationError),带有 .code、.message 和 .details。
from facetlab import FacetLabError, InsufficientFundsError
try:
test = client.product_tests.create(spec, images={"A": "a.png", "B": "b.png"})
except InsufficientFundsError as e:
print(f"Top up first: needs ${e.required}, balance ${e.balance}")
except FacetLabError as e:
print(e.code, e.message) # e.g. "audience_too_small"
print(e.details) # e.g. {"pool_size": 19195, "eligible": 7, "enough": False}常见错误码:unauthorized(401),insufficient_funds 和 quota_exceeded(402),tier_limit、free_tier_limit 和 plan_limit(403),needs_info 和 audience_too_small(422),以及 SDK 本地检查的 invalid_image。
对 API 或 SDK 有疑问?请发邮件至 qyzkai@gmail.com。