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.

fix(inference): read array-form message content from a Livepeer orchestrator

nirholas5b4db4540f8f
diff --git a/api/README.md b/api/README.md
index c3fab4d93..b07253e81 100644
--- a/api/README.md
+++ b/api/README.md
@@ -32,7 +32,7 @@ The `_`-prefixed folders are imported by the endpoints; they are not routes:
### AI, chat, and inference
- `chat.js` (Edge SSE, multi-provider routing across Groq / OpenRouter / OpenAI / Anthropic), `chat/`, `brain/chat.js`, `llm/anthropic.js`, `chat-skills.js`.
-- `inference/livepeer.js` — side-by-side Claude vs Livepeer LLM comparison.
+- `inference/livepeer.js`: side-by-side LLM comparison, the three.ws provider chain against a Livepeer AI gateway, each leg reporting its own latency, tokens, and error.
- `tts/` — text-to-speech (`speak`, `edge`, `eleven`, `eleven-clone`).
- `persona/`, `seed/` — persona extraction/preview and seed synthesis from X / GitHub / Farcaster.
- `mcp.js` — MCP server over Streamable HTTP (MCP 2025-06-18, JSON-RPC 2.0): `POST` tool calls, `GET` SSE, `DELETE` terminate. `pump-fun-mcp.js` — the pump.fun MCP surface.
diff --git a/api/inference/livepeer.js b/api/inference/livepeer.js
index 59801dff5..948695ae7 100644
--- a/api/inference/livepeer.js
+++ b/api/inference/livepeer.js
@@ -88,6 +88,24 @@ function clampTemp(n, fallback = 0.7) {
return Math.min(Math.max(v, 0), 2);
}
+// Reply text out of an OpenAI-compatible `message.content`.
+//
+// Orchestrators on the network run different inference servers, and the
+// OpenAI chat schema allows content to be either a plain string or an array
+// of typed parts. Treating the array case as a string turned a perfectly
+// valid gateway answer into a TypeError inside the leg, which surfaced as a
+// bare `leg_failed` with a JS message in the demo card. Normalize both here,
+// at the boundary, so everything downstream holds a string.
+function replyText(content) {
+ if (typeof content === 'string') return content;
+ if (Array.isArray(content)) {
+ return content
+ .map((part) => (typeof part === 'string' ? part : typeof part?.text === 'string' ? part.text : ''))
+ .join('');
+ }
+ return '';
+}
+
// Platform LLM leg.
//
// The non-Livepeer side of the comparison runs on the platform's funded free
@@ -235,7 +253,7 @@ async function callLivepeer({ prompt, model, max_tokens, temperature }) {
if (Array.isArray(data.choices) && data.choices.length) {
const first = data.choices[0];
- reply = first?.message?.content || first?.text || '';
+ reply = replyText(first?.message?.content) || replyText(first?.text);
prompt_tokens = data?.usage?.prompt_tokens ?? null;
completion_tokens = data?.usage?.completion_tokens ?? null;
} else if (typeof data.response === 'string') {
diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.js
index 072fc90b1..08e3bf048 100644
--- a/tests/api/text-to-image.test.js
+++ b/tests/api/text-to-image.test.js
@@ -383,6 +383,33 @@ function livepeerSuccessResponse(url = 'https://gateway.test/images/out.png') {
});
}
+// A Livepeer job is TWO fetches against the same gateway host: POST
+// /text-to-image returns the job JSON, then the artifact URL it names is
+// downloaded and magic-byte verified before the lane is allowed to succeed.
+// Route the artifact path FIRST (stubFetch is first-match-wins on a substring)
+// so the download gets real PNG bytes instead of the job JSON, which the
+// provider correctly rejects as "no image signature".
+// A real PNG signature padded past the provider's 1 KB size floor, the same
+// fixture shape tests/livepeer-federation.test.js uses.
+const LIVEPEER_PNG_BYTES = Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ Buffer.alloc(2048, 1),
+]);
+
+function livepeerRoutes() {
+ return [
+ [
+ 'gateway.test/images/',
+ () =>
+ new Response(LIVEPEER_PNG_BYTES, {
+ status: 200,
+ headers: { 'content-type': 'image/png' },
+ }),
+ ],
+ ['gateway.test', () => livepeerSuccessResponse()],
+ ];
+}
+
describe('textToImage: Livepeer federation lane counts as a real fallback', () => {
beforeEach(() => {
process.env.LIVEPEER_FEDERATION_ENABLED = '1';
@@ -394,14 +421,17 @@ describe('textToImage: Livepeer federation lane counts as a real fallback', () =
process.env.NVIDIA_API_KEY = 'nvapi-test';
const calls = stubFetch([
['ai.api.nvidia.com', () => new Response('boom', { status: 500 })],
- ['gateway.test', () => livepeerSuccessResponse()],
+ ...livepeerRoutes(),
]);
const textToImage = await freshTextToImage();
const result = await textToImage('a red teapot');
- expect(result.imageUrl).toBe('https://gateway.test/images/out.png');
- expect(calls.some((c) => c.url.includes('gateway.test'))).toBe(true);
+ // The verified artifact is persisted to our own storage, so the lane
+ // returns the durable CDN URL, never the gateway's ephemeral one.
+ expect(result.imageUrl).toMatch(/^https:\/\/cdn\.example\/forge\/refs\/.+\.png$/);
+ expect(result.lane).toBe('livepeer');
+ expect(calls.some((c) => c.url.includes('gateway.test/images/'))).toBe(true);
});
it('hands a failed Vertex lead off to Livepeer when it is the only lane downstream', async () => {
@@ -410,13 +440,14 @@ describe('textToImage: Livepeer federation lane counts as a real fallback', () =
vertexState.generate = async () => {
throw new Error('vertex exploded');
};
- const calls = stubFetch([['gateway.test', () => livepeerSuccessResponse()]]);
+ const calls = stubFetch(livepeerRoutes());
const textToImage = await freshTextToImage();
const result = await textToImage('a red teapot');
- expect(result.imageUrl).toBe('https://gateway.test/images/out.png');
- expect(calls.some((c) => c.url.includes('gateway.test'))).toBe(true);
+ expect(result.imageUrl).toMatch(/^https:\/\/cdn\.example\/forge\/refs\/.+\.png$/);
+ expect(result.lane).toBe('livepeer');
+ expect(calls.some((c) => c.url.includes('gateway.test/images/'))).toBe(true);
});
it('still surfaces the upstream error when Livepeer federation is off', async () => {
diff --git a/tests/inference-livepeer.test.js b/tests/inference-livepeer.test.js
index 966f9c183..abffee1e3 100644
--- a/tests/inference-livepeer.test.js
+++ b/tests/inference-livepeer.test.js
@@ -246,6 +246,47 @@ describe('POST /api/inference/livepeer Livepeer leg', () => {
expect(json.livepeer.completion_tokens).toBe(30);
});
+ it('parses OpenAI content parts, which some orchestrators return instead of a string', async () => {
+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.internal';
+ fetchMock.mockResolvedValue(
+ gatewayResponse(200, {
+ choices: [
+ {
+ message: {
+ role: 'assistant',
+ content: [{ type: 'text', text: 'part one ' }, { type: 'text', text: 'part two' }],
+ },
+ },
+ ],
+ usage: { prompt_tokens: 9, completion_tokens: 4 },
+ }),
+ );
+
+ const { json } = await call(mkReq({ body: { prompt: 'hi' } }));
+
+ // Before this was normalized the array reached String.prototype.trim and
+ // threw, collapsing a good answer into a bare leg_failed.
+ expect(json.livepeer).toMatchObject({
+ ok: true,
+ reply: 'part one part two',
+ prompt_tokens: 9,
+ completion_tokens: 4,
+ });
+ expect(json.livepeer.error).toBeUndefined();
+ });
+
+ it('treats an unusable content shape as empty_response, never a thrown leg', async () => {
+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.internal';
+ fetchMock.mockResolvedValue(gatewayResponse(200, { choices: [{ message: { content: { unexpected: true } } }] }));
+
+ const { res, json } = await call(mkReq({ body: { prompt: 'hi' } }));
+
+ expect(res.statusCode).toBe(200);
+ expect(json.livepeer).toMatchObject({ ok: false, error: 'empty_response' });
+ expect(json.livepeer.gateway).toBe('override');
+ expect(json.platform.ok).toBe(true);
+ });
+
it('codes a non-2xx gateway as upstream_error and keeps the request 200', async () => {
process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.internal';
fetchMock.mockResolvedValue(gatewayResponse(503, 'no orchestrators available'));