dev-avatar-service

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Avatar service

头像服务

A service endpoint that returns a branded avatar for any user: photoreal, illustrated, or pixel, deterministic from a seed (user ID / email hash / initials). Built around a fallback hierarchy — real photo → upload → AI from initials → static default — with caching by seed so you pay once per user.
这是一个可为任意用户返回品牌化头像的服务端点:支持写实风、插画风或像素风,基于种子(用户ID/邮箱哈希/姓名首字母)生成确定性头像。服务围绕 fallback 层级构建——真实照片→用户上传头像→基于首字母生成AI头像→静态默认头像——并按种子进行缓存,因此每个用户仅需支付一次生成成本。

When to Use

使用场景

  • New user signup where you need an immediate profile image.
  • Comment systems or forums that default to gravatars.
  • Team pages, directories, leaderboards without uploaded photos.
  • Placeholder avatars during onboarding before the user picks one.
  • Branded alternative to Gravatar / UI Avatars / DiceBear.
  • Mock data for staging/demo environments.
Not for: deepfaking real people from a single photo (wrong tool + wrong ethics), or stylizing an already-great uploaded photo — let users keep their own.
  • 新用户注册时,需要立即提供个人资料图片的场景。
  • 默认使用Gravatar的评论系统或论坛。
  • 没有用户上传照片的团队页面、人员目录、排行榜。
  • 用户选择头像前,引导流程中的占位头像。
  • Gravatar / UI Avatars / DiceBear的品牌化替代方案。
  • staging/演示环境中的模拟数据。
不适用场景:从单张照片深度伪造真人(工具和伦理均不适用),或对已上传的优质照片进行风格化处理——应保留用户自己的照片。

Prerequisites

前置准备

Before building, ask (one message, 5 questions):
  1. Seed source: user ID, email hash, username, initials? Is it stable forever?
  2. Style: photoreal portrait, illustrated (Pixar/Disney-ish), flat vector, pixel art, claymorphic, monogram?
  3. Brand palette: accent color for backgrounds + monogram fallbacks.
  4. Storage + cache: S3/CDN + DB column, Picsart Drive URL, or KV key? TTL?
  5. Fallback chain: photo → AI avatar → initials-on-color → default SVG? Order matters.
Skip if the user hands over a detailed brief.
在构建之前,先确认以下5个问题(只需一条消息询问):
  1. 种子来源:用户ID、邮箱哈希、用户名还是姓名首字母?是否永久稳定?
  2. 风格:写实肖像、插画风格(皮克斯/迪士尼风)、扁平化矢量图、像素艺术、黏土风格、字母组合头像?
  3. 品牌调色板:背景和字母组合 fallback 的强调色。
  4. 存储与缓存:S3/CDN + 数据库列、Picsart Drive URL,还是KV键?TTL(过期时间)是多少?
  5. Fallback 链:照片→AI头像→彩色背景首字母→默认SVG?顺序很重要。
如果用户提供了详细的需求说明,则可跳过此步骤。

How to Run

