[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -1,92 +1,161 @@
---
id: wiki-2026-0508-api-backed-image-generation-work
title: API backed Image Generation Workflow
title: API-backed Image Generation Workflow
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Image Gen API, Cloud Image Generation, Hosted Diffusion API]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [image-generation, api, workflow, diffusion, production]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: Python
framework: OpenAI/Replicate/FAL SDKs
---
# [[API-backed Image Generation Workflow|API-backed Image Generation Workflow]]
# API-backed Image Generation Workflow
## 📌 한 줄 통찰 (The Karpathy Summary)
API 기반 이미지 생성 워크플로우는 수동적인 이미지 창작을 프로그래밍 방식으로 제어 가능한 자동화 파이프라인으로 전환하는 프로세스를 의미합니다 [1, 2]. 이는 애플리케이션 내에서 생성 작업을 예약하고, 비동기 상태를 관리하며, 비용 효율적인 초안 모드(Draft Mode)를 거쳐 최종 이미지를 확정하는 일련의 과정을 포함합니다 [2-5]. 개발자와 기업은 이러한 API를 통해 고도의 프롬프트 엔지니어링 및 이미지/비디오 생성 기능을 외부 도구나 자체 서비스에 직접 통합할 수 있습니다 [6, 7].
## 한 줄
> **"매 prompt → API → asset, GPU 의 X"**. Hosted endpoint (OpenAI Images, Replicate, FAL, Stability, BFL) 의 호출하여 image asset 를 generate — 매 GPU infra ownership 의 X, 매 per-call cost 의 trade. 2026 production app 의 매 default mode (self-host 의 매 scale-driven decision).
## 📖 구조화된 지식 (Synthesized Content)
- **프로그래밍 방식의 작업 제어 및 아키텍처 설계:** API 경로를 통해 이미지 생성 모델(예: Midjourney V7, Veo 3.1)을 호출하면, 프로그래밍 방식으로 작업을 생성하고 결과를 파이프라인의 다음 단계로 전달할 수 있습니다 [2, 7, 8]. 이는 단순히 하나의 단일 모델로 모든 작업을 처리하는 대신, 컨셉 도출, 정확한 편집, 텍스트가 많은 디자인 등 각 작업의 특성에 맞춰 여러 이미지 생성 모델(라우트)을 유연하게 비교하고 활용하는 건강한 아키텍처 구축을 가능하게 합니다 [8, 9].
- **비동기 상태 관리 (Async State Machine):** 프로덕션 환경의 API 통합에서는 비동기적 생성 과정의 상태 관리가 매우 중요합니다 [2, 5]. 시스템은 단순히 작업을 '완료'나 '오류'로만 분류해서는 안 되며, 생성 실행 중, 기술적 실패, 콘텐츠 필터링 차단, 사용자 검토 대기, 고품질 향상(enhancement) 선택됨, 최종 에셋 준비 완료 등 세분화된 상태를 구별하여 설계해야 합니다 [2, 5].
- **디버깅과 자동화를 위한 데이터 모델링:** API 기반 시스템에서는 단순히 최종 결과물의 URL만 저장하는 것이 아니라, 사용된 프롬프트, 참조(References) 이미지, 선택된 시안 후보, 생성 경로 등의 전체 데이터를 저장하는 것이 권장됩니다 [10, 11]. 이를 통해 특정 결과물의 생성 원인을 디버깅할 수 있고, 사용자가 어떤 스타일을 선택하는지 또는 어떤 프롬프트 패턴이 지속적으로 실패하는지 학습하여 향후 자동화를 용이하게 만들 수 있습니다 [10, 11].
- **초안 모드(Draft Mode)를 활용한 비용 및 워크플로우 최적화:** 모든 프롬프트가 즉시 완성된 에셋을 도출해야 한다는 가정은 API 환경에서 비용을 높이고 비효율을 초래합니다 [4, 12]. 대신 처리 비용이 저렴한 초안 모드로 여러 구성의 시안을 생성한 뒤, 사용자가 유망한 방향을 선택하면 이를 고품질 결과물로 승격시키는(promote) 루프를 설계하는 것이 매우 중요합니다 [3, 4].
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Related Topics:** 비동기적 생성 상태 관리 (Async Generation State), 프롬프트 데이터 모델링 (Prompt Data Modeling), 초안 모드 (Draft Mode)
- **Projects/Contexts:** Midjourney V7 API Workflow, Vertex AI Veo 3.1 API Integration
- **Contradictions/Notes:** API 환경에서 프롬프트에 스타일 참조나 옴니 참조 기능을 적용하더라도 이미지 생성이 완벽하게 결정론적(deterministic)으로 이루어지는 것은 아니므로 프로덕션 팀은 이를 인지하고 워크플로우를 설계해야 합니다 [5]. 또한, 모델의 구성이 훌륭하다고 해서 텍스트 타이포그래피까지 정확하게 생성되는 것은 아니므로 정확한 텍스트가 필요한 경우 별도의 디자인 단계를 계획해야 합니다 [5].
### 매 hosted vs self-host trade
- **Hosted**: 매 zero infra, 매 latest model (FLUX 1.1 Pro Ultra, Imagen 4, gpt-image-1) 즉시 access, 매 per-image $0.02-0.08.
- **Self-host (vLLM/MLX/ComfyUI)**: 매 fixed GPU cost, 매 high-volume (>100k img/mo) 의 break-even.
- **Break-even**: ~50k img/mo @ A100 spot price ($1.5/hr).
---
*Last updated: 2026-04-30*
### 매 provider matrix (2026)
- **BFL FLUX 1.1 Pro Ultra**: 매 photoreal SOTA, 4MP, $0.06/img.
- **OpenAI gpt-image-1**: 매 text rendering best, multimodal edit, $0.04-0.19/img.
- **Google Imagen 4**: 매 prompt adherence, $0.04/img.
- **Replicate / FAL**: 매 aggregator, 매 100+ model 의 unified API.
- **Stability SD 3.5**: 매 open-weight + hosted dual.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 workflow stage
1. **Prompt construction**: template + user input + style tokens.
2. **API call**: async, retry, idempotency key.
3. **Polling/webhook**: 매 long-running job (>5s) 의 webhook, 매 short job 의 sync.
4. **Asset storage**: S3/R2 + CDN, signed URL.
5. **Moderation**: pre-prompt filter + post-image NSFW check.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### FAL async (recommended 2026)
```python
import fal_client
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
handler = fal_client.submit(
"fal-ai/flux-pro/v1.1-ultra",
arguments={"prompt": "cyberpunk city, neon rain, 8k", "aspect_ratio": "16:9"},
)
# webhook 또는 poll
result = handler.get() # blocks until done
url = result["images"][0]["url"]
```
## 🤔 의사결정 기준 (Decision Criteria)
### OpenAI gpt-image-1
```python
from openai import OpenAI
client = OpenAI()
resp = client.images.generate(
model="gpt-image-1",
prompt="A futuristic library, isometric, soft lighting",
size="1024x1024",
quality="high",
n=1,
)
b64 = resp.data[0].b64_json
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Replicate (model marketplace)
```python
import replicate
output = replicate.run(
"black-forest-labs/flux-1.1-pro-ultra",
input={"prompt": "...", "aspect_ratio": "21:9", "raw": False},
)
# output: list[FileOutput] — stream to S3
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Webhook handler (FastAPI)
```python
@app.post("/webhooks/fal")
async def on_fal(req: Request):
payload = await req.json()
if payload["status"] == "OK":
url = payload["payload"]["images"][0]["url"]
await store_to_r2(url, key=payload["request_id"])
return {"ok": True}
```
**기본값:**
> *(TODO)*
### Retry + idempotency
```python
import httpx
from tenacity import retry, stop_after_attempt, wait_exponential
## ❌ 안티패턴 (Anti-Patterns)
@retry(stop=stop_after_attempt(3), wait=wait_exponential(min=1, max=10))
async def gen(prompt: str, idem: str):
async with httpx.AsyncClient(timeout=120) as c:
r = await c.post(URL, json={"prompt": prompt}, headers={"Idempotency-Key": idem})
r.raise_for_status()
return r.json()
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Pre-moderation
```python
def safe_prompt(p: str) -> bool:
bad = {"nsfw", "gore", "csam"} # 매 minimal — provider 의 strong filter 의 추가 layer
return not any(t in p.lower() for t in bad)
```
### Cost meter
```python
COSTS = {"flux-pro-ultra": 0.06, "gpt-image-1-high": 0.19, "imagen-4": 0.04}
def charge(user_id: str, model: str, n: int):
cost = COSTS[model] * n
db.execute("UPDATE users SET credit = credit - ? WHERE id = ?", (cost, user_id))
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Photoreal hero asset | FLUX 1.1 Pro Ultra |
| Text-in-image (poster, UI) | gpt-image-1 |
| Bulk variant (>10k/day) | self-host SDXL/SD3.5 + ComfyUI cluster |
| Prototype / MVP | Replicate (zero setup) |
| Edit / inpaint / multimodal | gpt-image-1 또는 FLUX Fill |
**기본값**: FAL FLUX 1.1 Pro Ultra (cost/quality 의 sweet spot 2026).
## 🔗 Graph
- 부모: [[Image Generation]] · [[Diffusion Models]]
- 변형: [[Self-hosted ComfyUI Workflow]] · [[Edge Image Generation]]
- 응용: [[AdSense Revenue Blog Architecture]] · [[E-commerce Product Photography]]
- Adjacent: [[Webhook Patterns]] · [[CDN Asset Pipeline]] · [[Prompt Engineering for Images]]
## 🤖 LLM 활용
**언제**: 매 product feature (avatar, blog hero, marketing) 의 image gen — 매 launch speed 의 priority.
**언제 X**: 매 >100k img/mo 의 sustained volume (self-host 의 cheaper), 매 strict on-prem (HIPAA/gov).
## ❌ 안티패턴
- **Sync block 60s+**: 매 user request thread 의 block — 매 webhook 또는 background job 의 use.
- **No idempotency**: 매 retry 의 duplicate charge — 매 idempotency key 의 always.
- **Raw provider URL serve**: 매 expire 24h — 매 own CDN 의 mirror.
- **Skip moderation**: 매 brand risk + provider TOS violation.
- **Hard-coded provider**: 매 single API 에 lock-in — 매 abstraction layer (e.g. `ImageProvider` interface).
## 🧪 검증 / 중복
- Verified (BFL 2025-10 release notes; OpenAI gpt-image-1 docs 2025; FAL/Replicate pricing 2026-Q1).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 2026 provider matrix, FAL/FLUX/gpt-image-1 patterns |