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: watsonx integration for brain/chat + agent wiring

nirholas4a954f858c17
diff --git a/.env.example b/.env.example
index 6c3e555b9..ef048797c 100644
--- a/.env.example
+++ b/.env.example
@@ -76,6 +76,19 @@ DASHSCOPE_API_KEY=
# Get a token at https://modelscope.cn
MODELSCOPE_API_KEY=
+# IBM watsonx.ai — adds IBM Granite as a selectable brain in /api/chat (the 3D
+# avatar) and /api/brain/chat (the model playground). The key is exchanged for
+# a short-lived IAM bearer token and every call is scoped to your project, so
+# both WATSONX_API_KEY and WATSONX_PROJECT_ID (or WATSONX_SPACE_ID) are required
+# for Granite to appear. Create an API key at https://cloud.ibm.com/iam/apikeys
+# and find the project id under watsonx.ai → project → Manage → General.
+WATSONX_API_KEY=
+WATSONX_PROJECT_ID=
+# WATSONX_SPACE_ID= # alternative to WATSONX_PROJECT_ID
+# WATSONX_URL=https://us-south.ml.cloud.ibm.com # regional host (eu-de, jp-tok, …)
+# WATSONX_MODEL_ID=ibm/granite-3-8b-instruct # default Granite chat model
+# WATSONX_API_VERSION=2024-05-31
+
# Privy wallet auth (client-side — get app ID from https://dashboard.privy.io)
VITE_PRIVY_APP_ID=
# Privy app ID (server-side — for verifying identity tokens in /api/auth/privy/verify)
diff --git a/api/_lib/env.js b/api/_lib/env.js
index ac45f1227..8a8f585d1 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -89,6 +89,30 @@ export const env = {
return opt('GROQ_API_KEY');
},
+ // IBM watsonx.ai (Granite foundation models) — selectable brain in
+ // /api/chat and /api/brain/chat. Requires the API key AND a project (or
+ // space) id; the shared client in _lib/watsonx.js exchanges the key for an
+ // IAM bearer token and scopes every call. Optional — when unset, Granite is
+ // reported as unavailable and other providers are used.
+ get WATSONX_API_KEY() {
+ return opt('WATSONX_API_KEY');
+ },
+ get WATSONX_PROJECT_ID() {
+ return opt('WATSONX_PROJECT_ID');
+ },
+ get WATSONX_SPACE_ID() {
+ return opt('WATSONX_SPACE_ID');
+ },
+ get WATSONX_URL() {
+ return opt('WATSONX_URL');
+ },
+ get WATSONX_MODEL_ID() {
+ return opt('WATSONX_MODEL_ID');
+ },
+ get WATSONX_API_VERSION() {
+ return opt('WATSONX_API_VERSION');
+ },
+
// Etherscan V2 — unified multichain explorer API (one key, all chains).
// Used by api/cron/erc8004-crawl.js to index ERC-8004 Registered events.
get ETHERSCAN_API_KEY() {
diff --git a/api/_lib/orchestrate.js b/api/_lib/orchestrate.js
new file mode 100644
index 000000000..b9a5993e6
--- /dev/null
+++ b/api/_lib/orchestrate.js
@@ -0,0 +1,35 @@
+// IBM watsonx Orchestrate (Agent Connect) configuration for the chat proxy.
+//
+// A watsonx Orchestrate agent — built in the Agent Builder / ADK — exposes an
+// OpenAI-compatible chat-completions endpoint (the service instance "Test URL"
+// with /chat/completions appended) secured by a bearer token. Because the wire
+// format is OpenAI-shaped (messages in, choices[].delta.content SSE out), the
+// proxy treats Orchestrate as an OpenAI-style provider: this module only
+// resolves the endpoint URL, bearer token, and agent id from the environment.
+//
+// No mock path. When the URL or key is absent, configured() is false and the
+// proxy reports the provider unavailable; auth/upstream failures surface as the
+// real error from the stream loop.
+
+// Accept either the bare service-instance URL or a full chat-completions URL,
+// and normalise to the endpoint that actually serves completions.
+function chatCompletionsUrl(raw) {
+ const base = raw.replace(/\/+$/, '');
+ if (/\/chat\/completions$/.test(base)) return base;
+ if (/\/v1$/.test(base)) return `${base}/chat/completions`;
+ return `${base}/chat/completions`;
+}
+
+export function orchestrateConfig(env = process.env) {
+ const apiKey = env.WATSONX_ORCHESTRATE_API_KEY?.trim();
+ const url = env.WATSONX_ORCHESTRATE_URL?.trim();
+ return {
+ configured: Boolean(apiKey && url),
+ apiKey,
+ // Full chat-completions endpoint for the configured agent.
+ chatUrl: url ? chatCompletionsUrl(url) : null,
+ // Orchestrate uses the OpenAI `model` field to name the target agent;
+ // when unset many deployments ignore it, so a stable placeholder is fine.
+ agent: env.WATSONX_ORCHESTRATE_AGENT?.trim() || 'orchestrate-agent',
+ };
+}
diff --git a/api/_lib/watsonx.js b/api/_lib/watsonx.js
new file mode 100644
index 000000000..9e2738459
--- /dev/null
+++ b/api/_lib/watsonx.js
@@ -0,0 +1,115 @@
+// Shared server-side IBM watsonx.ai client for the LLM proxies.
+//
+// Mirrors the verified REST contract used by packages/ibm-watsonx-mcp:
+// an IBM Cloud API key is exchanged for a short-lived IAM bearer token (cached
+// across warm invocations), every inference call is scoped to a project (or
+// deployment space), and the endpoint is version-stamped. The streaming chat
+// endpoint returns an OpenAI-shaped SSE stream (choices[].delta.content), so
+// callers can reuse an OpenAI delta reader verbatim.
+//
+// There is no mock path. When credentials are absent watsonxConfig() reports
+// `configured: false` so a proxy can mark the provider unavailable; any IAM or
+// upstream failure throws so the proxy reports the real cause to the caller.
+
+const IAM_TOKEN_URL = 'https://iam.cloud.ibm.com/identity/token';
+
+// Refresh the IAM token this many ms before its stated expiry so an in-flight
+// request never races the hard expiry boundary.
+const TOKEN_SKEW_MS = 5 * 60 * 1000;
+
+// Module-scoped token cache. Vercel keeps a function instance warm across
+// invocations, so caching the ~1h IAM token here saves a token round-trip on
+// every chat request. Keyed by API key so multiple keys never cross-pollute.
+const tokenCache = new Map(); // apiKey → { token, expiresAt }
+const inflight = new Map(); // apiKey → Promise<string>
+
+// Read and normalise watsonx configuration from the environment. `configured`
+// is true only when an API key AND a project (or space) are both present —
+// watsonx requires scoping on every inference request, so a key alone is not
+// enough to serve a model.
+export function watsonxConfig(env = process.env) {
+ const apiKey = env.WATSONX_API_KEY?.trim();
+ const projectId = env.WATSONX_PROJECT_ID?.trim();
+ const spaceId = env.WATSONX_SPACE_ID?.trim();
+ return {
+ configured: Boolean(apiKey && (projectId || spaceId)),
+ apiKey,
+ projectId,
+ spaceId,
+ // us-south is the default deployment region; override per region host.
+ url: (env.WATSONX_URL?.trim() || 'https://us-south.ml.cloud.ibm.com').replace(/\/$/, ''),
+ iamUrl: env.WATSONX_IAM_URL?.trim() || IAM_TOKEN_URL,
+ apiVersion: env.WATSONX_API_VERSION?.trim() || '2024-05-31',
+ chatModel: env.WATSONX_MODEL_ID?.trim() || 'ibm/granite-3-8b-instruct',
+ };
+}
+
+// Mint (or reuse) an IAM bearer token for the given config. Concurrent callers
+// coalesce onto a single in-flight IAM round-trip per API key.
+export async function watsonxToken(cfg) {
+ if (!cfg.apiKey) throw new Error('WATSONX_API_KEY is not set');
+ const now = Date.now();
+ const cached = tokenCache.get(cfg.apiKey);
+ if (cached && cached.expiresAt - TOKEN_SKEW_MS > now) return cached.token;
+ if (inflight.has(cfg.apiKey)) return inflight.get(cfg.apiKey);
+
+ const p = (async () => {
+ const res = await fetch(cfg.iamUrl, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/x-www-form-urlencoded',
+ accept: 'application/json',
+ },
+ body: new URLSearchParams({
+ grant_type: 'urn:ibm:params:oauth:grant-type:apikey',
+ apikey: cfg.apiKey,
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok || !data.access_token) {
+ throw new Error(
+ `watsonx IAM auth failed (${res.status}): ${data.errorMessage || data.errorCode || 'no access_token'}`,
+ );
+ }
+ tokenCache.set(cfg.apiKey, {
+ token: data.access_token,
+ expiresAt: now + (Number(data.expires_in) || 3600) * 1000,
+ });
+ return data.access_token;
+ })();
+
+ inflight.set(cfg.apiKey, p);
+ try {
+ return await p;
+ } finally {
+ inflight.delete(cfg.apiKey);
+ }
+}
+
+// Authorization headers for a streaming chat request. Separated from the body
+// so callers that build their own payload (api/chat.js) can resolve headers
+// lazily inside their own fetch/failover loop.
+export async function watsonxAuthHeaders(cfg) {
+ return {
+ Authorization: `Bearer ${await watsonxToken(cfg)}`,
+ 'Content-Type': 'application/json',
+ Accept: 'text/event-stream',
+ };
+}
+
+// Build a ready-to-fetch streaming chat request. `messages` is the standard
+// [{ role, content }] array (system messages allowed). The response body is an
+// SSE stream of OpenAI-shaped chat completion chunks.
+export async function watsonxChatRequest(cfg, { model, messages, maxTokens } = {}) {
+ const headers = await watsonxAuthHeaders(cfg);
+ return {
+ url: `${cfg.url}/ml/v1/text/chat_stream?version=${cfg.apiVersion}`,
+ headers,
+ body: {
+ model_id: model || cfg.chatModel,
+ ...(cfg.projectId ? { project_id: cfg.projectId } : { space_id: cfg.spaceId }),
+ messages,
+ ...(maxTokens ? { max_tokens: maxTokens } : {}),
+ },
+ };
+}
diff --git a/api/brain/chat.js b/api/brain/chat.js
index 70ce4e540..9772eb444 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -16,6 +16,7 @@ import { createOpenAI } from '@ai-sdk/openai';
import { createQwen } from 'qwen-ai-provider';
import { env } from '../_lib/env.js';
import { cors, method, readJson, error, wrap } from '../_lib/http.js';
+import { watsonxConfig, watsonxChatRequest } from '../_lib/watsonx.js';
export const maxDuration = 120;
@@ -155,6 +156,19 @@ const PROVIDERS = {
return null;
},
},
+ // IBM watsonx.ai Granite. watsonx is not OpenAI-compatible at the API layer
+ // (IAM bearer token, project scoping, version param), so it can't be a
+ // Vercel AI SDK model object. The `watsonx` flag routes it to a dedicated
+ // streaming path; build() only reports availability.
+ 'ibm-granite': {
+ label: 'IBM Granite 3.8B',
+ network: 'IBM watsonx.ai',
+ tier: 'balanced',
+ maxOutput: 4096,
+ description: 'IBM’s open, enterprise-governed foundation model on watsonx.ai.',
+ watsonx: true,
+ build: () => (watsonxConfig().configured ? { watsonx: true } : null),
+ },
};
function openrouter() {
@@ -165,6 +179,73 @@ function openrouter() {
});
}
+// Stream IBM Granite (watsonx.ai) to the page using the same SSE protocol as
+// the AI SDK path. watsonx returns OpenAI-shaped chat completion chunks
+// (choices[].delta.content) plus a usage block on the final chunk.
+async function streamWatsonx(res, { messages, system, maxTokens, t0 }) {
+ const cfg = watsonxConfig();
+ const wxMessages = system ? [{ role: 'system', content: system }, ...messages] : messages;
+ const { url, headers, body } = await watsonxChatRequest(cfg, {
+ messages: wxMessages,
+ maxTokens,
+ });
+
+ const upstream = await fetch(url, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(body),
+ });
+ if (!upstream.ok || !upstream.body) {
+ const detail = await upstream.text().catch(() => '');
+ throw new Error(`watsonx ${upstream.status}: ${detail.slice(0, 200)}`);
+ }
+
+ const reader = upstream.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ let firstTokenMs = null;
+ let usage = null;
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ const lines = buf.split('\n');
+ buf = lines.pop();
+ for (const line of lines) {
+ if (!line.startsWith('data:')) continue;
+ const raw = line.slice(5).trim();
+ if (!raw || raw === '[DONE]') continue;
+ let evt;
+ try {
+ evt = JSON.parse(raw);
+ } catch {
+ continue;
+ }
+ const delta = evt.choices?.[0]?.delta?.content;
+ if (delta) {
+ if (firstTokenMs === null) {
+ firstTokenMs = Date.now() - t0;
+ res.write(`event: first\ndata: ${JSON.stringify({ firstTokenMs })}\n\n`);
+ }
+ res.write(`data: ${JSON.stringify(delta)}\n\n`);
+ }
+ if (evt.usage) {
+ usage = {
+ inputTokens: evt.usage.prompt_tokens,
+ outputTokens: evt.usage.completion_tokens,
+ totalTokens: evt.usage.total_tokens,
+ };
+ }
+ }
+ }
+
+ const elapsedMs = Date.now() - t0;
+ res.write(`event: done\ndata: ${JSON.stringify({ elapsedMs, firstTokenMs, usage })}\n\n`);
+ res.write('data: [DONE]\n\n');
+ res.end();
+}
+
function validateMessages(input) {
if (!Array.isArray(input)) {
throw Object.assign(new Error('messages must be an array'), { status: 400 });
@@ -262,6 +343,13 @@ export default wrap(async function handler(req, res) {
let firstTokenMs = null;
try {
+ // watsonx.ai isn't an AI SDK model — stream it through the shared client,
+ // emitting the same first/chunk/done event protocol the page expects.
+ if (spec.watsonx) {
+ await streamWatsonx(res, { messages, system, maxTokens, t0 });
+ return;
+ }
+
const result = streamText({
model,
system,
diff --git a/api/chat.js b/api/chat.js
index 4475a9b7d..050ccf782 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -9,10 +9,16 @@
// 3. OPENROUTER_API_KEY → OpenRouter free tier.
// 4. OPENAI_API_KEY → OpenAI.
// 5. ANTHROPIC_API_KEY → Anthropic (BYOK only — never set as a server key).
-// Anthropic and the OpenAI-compatible providers (OpenRouter / Groq / OpenAI)
-// use different request shapes, tool-call wire formats, and SSE event names —
-// this file translates both directions so the client only sees the same
-// { chunk → done } event stream regardless of upstream.
+// 6. WATSONX_API_KEY (+ project) → IBM Granite on watsonx.ai (server key only;
+// explicit `provider: "watsonx"` from the client, never the silent default).
+// Anthropic, the OpenAI-compatible providers (OpenRouter / Groq / OpenAI), and
+// watsonx.ai use different request shapes, auth, tool-call wire formats, and SSE
+// event names — this file translates all of them so the client only ever sees
+// the same { chunk → done } event stream regardless of upstream. watsonx adds
+// one wrinkle: its bearer token is minted from an IAM exchange, so its request
+// headers are resolved asynchronously (route.resolveHeaders) inside the loop
+// rather than baked in up front; its SSE deltas are OpenAI-shaped, so the
+// OpenAI stream reader handles them verbatim.
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
@@ -22,6 +28,7 @@ import { captureException } from './_lib/sentry.js';
import { sql } from './_lib/db.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { loadUserProviderKeys } from './_lib/provider-keys.js';
+import { watsonxConfig, watsonxAuthHeaders } from './_lib/watsonx.js';
import { z } from 'zod';
// Providers anonymous (unauthenticated) callers may use. Groq and OpenRouter
@@ -64,6 +71,14 @@ const PROVIDERS = {
url: 'https://api.openai.com/v1/chat/completions',
style: 'openai',
},
+ // IBM watsonx.ai (Granite). URL + headers are derived in makeRoute from the
+ // shared watsonx client (region host, version param, IAM bearer token), so
+ // no static `url` here. Requires WATSONX_API_KEY + a project/space id.
+ watsonx: {
+ envKey: 'WATSONX_API_KEY',
+ defaultModel: 'ibm/granite-3-8b-instruct',
+ style: 'watsonx',
+ },
};
const contextSchema = z
@@ -91,7 +106,7 @@ const chatBody = z.object({
context: contextSchema,
system_prompt: z.string().trim().min(1).max(2000).optional(),
agentId: z.string().uuid().optional(),
- provider: z.enum(['anthropic', 'openrouter', 'groq', 'openai']).optional(),
+ provider: z.enum(['anthropic', 'openrouter', 'groq', 'openai', 'watsonx']).optional(),
model: z.string().min(1).max(120).optional(),
history: z
.array(
@@ -323,9 +338,12 @@ export default wrap(async (req, res) => {
let retriedTransient = false;
while (true) {
try {
+ // Most routes carry static headers; watsonx resolves a fresh IAM
+ // bearer token (cached between requests) just before the fetch.
+ const reqHeaders = route.headers || (await route.resolveHeaders());
upstream = await fetch(route.url, {
method: 'POST',
- headers: route.headers,
+ headers: reqHeaders,
body: JSON.stringify(route.buildPayload({ systemPrompt, history, maxTokens, includeTools })),
});
} catch (err) {
@@ -446,6 +464,8 @@ export default wrap(async (req, res) => {
res.write(`data: ${JSON.stringify(obj)}\n\n`);
}
+ // watsonx streams OpenAI-shaped chat completion chunks, so the OpenAI reader
+ // parses its deltas and usage verbatim; only Anthropic needs its own reader.
const result =
route.style === 'anthropic'
? await streamAnthropic(upstream, sendSSE)
@@ -497,7 +517,14 @@ function pickProvider(requested, model, userKeys = {}) {
const cfg = PROVIDERS[name];
const apiKey = userKeys[name] || process.env[cfg.envKey];
if (!apiKey) continue;
- const chosenModel = (requested === name && model) || process.env.CHAT_MODEL || cfg.defaultModel;
+ // watsonx needs both a key and a project/space scope to serve a model.
+ if (name === 'watsonx' && !watsonxConfig().configured) continue;
+ // CHAT_MODEL is an Anthropic-style id; it must not leak into a watsonx
+ // request (which expects an `ibm/…` model id). watsonx uses the
+ // client-named model or its own Granite default.
+ const chosenModel =
+ (requested === name && model) ||
+ (name === 'watsonx' ? cfg.defaultModel : process.env.CHAT_MODEL || cfg.defaultModel);
return makeRoute(name, cfg, apiKey, chosenModel);
}
return null;
@@ -546,6 +573,7 @@ function buildFallbackChain(primary, userKeys = {}) {
const cfg = PROVIDERS[name];
const apiKey = userKeys[name] || process.env[cfg.envKey];
if (!apiKey) continue;
+ if (name === 'watsonx' && !watsonxConfig().configured) continue;
const key = `${name}:${cfg.defaultModel}`;
if (seen.has(key)) continue;
seen.add(key);
@@ -577,6 +605,27 @@ function makeRoute(name, cfg, apiKey, model) {
}),
};
}
+ if (cfg.style === 'watsonx') {
+ const wx = watsonxConfig();
+ const scope = wx.projectId ? { project_id: wx.projectId } : { space_id: wx.spaceId };
+ return {
+ name,
+ model,
+ url: `${wx.url}/ml/v1/text/chat_stream?version=${wx.apiVersion}`,
+ style: 'watsonx',
+ // No static headers: the IAM bearer token is minted (and cached) on
+ // demand. The request loop awaits resolveHeaders() before each fetch.
+ resolveHeaders: () => watsonxAuthHeaders(wx),
+ // watsonx has no action-tool wiring here; Granite chats and animates
+ // via text, but scene tool-calls are owned by the other providers.
+ buildPayload: ({ systemPrompt, history, maxTokens }) => ({
+ model_id: model,
+ ...scope,
+ messages: [{ role: 'system', content: systemPrompt }, ...history],
+ max_tokens: maxTokens,
+ }),
+ };
+ }
return {
name,
model,
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 734b16325..f8cbdb4af 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -78,6 +78,7 @@ const MODEL_OPTIONS = [
},
{ id: 'groq:llama-70b', label: 'Groq Llama 3.3 70B', provider: 'groq', model: 'llama-3.3-70b-versatile' },
{ id: 'openai:gpt-4o-mini', label: 'GPT-4o mini', provider: 'openai', model: 'gpt-4o-mini' },
+ { id: 'watsonx:granite', label: 'IBM Granite 3 (watsonx)', provider: 'watsonx', model: 'ibm/granite-3-8b-instruct' },
];
const MODEL_STORAGE_KEY = 'avatar_chat_model_v1';
diff --git a/src/brain.js b/src/brain.js
index 5dc0bef45..e4182f1cc 100644
--- a/src/brain.js
+++ b/src/brain.js
@@ -12,6 +12,7 @@ const PROVIDERS = [
{ key: 'qwen-plus', label: 'Qwen Plus', short: 'Qwen+', network: 'DashScope', color: '#69db7c', ctx: '131K', tier: 'Balanced' },
{ key: 'modelscope-qwen', label: 'Qwen3-Coder 480B', short: 'Qwen3-Code', network: 'ModelScope', color: '#40c057', ctx: '32K', tier: 'Flagship' },
{ key: 'deepseek-r1', label: 'DeepSeek R1', short: 'DeepSeek', network: 'DeepSeek', color: '#b197fc', ctx: '64K', tier: 'Reasoning' },
+ { key: 'ibm-granite', label: 'IBM Granite 3.8B', short: 'Granite', network: 'IBM watsonx.ai', color: '#0f62fe', ctx: '128K', tier: 'Balanced' },
];
const PMAP = new Map(PROVIDERS.map(p => [p.key, p]));
diff --git a/src/nich-agent.js b/src/nich-agent.js
index f89645f3c..00897baa6 100644
--- a/src/nich-agent.js
+++ b/src/nich-agent.js
@@ -832,4 +832,10 @@ const MODEL_OPTIONS = [
model: 'llama-3.3-70b-versatile',
},
{ id: 'openai:gpt-4o-mini', label: 'GPT-4o mini', provider: 'openai', model: 'gpt-4o-mini' },
+ {
+ id: 'watsonx:granite',
+ label: 'IBM Granite 3 (watsonx)',
+ provider: 'watsonx',
+ model: 'ibm/granite-3-8b-instruct',
+ },
];