运行步骤

  1. Decide the fallback hierarchy first. This is the whole service:
    1. user.photo_url          → return as-is
    2. cache.get(seed)         → return stored AI avatar URL
    3. gen-ai generate         → store URL + return
    4. initials on brand color → SVG fallback (no credits)
    5. static /default.png     → last resort
  2. Estimate + validate model.
    bash
    gen-ai models info recraftv4
    gen-ai pricing recraftv4
    gen-ai generate -m recraftv4 -p "illustrated avatar, seed abc123" \
      --aspect-ratio 1:1 --dry-run --debug
  3. Deterministic seed → prompt. Hash the seed into stable attribute picks. Never inject
    Math.random()
    or timestamps.
    bash
    SEED="u_482c91"
    # Pick palette + mood from the seed, not from RNG
    HUE=$(printf "%s" "$SEED" | shasum | cut -c1-2)   # 0-255 from hash
    gen-ai generate -m recraftv4 \
      -p "illustrated profile avatar, round frame, abstract humanoid silhouette, HSL hue ${HUE}, friendly neutral expression, flat vector, centered composition, studio background" \
      --aspect-ratio 1:1 \
      --negative-prompt "text, watermark, letters, realistic face, specific person" \
      --save-to-drive --drive-folder avatars \
      --json --no-input | jq -r '.url'
  4. Cache the URL (not the binary) keyed on the seed. Any store: Redis, KV, Postgres column, S3 + stable filename.
  5. Initials fallback (zero credits). When gen-ai is down, rate-limited, or over budget — return an SVG built from the user's initials on a hue derived from the same seed. Users never see a broken image.
    ts
    const initials = name.split(' ').map(p => p[0]).slice(0, 2).join('').toUpperCase();
    const hue = parseInt(sha1(seed).slice(0, 2), 16);
    const svg = `<svg viewBox="0 0 64 64"><rect width="64" height="64" fill="hsl(${hue} 70% 45%)"/><text x="32" y="40" text-anchor="middle" font-size="28" fill="#fff" font-family="system-ui">${initials}</text></svg>`;
  6. Wire the endpoint.
    /avatar/:seed
    → check photo → check cache → gen-ai → initials. 302 to CDN URL on success; inline SVG on fallback.
  7. Pre-warm the cache in batch for existing users so your prod rollout doesn't hammer gen-ai live:
    bash
    gen-ai batch run avatars-backfill.json -c 4 -o ./avatars-out
  1. 首先确定Fallback层级。这是整个服务的核心:
    1. user.photo_url          → 直接返回
    2. cache.get(seed)         → 返回存储的AI头像URL
    3. gen-ai generate         → 存储URL并返回
    4. 品牌色背景上的首字母 → SVG fallback(无需付费)
    5. static /default.png     → 最终备选方案
  2. 评估并验证模型
    bash
    gen-ai models info recraftv4
    gen-ai pricing recraftv4
    gen-ai generate -m recraftv4 -p "illustrated avatar, seed abc123" \
      --aspect-ratio 1:1 --dry-run --debug
  3. 确定性种子→提示词。将种子哈希为稳定的属性选择。绝对不要注入
    Math.random()
    或时间戳。
    bash
    SEED="u_482c91"
    # 从种子中选择调色板和风格,而非随机数生成器
    HUE=$(printf "%s" "$SEED" | shasum | cut -c1-2)   # 从哈希值获取0-255的数值
    gen-ai generate -m recraftv4 \
      -p "illustrated profile avatar, round frame, abstract humanoid silhouette, HSL hue ${HUE}, friendly neutral expression, flat vector, centered composition, studio background" \
      --aspect-ratio 1:1 \
      --negative-prompt "text, watermark, letters, realistic face, specific person" \
      --save-to-drive --drive-folder avatars \
      --json --no-input | jq -r '.url'
  4. 缓存URL(而非二进制文件),以种子为键。可使用任意存储:Redis、KV、Postgres列、S3 + 稳定文件名。
  5. 首字母Fallback(零成本)。当gen-ai服务宕机、触发限流或超出预算时——返回基于用户首字母和同一种子派生的色调构建的SVG。用户永远不会看到损坏的图片。
    ts
    const initials = name.split(' ').map(p => p[0]).slice(0, 2).join('').toUpperCase();
    const hue = parseInt(sha1(seed).slice(0, 2), 16);
    const svg = `<svg viewBox="0 0 64 64"><rect width="64" height="64" fill="hsl(${hue} 70% 45%)"/><text x="32" y="40" text-anchor="middle" font-size="28" fill="#fff" font-family="system-ui">${initials}</text></svg>`;
  6. 对接端点
    /avatar/:seed
    → 检查照片→检查缓存→调用gen-ai→生成首字母头像。成功时302跳转至CDN URL;Fallback时返回内联SVG。
  7. 批量预缓存现有用户的头像,这样生产环境上线时不会实时冲击gen-ai服务:
    bash
    gen-ai batch run avatars-backfill.json -c 4 -o ./avatars-out

Quick Reference

快速参考

