feat(models): connect a Bifrost gateway with model prices (#1769)

Thanks Romeo!

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Luka Zivkovic <luka.zivkovic@n8n.io>
This commit is contained in:
authored and GitHub committed 2026-12-01 17:02:15 +01:00
1 parent 80dd69f4a7
commit fcd09abaaf
16 files changed
+241 -82

No files matched your search

+2
View File
@@ -50,6 +50,7 @@ XIAOMI_TOKEN_PLAN_SGP_API_KEY=
ZAI_API_KEY=
ZAI_CODING_CN_API_KEY=
OPENAI_COMPATIBLE_API_KEY=
BIFROST_API_KEY=
AWS_REGION=
CLOUDFLARE_ACCOUNT_ID=
CLOUDFLARE_GATEWAY_ID=
@@ -57,6 +58,7 @@ AZURE_OPENAI_ENDPOINT=
AZURE_OPENAI_MODEL=
AZURE_OPENAI_DEPLOYMENT=
OPENAI_COMPATIBLE_BASE_URL=
BIFROST_BASE_URL=
NOD_COMPOSIO_PROXY_URL=https://composio.n8n.cloud
TYPESAFE_API_KEY=
NOD_TRUST_MODEL=selected
+10 -10
View File
@@ -142,16 +142,16 @@ If the server offers Ollama model details, Nod uses its capability list to filte
## What changes with these connections
| Area | With a local or OpenAI-compatible model |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Spending | Nod doesn't know the server's prices, so **Usage** shows its requests as **No price**. That usage doesn't count toward the [monthly limit or task check-ins](/use/spending/#how-each-model-is-priced). A paid service still bills you. |
| Images | Ollama and LM Studio models that support vision get screenshots and images. Models on other servers get text only. |
| Thinking levels | Ollama models offer them, and so do models whose server lists `reasoning.supported_efforts`. Other models use their own default. |
| Decision checks | Trust uses a separate small model or decision service. Email checks use the background model unless a decision service is available. See [Decision checks](/connect/models/#decision-checks). |
| Background work | Memory upkeep and other background work use your selected model. [Automatic preparation](/use/spending/#automatic-preparation-allowance) needs a known price, so it doesn't run on a local or otherwise unpriced model. |
| Slow replies | A slow first reply is normal. After a quiet minute, the chat shows **Waiting for** and your model's name, with how long it has been quiet. If the server sends nothing at all for 30 minutes, Nod sends the request again, up to three times, and then says it failed. **Stop** ends it sooner. |
| Where requests go | Chat and confirmation wording requests go to the address you enter. Trust requests go to the checker connection. Web search, websites, apps and chat channels work as before. See [Your data and privacy](/trust/privacy/). |
| Where your key goes | Keys saved in **Models** are encrypted. Keys from `.env` stay in server configuration and memory. The server adds the key to requests and sends your server key only to the address you entered. See [Where your keys go](/connect/models/#where-your-keys-go). |
| Area | With a local or OpenAI-compatible model |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Spending | Nod doesn't know the server's prices, so **Usage** shows its requests as **No price**. That usage doesn't count toward the [monthly limit or task check-ins](/use/spending/#how-each-model-is-priced). A paid service still bills you. A [Bifrost connection](/connect/models/#connect-a-service) prices the models that appear in Bifrost's public price list. |
| Images | Ollama and LM Studio models that support vision get screenshots and images. Models on other servers get text only. |
| Thinking levels | Ollama models offer them, and so do models whose server lists `reasoning.supported_efforts`. Other models use their own default. |
| Decision checks | Trust uses a separate small model or decision service. Email checks use the background model unless a decision service is available. See [Decision checks](/connect/models/#decision-checks). |
| Background work | Memory upkeep and other background work use your selected model. [Automatic preparation](/use/spending/#automatic-preparation-allowance) needs a known price, so it doesn't run on a local or otherwise unpriced model. |
| Slow replies | A slow first reply is normal. After a quiet minute, the chat shows **Waiting for** and your model's name, with how long it has been quiet. If the server sends nothing at all for 30 minutes, Nod sends the request again, up to three times, and then says it failed. **Stop** ends it sooner. |
| Where requests go | Chat and confirmation wording requests go to the address you enter. Trust requests go to the checker connection. Web search, websites, apps and chat channels work as before. See [Your data and privacy](/trust/privacy/). |
| Where your key goes | Keys saved in **Models** are encrypted. Keys from `.env` stay in server configuration and memory. The server adds the key to requests and sends your server key only to the address you entered. See [Where your keys go](/connect/models/#where-your-keys-go). |
## Troubleshooting
+18 -3
View File
@@ -31,6 +31,7 @@ Select **Add connection** (or **Add** when you already have a connection), then
| Azure OpenAI | Endpoint, deployment, model, and API key | The deployment's model |
| Cloudflare Workers AI / AI Gateway | Token, account ID, and gateway ID for AI Gateway | GLM 5.3 / GPT-6.1 Sol |
| Other named providers | Service-specific API key | A capable model from that connection |
| Bifrost | Gateway address and optional key | A model offered by the gateway |
| OpenAI-compatible | Server address and optional key | A model offered by the server |
Other providers include Ant Ling, Baseten, Cerebras, DeepSeek, Fireworks AI, Groq, Hugging Face, Kimi Coding China, Meta, MiniMax, Mistral, Moonshot AI, NVIDIA, OpenCode Zen and Go, Qwen Token Plan, Radius, Together AI, Vercel AI Gateway, xAI, Xiaomi MiMo and token plans, and Z.AI. The picker includes their supported regional variants.
@@ -228,6 +229,19 @@ Nod uses Azure's v1 API at that endpoint and sends the key only there. The endpo
Each deployment is one connection with one model. Add another connection for each deployment you want to use. The model you choose sets the context size and the prices Nod counts toward your [spending](/use/spending/). Microsoft Entra ID sign-in isn't supported.
</TabItem>
<TabItem label="Bifrost">
<Steps>
1. Choose **Bifrost** from the provider list.
2. Enter the gateway's **Server address**, such as `http://localhost:8080`. Add an **API key** only if the gateway needs a virtual key.
3. Select **Connect**.
</Steps>
Nod lists the gateway's models and gets their prices from [Bifrost's public price list](https://getbifrost.ai/datasheet). This request doesn't include your key or address. A model ID such as `anthropic/claude-fable-5` gets the price of `claude-fable-5` from Anthropic. A model that isn't in the list shows **No price**, the same as an [OpenAI-compatible server](/connect/local-models/#what-changes-with-these-connections). Nod doesn't read prices you set on your own gateway. Select **Reload models** to update the prices.
</TabItem>
<TabItem label="OpenAI-compatible">
@@ -248,7 +262,7 @@ Use this for Ollama, LM Studio, vLLM, llama.cpp and hosted services with an Open
All the models from your connections appear in one searchable list, grouped by connection. Choosing a model also chooses the connection that pays for it.
OpenRouter and Hostinger AI Router models show input and output token prices beside each model name, in USD per million tokens. Prices can wrap to the next line on small screens. The list identifies free tokens and prices that vary by model. These are the rates from the last model list update. Actual charges can vary with routing, caching, context length, and extra services. See [OpenRouter's model pricing](https://openrouter.ai/docs/guides/overview/models#pricing-object) or Hostinger's rates in [hPanel's AI Router page](https://hpanel.hostinger.com/ai-router/).
OpenRouter, Hostinger AI Router and Bifrost models show input and output token prices beside each model name, in USD per million tokens. Prices can wrap to the next line on small screens. The list identifies free tokens and prices that vary by model. A Bifrost model with a zero price shows **No price** instead. These are the rates from the last model list update. Actual charges can vary with routing, caching, context length, and extra services. See [OpenRouter's model pricing](https://openrouter.ai/docs/guides/overview/models#pricing-object) or Hostinger's rates in [hPanel's AI Router page](https://hpanel.hostinger.com/ai-router/).
You can connect several accounts of one service, such as two ChatGPT accounts or a personal and a work API key. A ChatGPT connection shows the account's email. A key connection, including one an OpenRouter sign-in created, shows only the last four characters of a key longer than four characters. Shorter keys stay hidden. The model never sees this display value. Signing in again with an account you already connected, or adding the same key or server address to the same service again, updates that connection instead of adding another.
@@ -383,7 +397,7 @@ Open **Settings → Voice & audio**. Open **Voice** to compare samples, or choos
In a source install or self-hosted server, you can add connections in `.env`. They show **Server settings** in **Models**. Update their values in `.env`, then [apply the configuration change](/deploy/configuration/#how-settings-work).
Removing an API key removes its server-managed connection. For an OpenAI-compatible server, remove `OPENAI_COMPATIBLE_BASE_URL` instead. Connections saved through the app stay intact. If you removed the selected connection, choose another model in **Models**.
Removing an API key removes its server-managed connection. For an OpenAI-compatible server or Bifrost, remove `OPENAI_COMPATIBLE_BASE_URL` or `BIFROST_BASE_URL` instead. Connections saved through the app stay intact. If you removed the selected connection, choose another model in **Models**.
Every service below supports environment setup. You can add several provider keys at once. Set `LLM_PROVIDER` to the provider ID for your initial model choice. Leave `LLM_MODEL` empty for the [provider's default](#supported-connections), or set an exact model ID from its list. A model you choose in the app takes priority. ChatGPT subscriptions still need browser sign-in in **Models**.
@@ -439,6 +453,7 @@ Additional settings:
| Amazon Bedrock | `AWS_REGION`, such as `us-east-1`. Set `LLM_MODEL` to select a model or inference profile when several are available. |
| Azure OpenAI | `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_MODEL`, the model ID your deployment runs. Set `AZURE_OPENAI_DEPLOYMENT` if the deployment has a different name. |
| Cloudflare | `CLOUDFLARE_ACCOUNT_ID`, the 32-character hexadecimal account ID. AI Gateway also requires `CLOUDFLARE_GATEWAY_ID`. |
| Bifrost | `BIFROST_BASE_URL` and optional `BIFROST_API_KEY`. Use `LLM_PROVIDER=bifrost` for the initial choice. |
| OpenAI-compatible | `OPENAI_COMPATIBLE_BASE_URL` and optional `OPENAI_COMPATIBLE_API_KEY`. Use `LLM_PROVIDER=compatible` for the initial choice. |
Set the cloud provider's required fields before starting Nod. A Cloudflare gateway ID has one to 64 lowercase letters, digits, or hyphens, starting with a letter or digit. Both Cloudflare connections use the same account ID from `.env`; connections saved in **Models** can use separate accounts and gateways.
@@ -470,7 +485,7 @@ flowchart LR
- Nod encrypts saved keys and sign-ins with the Vault key. macOS uses Keychain, the Windows app uses Windows DPAPI, and the Linux Flatpak uses Secret Service. Linux source installs use a private file. The self-hosting stack generates `NOD_VAULT_KEY` in its private `.env`. See [Vault configuration](/deploy/configuration/#vault).
- Nod checks credential storage before starting a connection. If storage is unavailable, check the Vault configuration, permissions and database connection, then try again.
- Keys from `.env` stay in server memory and aren't copied into the database.
- Each key goes only to its own service: Amazon Bedrock in the Region you entered, Google Vertex AI, the Azure OpenAI endpoint you entered, or the OpenAI-compatible server address you entered.
- Each key goes only to its own service: Amazon Bedrock in the Region you entered, Google Vertex AI, the Azure OpenAI endpoint you entered, or the Bifrost or OpenAI-compatible server address you entered.
- Your browser doesn't store the key, and Nod removes it from provider errors.
- Requests to model, speech and decision services identify the app as `nod`. OpenRouter and Vercel AI Gateway show Nod's usage under that name.
+18 -16
View File
@@ -73,22 +73,24 @@ Use the [self-hosting guide](/deploy/self-host/) to configure HTTPS and private
Keys set here become server-managed connections. They stay in server memory and aren't copied into the database. You can also add connections in **Models** without any variable. See [Models](/connect/models/).
| Variable | What it does | Default |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| `LLM_PROVIDER` | The provider of the first model choice: any [supported provider ID](/connect/models/#set-connections-in-server-settings). A model you pick in the app takes priority. | `openai` |
| `LLM_MODEL` | The first model choice. | The [provider's default](/connect/models/#supported-connections) |
| `OPENAI_API_KEY` | Adds an OpenAI connection. It also turns on voice transcription and voice replies. | Empty |
| `ANTHROPIC_API_KEY` | Adds an Anthropic connection. | Empty |
| `ANTHROPIC_WORKSPACE_ID` | The workspace for `ANTHROPIC_API_KEY`. Required only for organization keys that aren't limited to one workspace. | Empty |
| `OPENROUTER_API_KEY` | Adds an OpenRouter connection with ElevenLabs and Kokoro voices. Also enables transcription when no OpenAI API connection is available. | Empty |
| `ELEVENLABS_API_KEY` | Adds an ElevenLabs connection for account voices and transcription, without a chat model. | Empty |
| `OPENAI_COMPATIBLE_BASE_URL` | Adds an [OpenAI-compatible server](/connect/local-models/), such as Ollama at `http://localhost:11434/v1`. The address must be reachable from Nod's server. | Empty |
| `OPENAI_COMPATIBLE_API_KEY` | The key for that server, if it needs one. | Empty |
| `TYPESAFE_API_KEY` | Selects direct Jev for account-access email and for Trust checks in `decision` mode. | Empty |
| `NOD_TRUST_MODEL` | Selects the action checker: `selected`, `llm` or `decision`. The checker also checks strict app reads and confirmation replies. | `selected` |
| `TTS_MODEL` | The OpenAI speech model for voice replies. | `gpt-4o-mini-tts` |
| `STT_MODEL` | The OpenAI or OpenRouter model for incoming voice messages. On OpenRouter, a model ID without `/` gets the `openai/` prefix. | `gpt-transcribe` (`openai/gpt-transcribe` on OpenRouter) |
| `TTS_VOICE` | The voice for voice replies. | `coral` |
| Variable | What it does | Default |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| `LLM_PROVIDER` | The provider of the first model choice: any [supported provider ID](/connect/models/#set-connections-in-server-settings). A model you pick in the app takes priority. | `openai` |
| `LLM_MODEL` | The first model choice. | The [provider's default](/connect/models/#supported-connections) |
| `OPENAI_API_KEY` | Adds an OpenAI connection. It also turns on voice transcription and voice replies. | Empty |
| `ANTHROPIC_API_KEY` | Adds an Anthropic connection. | Empty |
| `ANTHROPIC_WORKSPACE_ID` | The workspace for `ANTHROPIC_API_KEY`. Required only for organization keys that aren't limited to one workspace. | Empty |
| `OPENROUTER_API_KEY` | Adds an OpenRouter connection with ElevenLabs and Kokoro voices. Also enables transcription when no OpenAI API connection is available. | Empty |
| `ELEVENLABS_API_KEY` | Adds an ElevenLabs connection for account voices and transcription, without a chat model. | Empty |
| `OPENAI_COMPATIBLE_BASE_URL` | Adds an [OpenAI-compatible server](/connect/local-models/), such as Ollama at `http://localhost:11434/v1`. The address must be reachable from Nod's server. | Empty |
| `OPENAI_COMPATIBLE_API_KEY` | The key for that server, if it needs one. | Empty |
| `BIFROST_BASE_URL` | Adds a [Bifrost gateway](/connect/models/#connect-a-service), such as `http://localhost:8080`. It must be a plain http or https address without credentials, a query or a fragment, and reachable from Nod's server. | Empty |
| `BIFROST_API_KEY` | The virtual key for that gateway, if it needs one. | Empty |
| `TYPESAFE_API_KEY` | Selects direct Jev for account-access email and for Trust checks in `decision` mode. | Empty |
| `NOD_TRUST_MODEL` | Selects the action checker: `selected`, `llm` or `decision`. The checker also checks strict app reads and confirmation replies. | `selected` |
| `TTS_MODEL` | The OpenAI speech model for voice replies. | `gpt-4o-mini-tts` |
| `STT_MODEL` | The OpenAI or OpenRouter model for incoming voice messages. On OpenRouter, a model ID without `/` gets the `openai/` prefix. | `gpt-transcribe` (`openai/gpt-transcribe` on OpenRouter) |
| `TTS_VOICE` | The voice for voice replies. | `coral` |
The [provider settings table](/connect/models/#set-connections-in-server-settings) lists every supported key, including `GEMINI_API_KEY` for Google Gemini and `GOOGLE_CLOUD_API_KEY` for Vertex AI. It also lists the required Bedrock Region, Azure endpoint and model, and Cloudflare account and gateway settings. You can configure several providers at once; `LLM_PROVIDER` only sets the initial selection.
+8
View File
@@ -63,4 +63,12 @@ Local asset: hostinger.svg
The SVG path is unmodified. The title and role attributes are removed and
width and height are set to 24 pixels.
Bifrost
Source: https://github.com/maximhq/bifrost
Source file: docs/favicon.png
License: Apache-2.0.
Local asset: bifrost.svg
The five blocks of the PNG mark are redrawn as an SVG path on a 24-pixel
grid, without the black background.
Provider names and trademarks remain with their respective owners.
+1
View File
@@ -0,0 +1 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 2h12v4H4zM16 6h4v4h-4zM8 10h4v4H8zM16 14h4v4h-4zM4 18h12v4H4z" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 198 B

+55 -15
View File
@@ -43,6 +43,7 @@ import {
modelProviderNames,
type ModelProvider,
type ModelMethod,
usesServerAddress,
} from '../../shared/models.ts';
import { signInPage } from '../../shared/sign-in-page.ts';
import type { PiModelCall, ModelRequestFacts } from './traces.ts';
@@ -76,7 +77,10 @@ function supportedModel(model: Model<Api>): Model<Api> {
return { ...model, compat: { ...model.compat, supportsStrictMode: false } };
if (model.provider === 'openrouter' && model.id === 'openrouter/free')
return { ...model, thinkingLevelMap: { ...model.thinkingLevelMap, off: null } };
if (model.provider === 'compatible' && model.thinkingLevelMap?.high === 'true')
if (
(model.provider === 'compatible' || model.provider === 'bifrost') &&
model.thinkingLevelMap?.high === 'true'
)
return { ...model, thinkingLevelMap: { ...model.thinkingLevelMap, high: 'high' } };
return model;
}
@@ -92,6 +96,24 @@ const routers = {
hostinger: { baseUrl: 'https://router.hostinger.com/v1', perMillion: 10_000, compat: {} },
} as const;
const issuer = 'https://auth.openai.com';
const bifrostPrices = 'https://getbifrost.ai/datasheet';
const bifrostPriceBytes = 20_000_000;
const bifrostPriceSchema = z.object({
provider: z.string().nullish(),
input_cost_per_token: z.number().nonnegative(),
output_cost_per_token: z.number().nonnegative(),
cache_read_input_token_cost: z.number().nonnegative().nullish(),
cache_creation_input_token_cost: z.number().nonnegative().nullish(),
supports_vision: z.boolean().nullish(),
});
function bifrostPrice(sheet: Record<string, unknown>, id: string) {
const exact = bifrostPriceSchema.safeParse(sheet[id]).data;
if (exact) return exact;
const slash = id.indexOf('/');
const bare = bifrostPriceSchema.safeParse(sheet[id.slice(slash + 1)]).data;
return slash > 0 && bare?.provider === id.slice(0, slash) ? bare : undefined;
}
const registration = 'dynamic_agent_client';
const planScope = 'chatgpt.tokens.use.direct';
@@ -277,12 +299,23 @@ export function createPiModelBackend(options: { fetch?: typeof fetch } = {}): Mo
spec: JSON.parse(JSON.stringify(model)),
};
}
async function endpointCatalog(credential?: ModelCredential) {
async function endpointCatalog(provider: 'compatible' | 'bifrost', credential?: ModelCredential) {
if (credential?.type !== 'endpoint') throw new Error('Add the server address in Models.');
const headers: Record<string, string> = credential.key
? { Authorization: `Bearer ${credential.key}` }
: {};
const secrets = [credential.url, credential.key ?? ''];
const pendingPrices: Promise<Record<string, unknown>> =
provider === 'bifrost'
? request(bifrostPrices, { redirect: 'error', signal: AbortSignal.timeout(30000) })
.then(async (response) => {
const text = response.ok ? await response.text() : '';
return text.length > bifrostPriceBytes
? {}
: z.record(z.string(), z.unknown()).parse(JSON.parse(text));
})
.catch(() => ({}))
: Promise.resolve({});
const failures: ModelCatalogFailure[] = [];
let found: { url: string; data: unknown[] } | undefined;
for (const url of credential.url.endsWith('/v1')
@@ -339,10 +372,10 @@ export function createPiModelBackend(options: { fetch?: typeof fetch } = {}): Mo
})
.then((response) => (response.ok ? response.json() : undefined))
.catch(() => undefined);
const [version, studio] = await Promise.all([
serverJson('/api/version'),
serverJson('/api/v1/models'),
]);
const [version, studio] =
provider === 'compatible'
? await Promise.all([serverJson('/api/version'), serverJson('/api/v1/models')])
: [];
const ollama = z.object({ version: z.string() }).safeParse(version).success;
const running = ollama ? await serverJson('/api/ps') : undefined;
const loadedModels = entries(
@@ -357,6 +390,7 @@ export function createPiModelBackend(options: { fetch?: typeof fetch } = {}): Mo
z.object({ models: z.array(z.unknown()) }).safeParse(studio).data?.models ?? [],
lmStudioModelSchema,
);
const prices = await pendingPrices;
const models: ModelDefinition[] = [];
for (let index = 0; index < listed.length; index += 3) {
const batch = await Promise.all(
@@ -398,12 +432,13 @@ export function createPiModelBackend(options: { fetch?: typeof fetch } = {}): Mo
.filter((model) => model.name === entry.id || model.model === entry.id)
.map((model) => model.context_length)),
);
const price = bifrostPrice(prices, entry.id);
return [
definition({
id: entry.id,
name: entry.id,
api: 'openai-completions',
provider: 'compatible',
provider,
baseUrl: found.url,
compat: {
supportsStore: false,
@@ -412,10 +447,15 @@ export function createPiModelBackend(options: { fetch?: typeof fetch } = {}): Mo
},
reasoning: !!thinkingLevelMap,
thinkingLevelMap,
input: known?.images ? ['text', 'image'] : ['text'],
input: known?.images || price?.supports_vision ? ['text', 'image'] : ['text'],
contextWindow,
maxTokens: Math.min(32_768, Math.floor(contextWindow / 2)),
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
cost: {
input: (price?.input_cost_per_token ?? 0) * 1_000_000,
output: (price?.output_cost_per_token ?? 0) * 1_000_000,
cacheRead: (price?.cache_read_input_token_cost ?? 0) * 1_000_000,
cacheWrite: (price?.cache_creation_input_token_cost ?? 0) * 1_000_000,
},
} as Model<Api>),
];
}),
@@ -795,7 +835,8 @@ export function createPiModelBackend(options: { fetch?: typeof fetch } = {}): Mo
}
if (!modelProviders.includes(provider))
throw new Error('This model provider is unavailable.');
if (provider === 'compatible') return endpointCatalog(credential);
if (provider === 'compatible' || provider === 'bifrost')
return endpointCatalog(provider, credential);
let local = assistantModels(
provider === 'ant-ling' ? [antLingModel] : (await runtime()).getModels(provider),
);
@@ -1259,17 +1300,16 @@ export async function createPiModelRuntime(
let silenceTimer: ReturnType<typeof setTimeout> | undefined;
const heard = () => clearTimeout(silenceTimer);
const guardedFetch =
access.provider === 'compatible' ||
usesServerAddress(access.provider) ||
access.provider === 'radius' ||
access.provider === 'cloudflare-workers-ai' ||
access.provider === 'cloudflare-ai-gateway' ||
(access.provider === 'openai' && !subscription) ||
Boolean(usage);
const sent = audio?.context ?? context;
const replay =
access.provider === 'compatible'
? { ...sent, messages: portableToolCallIds(sent.messages, target.id) }
: sent;
const replay = usesServerAddress(access.provider)
? { ...sent, messages: portableToolCallIds(sent.messages, target.id) }
: sent;
const output = Math.min(options?.maxTokens ?? target.maxTokens, target.maxTokens);
const upstream = stream(target, replay, {
...options,
+12
View File
@@ -302,6 +302,11 @@ export function modelEnvironment(
throw new Error(
'OPENAI_COMPATIBLE_BASE_URL must be a plain http or https address, such as http://localhost:11434/v1.',
);
const bifrost = env.BIFROST_BASE_URL && endpointAddress(env.BIFROST_BASE_URL);
if (env.BIFROST_BASE_URL && !bifrost)
throw new Error(
'BIFROST_BASE_URL must be a plain http or https address, such as http://localhost:8080.',
);
return {
provider,
model: env.LLM_MODEL || undefined,
@@ -341,6 +346,13 @@ export function modelEnvironment(
...(env.OPENAI_COMPATIBLE_API_KEY && { key: env.OPENAI_COMPATIBLE_API_KEY }),
},
}),
...(bifrost && {
bifrost: {
type: 'endpoint',
url: bifrost,
...(env.BIFROST_API_KEY && { key: env.BIFROST_API_KEY }),
},
}),
},
};
}
+11 -6
View File
@@ -98,7 +98,7 @@ function modelPricing(model: ModelDefinition): ModelChoice['pricing'] {
if (model.spec.provider === 'compatible') return undefined;
if (model.choice.id === 'openrouter/auto') return 'variable';
const cost = modelRates.safeParse(model.spec.cost).data;
if (!cost) return undefined;
if (!cost || (model.spec.provider === 'bifrost' && !cost.output)) return undefined;
const { tiers, ...rates } = cost;
if ([rates, ...(tiers ?? [])].some((rate) => Object.values(rate).some((value) => value < 0)))
return 'variable';
@@ -1539,20 +1539,24 @@ export function createModelService(options: {
return save(provider, 'api_key', value, await catalog(provider, 'api_key', value));
});
},
async addEndpoint(address: string, key?: string) {
async addEndpoint(
address: string,
key?: string,
provider: 'compatible' | 'bifrost' = 'compatible',
) {
const url = endpointAddress(address);
if (!url)
throw new ConnectionError('Enter a server address such as http://localhost:11434/v1.');
const value: ModelCredential = { type: 'endpoint', url, ...(key ? { key } : {}) };
remember(value);
return tracked('compatible', 'api_key', async () => {
return tracked(provider, 'api_key', async () => {
await checkStorage();
const definitions = await catalog('compatible', 'api_key', value);
const definitions = await catalog(provider, 'api_key', value);
if (!definitions.length)
throw new ConnectionError(
'This server has no models Nod can use. Nod needs models with tool support.',
);
return save('compatible', 'api_key', value, definitions);
return save(provider, 'api_key', value, definitions);
});
},
async select(input: ModelSelection, actor: SettingActor = 'owner', client?: PoolClient) {
@@ -1761,10 +1765,11 @@ export function createModelService(options: {
.object({
url: z.string().trim().min(1).max(2000),
key: z.string().trim().max(32000).optional(),
provider: z.enum(['compatible', 'bifrost']).optional(),
})
.strict()
.parse(request.body);
await service.addEndpoint(input.url, input.key || undefined);
await service.addEndpoint(input.url, input.key || undefined, input.provider);
return service.view();
});
routes.put('/api/models/selection', async (request) => {
+1 -1
View File
@@ -1578,7 +1578,7 @@ const offlineHint = `Scheduled tasks run only while this computer is awake and o
function offlineFailure(error: unknown, provider: string | undefined) {
if (
!(error instanceof ModelRequestError) ||
['compatible', 'azure', 'amazon-bedrock'].includes(String(provider))
['compatible', 'bifrost', 'azure', 'amazon-bedrock'].includes(String(provider))
)
return;
const code = offlineCause.exec(error.message)?.[1];
+1
View File
@@ -35,6 +35,7 @@ const providers = [
'google-vertex',
'azure',
'compatible',
'bifrost',
'other',
];
const methods = ['managed_app', 'browser', 'http', 'mcp', 'cli'];
+4 -3
View File
@@ -1,4 +1,4 @@
import { modelProviderNames, type ModelProvider } from './models.ts';
import { modelProviderNames, usesServerAddress, type ModelProvider } from './models.ts';
const keyFormats: { prefix: string; providers: ModelProvider[]; name?: string }[] = [
{ prefix: 'sk-ant-', providers: ['anthropic'] },
@@ -13,12 +13,13 @@ const keyFormats: { prefix: string; providers: ModelProvider[]; name?: string }[
];
export function modelKeyError(provider: ModelProvider, key: string) {
if (provider === 'compatible') return;
const value = key.trim();
if (value.length < 8 || value.length > 32000)
const server = usesServerAddress(provider);
if (!server && (value.length < 8 || value.length > 32000))
return 'Paste the complete API key from your provider.';
if (/[\s\x00-\x1f\x7f-\x9f]/.test(value))
return 'API keys cannot contain spaces or control characters. Paste the key again.';
if (server) return;
const format = keyFormats.find(({ prefix }) => value.startsWith(prefix));
if (format && value.length < format.prefix.length + 8)
return 'Paste the complete API key from your provider.';
+6 -2
View File
@@ -42,8 +42,10 @@ export const apiKeyModelProviders = [
] as const;
export const apiKeyConnectionProviders = [...apiKeyModelProviders, 'elevenlabs'] as const;
export const modelProviders = [...apiKeyModelProviders, 'compatible'] as const;
export type ModelProvider = (typeof apiKeyConnectionProviders)[number] | 'compatible';
export const modelProviders = [...apiKeyModelProviders, 'bifrost', 'compatible'] as const;
export type ModelProvider = (typeof apiKeyConnectionProviders)[number] | 'bifrost' | 'compatible';
export const usesServerAddress = (provider: ModelProvider) =>
provider === 'compatible' || provider === 'bifrost';
export type ModelMethod = 'api_key' | 'subscription' | 'oauth';
export type ModelEffort = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
@@ -323,6 +325,7 @@ export const modelProviderNames = {
'xiaomi-token-plan-sgp': 'Xiaomi Token Plan Singapore',
zai: 'Z.AI',
'zai-coding-cn': 'Z.AI Coding China',
bifrost: 'Bifrost',
compatible: 'OpenAI-compatible',
} as const satisfies Record<ModelProvider, string>;
@@ -475,6 +478,7 @@ export const modelProviderInfo: Record<
},
zai: { keyUrl: 'z.ai/manage-apikey/apikey-list', env: 'ZAI_API_KEY', catalog: 'bundled' },
'zai-coding-cn': { keyUrl: 'open.bigmodel.cn', env: 'ZAI_CODING_CN_API_KEY', catalog: 'bundled' },
bifrost: { keyUrl: '', env: 'BIFROST_API_KEY', catalog: 'account' },
compatible: { keyUrl: '', env: 'OPENAI_COMPATIBLE_API_KEY', catalog: 'account' },
};
+25 -15
View File
@@ -32,6 +32,7 @@ import {
modelProviders,
modelSource,
openAIRegions,
usesServerAddress,
canReuseWorkCost,
repriceUsd,
} from '../../shared/models';
@@ -66,7 +67,7 @@ import {
} from './ui';
const listsPrices = (provider: ModelProvider) =>
provider === 'openrouter' || provider === 'hostinger';
provider === 'openrouter' || provider === 'hostinger' || provider === 'bifrost';
const modelProviderLogos: Partial<Record<ModelProvider, string>> = {
openai: 'models/openai',
@@ -109,6 +110,7 @@ const modelProviderLogos: Partial<Record<ModelProvider, string>> = {
'xiaomi-token-plan-sgp': 'models/xiaomi',
zai: 'models/zai',
'zai-coding-cn': 'models/zai',
bifrost: 'models/bifrost',
compatible: 'server',
};
@@ -215,6 +217,8 @@ function providerDescription(provider: ModelProvider) {
return 'Models through your Cloudflare gateway';
case 'compatible':
return 'Ollama, LM Studio, vLLM or any other server';
case 'bifrost':
return 'Models through your Bifrost gateway, with prices';
default:
return `Models with a ${modelProviderNames[provider]} API key`;
}
@@ -231,7 +235,7 @@ function connectionName(connection: ModelConnection, short = false) {
function ModelConnectionAvatar({ connection }: { connection: ModelConnection }) {
return (
<span className="model-connection-avatar" aria-hidden="true">
{connection.provider === 'compatible' ? (
{usesServerAddress(connection.provider) ? (
<Server size={18} />
) : connection.method === 'api_key' ? (
<KeyRound size={18} />
@@ -477,7 +481,7 @@ export function ModelSettings({ onDirtyChange }: { onDirtyChange?(dirty: boolean
keyProvider &&
!keyFormatError &&
(!models.workspaces.length || settings.workspaceId.trim()) &&
(keyProvider === 'compatible'
(usesServerAddress(keyProvider)
? url.trim()
: key.trim() && keySettingsReady(keyProvider, settings)),
);
@@ -502,10 +506,10 @@ export function ModelSettings({ onDirtyChange }: { onDirtyChange?(dirty: boolean
return false;
}
const saved = await models.change(
keyProvider === 'compatible' ? '/api/models/endpoints' : '/api/models/keys',
usesServerAddress(keyProvider) ? '/api/models/endpoints' : '/api/models/keys',
'POST',
keyProvider === 'compatible'
? { url: url.trim(), key }
usesServerAddress(keyProvider)
? { url: url.trim(), key, provider: keyProvider }
: keyConnection(keyProvider, key, settings),
);
if (saved) {
@@ -722,7 +726,7 @@ export function ModelSettings({ onDirtyChange }: { onDirtyChange?(dirty: boolean
? 'ChatGPT plan'
: connection.method === 'oauth'
? 'Connected with sign-in'
: connection.provider === 'compatible'
: usesServerAddress(connection.provider)
? 'Model server'
: 'API key'}
{connection.status === 'reconnect'
@@ -779,7 +783,7 @@ export function ModelSettings({ onDirtyChange }: { onDirtyChange?(dirty: boolean
>
{connection.method !== 'api_key'
? 'Reconnect'
: connection.provider === 'compatible'
: usesServerAddress(connection.provider)
? 'Add server'
: 'Add key'}
</Button>
@@ -883,14 +887,18 @@ export function ModelSettings({ onDirtyChange }: { onDirtyChange?(dirty: boolean
void saveKey();
}}
>
{panel.provider === 'compatible' && (
{usesServerAddress(panel.provider) && (
<Field label="Server address">
<Input
inputMode="url"
value={url}
required
maxLength={2000}
placeholder={localServerAddress}
placeholder={
panel.provider === 'bifrost'
? 'http://localhost:8080'
: localServerAddress
}
autoComplete="off"
spellCheck={false}
autoFocus
@@ -910,12 +918,14 @@ export function ModelSettings({ onDirtyChange }: { onDirtyChange?(dirty: boolean
}}
disabled={busy}
/>
<Field label={panel.provider === 'compatible' ? 'API key (optional)' : 'API key'}>
<Field
label={usesServerAddress(panel.provider) ? 'API key (optional)' : 'API key'}
>
<Input
type="password"
value={key}
required={panel.provider !== 'compatible'}
minLength={panel.provider === 'compatible' ? undefined : 8}
required={!usesServerAddress(panel.provider)}
minLength={usesServerAddress(panel.provider) ? undefined : 8}
maxLength={32000}
autoComplete="off"
spellCheck={false}
@@ -935,8 +945,8 @@ export function ModelSettings({ onDirtyChange }: { onDirtyChange?(dirty: boolean
<Notice>{keyError}</Notice>
</div>
)}
{panel.provider !== 'compatible' && <ModelKeyHelp provider={panel.provider} />}
{panel.provider === 'compatible' && (
{!usesServerAddress(panel.provider) && <ModelKeyHelp provider={panel.provider} />}
{usesServerAddress(panel.provider) && (
<p className="model-key-note">
Nod also uses this model to check actions. Smaller models decide less
reliably.
+20 -11
View File
@@ -21,6 +21,7 @@ import {
modelProviderNames,
modelProviders,
modelSource,
usesServerAddress,
} from '../../../../shared/models';
import { Button, Input, Notice, SearchField } from '../../../components/ui';
import {
@@ -78,7 +79,10 @@ function signsIn(provider: ModelProvider): provider is SignInProvider {
}
function ownerChooses(source: ModelConnection) {
return ['amazon-bedrock', 'compatible'].includes(source.provider) && source.models.length > 1;
return (
['amazon-bedrock', 'compatible', 'bifrost'].includes(source.provider) &&
source.models.length > 1
);
}
function recommended(source: ModelConnection) {
@@ -127,7 +131,7 @@ function useConnect() {
async function save(provider: ModelProvider, key: string, settings = noKeySettings, url = '') {
if (submitting.current) return false;
const value = key.trim();
const endpoint = provider === 'compatible';
const endpoint = usesServerAddress(provider);
if (endpoint && !url.trim()) return (setKeyError('Enter the server address first.'), false);
if (!keySettingsReady(provider, settings))
return (setKeyError('Fill in every field first.'), false);
@@ -143,7 +147,9 @@ function useConnect() {
{
method: 'POST',
body: JSON.stringify(
endpoint ? { url: url.trim(), key: value } : keyConnection(provider, value, settings),
endpoint
? { url: url.trim(), key: value, provider }
: keyConnection(provider, value, settings),
),
},
);
@@ -384,8 +390,8 @@ function KeyForm({
);
}
function ServerForm({ c }: { c: Connect }) {
const [url, setUrl] = useState(localServerAddress);
function ServerForm({ c, provider }: { c: Connect; provider: 'compatible' | 'bifrost' }) {
const [url, setUrl] = useState(provider === 'compatible' ? localServerAddress : '');
const [key, setKey] = useState('');
return (
<form
@@ -393,7 +399,7 @@ function ServerForm({ c }: { c: Connect }) {
noValidate
onSubmit={(event) => {
event.preventDefault();
void c.save('compatible', key, noKeySettings, url).then((saved) => saved && setKey(''));
void c.save(provider, key, noKeySettings, url).then((saved) => saved && setKey(''));
}}
>
<label className="ob-brain-label" htmlFor="ob-brain-url">
@@ -405,7 +411,7 @@ function ServerForm({ c }: { c: Connect }) {
autoComplete="off"
spellCheck={false}
maxLength={2000}
placeholder={localServerAddress}
placeholder={provider === 'compatible' ? localServerAddress : 'http://localhost:8080'}
autoFocus
value={url}
disabled={c.checking}
@@ -418,7 +424,9 @@ function ServerForm({ c }: { c: Connect }) {
}}
/>
<p className="ob-brain-note ob-brain-server-hint" id="ob-brain-url-hint">
Ollama, LM Studio, vLLM or any OpenAI-compatible server.
{provider === 'compatible'
? 'Ollama, LM Studio, vLLM or any OpenAI-compatible server.'
: 'The address of your Bifrost gateway. I use its public price list to track spending.'}
</p>
<label className="ob-brain-label" htmlFor="ob-brain-server-key">
API key <span className="ob-brain-optional">optional</span>
@@ -486,7 +494,8 @@ function SignInFirst({ c, provider }: { c: Connect; provider: SignInProvider })
function Setup({ c, provider }: { c: Connect; provider: ModelProvider }) {
if (c.signingIn) return <Waiting c={c} />;
if (provider === 'compatible') return <ServerForm c={c} />;
if (provider === 'compatible' || provider === 'bifrost')
return <ServerForm c={c} provider={provider} />;
if (signsIn(provider)) return <SignInFirst c={c} provider={provider} />;
return <KeyForm c={c} provider={provider} autoFocus />;
}
@@ -510,7 +519,7 @@ function Connected({ c, onReconnect }: { c: Connect; onReconnect: () => void })
<p className="ob-brain-title">
{saved ? 'Key saved for ' : 'Connected to '}
<span data-analytics-private>
{source.provider === 'compatible' ? source.label : modelSource(source)}
{usesServerAddress(source.provider) ? source.label : modelSource(source)}
</span>
</p>
<p className="ob-brain-note">
@@ -552,7 +561,7 @@ function Connected({ c, onReconnect }: { c: Connect; onReconnect: () => void })
)}
{(source.status === 'loading' || missing) && (
<Button variant="ghost" disabled={c.locked} onClick={onReconnect}>
{source.provider === 'compatible'
{usesServerAddress(source.provider)
? 'Change server'
: source.method === 'api_key'
? 'Use another API key'
+49
View File
@@ -14025,6 +14025,55 @@ test('compatible servers offer the effort levels they publish for each model', a
);
});
test('Bifrost models take prices from the Bifrost price sheet for their own provider', async () => {
const price = (provider: string, input: number) => ({
provider,
input_cost_per_token: input,
output_cost_per_token: input * 5,
cache_read_input_token_cost: input / 10,
supports_vision: true,
});
let sheet: unknown = {
'claude-fable-5': price('anthropic', 1e-5),
'openrouter/anthropic/claude-fable-5': price('openrouter', 2e-5),
'gpt-4o': price('openai', 3e-6),
};
const fetch = async (input: string | URL | Request) => {
const url = new URL(new Request(input).url);
if (url.href === 'https://getbifrost.ai/datasheet') return Response.json(sheet);
assert.equal(url.pathname, '/v1/models');
return Response.json({
data: [
'anthropic/claude-fable-5',
'openrouter/anthropic/claude-fable-5',
'azure/gpt-4o',
'ollama/llama3',
].map((id) => ({ id, context_window: 200000 })),
});
};
const catalog = () =>
createPiModelBackend({ fetch: fetch as typeof globalThis.fetch }).catalog(
'bifrost',
'api_key',
{ type: 'endpoint', url: 'http://127.0.0.1:1/v1', key: 'sk-bf-synthetic' },
);
const costs = async () =>
Object.fromEntries(
(await catalog()).map((entry) => [
entry.choice.id,
[(entry.spec as { cost: { input: number } }).cost.input, entry.choice.images],
]),
);
assert.deepEqual(await costs(), {
'anthropic/claude-fable-5': [10, true],
'openrouter/anthropic/claude-fable-5': [20, true],
'azure/gpt-4o': [0, false],
'ollama/llama3': [0, false],
});
sheet = '<html>';
assert.deepEqual(Object.values(await costs()), Array(4).fill([0, false]));
});
test('new and saved Ollama models keep the effort value the server reads', async (t) => {
const original = globalThis.fetch;
t.after(() => (globalThis.fetch = original));