diff --git a/.env.example b/.env.example index a13fe798d..6908ca948 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/docs/src/content/docs/connect/local-models.mdx b/docs/src/content/docs/connect/local-models.mdx index 3b959efab..2a6d2e8c8 100644 --- a/docs/src/content/docs/connect/local-models.mdx +++ b/docs/src/content/docs/connect/local-models.mdx @@ -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 diff --git a/docs/src/content/docs/connect/models.mdx b/docs/src/content/docs/connect/models.mdx index 8bf39594b..ca7d51f8f 100644 --- a/docs/src/content/docs/connect/models.mdx +++ b/docs/src/content/docs/connect/models.mdx @@ -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. + + + + + +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**. + + + +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. + @@ -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. diff --git a/docs/src/content/docs/deploy/configuration.md b/docs/src/content/docs/deploy/configuration.md index b4d1ef77a..7603c5846 100644 --- a/docs/src/content/docs/deploy/configuration.md +++ b/docs/src/content/docs/deploy/configuration.md @@ -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. diff --git a/public/logos/models/NOTICE.txt b/public/logos/models/NOTICE.txt index ca3d650d1..8bc9c59f8 100644 --- a/public/logos/models/NOTICE.txt +++ b/public/logos/models/NOTICE.txt @@ -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. diff --git a/public/logos/models/bifrost.svg b/public/logos/models/bifrost.svg new file mode 100644 index 000000000..3869f2209 --- /dev/null +++ b/public/logos/models/bifrost.svg @@ -0,0 +1 @@ + diff --git a/src/providers/pi/models.ts b/src/providers/pi/models.ts index 669b5dc31..e934bc48b 100644 --- a/src/providers/pi/models.ts +++ b/src/providers/pi/models.ts @@ -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): Model { 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, 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 = credential.key ? { Authorization: `Bearer ${credential.key}` } : {}; const secrets = [credential.url, credential.key ?? '']; + const pendingPrices: Promise> = + 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), ]; }), @@ -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 | 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, diff --git a/src/server/composition.ts b/src/server/composition.ts index e6122d330..1dac9cfac 100644 --- a/src/server/composition.ts +++ b/src/server/composition.ts @@ -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 }), + }, + }), }, }; } diff --git a/src/server/models.ts b/src/server/models.ts index 4c4d9a69a..e421dc520 100644 --- a/src/server/models.ts +++ b/src/server/models.ts @@ -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) => { diff --git a/src/server/thread.ts b/src/server/thread.ts index 269c62126..8741a2220 100644 --- a/src/server/thread.ts +++ b/src/server/thread.ts @@ -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]; diff --git a/src/shared/feedback-activity.ts b/src/shared/feedback-activity.ts index 0005d5134..7953d236e 100644 --- a/src/shared/feedback-activity.ts +++ b/src/shared/feedback-activity.ts @@ -35,6 +35,7 @@ const providers = [ 'google-vertex', 'azure', 'compatible', + 'bifrost', 'other', ]; const methods = ['managed_app', 'browser', 'http', 'mcp', 'cli']; diff --git a/src/shared/model-keys.ts b/src/shared/model-keys.ts index 75155457f..670f588ba 100644 --- a/src/shared/model-keys.ts +++ b/src/shared/model-keys.ts @@ -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.'; diff --git a/src/shared/models.ts b/src/shared/models.ts index 3d4902148..58b995652 100644 --- a/src/shared/models.ts +++ b/src/shared/models.ts @@ -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; @@ -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' }, }; diff --git a/src/web/components/models.tsx b/src/web/components/models.tsx index f82e28ad5..297038c94 100644 --- a/src/web/components/models.tsx +++ b/src/web/components/models.tsx @@ -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> = { openai: 'models/openai', @@ -109,6 +110,7 @@ const modelProviderLogos: Partial> = { '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 (