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): photoreal-by-default reference images, Vertex quality lane leads

nirholas87bd0fb4dbd4
diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.js
index 23297d7cc..2ad89b340 100644
--- a/api/_mcp3d/text-to-image.js
+++ b/api/_mcp3d/text-to-image.js
@@ -299,10 +299,35 @@ const COMPOSITION_CUE_WORDS = [
const COMPOSITION_CUE_RE = new RegExp(`\\b(?:${COMPOSITION_CUE_WORDS.join('|')})\\b`, 'i');
const FLUX_STYLE_SUFFIX = ', isolated subject, bright studio lighting, plain white background';
+// Deliberate art-style words — when the caller names a rendering style
+// (cartoon, voxel, watercolor…) the realism cues below must NOT fight it. This
+// list is only ever consulted to SKIP adding realism words; it never suppresses
+// the isolation suffix (see the regression note above — a cartoon fox still
+// needs a plain background to reconstruct cleanly).
+const ART_STYLE_WORDS = [
+ 'cartoon', 'anime', 'manga', 'toon', 'chibi', 'stylized', 'low[- ]poly', 'voxel',
+ 'pixel[- ]art', '8[- ]bit', '16[- ]bit', 'claymation', 'plasticine', 'illustration',
+ 'illustrated', 'painting', 'painterly', 'watercolor', 'sketch', 'hand[- ]drawn',
+ 'comic', 'cel[- ]shaded', 'origami', 'papercraft', 'plush', 'crochet', 'knitted',
+ 'lego', 'minecraft', 'abstract',
+];
+const ART_STYLE_RE = new RegExp(`\\b(?:${ART_STYLE_WORDS.join('|')})\\b`, 'i');
+
+// Realism cues, added by default: the reference image is the sole source of the
+// 3D model's texture and proportions, so photographic language here is what
+// makes the final mesh read as a real object/person rather than a render.
+// Skipped when the caller named an art style (respect the ask) — and the whole
+// suffix pipeline stays untouched when the prompt already carries composition
+// cues, exactly as before.
+const REALISM_SUFFIX =
+ ', photorealistic, true-to-life materials and surface detail, sharp focus, professional product photograph';
+
export function enhanceFluxPrompt(raw) {
const text = String(raw || '').trim();
if (!text) return text;
- return COMPOSITION_CUE_RE.test(text) ? text : text + FLUX_STYLE_SUFFIX;
+ if (COMPOSITION_CUE_RE.test(text)) return text;
+ const realism = ART_STYLE_RE.test(text) ? '' : REALISM_SUFFIX;
+ return text + realism + FLUX_STYLE_SUFFIX;
}
// Generate a single image from a text prompt.
@@ -319,7 +344,39 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false
const hasSeed = Number.isInteger(seed) && seed >= 0;
const token = readEnv('REPLICATE_API_TOKEN');
const hasVertex = !!readEnv('GOOGLE_CLOUD_PROJECT') && vertexImagenEnabled();
- const hasFallback = hasVertex || !!token;
+ // Quality-first ordering: the Vertex Gemini image model outdraws 4-step
+ // distilled FLUX for photoreal reference images, and it burns the GCP credit
+ // pool the platform is funded to spend — so when the lane is configured it
+ // leads by default. The reference image is the sole source of the 3D model's
+ // texture and proportions; this is the cheapest quality lever in the chain.
+ // VERTEX_IMAGEN_FIRST=0 restores the legacy NIM-first order without touching
+ // the lane's on/off gate (VERTEX_IMAGEN_ENABLED).
+ const vertexFirst = hasVertex && readEnv('VERTEX_IMAGEN_FIRST') !== '0';
+ // What remains DOWNSTREAM of the NIM lane. When Vertex leads it has already
+ // been consumed by the time NIM runs, so it no longer counts as a fallback —
+ // otherwise a NIM failure after a Vertex failure would "fall through" to a
+ // lane that was already tried and surface the wrong terminal error.
+ const hasFallback = (!vertexFirst && hasVertex) || !!token;
+
+ // One attempt at the Vertex lane, shared by both ladder positions. Returns
+ // null to mean "hand off to the next lane" (unconfigured, or a failure with a
+ // lane left to try); throws only when nothing remains downstream.
+ const tryVertex = async (laneRemains) => {
+ try {
+ const { generateImage, isConfigured } = await import('./vertex-imagen.js');
+ if (!isConfigured()) return null;
+ return logImageProvider(await persistDataUriImage(await generateImage(prompt, { aspectRatio })));
+ } catch (err) {
+ if (!laneRemains) throw err;
+ console.warn(`vertex imagen failed, falling back: ${err?.message}`);
+ return null;
+ }
+ };
+
+ if (vertexFirst) {
+ const served = await tryVertex(!!readEnv('NVIDIA_API_KEY') || !!token);
+ if (served) return served;
+ }
// ── NVIDIA NIM FLUX (free, first) ─────────────────────────────────────────
// Skip the NIM lane when a fallback exists AND either the caller just watched a
@@ -348,17 +405,10 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false
}
}
- // ── Vertex AI Imagen path ────────────────────────────────────────────────
- if (hasVertex) {
- try {
- const { generateImage, isConfigured } = await import('./vertex-imagen.js');
- if (isConfigured()) {
- return logImageProvider(await persistDataUriImage(await generateImage(prompt, { aspectRatio })));
- }
- } catch (err) {
- if (!token) throw err;
- console.error(`vertex imagen failed, falling back to replicate: ${err?.message}`);
- }
+ // ── Vertex AI Imagen path (legacy position — only when not already led) ──
+ if (hasVertex && !vertexFirst) {
+ const served = await tryVertex(!!token);
+ if (served) return served;
}
// ── Replicate fallback ───────────────────────────────────────────────────
diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.js
index e7100f724..ef86b1787 100644
--- a/tests/api/text-to-image.test.js
+++ b/tests/api/text-to-image.test.js
@@ -39,7 +39,14 @@ vi.mock('../../api/_lib/forge-scale.js', async (importOriginal) => {
});
const ORIGINAL_FETCH = globalThis.fetch;
-const ENV_KEYS = ['NVIDIA_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GCP_SERVICE_ACCOUNT_JSON', 'REPLICATE_API_TOKEN', 'VERTEX_IMAGEN_ENABLED'];
+const ENV_KEYS = [
+ 'NVIDIA_API_KEY',
+ 'GOOGLE_CLOUD_PROJECT',
+ 'GCP_SERVICE_ACCOUNT_JSON',
+ 'REPLICATE_API_TOKEN',
+ 'VERTEX_IMAGEN_ENABLED',
+ 'VERTEX_IMAGEN_FIRST',
+];
const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
async function freshTextToImage() {
@@ -106,7 +113,68 @@ afterEach(() => {
vi.restoreAllMocks();
});
-describe('textToImage — NIM FLUX free lane (first)', () => {
+describe('textToImage — Vertex quality lane leads by default', () => {
+ it('serves from Vertex before NIM when both are configured (credit-burner first)', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';
+ vertexState.configured = true;
+ const png = Buffer.from('vertex-first-png').toString('base64');
+ vertexState.generate = vi.fn(async () => ({
+ imageUrl: `data:image/png;base64,${png}`,
+ model: 'vertex-ai/gemini-2.5-flash-image',
+ }));
+ const calls = stubFetch([['ai.api.nvidia.com', () => nimSuccessResponse()]]);
+
+ const textToImage = await freshTextToImage();
+ const result = await textToImage('a red teapot');
+
+ expect(result.model).toBe('vertex-ai/gemini-2.5-flash-image');
+ expect(vertexState.generate).toHaveBeenCalledOnce();
+ expect(calls).toHaveLength(0); // NIM never touched — Vertex led and served
+ });
+
+ it('falls from a failed Vertex lead to NIM without surfacing an error', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';
+ vertexState.configured = true;
+ vertexState.generate = vi.fn(async () => {
+ throw new Error('vertex down');
+ });
+ const calls = stubFetch([['ai.api.nvidia.com', () => nimSuccessResponse()]]);
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const textToImage = await freshTextToImage();
+ const result = await textToImage('a red teapot');
+
+ expect(result.model).toBe('black-forest-labs/flux.1-schnell');
+ expect(vertexState.generate).toHaveBeenCalledOnce();
+ expect(calls).toHaveLength(1);
+ });
+
+ it('VERTEX_IMAGEN_FIRST=0 restores the legacy NIM-first order', async () => {
+ process.env.VERTEX_IMAGEN_FIRST = '0';
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';
+ 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(vertexState.generate).not.toHaveBeenCalled();
+ expect(calls).toHaveLength(1);
+ });
+});
+
+describe('textToImage — NIM FLUX free lane (legacy NIM-first order)', () => {
+ beforeEach(() => {
+ // These pin the legacy ladder (NIM → Vertex → Replicate), preserved
+ // behind VERTEX_IMAGEN_FIRST=0.
+ process.env.VERTEX_IMAGEN_FIRST = '0';
+ });
+
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';
@@ -648,28 +716,33 @@ describe('textToImage — VERTEX_IMAGEN_ENABLED gate', () => {
});
});
-describe('enhanceFluxPrompt — 3D-reference isolation suffix', () => {
- const SUFFIX = ', isolated subject, bright studio lighting, plain white background';
+describe('enhanceFluxPrompt — realism + 3D-reference isolation suffixes', () => {
+ const ISOLATION = ', isolated subject, bright studio lighting, plain white background';
+ const REALISM =
+ ', photorealistic, true-to-life materials and surface detail, sharp focus, professional product photograph';
async function enhance() {
const mod = await import('../../api/_mcp3d/text-to-image.js?t=' + Math.random());
return mod.enhanceFluxPrompt;
}
- it('appends the isolation suffix to a plain subject prompt', async () => {
+ it('appends realism + isolation to a plain subject prompt (photoreal by default)', async () => {
const enhanceFluxPrompt = await enhance();
- expect(enhanceFluxPrompt('a red teapot')).toBe('a red teapot' + SUFFIX);
+ expect(enhanceFluxPrompt('a red teapot')).toBe('a red teapot' + REALISM + ISOLATION);
});
- it('still isolates a stylized subject — style words must not suppress the suffix', async () => {
- // Regression: "cartoon"/"stylized" are art-style words, not composition cues.
- // Gating the suffix on them let the Gemini lane render a full illustrated
- // scene (background clutter the 3D backend cannot reconstruct).
+ it('respects a named art style — isolation stays, realism words are withheld', async () => {
+ // Regression (older): "cartoon"/"stylized" must never suppress isolation —
+ // a cartoon fox still needs a plain background to reconstruct cleanly.
+ // New contract: those same words DO suppress the realism cues, which would
+ // otherwise fight the caller's explicit style.
const enhanceFluxPrompt = await enhance();
expect(enhanceFluxPrompt('a cartoon fox character standing upright')).toBe(
- 'a cartoon fox character standing upright' + SUFFIX,
+ 'a cartoon fox character standing upright' + ISOLATION,
);
- expect(enhanceFluxPrompt('a stylized vibrant robot')).toBe('a stylized vibrant robot' + SUFFIX);
+ expect(enhanceFluxPrompt('a stylized vibrant robot')).toBe('a stylized vibrant robot' + ISOLATION);
+ expect(enhanceFluxPrompt('a low-poly wolf')).toBe('a low-poly wolf' + ISOLATION);
+ expect(enhanceFluxPrompt('a watercolor bird')).toBe('a watercolor bird' + ISOLATION);
});
it('leaves the prompt untouched when it already sets a background / composition cue', async () => {
@@ -683,9 +756,14 @@ describe('enhanceFluxPrompt — 3D-reference isolation suffix', () => {
}
});
- it('matches whole words only — a substring like "light" in "lightsaber" does not suppress', async () => {
+ it('matches whole words only — substrings never trigger or suppress', async () => {
const enhanceFluxPrompt = await enhance();
- expect(enhanceFluxPrompt('a glowing lightsaber')).toBe('a glowing lightsaber' + SUFFIX);
+ // "light" inside "lightsaber" is not a composition cue…
+ expect(enhanceFluxPrompt('a glowing lightsaber')).toBe('a glowing lightsaber' + REALISM + ISOLATION);
+ // …and "cartoonish" IS a style signal via the word boundary on "cartoon"?
+ // No: \b matches inside "cartoonish" only at the start — the suffix "ish"
+ // keeps the word alive, so assert the boundary behaves as written.
+ expect(enhanceFluxPrompt('a legolas figure')).toBe('a legolas figure' + REALISM + ISOLATION);
});
it('returns an empty prompt unchanged', async () => {