Backfill 500 existing users:
json
{
  "defaults": {
    "model": "recraftv4",
    "aspectRatio": "1:1",
    "negativePrompt": "text, watermark, letters, realistic face, specific person"
  },
  "jobs": [
    { "id": "u_482c91", "prompt": "illustrated profile avatar, round frame, flat vector, hue 42, friendly neutral, studio background" },
    { "id": "u_91ac3b", "prompt": "illustrated profile avatar, round frame, flat vector, hue 128, calm expression, studio background" },
    { "id": "u_7de119", "prompt": "illustrated profile avatar, round frame, flat vector, hue 201, warm smile, studio background" }
  ]
}
Output lands at
./avatars-out/<user-id>.webp
— upload to your CDN under the same key.
results.json
becomes the seed → URL lookup table.
批量生成500位现有用户的头像:
json
{
  "defaults": {
    "model": "recraftv4",
    "aspectRatio": "1:1",
    "negativePrompt": "text, watermark, letters, realistic face, specific person"
  },
  "jobs": [
    { "id": "u_482c91", "prompt": "illustrated profile avatar, round frame, flat vector, hue 42, friendly neutral, studio background" },
    { "id": "u_91ac3b", "prompt": "illustrated profile avatar, round frame, flat vector, hue 128, calm expression, studio background" },
    { "id": "u_7de119", "prompt": "illustrated profile avatar, round frame, flat vector, hue 201, warm smile, studio background" }
  ]
}
输出文件将保存至
./avatars-out/<user-id>.webp
——将其上传至CDN并使用相同的键。
results.json
将成为种子→URL的查找表。

Quick Reference

快速参考

Sub-taskModelWhy
Illustrated / vector / flat avatars
recraftv4
Clean, consistent, cheap — ideal default
Photoreal portrait (synthetic, generic person)
flux-2-pro
Best faces; use with generic descriptors only
Pixel-art avatars
recraftv4
with pixel-style prompt
Lowest credits, stylistic control
Stylize an uploaded real photo (opt-in)
flux-kontext-pro
+
-i photo.jpg
Edit model preserves identity
Cheap draft / style exploration
gemini-3.1-flash-image
Lowest per-call cost
Identity-locked variants across sizes
ideogram-character
+
-i master.png
Same face across multiple avatars
Verify live IDs with
gen-ai models --mode image
.
子任务模型原因
插画/矢量/扁平化头像
recraftv4
简洁、一致、成本低——是理想的默认选择
写实肖像(合成通用人物)
flux-2-pro
生成的面部效果最佳;仅搭配通用描述词使用
像素艺术头像
recraftv4
+ 像素风格提示词
成本最低,风格可控
对上传的真实照片进行风格化(可选)
flux-kontext-pro
+
-i photo.jpg
编辑模型可保留人物身份
低成本草稿/风格探索
gemini-3.1-flash-image
单次调用成本最低
不同尺寸下保持身份一致的变体
ideogram-character
+
-i master.png
多个头像保持同一张脸
使用
gen-ai models --mode image
验证可用的实时模型ID。

Procedure

操作规范

  • Determinism = cacheability. Derive every variable attribute (hue, pose, expression) from a hash of the seed. Same seed → same prompt → same image → one credit forever.
  • Version the prompt template. Bump
    V=2
    in the cache key when you restyle; old avatars age out, new ones regenerate on demand.
  • Fallback is not optional. Initials-on-hue SVG must always work. Never let the UI render a broken avatar because gen-ai 429'd.
  • Negative prompt matters. Always exclude
    text, watermark, letters, realistic face of specific person
    — avatars must not resemble real celebrities or render accidental copy.
  • Don't generate on every page load. Generate once per seed, cache forever (or until template version bump). A viral signup spike must not trigger a gen-ai spike.
  • Use Drive for storage.
    --save-to-drive --drive-folder avatars
    gives a stable CDN URL with no extra infra.
  • Pre-warm before launch. Batch-generate for existing users; don't migrate live traffic onto a cold cache.
  • Respect user uploads. If the user has uploaded a real photo, return that — never override. AI avatars are for missing photos only.
  • Rate-limit at the edge. Cap gen-ai calls per IP per hour. A bot probing
    /avatar/:random
    can burn your credit budget in minutes.
  • 确定性=可缓存性。从种子的哈希值派生所有可变属性(色调、姿势、表情)。相同种子→相同提示词→相同图片→永久仅需一次生成成本。
  • 版本化提示词模板。重新设计风格时,在缓存键中加入版本号(如
    V=2
    );旧头像会逐渐失效,新头像将按需重新生成。
  • Fallback不可省略。彩色背景首字母SVG必须始终可用。绝不能因为gen-ai返回429错误就让UI显示损坏的头像。
  • 负向提示词至关重要。始终排除
    text, watermark, letters, realistic face of specific person
    ——头像不得与真实名人相似,也不得意外生成可识别的人物。
  • 不要每次页面加载都生成。每个种子仅生成一次,永久缓存(或直到模板版本更新)。注册量暴增时不得触发gen-ai请求暴增。
  • 使用Drive存储
    --save-to-drive --drive-folder avatars
    可提供稳定的CDN URL,无需额外基础设施。
  • 上线前预缓存。为现有用户批量生成头像;不要将实时流量迁移到冷缓存上。
  • 尊重用户上传的照片。如果用户已上传真实照片,直接返回该照片——绝不能覆盖。AI头像仅用于缺失照片的情况。
  • 在边缘层限流。限制每IP每小时的gen-ai调用次数。爬虫批量请求
    /avatar/:random
    可能在几分钟内耗尽你的生成额度。

