Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: add magpie as a model provider (#21644)

Hardy7810497ce25f
diff --git a/apps/server/src/globalConfig/index.ts b/apps/server/src/globalConfig/index.ts
index e15e6b9c085..515bfdb158b 100644
--- a/apps/server/src/globalConfig/index.ts
+++ b/apps/server/src/globalConfig/index.ts
@@ -82,6 +82,9 @@ const getAiProviderSpecificConfig = () => {
lmstudio: {
fetchOnClient: getServerFetchOnClientOverride('lmstudio'),
},
+ magpie: {
+ fetchOnClient: getServerFetchOnClientOverride('magpie'),
+ },
ollama: {
enabled: isDesktop ? true : undefined,
fetchOnClient: getServerFetchOnClientOverride('ollama'),
diff --git a/apps/server/src/globalConfig/serverFetchOnClient.test.ts b/apps/server/src/globalConfig/serverFetchOnClient.test.ts
index 4be4e1cded1..87a38ab58a9 100644
--- a/apps/server/src/globalConfig/serverFetchOnClient.test.ts
+++ b/apps/server/src/globalConfig/serverFetchOnClient.test.ts
@@ -20,8 +20,15 @@ describe('getServerFetchOnClientOverride', () => {
expect(getServerFetchOnClientOverride('unsloth')).toBe(true);
});
+ it('sends magpie from the browser unless the deployment reaches another one', () => {
+ expect(getServerFetchOnClientOverride('magpie')).toBe(true);
+
+ vi.stubEnv('MAGPIE_PROXY_URL', 'http://magpie.internal:3425');
+ expect(getServerFetchOnClientOverride('magpie')).toBe(false);
+ });
+
// The settings switch shows this default; it must match what the relay does.
- it.each(['ollama', 'lmstudio', 'unsloth'])(
+ it.each(['magpie', 'ollama', 'lmstudio', 'unsloth'])(
'shows the same default for %s as the relay applies',
(provider) => {
const fetchOnClient = getServerFetchOnClientOverride(provider);
diff --git a/apps/server/src/globalConfig/serverFetchOnClient.ts b/apps/server/src/globalConfig/serverFetchOnClient.ts
index f01e90f6947..51ca3d53b9b 100644
--- a/apps/server/src/globalConfig/serverFetchOnClient.ts
+++ b/apps/server/src/globalConfig/serverFetchOnClient.ts
@@ -10,6 +10,12 @@ import { isDesktop } from '@/const/version';
* - On the web, local providers run on this device (the relay sends them to the
* tab), so the settings switch must show them on rather than unset.
* - A deployment with `OLLAMA_PROXY_URL` proxies Ollama through the server.
+ * - magpie is a desktop app on the user's own machine, answering on
+ * `127.0.0.1:3425`, and a hosted LobeHub cannot reach that from its server, so
+ * the browser sends the requests. A deployment that reaches a magpie
+ * elsewhere sets `MAGPIE_PROXY_URL` and the server sends them instead, which
+ * is what a magpie in Docker or on another host needs: it refuses a preflight
+ * that carries no key, which is the only kind a browser sends.
*/
export const getServerFetchOnClientOverride = (provider: string): boolean | undefined => {
switch (provider) {
@@ -17,6 +23,9 @@ export const getServerFetchOnClientOverride = (provider: string): boolean | unde
case 'unsloth': {
return !isDesktop;
}
+ case 'magpie': {
+ return isDesktop ? false : !process.env.MAGPIE_PROXY_URL;
+ }
case 'ollama': {
return isDesktop ? false : !process.env.OLLAMA_PROXY_URL;
}
diff --git a/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts b/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts
index 9375562bd93..9989c3b3733 100644
--- a/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts
+++ b/apps/server/src/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite.ts
@@ -48,8 +48,9 @@ export interface ResolveProviderRelayParams {
* Whether calls to `provider` must run on the user's device, i.e. be relayed:
* the relay is on for the user, the provider is not platform-owned, and the
* shared `fetchOnClient` rule — the one the client store applies, on the
- * user's config with this deployment's override (desktop, `OLLAMA_PROXY_URL`)
- * as the default — sends it to the device. `undefined` keeps it on the server.
+ * user's config with this deployment's override (desktop, `OLLAMA_PROXY_URL`,
+ * `MAGPIE_PROXY_URL`) as the default — sends it to the device. `undefined` keeps
+ * it on the server.
*/
export const resolveProviderRelay = async ({
db,
diff --git a/docs/self-hosting/environment-variables/model-provider.mdx b/docs/self-hosting/environment-variables/model-provider.mdx
index a61be392515..23ccc2ee80f 100644
--- a/docs/self-hosting/environment-variables/model-provider.mdx
+++ b/docs/self-hosting/environment-variables/model-provider.mdx
@@ -909,4 +909,13 @@ Connect to your own Unsloth Studio instance. See [Using Unsloth in LobeHub](/doc
- Default: Unset; uses the built-in example model list with the examples disabled. This does not guarantee local availability or change existing saved model selections.
- Example: `-all,+your-local-model-id=Local Model`
+## magpie
+
+### `MAGPIE_PROXY_URL`
+
+- Type: Optional
+- Description: The magpie gateway address the server sends requests to, and with it the switch that stops the browser from sending them. Leave it unset when magpie runs on the user's own machine: the browser reaches `127.0.0.1:3425`, which a hosted deployment's server cannot. Set it when magpie runs where the server can reach it: a container, another host, or behind a proxy. A browser cannot reach those directly, because magpie refuses a preflight that carries no gateway key and the browser never sends one.
+- Default: Unset; the browser sends the requests.
+- Example: `http://magpie.example.com:3425/v1`
+
[model-list]: /docs/self-hosting/advanced/model-list
diff --git a/docs/usage/providers/magpie.mdx b/docs/usage/providers/magpie.mdx
new file mode 100644
index 00000000000..719fc577795
--- /dev/null
+++ b/docs/usage/providers/magpie.mdx
@@ -0,0 +1,135 @@
+---
+title: Using magpie in LobeHub
+description: Configure a magpie gateway and choose the request mode that fits how it is deployed.
+tags:
+ - LobeHub
+ - magpie
+ - Model gateway
+ - Routing groups
+---
+
+# Using magpie in LobeHub
+
+[magpie](https://usemagpie.ai) is a model gateway. The subscriptions, keys, local models and routing groups you set up there are served on one endpoint, with every model exposed as `provider/model`.
+
+This guide walks through using magpie in LobeHub:
+
+<Steps>
+ ### Step 1: Install and start magpie
+
+ Download the desktop app from [usemagpie.ai](https://usemagpie.ai), or run it in Docker:
+
+ ```bash
+ docker run -d --name magpie \
+ --network host \
+ -e MAGPIE_ADDR=127.0.0.1:3425 \
+ -v magpie-config:/config \
+ ghcr.io/yetone/magpie:latest
+ ```
+
+ The gateway listens on `127.0.0.1:3425` by default.
+
+ ### Step 2: Add an upstream provider
+
+ Add a provider in magpie's interface, or from a terminal:
+
+ ```bash
+ magpie provider add deepseek sk-...
+ ```
+
+ List the models it serves:
+
+ ```bash
+ magpie models
+ ```
+
+ ### Step 3: Create a gateway key
+
+ Calls from another process need a gateway key:
+
+ ```bash
+ magpie gateway-key add "LobeHub"
+ ```
+
+ Keep the `sk-magpie-key-...` it prints for the next step. The full value lives in `~/.config/magpie/caller-keys.json`; the list command shows a masked form.
+
+ ### Step 4: Configure LobeHub
+
+ Open **Settings → AI Provider** and find `magpie`:
+
+ - **API Key**: the gateway key from the previous step
+ - **API Proxy URL**: the gateway address, for example `http://127.0.0.1:3425/v1`
+ - Click **Fetch Models** to read the catalogue magpie serves
+ - Enable the models you want
+
+ <Callout type={'info'}>
+ magpie returns ids shaped like `provider/model` (such as `deepseek/deepseek-chat`). A routing group comes as `group/<id>` when you made it, or `auto/<model>` when magpie found it; both carry the routing badge.
+ </Callout>
+</Steps>
+
+## Where the request leaves from
+
+LobeHub can send model requests to magpie two ways. Which one works is not a matter of a switch; it depends on whether magpie is reachable from whoever sends the request.
+
+### From the browser
+
+Turning on **Client request mode** in the provider settings sends model requests from the browser.
+
+This works in exactly one situation: **magpie runs directly on the same machine as the browser**. There the connection arrives from `127.0.0.1`, which is what makes magpie's cross-origin handling apply at all.
+
+### From the server
+
+When the server sends the request, credentials stay there and the browser plays no part in the model call, so cross-origin rules do not apply. magpie only has to be reachable from LobeHub's server.
+
+### Why browser access is so narrow
+
+magpie asks every caller for an enabled gateway key. A browser's preflight request carries none by specification, so magpie refuses it before cross-origin handling runs.
+
+magpie skips that key requirement only for connections arriving from `127.0.0.1`. In all of these cases the connection arrives from somewhere else, and the browser cannot reach magpie at all:
+
+- Docker port mapping, which rewrites the source to a bridge address
+- LAN access, where the source is the other machine's LAN address
+- Remote or public access, where the source is the other machine's public address
+
+`MAGPIE_TRUST_PROXY=1` does not change this; it only affects forwarding-header handling. `--network host` with `127.0.0.1` does keep the source on loopback, but that is equivalent to running magpie directly on the host network.
+
+### How to choose
+
+| Where magpie runs | Client request mode | Address to use |
+| --------------------------------------------- | ------------------- | ---------------------------------------- |
+| Same machine as the browser, running directly | Works | `http://127.0.0.1:3425/v1` |
+| Same machine, Docker with port mapping | Does not work | |
+| Same machine, Docker with `--network host` | Works | `http://127.0.0.1:3425/v1` |
+| Another machine on the LAN | Does not work | Server request, if the server reaches it |
+| Remote or public host | Does not work | Server request, if the server reaches it |
+
+<Callout type={'warning'}>
+ On a hosted service such as `app.lobehub.com`, LobeHub's server cannot reach a user's `127.0.0.1`. So a magpie on the user's own machine needs client request mode, and a magpie anywhere else needs an address the LobeHub server can reach.
+
+ On a self-hosted deployment that wants every magpie request to leave from the server, set `MAGPIE_PROXY_URL`; the default for client request mode follows and turns off.
+</Callout>
+
+### What client request mode needs, in full
+
+1. magpie on the same machine as the browser, running directly (not Docker port mapping, not the LAN, not remote)
+2. **Client request mode** turned on in the provider settings
+3. LobeHub's address added under **Network and sharing → Web pages allowed to call magpie**, for example `http://localhost:3000`
+4. The complete gateway key from `magpie gateway-key add` in the **API Key** field
+
+Step 3 cannot be skipped: even from this machine, a page needs a key, and only a listed origin receives the cross-origin response headers.
+
+## Troubleshooting
+
+**Fetching models fails and the console reports a cross-origin block**
+
+magpie did not return cross-origin headers. Make sure magpie runs on the same machine as the browser and is reached over `127.0.0.1`, and add LobeHub's address to the allowed pages; otherwise send the requests from the server over an address LobeHub can reach.
+
+**It asks for a gateway key**
+
+magpie requires every caller to present an enabled gateway key. Check that the API Key field holds the complete key from `magpie gateway-key add`.
+
+**A chat request returns 401**
+
+The key is not enabled or is wrong. Check its state with `magpie gateway-key list`; the full key is in `~/.config/magpie/caller-keys.json`.
+
+You can now chat with magpie's models in LobeHub.
diff --git a/docs/usage/providers/magpie.zh-CN.mdx b/docs/usage/providers/magpie.zh-CN.mdx
new file mode 100644
index 00000000000..76bcc6cf657
--- /dev/null
+++ b/docs/usage/providers/magpie.zh-CN.mdx
@@ -0,0 +1,135 @@
+---
+title: 在 LobeHub 中使用 magpie
+description: 学习如何配置 magpie 网关,并根据 magpie 的部署方式选择合适的请求模式。
+tags:
+ - LobeHub
+ - magpie
+ - 模型网关
+ - 路由组
+---
+
+# 在 LobeHub 中使用 magpie
+
+[magpie](https://usemagpie.ai) 是一个模型网关。你在其中接入的订阅、密钥、本地模型与路由组,都由同一个入口提供服务,模型统一以 `provider/model` 的形式暴露。
+
+本文档将指导你如何在 LobeHub 中使用 magpie:
+
+<Steps>
+ ### 步骤一:安装并启动 magpie
+
+ 前往 [magpie 官网](https://usemagpie.ai) 下载桌面版,或使用 Docker 部署:
+
+ ```bash
+ docker run -d --name magpie \
+ --network host \
+ -e MAGPIE_ADDR=127.0.0.1:3425 \
+ -v magpie-config:/config \
+ ghcr.io/yetone/magpie:latest
+ ```
+
+ magpie 网关默认监听 `127.0.0.1:3425`。
+
+ ### 步骤二:添加上游服务商
+
+ 在 magpie 界面中添加你要使用的服务商,或通过命令行:
+
+ ```bash
+ magpie provider add deepseek sk-...
+ ```
+
+ 添加完成后可以查看可用模型:
+
+ ```bash
+ magpie models
+ ```
+
+ ### 步骤三:创建网关密钥
+
+ 从其他进程调用 magpie 时需要网关密钥:
+
+ ```bash
+ magpie gateway-key add "LobeHub"
+ ```
+
+ 记下输出的 `sk-magpie-key-...`,下一步会用到。密钥完整值保存在 `~/.config/magpie/caller-keys.json`,列表命令只显示掩码。
+
+ ### 步骤四:在 LobeHub 中配置
+
+ 打开 **应用设置 → AI 服务商**,找到 `magpie`:
+
+ - **API Key** 填入上一步创建的网关密钥
+ - **API 代理地址** 填入 magpie 的地址,例如 `http://127.0.0.1:3425/v1`
+ - 点击 **获取模型列表**,LobeHub 会读取 magpie 提供的模型
+ - 启用需要的模型
+
+ <Callout type={'info'}>
+ magpie 返回的模型 id 形如 `provider/model`(例如 `deepseek/deepseek-chat`)。路由组有两种 id:自建组是 `group/<id>`,magpie 自动发现的是 `auto/<model>`,两者都会显示路由标记。
+ </Callout>
+</Steps>
+
+## 请求从哪里发出
+
+LobeHub 把模型请求送到 magpie,有两条路径。走哪条不取决于某个开关,而取决于 magpie 本身能不能被发起方访问到。
+
+### 浏览器直接请求
+
+服务商设置里的 **使用客户端请求模式** 打开后,模型请求从浏览器发出。
+
+这条路只在一种情况下成立:**magpie 与浏览器在同一台机器上,并且是直接运行的**。此时 magpie 收到的连接来自 `127.0.0.1`,它的跨域处理才会生效。
+
+### 服务端请求
+
+服务端请求时,凭据留在服务端,浏览器不参与模型调用,因此不受跨域限制。magpie 只需要能被 LobeHub 的服务端访问到。
+
+### 为什么浏览器直连的要求这么窄
+
+magpie 要求每个调用方携带一个已启用的网关密钥。浏览器发出的预检请求按规范不带密钥,所以 magpie 会先拒绝它,请求到不了跨域处理这一步。
+
+magpie 只对来自 `127.0.0.1` 的连接跳过这道密钥要求。下面这些情况,连接来源都不是 `127.0.0.1`,浏览器直连一律不可用:
+
+- Docker 的端口映射,来源被改写成网桥地址
+- 局域网访问,来源是对方的局域网地址
+- 远程或公网访问,来源是对方的公网地址
+
+`MAGPIE_TRUST_PROXY=1` 不改变这个判断,它只影响转发头的处理。`--network host` 加 `127.0.0.1` 能让来源保持 loopback,但这等于 magpie 直接跑在宿主机网络上。
+
+### 怎么选
+
+| magpie 运行位置 | 客户端请求模式 | 实际可达的配置 |
+| ----------------------------- | ------- | -------------------------- |
+| 与浏览器同一台机器,直接运行 | 可用 | `http://127.0.0.1:3425/v1` |
+| 同一台机器,Docker 端口映射 | 不可用 | |
+| 同一台机器,Docker `--network host` | 可用 | `http://127.0.0.1:3425/v1` |
+| 局域网内另一台机器 | 不可用 | 服务端可达时,可以使用服务端请求 |
+| 远程或公网 | 不可用 | 服务端可达时,可以使用服务端请求 |
+
+<Callout type={'warning'}>
+ 在 `app.lobehub.com` 这类托管服务上,LobeHub 的服务端连不到用户的 `127.0.0.1`。因此 magpie 跑在用户本机时,只能靠客户端请求模式;magpie 跑在别处时,需要一个 LobeHub 服务端能访问到的地址。
+
+ 自部署时如果希望 magpie 的请求一律从服务端发出,设置环境变量 `MAGPIE_PROXY_URL`,客户端请求模式的默认值会随之关闭。
+</Callout>
+
+### 开启客户端请求模式的完整条件
+
+1. magpie 与本机浏览器同机,且直接运行(非 Docker 端口映射,非局域网,非远程)
+2. 服务商设置里打开 **使用客户端请求模式**
+3. magpie 的 **网络与共享 → 允许调用 magpie 的网页** 里加入 LobeHub 的地址,例如 `http://localhost:3000`
+4. **API Key** 填入 `magpie gateway-key add` 生成的完整网关密钥
+
+第 3 条不可省略:即使连接来自本机,白名单页面也需要密钥,且只有列入白名单的来源才能读到跨域响应头。
+
+## 常见问题
+
+**模型列表拉取失败,控制台提示跨域被拦截**
+
+magpie 没有返回跨域响应头。确认 magpie 与浏览器同机、通过 `127.0.0.1` 访问,并把 LobeHub 地址加入允许列表;否则改用服务端请求,地址填 LobeHub 服务端能访问到的那个。
+
+**提示需要网关密钥**
+
+magpie 要求每个调用方携带一个已启用的网关密钥。确认 API Key 字段填的是 `magpie gateway-key add` 生成的完整密钥。
+
+**对话请求返回 401**
+
+密钥未启用或填错。用 `magpie gateway-key list` 查看状态,完整密钥在 `~/.config/magpie/caller-keys.json`。
+
+至此你已经可以在 LobeHub 中使用 magpie 的模型进行对话了。
diff --git a/locales/en-US/components.json b/locales/en-US/components.json
index 6a099865b2e..cc91fac3d01 100644
--- a/locales/en-US/components.json
+++ b/locales/en-US/components.json
@@ -148,6 +148,8 @@
"ModelSelect.featureTag.video": "This model supports video recognition",
"ModelSelect.featureTag.vision": "This model supports visual recognition.",
"ModelSelect.removed": "The model is not in the list. It will be automatically removed if deselected.",
+ "ModelSelect.routing": "Routing",
+ "ModelSelect.routingTooltip": "A routing group: several providers serve this model, and each request goes to whichever answers.",
"ModelSelect.staleModel.current": "Current selection",
"ModelSelect.staleModel.notEnabled.action": "Enable this model",
"ModelSelect.staleModel.notEnabled.actionFailed": "Failed to enable the model. Please try again.",
diff --git a/locales/en-US/providers.json b/locales/en-US/providers.json
index 4df34ce21d1..f529b4c8a70 100644
--- a/locales/en-US/providers.json
+++ b/locales/en-US/providers.json
@@ -37,6 +37,7 @@
"lmstudio.description": "LM Studio is a desktop app for developing and experimenting with LLMs on your computer.",
"lobehub.description": "LobeHub Cloud uses official APIs to access AI models and measures usage with Credits tied to model tokens.",
"longcat.description": "LongCat is a series of generative AI large models independently developed by Meituan. It is designed to enhance internal enterprise productivity and enable innovative applications through an efficient computational architecture and strong multimodal capabilities.",
+ "magpie.description": "magpie is an LLM gateway: the subscriptions, keys, local models and routing groups you set up there are all served on one endpoint.",
"meta.description": "Meta builds AI models and products that help people connect, create, and get things done, including the Llama and Muse model families.",
"minimax.description": "Founded in 2021, MiniMax builds general-purpose AI with multimodal foundation models, including trillion-parameter MoE text models, speech models, and vision models, along with apps like Hailuo AI.",
"minimaxcodingplan.description": "MiniMax Token Plan provides access to MiniMax models including M2.7 for coding tasks via a fixed-fee subscription.",
diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.json
index 4c1f8971c1b..f250acbe560 100644
--- a/locales/zh-CN/components.json
+++ b/locales/zh-CN/components.json
@@ -148,6 +148,8 @@
"ModelSelect.featureTag.video": "该模型支持视频识别",
"ModelSelect.featureTag.vision": "该模型支持视觉识别",
"ModelSelect.removed": "该模型不在列表中,若取消选中将会自动移除",
+ "ModelSelect.routing": "路由",
+ "ModelSelect.routingTooltip": "路由组:多个渠道提供同一模型,每次请求交给率先响应的那个",
"ModelSelect.staleModel.current": "当前配置",
"ModelSelect.staleModel.notEnabled.action": "启用此模型",
"ModelSelect.staleModel.notEnabled.actionFailed": "启用模型失败,请重试",
diff --git a/locales/zh-CN/providers.json b/locales/zh-CN/providers.json
index dc0fe723b22..bee8b76318a 100644
--- a/locales/zh-CN/providers.json
+++ b/locales/zh-CN/providers.json
@@ -37,6 +37,7 @@
"lmstudio.description": "LM Studio 是一款桌面应用,支持在本地开发与实验大语言模型。",
"lobehub.description": "LobeHub Cloud 通过官方 API 接入 AI 模型,并按模型令牌用量消耗积分。",
"longcat.description": "LongCat 是由美团自主研发的生成式 AI 大模型系列,旨在通过高效的计算架构和强大的多模态能力,提升企业内部工作效率并推动创新应用的发展。",
+ "magpie.description": "magpie 是一个 LLM 网关:你在其中接入的订阅、密钥、本地模型与路由组,都由同一个入口提供服务。",
"meta.description": "Meta 构建 AI 模型与产品,帮助人们交流、创作和完成任务,旗下包括 Llama 和 Muse 模型系列。",
"minimax.description": "MiniMax 成立于 2021 年,致力于构建通用 AI,拥有多模态基础模型,包括万亿参数的 MoE 文本模型、语音模型与视觉模型,并推出海螺 AI 等应用。",
"minimaxcodingplan.description": "MiniMax Token Plan 提供对 MiniMax 模型(包括 M2.7)的访问,适用于编程任务,采用固定月费订阅模式。",
diff --git a/package.json b/package.json
index 3f5a648cb39..a7a046479e8 100644
--- a/package.json
+++ b/package.json
@@ -327,7 +327,7 @@
"@lobehub/charts": "^6.0.0",
"@lobehub/desktop-ipc-typings": "workspace:*",
"@lobehub/editor": "^6.0.0",
- "@lobehub/icons": "^6.7.0",
+ "@lobehub/icons": "^6.13.0",
"@lobehub/market-sdk": "0.43.0",
"@lobehub/ui": "^6.9.0",
"@modelcontextprotocol/sdk": "^1.32.1",
diff --git a/packages/locales/src/default/components.ts b/packages/locales/src/default/components.ts
index 35f03a7343a..2a45fb9be88 100644
--- a/packages/locales/src/default/components.ts
+++ b/packages/locales/src/default/components.ts
@@ -169,6 +169,9 @@ export default {
'This model supports up to {{tokens}} tokens in a single session.',
'ModelSelect.featureTag.video': 'This model supports video recognition',
'ModelSelect.featureTag.vision': 'This model supports visual recognition.',
+ 'ModelSelect.routing': 'Routing',
+ 'ModelSelect.routingTooltip':
+ 'A routing group: several providers serve this model, and each request goes to whichever answers.',
'ModelSelect.removed':
'The model is not in the list. It will be automatically removed if deselected.',
'ModelSelect.staleModel.current': 'Current selection',
diff --git a/packages/model-bank/package.json b/packages/model-bank/package.json
index 6b6277cf6c4..1184e801cbd 100644
--- a/packages/model-bank/package.json
+++ b/packages/model-bank/package.json
@@ -49,6 +49,7 @@
"./kimiCodingPlan": "./src/aiModels/kimiCodingPlan.ts",
"./lmstudio": "./src/aiModels/lmstudio.ts",
"./longcat": "./src/aiModels/longcat.ts",
+ "./magpie": "./src/aiModels/magpie.ts",
"./meta": "./src/aiModels/meta.ts",
"./minimax": "./src/aiModels/minimax.ts",
"./minimaxCodingPlan": "./src/aiModels/minimaxCodingPlan.ts",
diff --git a/packages/model-bank/src/aiModels/index.ts b/packages/model-bank/src/aiModels/index.ts
index 921332f1a5a..85ce1300090 100644
--- a/packages/model-bank/src/aiModels/index.ts
+++ b/packages/model-bank/src/aiModels/index.ts
@@ -38,6 +38,7 @@ import { default as jina } from './jina';
import { default as kimicodingplan } from './kimiCodingPlan';
import { default as lmstudio } from './lmstudio';
import { default as longcat } from './longcat';
+import { default as magpie } from './magpie';
import { default as meta } from './meta';
import { default as minimax } from './minimax';
import { default as minimaxcodingplan } from './minimaxCodingPlan';
@@ -151,6 +152,7 @@ const staticModelMap: ModelsMap = {
kimicodingplan,
lmstudio,
longcat,
+ magpie,
meta,
minimax,
minimaxcodingplan,
@@ -270,6 +272,7 @@ export { default as jina } from './jina';
export { default as kimicodingplan } from './kimiCodingPlan';
export { default as lmstudio } from './lmstudio';
export { default as longcat } from './longcat';
+export { default as magpie } from './magpie';
export { default as meta } from './meta';
export { default as minimax } from './minimax';
export { default as minimaxcodingplan } from './minimaxCodingPlan';
diff --git a/packages/model-bank/src/aiModels/magpie.ts b/packages/model-bank/src/aiModels/magpie.ts
new file mode 100644
index 00000000000..ac963da6899
--- /dev/null
+++ b/packages/model-bank/src/aiModels/magpie.ts
@@ -0,0 +1,11 @@
+import type { AIChatModelCard } from '../types/aiModel';
+
+// magpie serves the models its user has: subscriptions, API keys, local models
+// and routing groups, each with the id magpie gives it. The list is the user's
+// own, so it is fetched from the gateway's /v1/models and nothing is predefined
+// here.
+const magpieChatModels: AIChatModelCard[] = [];
+
+export const allModels = [...magpieChatModels];
+
+export default allModels;
diff --git a/packages/model-bank/src/const/modelProvider.ts b/packages/model-bank/src/const/modelProvider.ts
index 1b7a5581ed3..e8922d9d6ab 100644
--- a/packages/model-bank/src/const/modelProvider.ts
+++ b/packages/model-bank/src/const/modelProvider.ts
@@ -37,6 +37,7 @@ export enum ModelProvider {
LMStudio = 'lmstudio',
LobeHub = 'lobehub',
LongCat = 'longcat',
+ Magpie = 'magpie',
Meta = 'meta',
Minimax = 'minimax',
MinimaxCodingPlan = 'minimaxcodingplan',
diff --git a/packages/model-bank/src/modelProviders/index.ts b/packages/model-bank/src/modelProviders/index.ts
index a7d7db68b8f..3c237e168ac 100644
--- a/packages/model-bank/src/modelProviders/index.ts
+++ b/packages/model-bank/src/modelProviders/index.ts
@@ -39,6 +39,7 @@ import KimiCodingPlanProvider from './kimiCodingPlan';
import LMStudioProvider from './lmstudio';
import LobeHubProvider from './lobehub';
import LongCatProvider from './longcat';
+import MagpieProvider from './magpie';
import MetaProvider from './meta';
import MinimaxProvider from './minimax';
import MinimaxCodingPlanProvider from './minimaxCodingPlan';
@@ -231,6 +232,7 @@ export const DEFAULT_MODEL_PROVIDER_LIST = [
OpenCodeCodingPlanProvider,
StraicoProvider,
LongCatProvider,
+ MagpieProvider,
StreamLakeProvider,
AntGroupProvider,
];
@@ -250,8 +252,12 @@ export const isProviderDisableBrowserRequest = (id: string) => {
* Providers that run on the user's own machine: requests leave from the device
* unless `fetchOnClient` says otherwise (a desktop app or a deployment that
* proxies them sets it to `false`).
+ *
+ * magpie belongs here for the same reason: the user runs it, and it answers on
+ * `127.0.0.1`. A deployment that reaches one elsewhere sets `MAGPIE_PROXY_URL`,
+ * which arrives as `fetchOnClient: false` and keeps the requests on the server.
*/
-const LOCAL_FETCH_ON_CLIENT_PROVIDERS = new Set(['lmstudio', 'ollama', 'unsloth']);
+const LOCAL_FETCH_ON_CLIENT_PROVIDERS = new Set(['lmstudio', 'magpie', 'ollama', 'unsloth']);
export interface ProviderFetchOnClientConfig {
/** The user's choice, else the deployment's override for the provider. */
@@ -265,7 +271,7 @@ export interface ProviderFetchOnClientConfig {
* server never relays a call the client did not prepare for (or the reverse).
*
* 1. A provider that disables browser requests always runs on the server.
- * 2. Local providers (Ollama / LM Studio / Unsloth) follow `fetchOnClient`, default the device.
+ * 2. Local providers (magpie / Ollama / LM Studio / Unsloth) follow `fetchOnClient`, default the device.
* 3. Neither a base URL nor an API key: the server's own configuration.
* 4. Only a base URL: an endpoint the server may not reach, so the device.
* 5. Otherwise `fetchOnClient`, default the server.
@@ -337,6 +343,7 @@ export { default as KimiCodingPlanProviderCard } from './kimiCodingPlan';
export { default as LMStudioProviderCard } from './lmstudio';
export { default as LobeHubProviderCard } from './lobehub';
export { default as LongCatProviderCard } from './longcat';
+export { default as MagpieProviderCard } from './magpie';
export { default as MetaProviderCard } from './meta';
export { default as MinimaxProviderCard } from './minimax';
export { default as MinimaxCodingPlanProviderCard } from './minimaxCodingPlan';
diff --git a/packages/model-bank/src/modelProviders/magpie.ts b/packages/model-bank/src/modelProviders/magpie.ts
new file mode 100644
index 00000000000..0cb59fddfbe
--- /dev/null
+++ b/packages/model-bank/src/modelProviders/magpie.ts
@@ -0,0 +1,34 @@
+import type { ModelProviderCard } from '../types';
+
+// magpie is an LLM gateway: every model the user has in magpie —
+// subscriptions, API keys, local models, routing groups — is served there under
+// one id each, so this is one provider entry rather than one per vendor.
+//
+// The model list is the user's own configuration, so it is never shipped here:
+// `chatModels` stays empty and the catalog comes from the gateway's /v1/models.
+// See https://usemagpie.ai/docs/integrate
+const Magpie: ModelProviderCard = {
+ chatModels: [],
+ description:
+ 'magpie is an LLM gateway: every model and subscription you have there is served on one endpoint.',
+ id: 'magpie',
+ name: 'magpie',
+ settings: {
+ // magpie is a desktop app on the user's own machine, so on the web the
+ // browser sends the requests and the switch starts on; it is offered either
+ // way, and a deployment reaching a magpie elsewhere sets `MAGPIE_PROXY_URL`
+ // to have the server send them instead.
+ defaultShowBrowserRequest: true,
+ proxyUrl: {
+ // A base URL the user gives is used as it stands, `/v1` included, so the
+ // placeholder has to carry it.
+ placeholder: 'http://127.0.0.1:3425/v1',
+ },
+ sdkType: 'openai',
+ showModelFetcher: true,
+ supportResponsesApi: true,
+ },
+ url: 'https://usemagpie.ai',
+};
+
+export default Magpie;
diff --git a/packages/model-runtime/src/providers/magpie/index.test.ts b/packages/model-runtime/src/providers/magpie/index.test.ts
new file mode 100644
index 00000000000..9a7192e6212
--- /dev/null
+++ b/packages/model-runtime/src/providers/magpie/index.test.ts
@@ -0,0 +1,318 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+import OpenAI from 'openai';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { magpieModelKey, params } from './index';
+
+const model = (over: Record<string, any>) => ({ object: 'model', ...over });
+
+const serveModels = (data: any[]) => vi.fn().mockResolvedValue({ data, object: 'list' });
+
+describe('magpieModelKey', () => {
+ it('drops the provider prefix magpie puts on every id', () => {
+ expect(magpieModelKey('workbuddy/kimi-k3-1')).toBe('kimi-k3-1');
+ expect(magpieModelKey('anthropic/claude-opus-5.5')).toBe('claude-opus-5-5');
+ });
+
+ it('reads a version dot as magpie spells it, a dash', () => {
+ expect(magpieModelKey('kimi-k3.1')).toBe('kimi-k3-1');
+ expect(magpieModelKey('kimi-k2.7-code')).toBe('kimi-k2-7-code');
+ });
+
+ it('spells Fireworks p for a dot as a dash too', () => {
+ expect(magpieModelKey('deepseek-v4p1')).toBe('deepseek-v4-1');
+ });
+
+ it('keeps a letter after the digits, so gpt-4o keeps its name', () => {
+ expect(magpieModelKey('gpt-4o')).toBe('gpt-4o');
+ expect(magpieModelKey('openai/gpt-4o-mini')).toBe('gpt-4o-mini');
+ });
+
+ it('takes a vendor snapshot date off', () => {
+ expect(magpieModelKey('claude-opus-4-5-20251101')).toBe('claude-opus-4-5');
+ expect(magpieModelKey('glm-4.6@20250501')).toBe('glm-4-6');
+ });
+
+ it('reduces spaces and underscores to one dash', () => {
+ expect(magpieModelKey('GPT-6 Sol')).toBe('gpt-6-sol');
+ expect(magpieModelKey('some_model')).toBe('some-model');
+ });
+
+ it('reads the model of a routing group, by either id magpie gives one', () => {
+ expect(magpieModelKey('auto/claude-opus-5.5')).toBe('claude-opus-5-5');
+ expect(magpieModelKey('group/auto-claude-opus-5-5')).toBe('claude-opus-5-5');
+ });
+
+ it('drops every prefix, not just one', () => {
+ expect(magpieModelKey('remote/magpieai/openai/gpt-5.6-sol')).toBe('gpt-5-6-sol');
+ });
+});
+
+describe('params', () => {
+ it('registers as its own provider', () => {
+ expect(params.provider).toBe(ModelProvider.Magpie);
+ });
+
+ it('points at the gateway on the loopback port', () => {
+ expect(params.baseURL).toBe('http://127.0.0.1:3425/v1');
+ });
+
+ it('names LobeHub in the User-Agent the gateway counts callers by', () => {
+ const client = params.customClient!.createClient!({ apiKey: 'placeholder-to-avoid-error' });
+
+ expect(client).toBeInstanceOf(OpenAI);
+ // The SDK keeps its headers on the client it builds.
+ expect(client['_options']?.defaultHeaders?.['User-Agent']).toMatch(/^lobehub\//);
+ });
+
+ it('keeps a header it was handed, rather than overwriting it', () => {
+ const client = params.customClient!.createClient!({
+ apiKey: 'placeholder-to-avoid-error',
+ defaultHeaders: { 'X-Trace': 'kept' },
+ });
+
+ expect(client['_options']?.defaultHeaders?.['X-Trace']).toBe('kept');
+ });
+
+ it('turns debug output on only when asked', () => {
+ delete process.env.DEBUG_MAGPIE_CHAT_COMPLETION;
+ delete process.env.DEBUG_MAGPIE_RESPONSES;
+ expect(params.debug!.chatCompletion!()).toBe(false);
+ expect(params.debug!.responses!()).toBe(false);
+
+ process.env.DEBUG_MAGPIE_CHAT_COMPLETION = '1';
+ process.env.DEBUG_MAGPIE_RESPONSES = '1';
+ expect(params.debug!.chatCompletion!()).toBe(true);
+ expect(params.debug!.responses!()).toBe(true);
+
+ delete process.env.DEBUG_MAGPIE_CHAT_COMPLETION;
+ delete process.env.DEBUG_MAGPIE_RESPONSES;
+ });
+});
+
+describe('the model list magpie serves', () => {
+ let listModels: ReturnType<typeof serveModels>;
+
+ const load = async (data: any[]) => {
+ listModels = serveModels(data);
+ const client = { models: { list: listModels } } as any;
+
+ return params.models!({ client } as any);
+ };
+
+ beforeEach(() => {
+ listModels = serveModels([]);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('keeps the id magpie serves, so a request goes to the model it listed', async () => {
+ const cards = await load([
+ model({ id: 'workbuddy/kimi-k3-1', display_name: 'Kimi K3.1' }),
+ model({ id: 'openai/gpt-5.6-sol', display_name: 'GPT-5.6 Sol' }),
+ ]);
+
+ expect(cards.map((c) => c.id)).toEqual(['workbuddy/kimi-k3-1', 'openai/gpt-5.6-sol']);
+ });
+
+ it('takes magpie’s window over model-bank’s, the user being able to set it', async () => {
+ const cards = await load([model({ context_length: 400_000, id: 'anthropic/claude-opus-5.5' })]);
+
+ expect(cards[0].contextWindowTokens).toBe(400_000);
+ });
+
+ it('takes magpie’s reply limit as it is, having kept it within the window already', async () => {
+ const cards = await load([
+ model({ context_length: 200_000, id: 'openai/gpt-5.6-sol', max_output_tokens: 128_000 }),
+ ]);
+
+ expect(cards[0].maxOutput).toBe(128_000);
+ });
+
+ it('takes whether the model sees images from magpie, which the user can switch either way', async () => {
+ const sees = await load([
+ model({ id: 'openai/gpt-5.6-sol', modalities: { input: ['text', 'image'] } }),
+ ]);
+ expect(sees[0].vision).toBe(true);
+
+ const blind = await load([
+ model({ id: 'openai/gpt-5.6-sol', modalities: { input: ['text'] } }),
+ ]);
+ expect(blind[0].vision).toBe(false);
+ });
+
+ it('leaves vision unsaid for a model magpie says nothing about', async () => {
+ const cards = await load([model({ id: 'someone/unknown-model-x' })]);
+
+ expect(cards[0]).not.toHaveProperty('vision', true);
+ });
+
+ it('takes the reasoning levels magpie kept', async () => {
+ const cards = await load([
+ model({ id: 'openai/gpt-5.6-sol', reasoning_levels: ['low', 'high'] }),
+ ]);
+
+ expect(cards[0].reasoning).toBe(true);
+ });
+
+ it('keeps the user switching reasoning off, rather than model-bank’s answer', async () => {
+ const cards = await load([
+ // model-bank says kimi-k3 thinks; the user turned it off in magpie.
+ model({ id: 'moonshot/kimi-k3', reasoning: false }),
+ ]);
+
+ expect(cards[0].reasoning).toBe(false);
+ });
+
+ it('leaves reasoning to model-bank and the id when magpie says nothing', async () => {
+ const cards = await load([model({ id: 'somelab/experimental-llm-v0' })]);
+
+ expect(cards[0].reasoning).toBe(false);
+ });
+
+ it('reads tool calls from model-bank, which is the only one that says', async () => {
+ const cards = await load([model({ context_length: 1_000_000, id: 'moonshot/kimi-k3' })]);
+
+ expect(cards[0].functionCall).toBe(true);
+ });
+
+ it('takes the reasoning parameter from model-bank, which is what makes a level selectable', async () => {
+ const cards = await load([
+ model({ id: 'moonshot/kimi-k3', reasoning_levels: ['low', 'medium', 'high'] }),
+ ]);
+
+ // magpie's levels say the model thinks; the parameter that turns the
+ // strength differs by model family, and only model-bank names it.
+ expect(cards[0].reasoning).toBe(true);
+ expect(cards[0].settings?.extendParams).toEqual(['kimiK3ReasoningEffort']);
+ });
+
+ it('leaves the settings empty for a model model-bank does not know', async () => {
+ const cards = await load([model({ id: 'somelab/experimental-llm-v0' })]);
+
+ expect(cards[0].settings).toBeUndefined();
+ });
+
+ it('offers no thinking strength once the user turned thinking off in magpie', async () => {
+ const cards = await load([
+ model({ id: 'moonshot/kimi-k3', reasoning: false, reasoning_levels: ['low', 'high'] }),
+ ]);
+
+ // A level beside `reasoning: false` would let a choice be made that the
+ // gateway pushes back up to its lowest thinking level.
+ expect(cards[0].reasoning).toBe(false);
+ expect(cards[0].settings?.extendParams).toBeUndefined();
+ });
+
+ it('carries the params the vendor refuses, so the settings page hides them', async () => {
+ const cards = await load([model({ id: 'moonshot/kimi-k3' })]);
+
+ expect(cards[0].settings?.disabledParams).toEqual([
+ 'frequency_penalty',
+ 'presence_penalty',
+ 'temperature',
+ 'top_p',
+ ]);
+ });
+
+ it('reaches a model-bank entry through the dot magpie spells as a dash', async () => {
+ // `kimi-k3.1` is moonshot's; magpie serves it as `kimi-k3-1`.
+ const cards = await load([model({ id: 'workbuddy/kimi-k3-1' })]);
+
+ expect(cards[0].functionCall).toBeDefined();
+ });
+
+ it('reaches model-bank for a routing group too, the group serving that one model', async () => {
+ // A group magpie found for kimi-k3, under the id it hands out. Asserting the
+ // reasoning param rather than tool calls keeps this about the lookup: tool
+ // calls also come out true from the vendor keyword alone, so they pass
+ // whether or not model-bank was reached.
+ const cards = await load([model({ id: 'auto/kimi-k3' })]);
+
+ expect(cards[0].settings?.extendParams).toContain('kimiK3ReasoningEffort');
+ });
+
+ it('finds no model-bank entry for a group of the user’s own, leaving the settings empty', async () => {
+ const cards = await load([model({ id: 'group/my-fastest' })]);
+
+ expect(cards[0].settings).toBeUndefined();
+ });
+
+ it('takes the name alone, the tag saying what a group is', async () => {
+ const cards = await load([
+ model({
+ display_name: 'Claude Opus 5.5',
+ id: 'group/auto-claude-opus-5-5',
+ magpie_label: 'Claude Opus 5.5 · routing group',
+ }),
+ ]);
+
+ expect(cards[0].displayName).toBe('Claude Opus 5.5');
+ });
+
+ it('keeps a label that says nothing extra, having no ` · ` to cut', async () => {
+ const cards = await load([
+ model({ id: 'somelab/experimental-llm-v0', magpie_label: 'experimental-llm-v0' }),
+ ]);
+
+ expect(cards[0].displayName).toBe('experimental-llm-v0');
+ });
+
+ it('keeps the provider magpie puts after the name, two vendors serving one model', async () => {
+ const cards = await load([
+ model({
+ display_name: 'GPT-5.6 Sol',
+ id: 'openai/gpt-5.6-sol',
+ magpie_label: 'GPT-5.6 Sol · OpenAI',
+ }),
+ model({
+ display_name: 'GPT-5.6 Sol',
+ id: 'workbuddy/gpt-5.6-sol',
+ magpie_label: 'GPT-5.6 Sol · WorkBuddy',
+ }),
+ ]);
+
+ // Both rows sit under magpie, so the provider is the only thing telling the
+ // two apart in the picker.
+ expect(cards.map((c) => c.displayName)).toEqual([
+ 'GPT-5.6 Sol · OpenAI',
+ 'GPT-5.6 Sol · WorkBuddy',
+ ]);
+ });
+
+ it('lists a model once though magpie repeats its row', async () => {
+ const cards = await load([
+ model({ display_name: 'GPT-5.6 Sol', id: 'openai/gpt-5.6-sol' }),
+ model({ display_name: 'GPT-5.6 Sol', id: 'openai/gpt-5.6-sol' }),
+ ]);
+
+ expect(cards).toHaveLength(1);
+ });
+
+ it('drops the bare id magpie lists beside the model it names', async () => {
+ const cards = await load([
+ model({ display_name: 'GPT-5.6 Sol', id: 'openai/gpt-5.6-sol' }),
+ model({ display_name: 'GPT-5.6 Sol', id: 'gpt-5.6-sol' }),
+ ]);
+
+ expect(cards.map((c) => c.id)).toEqual(['openai/gpt-5.6-sol']);
+ });
+
+ it('keeps two providers serving one model apart, both ids carrying a prefix', async () => {
+ const cards = await load([
+ model({ display_name: 'GPT-5.6 Sol', id: 'openai/gpt-5.6-sol' }),
+ model({ display_name: 'GPT-5.6 Sol', id: 'cpa/gpt-5.6-sol' }),
+ ]);
+
+ expect(cards.map((c) => c.id)).toEqual(['openai/gpt-5.6-sol', 'cpa/gpt-5.6-sol']);
+ });
+
+ it('asks the gateway for its list once', async () => {
+ await load([model({ id: 'openai/gpt-5.6-sol' })]);
+
+ expect(listModels).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/model-runtime/src/providers/magpie/index.ts b/packages/model-runtime/src/providers/magpie/index.ts
new file mode 100644
index 00000000000..ba7427a3ec5
--- /dev/null
+++ b/packages/model-runtime/src/providers/magpie/index.ts
@@ -0,0 +1,284 @@
+import { CURRENT_VERSION } from '@lobechat/const';
+import type { ChatModelCard } from '@lobechat/types';
+import { loadModels, MODEL_REASONING_EXTEND_PARAMS, ModelProvider } from 'model-bank';
+import OpenAI from 'openai';
+
+import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatibleFactory';
+import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
+import { processMultiProviderModelList } from '../../utils/modelParse';
+
+type ModelSettings = NonNullable<ChatModelCard['settings']>;
+
+/** The params that set how hard a model thinks, which a `reasoning: false` card must not offer. */
+const REASONING_PARAMS = new Set<string>(MODEL_REASONING_EXTEND_PARAMS);
+
+/**
+ * One row of magpie's `GET /v1/models`.
+ *
+ * magpie serves every model the user has as `provider/model`, so an id is not
+ * the vendor's own: `workbuddy/kimi-k3-1`, a routing group's `group/<id>` or
+ * `auto/<model>`, and, with bare ids turned on, the model's name alone.
+ *
+ * The specs magpie can rewrite belong to magpie. Its window and reply limit
+ * come from the vendor's list or models.dev and then from what the user set;
+ * whether it takes images and which reasoning levels it has are the user's to
+ * override too. Everything magpie neither lists nor rewrites is read from
+ * model-bank.
+ */
+interface MagpieModelCard {
+ context_length?: number;
+ /** The user's name for the model, else the vendor's. */
+ display_name?: string;
+ id: string;
+ /** The model's name as magpie's own lists label it, `· provider` and all. */
+ magpie_label?: string;
+ max_input_tokens?: number;
+ max_output_tokens?: number;
+ modalities?: {
+ input?: string[];
+ output?: string[];
+ };
+ native_endpoints?: string[];
+ object?: string;
+ owned_by?: string;
+ pricing?: Record<string, unknown>;
+ /** A model thinks when it has levels, or says so. */
+ reasoning?: boolean;
+ reasoning_levels?: string[];
+ supported_reasoning_levels?: { effort: string }[];
+}
+
+const DEFAULT_BASE_URL = 'http://127.0.0.1:3425';
+
+/**
+ * A magpie id reduced to the key model-bank knows the model by, spelt as magpie
+ * spells one when it agrees on it (`internal/provider/group.go`'s `sameModel`):
+ * lowercased, without the vendor's or the routing group's prefix, a version's
+ * dot as a dash, whitespace, `_` and `-` as one dash, a vendor's snapshot date
+ * off.
+ */
+export const magpieModelKey = (id: string): string => {
+ let key = id.trim().toLowerCase();
+
+ // A routing group magpie found goes by two ids: `auto/<model>`, the one it
+ // hands out, and `group/auto-<slug>`, the one it keeps. The slug carries
+ // `auto-` before the model's name, which the model itself never does.
+ if (key.startsWith('group/auto-')) key = key.slice('group/auto-'.length);
+
+ const slash = key.lastIndexOf('/');
+ if (slash >= 0) key = key.slice(slash + 1);
+
+ key = key.replaceAll(/[\s_-]+/gu, '-');
+
+ // A version's dot, or Fireworks' `p` standing for one (`deepseek-v4p1`), as a
+ // dash. Only between two digits, so `gpt-4o` keeps its name and `kimi-k3.1`
+ // becomes `kimi-k3-1`, the id magpie serves that model under.
+ key = key.replaceAll(/(?<=\d)[.p](?=\d)/g, '-');
+
+ key = key.replace(/[-@]\d{8}$/, '');
+ key = key.replace(/[-@]\d{6}$/, '');
+
+ return key;
+};
+
+/** model-bank's entries, by the key a magpie id for one reduces to. */
+const buildModelBankIndex = async () => {
+ const index = new Map<string, any>();
+
+ for (const model of await loadModels()) {
+ const key = magpieModelKey(model.id);
+ if (key && !index.has(key)) index.set(key, model);
+ }
+
+ return index;
+};
+
+/**
+ * The model-bank entry for a magpie id, when one is the same model: matched on
+ * the name after the provider prefix, so `workbuddy/kimi-k3-1` reaches
+ * `kimi-k3.1`.
+ *
+ * A routing group reaches one too. `auto/kimi-k3.1` is the pool magpie found for
+ * the model of that name across the providers serving it, so what model-bank
+ * says of `kimi-k3.1` is what the group serves: it takes tool calls, it sees
+ * images. Only the id stays the group's, since that is what a request reaches.
+ */
+const findKnownModel = (
+ id: string,
+ index: Map<string, any>,
+ byId: Map<string, any>,
+): any | undefined => byId.get(id) ?? index.get(magpieModelKey(id));
+
+/**
+ * magpie's own fields for one model, laid over model-bank's.
+ *
+ * Only what magpie can rewrite is written here, since a field this card hands
+ * over wins over model-bank's. Tool calls are left to model-bank alone: magpie's
+ * list says nothing of them, and `false` would turn a model's tool calls off.
+ */
+const fromMagpie = (model: MagpieModelCard): Partial<ChatModelCard> => {
+ const contextWindow = model.context_length ?? model.max_input_tokens;
+
+ // magpie answers what a model takes; saying nothing is no answer, not `false`.
+ const takesImages = model.modalities?.input
+ ? model.modalities.input.includes('image')
+ : undefined;
+
+ // A model thinks when magpie says so, or when it kept reasoning levels for it.
+ // Its `false` is the user switching reasoning off, which must survive rather
+ // than fall back to model-bank's answer.
+ const levels = model.reasoning_levels ?? model.supported_reasoning_levels?.map((l) => l.effort);
+ const thinks =
+ model.reasoning === undefined ? (levels?.length ? true : undefined) : model.reasoning;
+
+ return {
+ displayName: plainName(model),
+ ...(contextWindow ? { contextWindowTokens: contextWindow } : {}),
+ ...(model.max_output_tokens ? { maxOutput: model.max_output_tokens } : {}),
+ ...(takesImages === undefined ? {} : { vision: takesImages }),
+ ...(thinks === undefined ? {} : { reasoning: thinks }),
+ };
+};
+
+/** What magpie appends to a routing group's label, which LobeHub says by its tag. */
+const ROUTING_GROUP_SUFFIX = ' · routing group';
+
+/**
+ * The name magpie gives a model, without the `· routing group` it appends: the
+ * tag says that, drawn from the id.
+ *
+ * A `· provider` suffix stays. Two vendors serving one model are both listed
+ * under magpie, so the row alone cannot tell them apart. Without the suffix the
+ * picker shows two entries of one name with nothing to choose between them.
+ */
+const plainName = (model: MagpieModelCard): string | undefined => {
+ const label = model.magpie_label;
+ if (!label) return model.display_name;
+
+ return label.endsWith(ROUTING_GROUP_SUFFIX)
+ ? label.slice(0, -ROUTING_GROUP_SUFFIX.length)
+ : label;
+};
+
+/**
+ * model-bank's settings for one model, limited to the parts magpie leaves unsaid.
+ *
+ * `reasoning_levels` says a model thinks, not which parameter turns the
+ * strength, and that parameter differs by model family (`gpt5_6ReasoningEffort`,
+ * `kimiK3ReasoningEffort`, …), so the one this entry names is what puts the
+ * choice in the chat settings at all.
+ *
+ * The reasoning params go when the user turned thinking off in magpie: the
+ * card says `reasoning: false`, and offering a strength beside it would let a
+ * choice be made for a model the gateway then pushes back up to its lowest
+ * thinking level.
+ *
+ * `disabledParams` hides controls the vendor refuses. It never reaches a
+ * request, since magpie drops what an upstream rejects, but the settings page
+ * would otherwise offer a slider that does nothing. `searchImpl` and
+ * `searchProvider` stay out: magpie's search is its own, not the vendor's
+ * way of implementing it.
+ */
+const knownSettings = (
+ known: any,
+ thinks: boolean | undefined,
+): Pick<ChatModelCard, 'settings'> => {
+ const extendParams: ModelSettings['extendParams'] = known?.settings?.extendParams;
+ const disabledParams: ModelSettings['disabledParams'] = known?.settings?.disabledParams;
+
+ const usable =
+ thinks === false ? extendParams?.filter((param) => !REASONING_PARAMS.has(param)) : extendParams;
+
+ if (!usable?.length && !disabledParams) return {};
+
+ return {
+ settings: {
+ ...(usable?.length ? { extendParams: usable } : {}),
+ ...(disabledParams ? { disabledParams } : {}),
+ },
+ };
+};
+
+/**
+ * What magpie serves, as model cards.
+ *
+ * The gateway's list is the only source: the models come and go with the
+ * providers the user turns on there, so nothing is shipped in the card and
+ * nothing is kept for a gateway that isn't running. model-bank fills what
+ * magpie leaves unsaid, so a model magpie lists without one still takes tool
+ * calls as its vendor's entry says.
+ */
+const fetchMagpieModels = async (client: OpenAI): Promise<ChatModelCard[]> => {
+ const response = await client.models.list();
+ const rows = (response.data as unknown as MagpieModelCard[]).filter((row) => !!row?.id);
+
+ const models = await loadModels();
+ const index = await buildModelBankIndex();
+ const byId = new Map(models.map((model) => [model.id, model]));
+
+ const prepared = rows.map((row) => {
+ const known = findKnownModel(row.id, index, byId);
+ const card = fromMagpie(row);
+
+ return {
+ id: row.id,
+ ...card,
+ // What magpie never says anything about, and only model-bank knows.
+ ...(known?.abilities?.functionCall === undefined
+ ? {}
+ : { functionCall: known.abilities.functionCall }),
+ // `card.reasoning` is magpie's own answer, so a model it reports as not
+ // thinking offers no strength to choose.
+ ...knownSettings(known, card.reasoning),
+ };
+ });
+
+ // magpie lists a model by its bare id too when the user asks for it, next to
+ // its `provider/model` row. The bare row names the same model, so the
+ // prefixed one is kept and the alias dropped. Two providers serving one model
+ // stay apart: their ids both carry a prefix.
+ const byName = new Set<string>();
+ for (const card of prepared) {
+ if (card.id.includes('/')) byName.add(card.id.slice(card.id.lastIndexOf('/') + 1));
+ }
+
+ const seen = new Set<string>();
+ const unique = prepared.filter((card) => {
+ if (seen.has(card.id)) return false;
+
+ // A bare id, when a prefixed row already names that model.
+ if (!card.id.includes('/') && byName.has(card.id)) return false;
+
+ seen.add(card.id);
+ return true;
+ });
+
+ return processMultiProviderModelList(unique, ModelProvider.Magpie);
+};
+
+export const params = {
+ apiKey: 'placeholder-to-avoid-error',
+ baseURL: `${DEFAULT_BASE_URL}/v1`,
+ customClient: {
+ // The gateway names the caller by its key (`magpie-<app>`) or else by its
+ // User-Agent. The OpenAI SDK builds one from its class name, which a
+ // minified build shortens to a single letter, so magpie would count
+ // LobeHub's calls under that letter.
+ createClient: (options: any) =>
+ new OpenAI({
+ ...options,
+ defaultHeaders: {
+ 'User-Agent': `lobehub/${CURRENT_VERSION}`,
+ ...options?.defaultHeaders,
+ },
+ }),
+ },
+ debug: {
+ chatCompletion: () => process.env.DEBUG_MAGPIE_CHAT_COMPLETION === '1',
+ responses: () => process.env.DEBUG_MAGPIE_RESPONSES === '1',
+ },
+ models: async ({ client }: { client: OpenAI }) => fetchMagpieModels(client),
+ provider: ModelProvider.Magpie,
+} satisfies OpenAICompatibleFactoryOptions;
+
+export const LobeMagpieAI = createOpenAICompatibleRuntime(params);
diff --git a/packages/model-runtime/src/runtimeMap.ts b/packages/model-runtime/src/runtimeMap.ts
index 2b66ae64709..c4b9d0a1a6c 100644
--- a/packages/model-runtime/src/runtimeMap.ts
+++ b/packages/model-runtime/src/runtimeMap.ts
@@ -36,6 +36,7 @@ import { LobeKimiCodingPlanAI } from './providers/kimiCodingPlan';
import { LobeLMStudioAI } from './providers/lmstudio';
import { LobeHubAI } from './providers/lobehub';
import { LobeLongCatAI } from './providers/longcat';
+import { LobeMagpieAI } from './providers/magpie';
import { LobeMetaAI } from './providers/meta';
import { LobeMinimaxAI } from './providers/minimax';
import { LobeMinimaxCodingPlanAI } from './providers/minimaxCodingPlan';
@@ -124,6 +125,7 @@ export const providerRuntimeMap = {
lmstudio: LobeLMStudioAI,
lobehub: LobeHubAI,
longcat: LobeLongCatAI,
+ magpie: LobeMagpieAI,
meta: LobeMetaAI,
minimax: LobeMinimaxAI,
minimaxcodingplan: LobeMinimaxCodingPlanAI,
diff --git a/src/components/ModelSelect/RoutingBadge.tsx b/src/components/ModelSelect/RoutingBadge.tsx
new file mode 100644
index 00000000000..4072a8b059e
--- /dev/null
+++ b/src/components/ModelSelect/RoutingBadge.tsx
@@ -0,0 +1,35 @@
+import { Tag, Tooltip } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { isRoutingGroupId } from './isRoutingGroupId';
+
+interface RoutingBadgeProps {
+ /**
+ * The model's id, `group/<id>` or `auto/<model>` for a magpie routing group.
+ */
+ id: string;
+ /** The provider the row belongs to, which decides whether the id means that. */
+ provider?: string;
+}
+
+/**
+ * The tag a routing group's row carries, as the new-release badge does: a small
+ * filled tag rather than wording in the name, since a name reads as one model
+ * and a group is a pool of them.
+ */
+export const RoutingBadge = memo<RoutingBadgeProps>(({ id, provider }) => {
+ const { t } = useTranslation('components');
+
+ if (!isRoutingGroupId(id, provider)) return null;
+
+ return (
+ <Tooltip title={t('ModelSelect.routingTooltip')}>
+ <Tag color={'blue'} size={'small'}>
+ {t('ModelSelect.routing')}
+ </Tag>
+ </Tooltip>
+ );
+});
+
+export default RoutingBadge;
diff --git a/src/components/ModelSelect/index.tsx b/src/components/ModelSelect/index.tsx
index 65a1403811b..a35fc13e6b9 100644
--- a/src/components/ModelSelect/index.tsx
+++ b/src/components/ModelSelect/index.tsx
@@ -32,6 +32,7 @@ import { type AiProviderSourceType } from '@/types/aiProvider';
import { formatTokenNumber } from '@/utils/format';
import NewModelBadgeI18n, { NewModelBadge as NewModelBadgeCore } from './NewModelBadge';
+import RoutingBadge from './RoutingBadge';
export const TAG_CLASSNAME = 'lobe-model-info-tags';
@@ -264,6 +265,8 @@ interface ModelItemRenderProps extends ChatModelCard, Pick<FlexboxProps, 'classN
nameSuffix?: ReactNode;
newBadgeLabel?: string;
proBadgeLabel?: string;
+ /** The provider the row belongs to, which some markers read the id against */
+ provider?: string;
/** Muted text right after the model name, e.g. the current reasoning effort */
secondaryText?: string;
showInfoTag?: boolean;
@@ -282,6 +285,7 @@ export const ModelItemRender = memo<ModelItemRenderProps>(
nameSuffix,
newBadgeLabel,
proBadgeLabel,
+ provider,
secondaryText,
video,
vision,
@@ -330,6 +334,7 @@ export const ModelItemRender = memo<ModelItemRenderProps>(
</Text>
)}
{nameSuffix}
+ <RoutingBadge id={id} provider={provider} />
{newBadgeLabel ? (
<NewModelBadgeCore label={newBadgeLabel} releasedAt={releasedAt} />
) : (
diff --git a/src/components/ModelSelect/isRoutingGroupId.test.ts b/src/components/ModelSelect/isRoutingGroupId.test.ts
new file mode 100644
index 00000000000..0eec5b559e8
--- /dev/null
+++ b/src/components/ModelSelect/isRoutingGroupId.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { isRoutingGroupId } from './isRoutingGroupId';
+
+describe('isRoutingGroupId', () => {
+ it('knows both ids magpie gives a routing group', () => {
+ expect(isRoutingGroupId('group/my-fastest', 'magpie')).toBe(true);
+ expect(isRoutingGroupId('group/auto-claude-opus-5-5', 'magpie')).toBe(true);
+ expect(isRoutingGroupId('auto/claude-opus-5.5', 'magpie')).toBe(true);
+ });
+
+ it('is false for a model one provider serves', () => {
+ expect(isRoutingGroupId('workbuddy/kimi-k3-1', 'magpie')).toBe(false);
+ expect(isRoutingGroupId('gpt-5.6-sol', 'magpie')).toBe(false);
+ });
+
+ it('reads the prefix only for magpie, whose ids spell a group that way', () => {
+ // Another provider's `group/…` is that provider's own id, not a routing group.
+ expect(isRoutingGroupId('group/some-id', 'openai')).toBe(false);
+ expect(isRoutingGroupId('auto/whatever', 'ollama')).toBe(false);
+ expect(isRoutingGroupId('group/some-id')).toBe(false);
+ });
+});
diff --git a/src/components/ModelSelect/isRoutingGroupId.ts b/src/components/ModelSelect/isRoutingGroupId.ts
new file mode 100644
index 00000000000..b2f324246c3
--- /dev/null
+++ b/src/components/ModelSelect/isRoutingGroupId.ts
@@ -0,0 +1,20 @@
+/**
+ * The provider whose model ids spell a routing group: magpie serves a model it
+ * routes across providers as `group/<id>`, and a group it found itself as
+ * `auto/<model>` too.
+ *
+ * The prefix alone says nothing about another provider's ids: a `group/…` id
+ * elsewhere may be an ordinary model's name, so the check is scoped to magpie.
+ */
+export const ROUTING_GROUP_PROVIDER = 'magpie';
+
+/**
+ * Whether a model id names a magpie routing group rather than one provider's
+ * model: a set of providers serving one model, a request for it reaching
+ * whichever answers.
+ */
+export const isRoutingGroupId = (id: string, provider?: string) => {
+ if (provider !== ROUTING_GROUP_PROVIDER) return false;
+
+ return id.startsWith('group/') || id.startsWith('auto/');
+};
diff --git a/src/features/ModelSelect/index.tsx b/src/features/ModelSelect/index.tsx
index 894af6c6568..f1361b4e7b7 100644
--- a/src/features/ModelSelect/index.tsx
+++ b/src/features/ModelSelect/index.tsx
@@ -158,7 +158,14 @@ const ModelSelect = memo<ModelSelectProps>(
return models.map((model) => ({
...model,
- label: <ModelItemRender {...model} {...model.abilities} showInfoTag={false} />,
+ label: (
+ <ModelItemRender
+ {...model}
+ {...model.abilities}
+ provider={provider.id}
+ showInfoTag={false}
+ />
+ ),
provider: provider.id,
title: model.displayName || model.id,
value: `${provider.id}/${model.id}`,
@@ -388,6 +395,7 @@ const ModelSelect = memo<ModelSelectProps>(
<ModelItemRender
{...(option as ModelOption)}
{...(option as ModelOption).abilities}
+ provider={(option as ModelOption).provider}
showInfoTag={false}
/>
);
diff --git a/src/features/ModelSwitchPanel/components/List/ModelRowRender.tsx b/src/features/ModelSwitchPanel/components/List/ModelRowRender.tsx
index d3910400899..a33232ee622 100644
--- a/src/features/ModelSwitchPanel/components/List/ModelRowRender.tsx
+++ b/src/features/ModelSwitchPanel/components/List/ModelRowRender.tsx
@@ -32,6 +32,7 @@ export const ModelRowRender = memo<ModelRowRenderProps>(
nameSuffix={model.abilities?.imageOutput && <ImageOutputMark />}
newBadgeLabel={newLabel}
proBadgeLabel={proBadgeLabel}
+ provider={provider}
secondaryText={(isActive && activeEffortLabel) || effortLabel}
/>
);
diff --git a/src/features/Settings/provider/features/ModelList/ModelItem.tsx b/src/features/Settings/provider/features/ModelList/ModelItem.tsx
index 218d6d9d78e..c4496ded48d 100644
--- a/src/features/Settings/provider/features/ModelList/ModelItem.tsx
+++ b/src/features/Settings/provider/features/ModelList/ModelItem.tsx
@@ -19,6 +19,7 @@ import { useTranslation } from 'react-i18next';
import { ModelIcon } from '@/components/LobeIcons';
import { ModelInfoTags } from '@/components/ModelSelect';
import NewModelBadge from '@/components/ModelSelect/NewModelBadge';
+import RoutingBadge from '@/components/ModelSelect/RoutingBadge';
import { useIsMobile } from '@/hooks/useIsMobile';
import { usePermission } from '@/hooks/usePermission';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
@@ -255,6 +256,7 @@ const ModelItem = memo<ModelItemProps>(
<Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
<Flexbox horizontal align={'center'} gap={8}>
{displayName || id}
+ <RoutingBadge id={id} provider={activeAiProvider} />
<Flexbox horizontal align={'center'} gap={8}>
<ModelInfoTags
placement={'top'}
@@ -289,6 +291,7 @@ const ModelItem = memo<ModelItemProps>(
<Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
<Flexbox horizontal align={'center'} gap={8}>
{displayName || id}
+ <RoutingBadge id={id} provider={activeAiProvider} />
{ModelIdTag}
{NewTag}
{Actions && Actions()}