Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(forge): free NIM FLUX lane as first hop in text→image

nirholas892c57371dad
diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.js
index e9520378a..530721c6b 100644
--- a/api/_mcp3d/text-to-image.js
+++ b/api/_mcp3d/text-to-image.js
@@ -1,23 +1,46 @@
// Text → image helper for the 3D Studio MCP.
//
-// Provider selection (first configured wins):
-// 1. GOOGLE_CLOUD_PROJECT set → Vertex AI Imagen 3 (best quality, free with GCP credits)
-// 2. REPLICATE_API_TOKEN set → flux-schnell via Replicate (fast, $0.003/image)
+// Provider selection (free lanes first, per platform policy; first that serves wins):
+// 1. NVIDIA_API_KEY set → FLUX.1-schnell on NVIDIA NIM (free, ~1–2s)
+// 2. GOOGLE_CLOUD_PROJECT set → Vertex AI Imagen 3 (high quality, free with GCP credits)
+// 3. REPLICATE_API_TOKEN set → flux-schnell via Replicate (paid backstop, $0.003/image)
//
// The image-to-3D backend (TRELLIS / Hunyuan3D / TripoSR) reconstructs a
// textured GLB from the generated image. Both steps share the same call site.
//
+// NVIDIA_API_KEY — nvapi key from build.nvidia.com (enables the free NIM lane)
// GOOGLE_CLOUD_PROJECT — GCP project id (enables Vertex AI Imagen path)
// VERTEX_IMAGEN_MODEL — override Imagen model (default: imagen-3.0-generate-001)
-// REPLICATE_API_TOKEN — required when GCP not configured
+// REPLICATE_API_TOKEN — paid backstop when the free lanes are absent or down
// REPLICATE_TXT2IMG_MODEL — optional Replicate model override
//
-// Replicate fallback: black-forest-labs/flux-schnell — Apache-2.0,
-// commercial-OK, ~1–3s per image on Replicate's fleet, $0.003/run.
+// NIM lane: black-forest-labs/flux.1-schnell — Apache-2.0, commercial-OK, served
+// free on the NVIDIA NIM catalog as a base64 PNG (no poll; returns inline).
+// Replicate backstop: black-forest-labs/flux-schnell — same family, $0.003/run.
const REPLICATE_BASE = 'https://api.replicate.com/v1';
const DEFAULT_TXT2IMG_MODEL = 'black-forest-labs/flux-schnell';
+// NVIDIA NIM FLUX.1-schnell — synchronous genai invoke (no 202/poll), returns
+// { artifacts: [{ base64, finishReason }] }. flux-schnell is the fast 4-step
+// distilled model, so a tight per-attempt timeout is safe: a hung free lane must
+// hand off to the paid lanes, never stall the whole text→3D pipeline.
+const NIM_FLUX_URL = 'https://ai.api.nvidia.com/v1/genai/black-forest-labs/flux.1-schnell';
+const NIM_FLUX_MODEL = 'black-forest-labs/flux.1-schnell';
+const NIM_TIMEOUT_MS = 60_000;
+
+// FLUX wants explicit pixel dimensions (multiples of 64). Map the caller's
+// aspect ratio to a sensible ~1MP size; anything unmapped falls back to square.
+const NIM_DIMENSIONS = {
+ '1:1': [1024, 1024],
+ '16:9': [1344, 768],
+ '9:16': [768, 1344],
+ '4:3': [1024, 768],
+ '3:4': [768, 1024],
+ '3:2': [1216, 832],
+ '2:3': [832, 1216],
+};
+
function readEnv(name) {
if (typeof process !== 'undefined' && process.env && process.env[name]) return process.env[name];
return null;
@@ -51,32 +74,105 @@ function parseRetryAfter(headers, message) {
return 10;
}
-// Vertex Imagen returns the PNG inline as a data: URI. Downstream image-to-3D
-// providers take URLs (Replicate caps inline data URIs at ~256 KB — a 1024px
-// Imagen PNG blows straight past that), so persist the bytes to object storage
-// and hand back a durable https URL instead.
-async function persistDataUriImage(result) {
- if (!result?.imageUrl?.startsWith('data:')) return result;
+// Persist a base64 PNG to object storage and return a durable https URL.
+// Downstream image-to-3D providers take URLs (Replicate caps inline data URIs at
+// ~256 KB — a 1024px PNG blows straight past that), so neither the Vertex inline
+// data URI nor the NIM base64 artifact can be forwarded as-is.
+async function persistPngBase64(b64) {
const { putObject, publicUrl } = await import('../_lib/r2.js');
- const b64 = result.imageUrl.split(',')[1] || '';
const key = `forge/refs/${globalThis.crypto.randomUUID()}.png`;
await putObject({ key, body: Buffer.from(b64, 'base64'), contentType: 'image/png' });
- return { ...result, imageUrl: publicUrl(key) };
+ return publicUrl(key);
+}
+
+// Vertex Imagen returns the PNG inline as a data: URI — persist it the same way
+// the NIM lane persists its base64 artifact.
+async function persistDataUriImage(result) {
+ if (!result?.imageUrl?.startsWith('data:')) return result;
+ const b64 = result.imageUrl.split(',')[1] || '';
+ return { ...result, imageUrl: await persistPngBase64(b64) };
+}
+
+// Free lane: FLUX.1-schnell on NVIDIA NIM. Synchronous invoke — the artifact
+// comes back inline as base64, no poll. Caller guarantees NVIDIA_API_KEY is set.
+// Throws on any failure (timeout, throttle, malformed body) so the caller can
+// degrade to the paid lanes; never returns a half-result.
+async function nimFluxImage(prompt, aspectRatio) {
+ const key = readEnv('NVIDIA_API_KEY');
+ const [width, height] = NIM_DIMENSIONS[aspectRatio] || NIM_DIMENSIONS['1:1'];
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), NIM_TIMEOUT_MS);
+ let res;
+ try {
+ res = await fetch(NIM_FLUX_URL, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${key}`,
+ accept: 'application/json',
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({
+ prompt,
+ mode: 'base',
+ cfg_scale: 3.5,
+ width,
+ height,
+ seed: 0,
+ steps: 4,
+ }),
+ signal: controller.signal,
+ });
+ } catch (err) {
+ const aborted = err?.name === 'AbortError';
+ throw Object.assign(
+ new Error(aborted ? 'nim flux timed out' : `nim flux unreachable: ${err?.message}`),
+ { code: aborted ? 'rate_limited' : 'provider_unreachable' },
+ );
+ } finally {
+ clearTimeout(timer);
+ }
+
+ if (!res.ok) {
+ const detail = await res.text().catch(() => '');
+ const message = `nim flux returned ${res.status}${detail ? `: ${detail.slice(0, 200)}` : ''}`;
+ // 429 (credit-metered free tier) is retryable; surface it so a caller can
+ // route, but here it just means "fall through to the paid lanes".
+ throw Object.assign(new Error(message), {
+ providerStatus: res.status,
+ ...(res.status === 429 ? { code: 'rate_limited' } : {}),
+ });
+ }
+
+ const data = await res.json().catch(() => ({}));
+ const b64 = data?.artifacts?.[0]?.base64;
+ if (!b64) throw new Error('nim flux finished but produced no image');
+ return { imageUrl: await persistPngBase64(b64), model: NIM_FLUX_MODEL };
}
// Generate a single image from a text prompt.
//
-// Prefers Vertex AI Imagen when GOOGLE_CLOUD_PROJECT is configured (free with
-// GCP credits, higher quality). Falls back to Replicate flux-schnell otherwise —
-// including when the Vertex path is configured but fails (bad service-account
-// JSON, expired model, missing object storage for the inline PNG): a broken
-// preferred provider must degrade to the working one, never take down the
-// whole text→3D pipeline.
+// Tries the free lanes first (NIM FLUX, then Vertex Imagen) and degrades to the
+// paid Replicate backstop on any failure — a broken or throttled preferred
+// provider must hand off, never take down the whole text→3D pipeline. The last
+// configured lane's error is surfaced only when nothing is left to try.
export async function textToImage(prompt, { aspectRatio = '1:1' } = {}) {
const token = readEnv('REPLICATE_API_TOKEN');
+ const hasVertex = !!readEnv('GOOGLE_CLOUD_PROJECT');
+
+ // ── NVIDIA NIM FLUX (free, first) ─────────────────────────────────────────
+ if (readEnv('NVIDIA_API_KEY')) {
+ try {
+ return await nimFluxImage(prompt, aspectRatio);
+ } catch (err) {
+ // Nothing downstream to fall through to → surface the NIM error.
+ if (!hasVertex && !token) throw err;
+ console.error(`nim flux failed, falling back: ${err?.message}`);
+ }
+ }
// ── Vertex AI Imagen path ────────────────────────────────────────────────
- if (readEnv('GOOGLE_CLOUD_PROJECT')) {
+ if (hasVertex) {
try {
const { generateImage, isConfigured } = await import('./vertex-imagen.js');
if (isConfigured()) {
@@ -92,7 +188,7 @@ export async function textToImage(prompt, { aspectRatio = '1:1' } = {}) {
if (!token) {
throw Object.assign(
new Error(
- 'text-to-image is not configured: set GOOGLE_CLOUD_PROJECT (Vertex AI) or REPLICATE_API_TOKEN (Replicate)',
+ 'text-to-image is not configured: set NVIDIA_API_KEY (NIM), GOOGLE_CLOUD_PROJECT (Vertex AI), or REPLICATE_API_TOKEN (Replicate)',
),
{ code: 'unconfigured' },
);
diff --git a/tasks/nvidia-nim/PLAN.md b/tasks/nvidia-nim/PLAN.md
index 5302c1f9c..34ed87882 100644
--- a/tasks/nvidia-nim/PLAN.md
+++ b/tasks/nvidia-nim/PLAN.md
@@ -40,7 +40,7 @@ Status legend: `[ ]` not started · `[~]` in progress (note who/when in Worklog)
### Phase 1 — Free 3D lane in /forge (top priority)
- [ ] **T1.1** [10-trellis-provider.md](10-trellis-provider.md) — `api/_providers/nvidia.js` (submit / poll / GLB→R2)
- [ ] **T1.2** [11-register-backend.md](11-register-backend.md) — backend in `forge-tiers.js`; draft-tier default
-- [ ] **T1.3** [12-flux-lane.md](12-flux-lane.md) — NIM FLUX lane in `api/_mcp3d/text-to-image.js`
+- [~] **T1.3** [12-flux-lane.md](12-flux-lane.md) — NIM FLUX lane in `api/_mcp3d/text-to-image.js` (code + tests done; live image pending key — see Worklog 2026-06-11)
- [ ] **T1.4** [13-tests.md](13-tests.md) — `tests/api/providers-nvidia.test.js` + registration coverage
- [ ] **T1.5** [14-deploy-smoke-changelog.md](14-deploy-smoke-changelog.md) — deploy + prod smoke + changelog
@@ -100,6 +100,24 @@ Status legend: `[ ]` not started · `[~]` in progress (note who/when in Worklog)
## Worklog (append-only; newest at top)
+- **2026-06-11** — **T1.3 (NIM FLUX lane) — code + tests complete, live run blocked.**
+ Added FLUX.1-schnell on NVIDIA NIM as the FIRST lane in `api/_mcp3d/text-to-image.js`,
+ ahead of Vertex Imagen and the Replicate paid backstop (free-first per policy). Built
+ against NVIDIA's documented synchronous `genai` invoke —
+ `POST https://ai.api.nvidia.com/v1/genai/black-forest-labs/flux.1-schnell`, body
+ `{prompt, mode:"base", cfg_scale:3.5, width, height, seed:0, steps:4}`, response
+ `{artifacts:[{base64,…}]}` (no 202/poll — returns inline). Reused the R2 persist path
+ (refactored `persistDataUriImage` to share a new `persistPngBase64` helper the NIM lane
+ also calls). Per-attempt 60s AbortController timeout so a hung free lane hands off
+ instead of stalling; 429 surfaced as `rate_limited`. Aspect ratio → FLUX pixel dims map.
+ Fallthrough wired so NIM→Vertex→Replicate degrades on any failure, and the last
+ configured lane's error surfaces only when nothing is left. Extended
+ `tests/api/text-to-image.test.js` with 5 NIM cases (serves-and-skips-others, aspect
+ mapping, NIM→Vertex, full NIM→Vertex→Replicate, NIM-only error surface) — **9/9 green**.
+ BLOCKED on live verification: no `NVIDIA_API_KEY` in this Codespace (no `.env`; T0.1 not
+ done) and `probes/flux.md` (T0.3) was never committed, so the documented recipe is
+ unverified against the live endpoint. Once a key lands, run a real generation and a
+ force-fail-NIM degrade check, then flip T1.3 to `[x]`.
- **2026-06-11** — Plan split into one self-contained prompt file per task
(00–42, linked in the checklist); paste a whole task file to a fresh agent to run it.
- **2026-06-11** — Plan created. Context: chat-side free-first failover (Groq → OpenRouter
diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.js
index c4c6f7e4a..49e171caf 100644
--- a/tests/api/text-to-image.test.js
+++ b/tests/api/text-to-image.test.js
@@ -28,7 +28,7 @@ vi.mock('../../api/_lib/r2.js', () => ({
}));
const ORIGINAL_FETCH = globalThis.fetch;
-const ENV_KEYS = ['GOOGLE_CLOUD_PROJECT', 'GCP_SERVICE_ACCOUNT_JSON', 'REPLICATE_API_TOKEN'];
+const ENV_KEYS = ['NVIDIA_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GCP_SERVICE_ACCOUNT_JSON', 'REPLICATE_API_TOKEN'];
const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
async function freshTextToImage() {
@@ -36,18 +36,40 @@ async function freshTextToImage() {
return mod.textToImage;
}
-function stubFluxSuccess() {
+// Route a mocked fetch by host so a single test can exercise the full fallback
+// chain (NIM → Vertex → Replicate) and assert which lanes were actually hit.
+// Each route is [substringMatch, () => Response]; the first match wins.
+function stubFetch(routes) {
const calls = [];
globalThis.fetch = vi.fn(async (url, opts = {}) => {
- calls.push({ url: String(url), body: opts.body ? JSON.parse(opts.body) : null });
- return new Response(
- JSON.stringify({ id: 'pred_flux', status: 'succeeded', output: ['https://replicate.delivery/out.png'] }),
- { status: 201, headers: { 'content-type': 'application/json' } },
- );
+ const u = String(url);
+ calls.push({ url: u, body: opts.body ? JSON.parse(opts.body) : null });
+ for (const [match, responder] of routes) {
+ if (u.includes(match)) return responder();
+ }
+ throw new Error(`unexpected fetch in test: ${u}`);
});
return calls;
}
+function nimSuccessResponse(b64 = Buffer.from('nim-png-bytes').toString('base64')) {
+ return new Response(JSON.stringify({ artifacts: [{ base64: b64, finishReason: 'SUCCESS' }] }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+
+function replicateSuccessResponse(url = 'https://replicate.delivery/out.png') {
+ return new Response(JSON.stringify({ id: 'pred_flux', status: 'succeeded', output: [url] }), {
+ status: 201,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+
+function stubFluxSuccess() {
+ return stubFetch([['api.replicate.com', () => replicateSuccessResponse()]]);
+}
+
beforeEach(() => {
vertexState.configured = false;
vertexState.generate = null;
@@ -64,6 +86,91 @@ afterEach(() => {
vi.restoreAllMocks();
});
+describe('textToImage — NIM FLUX free lane (first)', () => {
+ it('serves from NIM and never touches Vertex or Replicate', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ vertexState.configured = true;
+ vertexState.generate = vi.fn(async () => ({ imageUrl: 'data:image/png;base64,AAAA' }));
+ const calls = stubFetch([['ai.api.nvidia.com', () => nimSuccessResponse()]]);
+
+ const textToImage = await freshTextToImage();
+ const result = await textToImage('a red teapot');
+
+ expect(result.model).toBe('black-forest-labs/flux.1-schnell');
+ expect(result.imageUrl).toMatch(/^https:\/\/cdn\.example\/forge\/refs\/.+\.png$/);
+ // NIM artifact persisted to R2; Vertex and Replicate left untouched.
+ expect(r2State.puts).toHaveLength(1);
+ expect(vertexState.generate).not.toHaveBeenCalled();
+ expect(calls).toHaveLength(1);
+ expect(calls[0].url).toContain('flux.1-schnell');
+ expect(calls[0].body).toMatchObject({ prompt: 'a red teapot', steps: 4 });
+ });
+
+ it('maps aspect ratio to FLUX pixel dimensions', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ const calls = stubFetch([['ai.api.nvidia.com', () => nimSuccessResponse()]]);
+
+ const textToImage = await freshTextToImage();
+ await textToImage('a wide vista', { aspectRatio: '16:9' });
+
+ expect(calls[0].body).toMatchObject({ width: 1344, height: 768 });
+ });
+
+ it('falls through to Vertex when NIM fails', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';
+ vertexState.configured = true;
+ const png = Buffer.from('vertex-png').toString('base64');
+ vertexState.generate = vi.fn(async () => ({
+ imageUrl: `data:image/png;base64,${png}`,
+ model: 'vertex-ai/imagen-3.0-generate-001',
+ }));
+ const calls = stubFetch([['ai.api.nvidia.com', () => new Response('upstream boom', { status: 500 })]]);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const textToImage = await freshTextToImage();
+ const result = await textToImage('a red teapot');
+
+ expect(result.model).toBe('vertex-ai/imagen-3.0-generate-001');
+ expect(vertexState.generate).toHaveBeenCalledOnce();
+ expect(calls).toHaveLength(1); // NIM was attempted exactly once before handoff
+ expect(Buffer.compare(r2State.puts[0].body, Buffer.from('vertex-png'))).toBe(0);
+ });
+
+ it('falls all the way through NIM → Vertex → Replicate', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ vertexState.configured = true;
+ vertexState.generate = vi.fn(async () => {
+ throw Object.assign(new Error('vertex down'), { code: 'unconfigured' });
+ });
+ const calls = stubFetch([
+ ['ai.api.nvidia.com', () => new Response('boom', { status: 503 })],
+ ['api.replicate.com', () => replicateSuccessResponse()],
+ ]);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const textToImage = await freshTextToImage();
+ const result = await textToImage('a red teapot');
+
+ expect(result.imageUrl).toBe('https://replicate.delivery/out.png');
+ expect(vertexState.generate).toHaveBeenCalledOnce();
+ expect(calls.some((c) => c.url.includes('ai.api.nvidia.com'))).toBe(true);
+ expect(calls.some((c) => c.url.includes('api.replicate.com'))).toBe(true);
+ });
+
+ it('surfaces the NIM error when it is the only configured lane', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ stubFetch([['ai.api.nvidia.com', () => new Response('nope', { status: 401 })]]);
+
+ const textToImage = await freshTextToImage();
+ await expect(textToImage('a red teapot')).rejects.toThrow(/nim flux returned 401/);
+ });
+});
+
describe('textToImage — Vertex → Replicate fallback', () => {
it('falls back to Replicate flux when the Vertex path throws', async () => {
process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';