Pitfalls

常见陷阱

PitfallFix
Regenerated avatar looks different on every refreshNon-deterministic prompt — hash the seed, derive attributes, no RNG/timestamps
Cache never invalidates after restyleVersion the prompt template (
V=3
in the cache key)
AI renders real-looking faces resembling celebritiesAdd
negativePrompt: "realistic face of specific person, celebrity, known individual"
Text or watermarks appear in the avatarAdd
negativePrompt: "text, watermark, letters, logos"
Bot traffic burns credit budgetRate-limit per IP; allow only authed users to hit the generator; fallback to initials for anons
Gen-ai 429s cause broken avatar UISVG initials fallback must be the last step in the chain
Batch backfill half-fails
gen-ai batch resume <out>
retries only failures
Different avatar style across the appCommit the prompt template; never let callers pass raw prompts
陷阱修复方案
每次刷新时重新生成的头像外观不同提示词非确定性——对种子进行哈希,派生属性,不使用随机数生成器/时间戳
重新设计风格后缓存从未失效版本化提示词模板(在缓存键中加入
V=3
AI生成的逼真面部与名人相似添加负向提示词:
negativePrompt: "realistic face of specific person, celebrity, known individual"
头像中出现文字或水印添加负向提示词:
negativePrompt: "text, watermark, letters, logos"
爬虫流量耗尽生成额度按IP限流;仅允许已认证用户调用生成器;匿名用户返回首字母头像
Gen-ai返回429错误导致头像UI损坏SVG首字母Fallback必须是链中的最后一步
批量回填任务部分失败使用
gen-ai batch resume <out>
仅重试失败任务
应用中头像风格不一致提交提示词模板;绝不允许调用者传入原始提示词

Verification

验证方法

Run
gen-ai whoami
to confirm authentication, then re-run the failed command with
--debug
.
运行
gen-ai whoami
确认身份验证,然后添加
--debug
参数重新运行失败的命令。

Cost & time

成本与耗时

TaskCreditsTime
1 avatar (Recraft V4, illustrated)1-2~4-8s
1 avatar (Flux 2 Pro, photoreal)3-5~10-15s
1 avatar (Gemini 3.1 Flash, draft)1~3-5s
Initials SVG fallback0<1ms
Cache read (KV/Redis hit)0~2-5ms
Batch of 500 at concurrency 4~750-1000~15-20 min
In steady state, expect >99% cache hit rate — near-zero ongoing cost.
任务生成额度耗时
1个头像(Recraft V4,插画风格)1-2~4-8秒
1个头像(Flux 2 Pro,写实风格)3-5~10-15秒
1个头像(Gemini 3.1 Flash,草稿版)1~3-5秒
首字母SVG Fallback0<1毫秒
缓存读取(KV/Redis命中)0~2-5毫秒
并发数为4的500个批量任务~750-1000~15-20分钟
稳定运行状态下,预计缓存命中率>99%——持续成本几乎为零。

See also

相关文档

  • gen-ai-use.md
    — CLI reference, auth, scripting with
    --json --no-input
    /
    jq
  • gen-ai-batch.md
    — manifest shapes, batch resume, rate-limit strategy, Cloudflare Worker pattern
  • gen-ai-workflows.md
    — Workflow 6 (headshot studio) for stylizing uploaded photos
  • dev-og-image-service
    — same caching + determinism patterns for OG cards
  • gen-ai-use.md
    — CLI参考、身份验证、使用
    --json --no-input
    /
    jq
    进行脚本开发
  • gen-ai-batch.md
    — 清单格式、批量任务恢复、限流策略、Cloudflare Worker模式
  • gen-ai-workflows.md
    — 工作流6(头像工作室)用于对上传照片进行风格化处理
  • dev-og-image-service
    — 用于OG卡片的相同缓存+确定性模式