🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(model-runtime): add Meta AI provider with Muse Spark 1.3 (#19152)
YuTengjing8ea955ddc536
diff --git a/.env.example b/.env.exampleindex 816e0d9277c..81374879199 100644--- a/.env.example+++ b/.env.example@@ -56,6 +56,14 @@ OPENAI_API_KEY=sk-xxxxxxxxx# add your custom model name, multi model separate by comma. for example gpt-3.5-1106,gpt-4-1106# OPENAI_MODEL_LIST=gpt-3.5-turbo+# ## Meta Model API ###++# Setting a server key enables Meta; users may also configure their own key in settings.+# Create a key at https://dev.meta.ai/+# META_API_KEY=your-meta-model-api-key+# META_PROXY_URL=https://api.meta.ai/v1+# META_MODEL_LIST=-all,+muse-spark-1.3+# ## Azure OpenAI #### you can learn azure OpenAI Service on https://learn.microsoft.com/en-us/azure/ai-services/openai/overviewdiff --git a/Dockerfile b/Dockerfileindex 33afb539d76..51bc2105f42 100644--- a/Dockerfile+++ b/Dockerfile@@ -312,6 +312,8 @@ ENV \QWEN_API_KEY="" QWEN_MODEL_LIST="" QWEN_PROXY_URL="" \# SambaNovaSAMBANOVA_API_KEY="" SAMBANOVA_MODEL_LIST="" \+ # Meta+ META_API_KEY="" META_MODEL_LIST="" META_PROXY_URL="" \# Search1APISEARCH1API_API_KEY="" SEARCH1API_MODEL_LIST="" \# SenseNovadiff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.tsindex 621343e3363..02bdfd3b542 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts@@ -235,6 +235,58 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {});describe('resolveServerCallLlmContextHints - model-instance reasoning config', () => {+ it.each([+ { preserveThinking: undefined, provider: 'meta', replay: true },+ { preserveThinking: false, provider: 'meta', replay: true },+ { preserveThinking: true, provider: 'meta', replay: true },+ { preserveThinking: undefined, provider: 'openai', replay: false },+ { preserveThinking: false, provider: 'openai', replay: false },+ { preserveThinking: true, provider: 'openai', replay: false },+ ])(+ 'should preserve opaque Meta replay without changing other providers ($provider, preserveThinking=$preserveThinking)',+ async ({ preserveThinking, provider, replay }) => {+ const model = 'muse-spark-1.3';+ loadModelsMock.mockResolvedValue([+ { abilities: { reasoning: true }, id: model, providerId: provider, settings: {} },+ ]);+ const reasoning = {+ responseItems: [+ {+ encrypted_content:+ 'lobe-scoped-state-v1:reasoning:0123456789abcdef0123456789abcdef:opaque',+ id: 'rs_meta',+ summary: [],+ type: 'reasoning',+ },+ ],+ };+ const messages = [+ { content: 'Hello', id: 'user-1', role: 'user' },+ { content: 'Hi', id: 'assistant-1', reasoning, role: 'assistant' },+ { content: 'Continue', id: 'user-2', role: 'user' },+ ];+ const hints = await resolveServerCallLlmContextHints({+ ctx: createCtx({ chatConfig: { preserveThinking } }),+ llmPayload: { messages } as unknown as CallLLMPayload,+ model,+ provider,+ });++ expect(hints.shouldReplayAssistantReasoning).toBe(replay);+ expect(hints.messagesForContext).toEqual([+ messages[0],+ {+ content: 'Hi',+ id: 'assistant-1',+ ...(replay && { reasoning }),+ role: 'assistant',+ },+ messages[2],+ ]);+ expect(messages[1].reasoning).toEqual(reasoning);+ },+ );+it('should apply the user model-instance reasoning config', async () => {getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.tsindex f79b16bf886..a853c46b5b8 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts@@ -264,7 +264,16 @@ export const resolveServerCallLlmContextHints = async ({effectiveChatConfig?.deepseekV4ReasoningEffort === 'none');const deepseekForcesPreserveThinking =isDeepSeekThinkingEligibleModel(model) && !deepseekV4ThinkingDisabled;- const modelForcesPreserveThinking = kimiForcesPreserveThinking || deepseekForcesPreserveThinking;+ /**+ * Meta always uses Responses with stateless encrypted reasoning replay. This+ * opaque continuation state must survive history building and agent tool loops,+ * independently of the user's optional visible-thinking preservation setting.+ * The model runtime still validates the replay scope before sending the state.+ * @see https://dev.meta.ai/docs/features/responses#reasoning-items+ */+ const metaForcesPreserveThinking = provider === ModelProvider.Meta;+ const modelForcesPreserveThinking =+ kimiForcesPreserveThinking || deepseekForcesPreserveThinking || metaForcesPreserveThinking;const providerSupportsPreserveThinkingFallback =provider === 'qwen' || provider === 'zhipu' || provider === 'moonshot';const modelSupportsPreserveThinking =diff --git a/apps/workbench/app/stubs/loadI18nNamespaceModule.client.test.ts b/apps/workbench/app/stubs/loadI18nNamespaceModule.client.test.tsnew file mode 100644index 00000000000..6261efc27d4--- /dev/null+++ b/apps/workbench/app/stubs/loadI18nNamespaceModule.client.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';++import { loadI18nNamespaceModule } from './loadI18nNamespaceModule.client';++describe('workbench model runtime translations', () => {+ it.each(['en-US', 'zh-CN'])('loads error messages for %s', async (lng) => {+ const module = await loadI18nNamespaceModule({+ defaultLang: 'en-US',+ lng,+ normalizeLocale: (locale) => locale ?? 'en-US',+ ns: 'modelRuntime',+ });++ expect(module.default.ModelEmptyCompletion).toEqual(expect.any(String));+ if (lng === 'zh-CN') expect(module.default.ModelEmptyCompletion).toMatch(/[\u4E00-\u9FFF]/);+ });+});diff --git a/apps/workbench/app/stubs/loadI18nNamespaceModule.client.ts b/apps/workbench/app/stubs/loadI18nNamespaceModule.client.tsindex bab4dddefb7..fa42208e40e 100644--- a/apps/workbench/app/stubs/loadI18nNamespaceModule.client.ts+++ b/apps/workbench/app/stubs/loadI18nNamespaceModule.client.ts@@ -10,6 +10,7 @@ const defaultLoaders = import.meta.glob(['../../../../packages/locales/src/default/chat.ts','../../../../packages/locales/src/default/common.ts','../../../../packages/locales/src/default/error.ts',+ '../../../../packages/locales/src/default/modelRuntime.ts','../../../../packages/locales/src/default/plugin.ts','../../../../packages/locales/src/default/tool.ts','../../../../packages/locales/src/default/verify.ts',@@ -18,6 +19,7 @@ const localeLoaders = import.meta.glob(['../../../../locales/*/chat.json','../../../../locales/*/common.json','../../../../locales/*/error.json',+ '../../../../locales/*/modelRuntime.json','../../../../locales/*/plugin.json','../../../../locales/*/tool.json','../../../../locales/*/verify.json',diff --git a/docs/self-hosting/environment-variables/model-provider.mdx b/docs/self-hosting/environment-variables/model-provider.mdxindex 37854107963..36e4302674d 100644--- a/docs/self-hosting/environment-variables/model-provider.mdx+++ b/docs/self-hosting/environment-variables/model-provider.mdx@@ -66,6 +66,33 @@ The above example adds `qwen-7b-chat` and `glm-6b` to the model list, removes `gYou can find all current model names in [modelProviders](https://github.com/lobehub/lobehub/tree/main/src/config/modelProviders).+## Meta++Use the official [Meta Model API](https://dev.meta.ai/). See [Using Meta in LobeHub](/docs/usage/providers/meta) for setup instructions.++### `META_API_KEY`++- Type: Optional for the deployment; required when providing a shared server key. Users can instead enter their own key in Meta provider settings.+- Description: A key created in the [Model API dashboard](https://dev.meta.ai/). Setting a non-empty key automatically enables Meta in the server configuration. `ENABLED_META` is derived from this key, not a separate environment switch. LobeHub uses `META_API_KEY`, rather than the `MODEL_API_KEY` name in Meta's SDK examples.+- Default: Unset; no shared server key.+- Example: `your-meta-model-api-key`++### `META_PROXY_URL`++- Type: Optional+- Description: Overrides the Meta API base URL. The proxy must support the Responses API. Supply the base URL, not the full `/responses` endpoint.+- Default: `https://api.meta.ai/v1`+- Example: `https://meta-proxy.example.com/v1`++### `META_MODEL_LIST`++- Type: Optional+- Description: Customizes the model list using the shared [model-list syntax][model-list]: `+` adds a model, `-` hides a model, and `model_id=display_name` renames a model. Separate entries with commas. This does not grant access to models unavailable to your Meta account.+- Default: Unset; uses the built-in model list.+- Example: `-all,+muse-spark-1.3`++The example hides all default models and adds `muse-spark-1.3`. See the [Muse Spark product page](https://developer.meta.com/ai/models/muse-spark/) and Meta's [Muse Spark 1.3 announcement](https://www.threads.com/@metafordevelopers/post/Dcy9DWLmfVn) for version information. Model availability depends on your account's API access.+## Azure OpenAIIf you need to use Azure OpenAI to provide model services, you can refer to the [Deploying with Azure OpenAI](/docs/self-hosting/examples/azure-openai) section for detailed steps. Here, we will list the environment variables related to Azure OpenAI.diff --git a/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx b/docs/self-hosting/environment-variables/model-provider.zh-CN.mdxindex 12cf60cc139..5d9ef981256 100644--- a/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx+++ b/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx@@ -64,6 +64,33 @@ LobeHub 在部署时提供了丰富的模型服务商相关的环境变量,你你可以在 [modelProviders](https://github.com/lobehub/lobehub/tree/main/src/config/modelProviders) 查找到当前的所有模型名。+## Meta++连接官方 [Meta Model API](https://dev.meta.ai/),设置步骤见[在 LobeHub 中使用 Meta](/zh/docs/usage/providers/meta)。++### `META_API_KEY`++- 类型:部署时可选;提供共享服务端密钥时必填。用户也可以在 Meta 服务商设置中填写自己的密钥。+- 描述:在 [Model API 控制台](https://dev.meta.ai/) 创建的密钥。设置非空密钥后,服务端配置会自动启用 Meta。`ENABLED_META` 由此密钥派生,不是独立的环境变量开关。LobeHub 使用 `META_API_KEY`,与 Meta SDK 示例中的 `MODEL_API_KEY` 名称不同。+- 默认值:未设置,不提供共享服务端密钥。+- 示例:`your-meta-model-api-key`++### `META_PROXY_URL`++- 类型:可选+- 描述:覆盖 Meta API 基础地址。代理必须支持 Responses API。请填写基础地址,而非完整的 `/responses` 接口地址。+- 默认值:`https://api.meta.ai/v1`+- 示例:`https://meta-proxy.example.com/v1`++### `META_MODEL_LIST`++- 类型:可选+- 描述:使用通用[模型列表语法][model-list]自定义模型列表:`+` 增加模型,`-` 隐藏模型,`模型 ID=展示名` 修改展示名称,各项用英文逗号分隔。此配置不会授予 Meta 账户尚未拥有的模型访问权限。+- 默认值:未设置,使用内置模型列表。+- 示例:`-all,+muse-spark-1.3`++上例隐藏所有默认模型,再添加 `muse-spark-1.3`。版本信息请参阅 [Muse Spark 产品页](https://developer.meta.com/ai/models/muse-spark/)和 Meta 的 [Muse Spark 1.3 发布公告](https://www.threads.com/@metafordevelopers/post/Dcy9DWLmfVn),模型可用性以账户的 API 访问权限为准。+## Azure OpenAI如果你需要使用 Azure OpenAI 来提供模型服务,可以查阅 [使用 Azure OpenAI 部署](/zh/docs/self-hosting/examples/azure-openai) 章节查看详细步骤,这里将列举和 Azure OpenAI 相关的环境变量。diff --git a/docs/usage/providers/meta.mdx b/docs/usage/providers/meta.mdxnew file mode 100644index 00000000000..5826a4c2c7e--- /dev/null+++ b/docs/usage/providers/meta.mdx@@ -0,0 +1,42 @@+---+title: Using Meta in LobeHub+description: Configure the official Meta Model API in LobeHub to chat with Muse Spark.+tags:+ - LobeHub+ - Meta+ - Muse Spark+ - API Key+---++# Using Meta in LobeHub++[Meta Model API](https://dev.meta.ai/) provides API access to Muse Spark. You need a Meta Model API key to use this provider. API usage is billed separately by Meta; see the current [pricing and rate limits](https://dev.meta.ai/docs/pricing-rate-limits).++<Steps>+ ### Step 1: Create an API key++ - Log in to the [Model API dashboard](https://dev.meta.ai/) with an account that has API access.+ - Open **API keys**, click **Create API key**, give the key a name, and click **Create**.+ - Copy the key and store it securely. Meta displays it only once. See the [authentication guide](https://dev.meta.ai/docs/authentication) for key management.++ ### Step 2: Configure Meta in LobeHub++ - Open **Settings → AI Providers**, find **Meta**, and enable it.+ - Enter your API key. If your self-hosted administrator has already configured a server key, you can use that configuration without entering a personal key.+ - Keep the default API base URL, `https://api.meta.ai/v1`, unless you use a compatible proxy.+ - Run the connection check, then select an available Muse Spark model for your assistant and send a short message.+</Steps>++## API compatibility++LobeHub's Meta integration uses the **Responses API** for chat and structured output. A custom proxy must support `/responses` relative to its base URL; do not enter the full `/v1/responses` endpoint as the base URL. Requests go through the LobeHub server, so that server must be able to reach the API. Direct browser requests are disabled for this provider.++Meta also offers other API formats. See [Choosing an API](https://dev.meta.ai/docs/protocols) for their differences. Available models depend on your API access; consult the [official model catalog](https://dev.meta.ai/docs/models).++## Self-hosting and troubleshooting++Administrators can set `META_API_KEY` on the server to enable Meta with a shared key. `META_PROXY_URL` overrides the base URL, and `META_MODEL_LIST` customizes the model list. See the [Meta environment variables](/docs/self-hosting/environment-variables/model-provider#meta).++- If authentication fails, check that the key is a valid Meta Model API key and has not been revoked.+- If a connection check fails, verify the selected model is available to your account and that your server or proxy can reach the Responses API.+- If Meta returns HTTP 429, reduce concurrent requests and retry after a delay. Rate limits are shared by the team, even when using different API keys.diff --git a/docs/usage/providers/meta.zh-CN.mdx b/docs/usage/providers/meta.zh-CN.mdxnew file mode 100644index 00000000000..4507dee515c--- /dev/null+++ b/docs/usage/providers/meta.zh-CN.mdx@@ -0,0 +1,42 @@+---+title: 在 LobeHub 中使用 Meta+description: 在 LobeHub 中配置官方 Meta Model API,使用 Muse Spark 进行对话。+tags:+ - LobeHub+ - Meta+ - Muse Spark+ - API 密钥+---++# 在 LobeHub 中使用 Meta++[Meta Model API](https://dev.meta.ai/) 提供 Muse Spark 的 API 访问。使用此服务商需要 Meta Model API 密钥。API 用量由 Meta 单独计费,具体费用及限制请查看官方[价格与速率限制](https://dev.meta.ai/docs/pricing-rate-limits)。++<Steps>+ ### 步骤一:创建 API 密钥++ - 使用具有 API 访问权限的账户登录 [Model API 控制台](https://dev.meta.ai/)。+ - 打开 **API keys**,点击 **Create API key**,填写密钥名称后点击 **Create**。+ - 复制并妥善保存密钥。Meta 只会展示一次密钥,管理方式请查看[身份验证指南](https://dev.meta.ai/docs/authentication)。++ ### 步骤二:在 LobeHub 中配置 Meta++ - 打开**设置 → AI 服务商**,找到并启用 **Meta**。+ - 填入 API 密钥。如果自部署实例的管理员已配置服务端密钥,可以直接使用该配置,无需再填写个人密钥。+ - 保留默认 API 基础地址 `https://api.meta.ai/v1`;使用兼容代理时再修改。+ - 执行连通性检查,然后为助手选择可用的 Muse Spark 模型,发送一条简短消息。+</Steps>++## API 兼容性++LobeHub 的 Meta 集成使用 **Responses API** 处理对话和结构化输出。自定义代理必须支持基础地址下的 `/responses` 路径;不要把完整的 `/v1/responses` 接口地址填为基础地址。请求通过 LobeHub 服务端发送,因此服务端必须能够访问 API。此服务商不支持浏览器直连请求。++Meta 也提供其他 API 格式,区别见官方[API 选择指南](https://dev.meta.ai/docs/protocols)。可用模型取决于账户的 API 访问权限,请参阅[官方模型目录](https://dev.meta.ai/docs/models)。++## 自部署与排查++管理员可在服务端设置 `META_API_KEY`,启用 Meta 并提供共享密钥。`META_PROXY_URL` 用于覆盖基础地址,`META_MODEL_LIST` 用于自定义模型列表,详见 [Meta 环境变量](/zh/docs/self-hosting/environment-variables/model-provider#meta)。++- 身份验证失败时,检查密钥是否为有效的 Meta Model API 密钥,以及是否已被撤销。+- 连通性检查失败时,确认所选模型对当前账户可用,且服务端或代理可以访问 Responses API。+- Meta 返回 HTTP 429 时,减少并发请求,稍后重试。同一团队的多个 API 密钥共享速率限制。diff --git a/locales/en-US/models.json b/locales/en-US/models.jsonindex 4f6ecfc3287..28b1a4e2808 100644--- a/locales/en-US/models.json+++ b/locales/en-US/models.json@@ -1039,6 +1039,7 @@"moonshotai/kimi-k2.description": "Kimi K2 is a large MoE model from Moonshot AI with 1T total parameters and 32B active per forward pass, optimized for agent capabilities including advanced tool use, reasoning, and code synthesis.","morph/morph-v3-fast.description": "Morph provides a specialized model to apply code changes suggested by frontier models (e.g., Claude or GPT-4o) to your existing files at FAST 4500+ tokens/sec. It is the final step in an AI coding workflow and supports 16k input/output tokens.","morph/morph-v3-large.description": "Morph provides a specialized model to apply code changes suggested by frontier models (e.g., Claude or GPT-4o) to your existing files at FAST 2500+ tokens/sec. It is the final step in an AI coding workflow and supports 16k input/output tokens.",+ "muse-spark-1.3.description": "Meta's frontier reasoning model, trained for agentic workflows and optimized for competitive coding performance. Muse Spark 1.3 tracks context and prior results, works through messy or conflicting inputs, and asks for input when needed.","musesteamer-2.0-lite-i2v.description": "Compared to Turbo, it offers superior performance with excellent cost-effectiveness.","musesteamer-2.0-pro-i2v.description": "Based on Turbo, supports 1080P dynamic video generation, offering higher visual quality and enhanced video expressiveness.","musesteamer-2.0-turbo-i2v-audio.description": "Supports 5s and 10s 720P dynamic video generation with sound. Enables multi-person conversational audio-visual creation, with synchronized sound and visuals, cinematic-quality imagery, and master-level camera movements.",diff --git a/locales/en-US/providers.json b/locales/en-US/providers.jsonindex 9a8deebca80..8f726945549 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.",+ "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.","mistral.description": "Mistral offers advanced general, specialized, and research models for complex reasoning, multilingual tasks, and code generation, with function-calling for custom integrations.",diff --git a/locales/zh-CN/models.json b/locales/zh-CN/models.jsonindex c12d115f519..ba7f6f61da4 100644--- a/locales/zh-CN/models.json+++ b/locales/zh-CN/models.json@@ -1039,6 +1039,7 @@"moonshotai/kimi-k2.description": "Kimi K2 是 Moonshot AI 推出的超大规模 MoE 模型,拥有 1 万亿总参数和每次前向传播 320 亿激活参数,专为高级工具使用、推理和代码合成等智能体能力优化。","morph/morph-v3-fast.description": "Morph 提供专用模型,将前沿模型(如 Claude 或 GPT-4o)建议的代码更改快速应用于现有文件,速度达 4500+ tokens/秒,是 AI 编程流程的最后一步,支持 16k 输入/输出。","morph/morph-v3-large.description": "Morph 提供专用模型,将前沿模型(如 Claude 或 GPT-4o)建议的代码更改快速应用于现有文件,速度达 2500+ tokens/秒,是 AI 编程流程的最后一步,支持 16k 输入/输出。",+ "muse-spark-1.3.description": "Meta 的前沿推理模型,针对智能体工作流训练,并优化了竞赛编程表现。Muse Spark 1.3 能跟踪上下文和先前结果,处理杂乱或相互矛盾的输入,并在需要时请求补充信息。","musesteamer-2.0-lite-i2v.description": "与Turbo相比,性能更优,性价比更高。","musesteamer-2.0-pro-i2v.description": "基于Turbo,支持1080P动态视频生成,提供更高的视觉质量和增强的视频表现力。","musesteamer-2.0-turbo-i2v-audio.description": "支持5秒和10秒720P动态视频生成并带有声音。实现多人对话音视频创作,声音与画面同步,画质达到电影级别,摄像机运动达到大师级水平。",diff --git a/locales/zh-CN/providers.json b/locales/zh-CN/providers.jsonindex e841e75052b..4a5daee6248 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 大模型系列,旨在通过高效的计算架构和强大的多模态能力,提升企业内部工作效率并推动创新应用的发展。",+ "meta.description": "Meta 构建 AI 模型与产品,帮助人们交流、创作和完成任务,旗下包括 Llama 和 Muse 模型系列。","minimax.description": "MiniMax 成立于 2021 年,致力于构建通用 AI,拥有多模态基础模型,包括万亿参数的 MoE 文本模型、语音模型与视觉模型,并推出海螺 AI 等应用。","minimaxcodingplan.description": "MiniMax Token Plan 提供对 MiniMax 模型(包括 M2.7)的访问,适用于编程任务,采用固定月费订阅模式。","mistral.description": "Mistral 提供先进的通用、专业与研究型模型,支持复杂推理、多语言任务与代码生成,具备函数调用能力以实现定制集成。",diff --git a/package.json b/package.jsonindex c0f69ec3b34..ca5dfd33344 100644--- a/package.json+++ b/package.json@@ -309,7 +309,7 @@"@lobehub/charts": "^5.4.0","@lobehub/desktop-ipc-typings": "workspace:*","@lobehub/editor": "^4.23.1",- "@lobehub/icons": "^5.15.0",+ "@lobehub/icons": "^5.18.0","@lobehub/market-sdk": "0.41.0","@lobehub/tts": "^5.1.2","@lobehub/ui": "^5.38.0",diff --git a/packages/env/src/llm.ts b/packages/env/src/llm.tsindex 2811ea08126..33653c72702 100644--- a/packages/env/src/llm.ts+++ b/packages/env/src/llm.ts@@ -157,6 +157,9 @@ export const getLLMConfig = () => {ENABLED_XAI: z.boolean(),XAI_API_KEY: z.string().optional(),+ ENABLED_META: z.boolean(),+ META_API_KEY: z.string().optional(),+ENABLED_INTERNLM: z.boolean(),INTERNLM_API_KEY: z.string().optional(),@@ -411,6 +414,9 @@ export const getLLMConfig = () => {ENABLED_XAI: !!process.env.XAI_API_KEY,XAI_API_KEY: process.env.XAI_API_KEY,+ ENABLED_META: !!process.env.META_API_KEY,+ META_API_KEY: process.env.META_API_KEY,+ENABLED_INTERNLM: !!process.env.INTERNLM_API_KEY,INTERNLM_API_KEY: process.env.INTERNLM_API_KEY,diff --git a/packages/fetch-sse/package.json b/packages/fetch-sse/package.jsonindex 8c4724d6f27..482d767e251 100644--- a/packages/fetch-sse/package.json+++ b/packages/fetch-sse/package.json@@ -27,7 +27,8 @@"@lobechat/const": "workspace:*","@lobechat/model-runtime": "workspace:*","@lobechat/utils": "workspace:*",- "i18next": "^24.2.3"+ "i18next": "^24.2.3",+ "model-bank": "workspace:*"},"devDependencies": {"@lobechat/types": "workspace:*"diff --git a/packages/fetch-sse/src/__tests__/parseError.test.ts b/packages/fetch-sse/src/__tests__/parseError.test.tsindex b60b9cfcb58..ef8b84d1781 100644--- a/packages/fetch-sse/src/__tests__/parseError.test.ts+++ b/packages/fetch-sse/src/__tests__/parseError.test.ts@@ -1,10 +1,13 @@import type { ErrorResponse } from '@lobechat/types';+import { t } from 'i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getMessageError } from '../parseError';// Mock i18next+const loadNamespaces = vi.fn(async () => {});vi.mock('i18next', () => ({+ default: { loadNamespaces: (...args: unknown[]) => loadNamespaces(...(args as [])) },t: vi.fn((key) => `translated_${key}`),}));@@ -95,6 +98,101 @@ describe('getMessageError', () => {});});+ it('should look runtime error codes up in the modelRuntime namespace', async () => {+ // Regression: these keys live under `modelRuntime:<code>`, not the legacy+ // `error:response.<code>` map, so the old lookup echoed the raw key back and+ // users saw literal `response.InvalidProviderAPIKey` in the failure toast.+ const mockErrorResponse: ErrorResponse = {+ body: { provider: 'meta' },+ errorType: 'InvalidProviderAPIKey',+ };+ const mockResponse = createMockResponse(mockErrorResponse, false, 401);++ const error = await getMessageError(mockResponse as any);++ // `provider` is resolved from the id on the body to the provider's display name.+ expect(t).toHaveBeenCalledWith('InvalidProviderAPIKey', {+ defaultValue: 'translated_response.UnknownChatFetchError',+ ns: 'modelRuntime',+ provider: 'Meta',+ });+ expect(error.message).toBe('translated_InvalidProviderAPIKey');+ });++ it('should fall back to the raw provider id when it is not a known provider', async () => {+ const mockResponse = createMockResponse(+ { body: { provider: 'not-a-provider' }, errorType: 'InvalidProviderAPIKey' },+ false,+ 401,+ );++ await getMessageError(mockResponse as any);++ expect(t).toHaveBeenCalledWith(+ 'InvalidProviderAPIKey',+ expect.objectContaining({ ns: 'modelRuntime', provider: 'not-a-provider' }),+ );+ });++ it('should translate deprecated alias codes under their canonical key', async () => {+ /** Legacy server payloads may contain aliases excluded from the current ErrorResponse type. */+ const response = Response.json({ body: {}, errorType: 'PipelineError' }, { status: 500 });++ await getMessageError(response);++ expect(t).toHaveBeenCalledWith(+ 'ContextEnginePipelineError',+ expect.objectContaining({ ns: 'modelRuntime' }),+ );+ });++ it('should prefer the backend message as the fallback for codes without a locale entry', async () => {+ // `NoAvailableProvider` is a registered runtime code with no `modelRuntime`+ // key yet; without a defaultValue the toast would show the bare code.+ const mockResponse = createMockResponse(+ { body: { message: 'empty providers', provider: 'meta' }, errorType: 'NoAvailableProvider' },+ false,+ 500,+ );++ await getMessageError(mockResponse as any);++ expect(t).toHaveBeenCalledWith('NoAvailableProvider', {+ defaultValue: 'empty providers',+ ns: 'modelRuntime',+ provider: 'Meta',+ });+ });++ it('should load both namespaces before translating', async () => {+ // Namespaces are route-lazy and this path runs outside React, so without an+ // explicit load i18next echoes the key back instead of the message.+ const mockResponse = createMockResponse(+ { body: {}, errorType: 'InvalidProviderAPIKey' } satisfies ErrorResponse,+ false,+ 401,+ );++ await getMessageError(mockResponse as any);++ expect(loadNamespaces).toHaveBeenCalledWith(['error', 'modelRuntime']);+ });++ it('should keep app-only error types on the legacy error namespace', async () => {+ const mockErrorResponse: ErrorResponse = {+ body: 'Error occurred',+ errorType: 'InvalidAccessCode',+ };+ const mockResponse = createMockResponse(mockErrorResponse, false, 401);++ await getMessageError(mockResponse as any);++ expect(t).toHaveBeenCalledWith(+ 'response.InvalidAccessCode',+ expect.objectContaining({ ns: 'error', provider: '' }),+ );+ });+it('should handle timeout error correctly', async () => {const mockResponse = createMockResponse(undefined, false, 504);const error = await getMessageError(mockResponse as any);diff --git a/packages/fetch-sse/src/parseError.ts b/packages/fetch-sse/src/parseError.tsindex 13f79444939..8f5c7655603 100644--- a/packages/fetch-sse/src/parseError.ts+++ b/packages/fetch-sse/src/parseError.ts@@ -1,15 +1,60 @@+import { getRuntimeErrorI18nKey } from '@lobechat/model-runtime/errors';import type { ChatMessageError, ErrorResponse, ErrorType } from '@lobechat/types';-import { t } from 'i18next';+import { isRecord, pickTrimmedString } from '@lobechat/utils';+import i18next, { t } from 'i18next';+import { getProviderDisplayName } from 'model-bank/modelProviders';++/**+ * Runtime error codes live in their own `modelRuntime` namespace while HTTP+ * statuses and app-only codes stay under the legacy `error:response.<X>` map;+ * `getRuntimeErrorI18nKey` owns that routing (and alias canonicalisation).+ * Looking a runtime code up in the wrong place makes i18next echo the key back,+ * which is how users ended up seeing raw `response.InvalidProviderAPIKey` text+ * in the "fetch model list" toast.+ */+const translateErrorType = (errorType: ErrorResponse['errorType'], body: unknown) => {+ const { key, ns } = getRuntimeErrorI18nKey(errorType);++ // Both namespaces interpolate `{{provider}}`; the backend puts the provider+ // **id** on the error body, so resolve it to the display name the same way+ // `useProviderName` does — otherwise the toast reads "meta" instead of "Meta".+ const providerId = isRecord(body) ? pickTrimmedString(body.provider) : undefined;+ const provider = providerId ? getProviderDisplayName(providerId) : '';++ // A registered code with no locale entry yet (e.g. `NoAvailableProvider`) must+ // not surface as the bare code: prefer the backend's own message, then the+ // generic fetch-error copy, mirroring the connection checker's fallback chain.+ const defaultValue =+ (isRecord(body) ? pickTrimmedString(body.message) : pickTrimmedString(body)) ??+ t('response.UnknownChatFetchError', { ns: 'error' });++ return t(key, { defaultValue, ns, provider });+};++/**+ * Namespaces are lazy-loaded per route, and this runs outside React so no+ * `useTranslation` has pulled them in. Without an explicit load, `t` echoes the+ * key back and the UI shows a raw error code.+ */+const ensureNamespaces = async () => {+ try {+ await i18next.loadNamespaces(['error', 'modelRuntime']);+ } catch {+ // a failed namespace load must not swallow the error we came here to report+ }+};export const getMessageError = async (response: Response): Promise<ChatMessageError> => {let chatMessageError: ChatMessageError;+ await ensureNamespaces();+// try to get the biz errortry {const data = (await response.json()) as ErrorResponse;chatMessageError = {body: data.body,- message: t(`response.${data.errorType}`, { ns: 'error' }),+ message: translateErrorType(data.errorType, data.body),type: data.errorType,};} catch {diff --git a/packages/model-bank/package.json b/packages/model-bank/package.jsonindex e5915bfe5df..b66ea15d3e7 100644--- a/packages/model-bank/package.json+++ b/packages/model-bank/package.json@@ -46,6 +46,7 @@"./kimiCodingPlan": "./src/aiModels/kimiCodingPlan.ts","./lmstudio": "./src/aiModels/lmstudio.ts","./longcat": "./src/aiModels/longcat.ts",+ "./meta": "./src/aiModels/meta.ts","./minimax": "./src/aiModels/minimax.ts","./minimaxCodingPlan": "./src/aiModels/minimaxCodingPlan.ts","./mistral": "./src/aiModels/mistral.ts",diff --git a/packages/model-bank/src/aiModels/index.ts b/packages/model-bank/src/aiModels/index.tsindex 1e27b214522..f56a857a899 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 meta } from './meta';import { default as minimax } from './minimax';import { default as minimaxcodingplan } from './minimaxCodingPlan';import { default as mistral } from './mistral';@@ -148,6 +149,7 @@ const staticModelMap: ModelsMap = {kimicodingplan,lmstudio,longcat,+ meta,minimax,minimaxcodingplan,mistral,@@ -264,6 +266,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 meta } from './meta';export { default as minimax } from './minimax';export { default as minimaxcodingplan } from './minimaxCodingPlan';export { default as mistral } from './mistral';diff --git a/packages/model-bank/src/aiModels/meta.ts b/packages/model-bank/src/aiModels/meta.tsnew file mode 100644index 00000000000..b19ade3eed6--- /dev/null+++ b/packages/model-bank/src/aiModels/meta.ts@@ -0,0 +1,38 @@+import type { AIChatModelCard } from '../types/aiModel';++// https://dev.meta.ai/docs/models+const metaChatModels: AIChatModelCard[] = [+ {+ abilities: {+ functionCall: true,+ reasoning: true,+ search: true,+ structuredOutput: true,+ vision: true,+ },+ contextWindowTokens: 1_048_576,+ description:+ "Meta's frontier reasoning model, trained for agentic workflows and optimized for competitive coding performance. Muse Spark 1.3 tracks context and prior results, works through messy or conflicting inputs, and asks for input when needed.",+ displayName: 'Muse Spark 1.3',+ enabled: true,+ family: 'muse',+ generation: 'muse-spark-1.3',+ id: 'muse-spark-1.3',+ pricing: {+ units: [+ { name: 'textInput_cacheRead', rate: 0.15, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 4.25, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2026-09-02',+ settings: {+ searchImpl: 'params',+ },+ type: 'chat',+ },+];++export const allModels = [...metaChatModels];++export default allModels;diff --git a/packages/model-bank/src/const/modelProvider.ts b/packages/model-bank/src/const/modelProvider.tsindex 4bac75dc604..80fbd955d0c 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',+ Meta = 'meta',Minimax = 'minimax',MinimaxCodingPlan = 'minimaxcodingplan',Mistral = 'mistral',diff --git a/packages/model-bank/src/modelProviders/index.test.ts b/packages/model-bank/src/modelProviders/index.test.tsindex 5ec15532652..f0f70332c5a 100644--- a/packages/model-bank/src/modelProviders/index.test.ts+++ b/packages/model-bank/src/modelProviders/index.test.ts@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { type ModelProviderCard } from '../types';import {DEFAULT_MODEL_PROVIDER_LIST,+ getProviderDisplayName,isProviderDisableBrowserRequest,isProviderOAuthDeviceFlow,} from './index';@@ -50,6 +51,11 @@ describe('model provider predicates', () => {expect(isProviderDisableBrowserRequest('not-exists')).toBe(false);});+ it('resolves a provider id to its display name and falls back to the id', () => {+ expect(getProviderDisplayName('enabled-provider')).toBe('Test Provider');+ expect(getProviderDisplayName('not-exists')).toBe('not-exists');+ });+it('detects OAuth device flow providers', () => {expect(isProviderOAuthDeviceFlow('oauth-provider')).toBe(true);expect(isProviderOAuthDeviceFlow('enabled-provider')).toBe(false);diff --git a/packages/model-bank/src/modelProviders/index.ts b/packages/model-bank/src/modelProviders/index.tsindex a0b64b90d3b..ff43e0dcb09 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 MetaProvider from './meta';import MinimaxProvider from './minimax';import MinimaxCodingPlanProvider from './minimaxCodingPlan';import MistralProvider from './mistral';@@ -158,6 +159,13 @@ export const DEFAULT_MODEL_PROVIDER_LIST = [VertexAIProvider,{ ...AzureProvider, chatModels: [] },AzureAIProvider,+ MetaProvider,+ XAIProvider,+ QwenProvider,+ ZhiPuProvider,+ MinimaxProvider,+ MistralProvider,+ XiaomiMiMoProvider,AiHubMixProvider,OpenRouterProvider,FalProvider,@@ -179,21 +187,17 @@ export const DEFAULT_MODEL_PROVIDER_LIST = [FireworksAIProvider,GroqProvider,PerplexityProvider,- MistralProvider,ModelScopeProvider,Ai21Provider,UpstageProvider,- XAIProvider,SuperGrokProvider,JinaProvider,SambaNovaProvider,CohereProvider,V0Provider,- QwenProvider,WenxinProvider,TencentcloudProvider,HunyuanProvider,- ZhiPuProvider,SiliconCloudProvider,ZeroOneProvider,SparkProvider,@@ -202,7 +206,6 @@ export const DEFAULT_MODEL_PROVIDER_LIST = [BaichuanProvider,VolcengineProvider,VolcengineCodingPlanProvider,- MinimaxProvider,MinimaxCodingPlanProvider,LMStudioProvider,InternLMProvider,@@ -223,7 +226,6 @@ export const DEFAULT_MODEL_PROVIDER_LIST = [OpenCodeZenProvider,OpenCodeCodingPlanProvider,StraicoProvider,- XiaomiMiMoProvider,LongCatProvider,StreamLakeProvider,AntGroupProvider,@@ -240,6 +242,14 @@ export const isProviderDisableBrowserRequest = (id: string) => {return !!provider;};+/**+ * Human-readable provider name for a provider id (`meta` → `Meta`). Unknown ids+ * (custom providers, typos) fall back to the id itself so callers always get a+ * non-empty label.+ */+export const getProviderDisplayName = (id: string) =>+ DEFAULT_MODEL_PROVIDER_LIST.find((provider) => provider.id === id)?.name || id;+export const isProviderOAuthDeviceFlow = (id?: string) =>DEFAULT_MODEL_PROVIDER_LIST.some((provider) => provider.id === id && provider.settings?.authType === 'oauthDeviceFlow',@@ -283,6 +293,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 MetaProviderCard } from './meta';export { default as MinimaxProviderCard } from './minimax';export { default as MinimaxCodingPlanProviderCard } from './minimaxCodingPlan';export { default as MistralProviderCard } from './mistral';diff --git a/packages/model-bank/src/modelProviders/meta.ts b/packages/model-bank/src/modelProviders/meta.tsnew file mode 100644index 00000000000..4992e400f66--- /dev/null+++ b/packages/model-bank/src/modelProviders/meta.ts@@ -0,0 +1,23 @@+import type { ModelProviderCard } from '../types';++// ref: https://dev.meta.ai/docs+const Meta: ModelProviderCard = {+ chatModels: [],+ checkModel: 'muse-spark-1.3',+ description:+ 'Meta builds AI models and products that help people connect, create, and get things done, including the Llama and Muse model families.',+ disableBrowserRequest: true,+ id: 'meta',+ modelsUrl: 'https://dev.meta.ai/docs/models',+ name: 'Meta',+ settings: {+ disableBrowserRequest: true,+ proxyUrl: {+ placeholder: 'https://api.meta.ai/v1',+ },+ sdkType: 'openai',+ },+ url: 'https://dev.meta.ai',+};++export default Meta;diff --git a/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts b/packages/model-runtime/src/core/RouterRuntime/apiTypes.tsindex a8d97683705..7f80b29dc1a 100644--- a/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts+++ b/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts@@ -9,6 +9,7 @@ export type ApiType =| 'deepseek'| 'fal'| 'google'+ | 'meta'| 'minimax'| 'moonshot'| 'openai'diff --git a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.tsindex e9c6bacf65f..b4c299c7876 100644--- a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts+++ b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts@@ -6,6 +6,7 @@ import { LobeCloudflareAI } from '../../providers/cloudflare';import { LobeDeepSeekAI } from '../../providers/deepseek';import { LobeFalAI } from '../../providers/fal';import { LobeGoogleAI } from '../../providers/google';+import { LobeMetaAI } from '../../providers/meta';import { LobeMinimaxAI } from '../../providers/minimax';import { LobeMoonshotAI } from '../../providers/moonshot';import { LobeOpenAI } from '../../providers/openai';@@ -26,6 +27,7 @@ export const baseRuntimeMap = {deepseek: LobeDeepSeekAI,fal: LobeFalAI,google: LobeGoogleAI,+ meta: LobeMetaAI,minimax: LobeMinimaxAI,moonshot: LobeMoonshotAI,openai: LobeOpenAI,diff --git a/packages/model-runtime/src/errors/i18nKey.test.ts b/packages/model-runtime/src/errors/i18nKey.test.tsnew file mode 100644index 00000000000..64a52e66c27--- /dev/null+++ b/packages/model-runtime/src/errors/i18nKey.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';++import { AgentRuntimeErrorType } from '../types/error';+import { getRuntimeErrorI18nKey } from './i18nKey';++describe('getRuntimeErrorI18nKey', () => {+ it('routes registered runtime codes to the modelRuntime namespace', () => {+ expect(getRuntimeErrorI18nKey(AgentRuntimeErrorType.InvalidProviderAPIKey)).toEqual({+ key: 'InvalidProviderAPIKey',+ ns: 'modelRuntime',+ });+ });++ it('canonicalises deprecated aliases so the lookup hits an existing key', () => {+ expect(getRuntimeErrorI18nKey('PipelineError')).toEqual({+ key: AgentRuntimeErrorType.ContextEnginePipelineError,+ ns: 'modelRuntime',+ });+ expect(getRuntimeErrorI18nKey(AgentRuntimeErrorType.QuotaLimitReached)).toEqual({+ key: AgentRuntimeErrorType.RateLimitExceeded,+ ns: 'modelRuntime',+ });+ });++ it('keeps HTTP statuses and app-only codes on the legacy error namespace', () => {+ expect(getRuntimeErrorI18nKey(401)).toEqual({ key: 'response.401', ns: 'error' });+ expect(getRuntimeErrorI18nKey('InvalidAccessCode')).toEqual({+ key: 'response.InvalidAccessCode',+ ns: 'error',+ });+ });+});diff --git a/packages/model-runtime/src/errors/i18nKey.ts b/packages/model-runtime/src/errors/i18nKey.tsnew file mode 100644index 00000000000..5b1934bf5a2--- /dev/null+++ b/packages/model-runtime/src/errors/i18nKey.ts@@ -0,0 +1,26 @@+import { getErrorCodeSpec } from './specs';++export interface RuntimeErrorI18nKey {+ /** Flat key inside `ns`, e.g. `InvalidProviderAPIKey` or `response.401`. */+ key: string;+ ns: 'error' | 'modelRuntime';+}++/**+ * Locate the localized message for an error type.+ *+ * Runtime error codes (everything in `ERROR_CODE_SPECS`) live in the dedicated+ * `modelRuntime` namespace, one key per canonical code. HTTP statuses, `Plugin*`+ * and Cloud-only `ChatErrorType` values stay in the legacy `error:response.<X>`+ * map. Deprecated aliases (`PipelineError`, `QuotaLimitReached`) resolve to their+ * canonical code so the lookup hits the key that actually exists.+ *+ * Shared by the React-side `getRuntimeErrorMessage` and the non-React+ * `getMessageError` in `@lobechat/fetch-sse`, so the routing rule has a single+ * source of truth.+ */+export const getRuntimeErrorI18nKey = (code: string | number): RuntimeErrorI18nKey => {+ const spec = typeof code === 'string' ? getErrorCodeSpec(code) : undefined;++ return spec ? { key: spec.code, ns: 'modelRuntime' } : { key: `response.${code}`, ns: 'error' };+};diff --git a/packages/model-runtime/src/errors/index.ts b/packages/model-runtime/src/errors/index.tsindex 93dea0813c5..3e9b8eef3bd 100644--- a/packages/model-runtime/src/errors/index.ts+++ b/packages/model-runtime/src/errors/index.ts@@ -1,4 +1,5 @@export { ErrorClassifier, type ErrorClassifierType } from './classifier';+export { getRuntimeErrorI18nKey, type RuntimeErrorI18nKey } from './i18nKey';export { isUserSideError, matchErrorPattern, type MatchInput, type MatchResult } from './match';export { isEmptyModelCompletion, ModelEmptyError } from './modelEmptyCompletion';export { ModelRefusalError } from './modelRefusal';diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.tsindex 5e42d63b700..67e19b43a5d 100644--- a/packages/model-runtime/src/index.ts+++ b/packages/model-runtime/src/index.ts@@ -21,6 +21,7 @@ export {type ErrorSeverity,formatErrorRef,getErrorCodeSpec,+ getRuntimeErrorI18nKey,isEmptyModelCompletion,isUserSideError,matchErrorPattern,@@ -31,6 +32,7 @@ export {parseErrorRef,refineErrorCode,type RefineErrorInput,+ type RuntimeErrorI18nKey,type SpecErrorCode,} from './errors';export * from './helpers';diff --git a/packages/model-runtime/src/providers/meta/index.test.ts b/packages/model-runtime/src/providers/meta/index.test.tsnew file mode 100644index 00000000000..4f20ea8f85c--- /dev/null+++ b/packages/model-runtime/src/providers/meta/index.test.ts@@ -0,0 +1,335 @@+// @vitest-environment node+import { ModelProvider } from 'model-bank';+import type { Mock } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { testProvider } from '../../providerTestUtils';+import type { OnFinishData } from '../../types';+import { LobeMetaAI } from './index';++vi.mock('@lobechat/business-model-bank/model-config', () => ({+ loadModels: vi.fn().mockResolvedValue([]),+}));++const provider = ModelProvider.Meta;+const defaultBaseURL = 'https://api.meta.ai/v1';++testProvider({+ Runtime: LobeMetaAI,+ provider,+ defaultBaseURL,+ chatDebugEnv: 'DEBUG_META_CHAT_COMPLETION',+ responseDebugEnv: 'DEBUG_META_RESPONSES',+ chatModel: 'muse-spark-1.3',+ test: {+ useResponsesAPI: true,+ },+});++describe('LobeMetaAI - custom features', () => {+ let instance: InstanceType<typeof LobeMetaAI>;++ beforeEach(() => {+ instance = new LobeMetaAI({ apiKey: 'test_api_key' });+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(+ new ReadableStream() as any,+ );+ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(new ReadableStream() as any);+ });++ describe('Responses API routing', () => {+ it.each([true, false])(+ 'should preserve every encrypted reasoning item for the next turn (stream=%s)',+ async (stream) => {+ const reasoningItems = ['first', 'second'].map((part) => ({+ encrypted_content: `encrypted-${part}`,+ id: `rs_${part}`,+ summary: [],+ type: 'reasoning' as const,+ }));+ const response = {+ id: 'resp_first',+ model: 'muse-spark-1.3',+ output: [+ ...reasoningItems,+ {+ content: [{ annotations: [], text: 'Paris', type: 'output_text' }],+ id: 'msg_first',+ role: 'assistant',+ status: 'completed',+ type: 'message',+ },+ ],+ status: 'completed',+ };+ const events = [+ ...reasoningItems.map((item, output_index) => ({+ item,+ output_index,+ sequence_number: output_index,+ type: 'response.output_item.done',+ })),+ { delta: 'Paris', type: 'response.output_text.delta' },+ { response, sequence_number: 3, type: 'response.completed' },+ ];+ (instance['client'].responses.create as Mock).mockResolvedValueOnce(+ stream+ ? new ReadableStream({+ start(controller) {+ events.forEach((event) => controller.enqueue(event));+ controller.close();+ },+ })+ : response,+ );+ const onFinal = vi.fn<(data: OnFinishData) => void>();+ const firstTurn = await instance.chat(+ {+ messages: [{ content: 'What is the capital of France?', role: 'user' }],+ model: 'muse-spark-1.3',+ stream,+ temperature: 1,+ },+ { callback: { onFinal } },+ );+ await firstTurn.text();++ expect(onFinal).toHaveBeenCalledOnce();+ const completed = onFinal.mock.calls[0][0];+ expect(completed.text).toBe('Paris');+ expect(completed.reasoning?.responseItems).toHaveLength(2);++ await instance.chat({+ messages: [+ { content: 'What is the capital of France?', role: 'user' },+ { content: completed.text, reasoning: completed.reasoning, role: 'assistant' },+ { content: 'What is its population?', role: 'user' },+ ],+ model: 'muse-spark-1.3',+ temperature: 1,+ });++ const request = (instance['client'].responses.create as Mock).mock.calls[1][0];+ expect(request.input).toEqual([+ { content: 'What is the capital of France?', role: 'user' },+ ...reasoningItems,+ { content: 'Paris', role: 'assistant' },+ { content: 'What is its population?', role: 'user' },+ ]);+ expect(request.include).toEqual(['reasoning.encrypted_content']);+ expect(request.store).toBe(false);+ expect(request.previous_response_id).toBeUndefined();+ },+ );++ it('should send every request through the Responses API', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'muse-spark-1.3',+ temperature: 1,+ });++ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];++ expect(createCall.stream).toBe(true);+ expect(instance['client'].chat.completions.create).not.toHaveBeenCalled();+ });++ it('should ignore a caller-supplied chatCompletion apiMode', async () => {+ await instance.chat({+ apiMode: 'chatCompletion',+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'muse-spark-1.3',+ temperature: 1,+ } as any);++ expect(instance['client'].responses.create).toHaveBeenCalled();+ expect(instance['client'].chat.completions.create).not.toHaveBeenCalled();+ });++ it('should request encrypted reasoning so the chain of thought can be replayed', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'muse-spark-1.3',+ temperature: 1,+ });++ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];++ expect(createCall.include).toEqual(['reasoning.encrypted_content']);+ expect(createCall.store).toBe(false);+ expect(createCall.previous_response_id).toBeUndefined();+ });+ });++ describe('models', () => {+ it('should fetch the Meta model catalog through the SDK models endpoint', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>().mockResolvedValue(+ Response.json({+ data: [+ { created: 1788652800, id: 'muse-spark-future', object: 'model', owned_by: 'meta' },+ ],+ object: 'list',+ }),+ );+ const runtime = new LobeMetaAI({ apiKey: 'test_api_key', fetch });++ const models = await runtime.models();++ expect(fetch).toHaveBeenCalledOnce();+ const [input, init] = fetch.mock.calls[0];+ const request = new Request(input, init);+ expect(request.url).toBe('https://api.meta.ai/v1/models');+ expect(request.method).toBe('GET');+ expect(models).toEqual([expect.objectContaining({ id: 'muse-spark-future' })]);+ });+ });++ describe('generateObject', () => {+ it('should generate structured output through the Responses API', async () => {+ (instance['client'].responses.create as Mock).mockResolvedValue({+ output_text: '{"city":"Hangzhou"}',+ });++ const result = await instance.generateObject({+ messages: [{ content: 'Extract the city', role: 'user' }],+ model: 'muse-spark-1.3',+ schema: {+ name: 'location',+ schema: {+ properties: { city: { type: 'string' } },+ required: ['city'],+ type: 'object',+ },+ },+ });++ const request = (instance['client'].responses.create as Mock).mock.calls[0][0];++ expect(result).toEqual({ city: 'Hangzhou' });+ expect(instance['client'].chat.completions.create).not.toHaveBeenCalled();+ expect(request.text).toEqual({+ format: {+ name: 'location',+ schema: {+ properties: { city: { type: 'string' } },+ required: ['city'],+ type: 'object',+ },+ strict: true,+ type: 'json_schema',+ },+ });+ });+ });++ describe('responses.handlePayload', () => {+ it('should add the web_search tool alongside existing tools when enabledSearch is true', async () => {+ await instance.chat({+ enabledSearch: true,+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'muse-spark-1.3',+ temperature: 1,+ tools: [{ function: { description: 'test', name: 'test' }, type: 'function' as const }],+ });++ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];++ expect(createCall.tools).toEqual([+ { description: 'test', name: 'test', type: 'function' },+ { type: 'web_search' },+ ]);+ });++ it('should add the web_search tool without existing tools', async () => {+ await instance.chat({+ enabledSearch: true,+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'muse-spark-1.3',+ temperature: 1,+ });++ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];++ expect(createCall.tools).toEqual([{ type: 'web_search' }]);+ });++ it('should leave tools untouched when enabledSearch is not set', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'muse-spark-1.3',+ temperature: 1,+ tools: [{ function: { description: 'test', name: 'test' }, type: 'function' as const }],+ });++ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];++ expect(createCall.tools).toEqual([{ description: 'test', name: 'test', type: 'function' }]);+ });++ it('should map a json_schema response_format to text.format', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'muse-spark-1.3',+ response_format: {+ json_schema: {+ name: 'answer',+ schema: {+ additionalProperties: false,+ properties: { answer: { type: 'string' } },+ required: ['answer'],+ type: 'object',+ },+ strict: true,+ },+ type: 'json_schema',+ },+ temperature: 1,+ } as any);++ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];++ expect(createCall.response_format).toBeUndefined();+ expect(createCall.text).toEqual({+ format: {+ name: 'answer',+ schema: {+ additionalProperties: false,+ properties: { answer: { type: 'string' } },+ required: ['answer'],+ type: 'object',+ },+ strict: true,+ type: 'json_schema',+ },+ });+ });++ it('should map a json_object response_format to text.format', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'muse-spark-1.3',+ response_format: { type: 'json_object' },+ temperature: 1,+ } as any);++ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];++ expect(createCall.response_format).toBeUndefined();+ expect(createCall.text).toEqual({ format: { type: 'json_object' } });+ });++ it('should keep an explicit text payload when no response_format is given', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'muse-spark-1.3',+ temperature: 1,+ text: { verbosity: 'low' },+ } as any);++ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];++ expect(createCall.text).toEqual({ verbosity: 'low' });+ });+ });+});diff --git a/packages/model-runtime/src/providers/meta/index.ts b/packages/model-runtime/src/providers/meta/index.tsnew file mode 100644index 00000000000..da97ee4b624--- /dev/null+++ b/packages/model-runtime/src/providers/meta/index.ts@@ -0,0 +1,83 @@+import { ModelProvider } from 'model-bank';++import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';+import type { ChatResponseFormat, ChatStreamPayload } from '../../types';++/**+ * Meta Model API serves the same models over three wire formats, but only the Responses API+ * carries the model's chain of thought between calls and hosts search grounding — Chat+ * Completions does neither. Meta names Responses "the recommended default for new work", so+ * every request is routed there instead of the messages-array endpoint.+ *+ * ref: https://dev.meta.ai/docs/protocols+ */+const handleMetaChatCompletionPayload = (payload: ChatStreamPayload) =>+ ({+ ...payload,+ apiMode: 'responses',+ stream: payload.stream ?? true,+ }) as any;++/**+ * Meta's Responses API takes structured output under `text.format` and rejects the Chat+ * Completions `response_format` shape with HTTP 400, while callers still send the latter.+ */+const mapResponseFormatToResponsesText = (+ responseFormat?: ChatResponseFormat,+ text?: ChatStreamPayload['text'],+) => {+ if (!responseFormat) return text;++ if (responseFormat.type === 'json_schema') {+ return {+ ...text,+ format: { type: 'json_schema', ...responseFormat.json_schema },+ };+ }++ return {+ ...text,+ format: { type: responseFormat.type },+ };+};++export const handleMetaResponsesPayload = (payload: ChatStreamPayload) => {+ const { enabledSearch, response_format, text, tools, ...rest } = payload;++ return {+ ...rest,+ /**+ * Muse Spark never returns its raw chain of thought — reasoning replay is encrypted-only+ * and `encrypted_content` is omitted unless requested here. The factory already sends+ * `store: false`, which is exactly the stateless replay mode Meta recommends. This must+ * not be combined with `previous_response_id` (HTTP 400), which the factory never sends.+ */+ include: ['reasoning.encrypted_content'],+ text: mapResponseFormatToResponsesText(response_format, text),+ tools: enabledSearch ? [...(tools || []), { type: 'web_search' }] : tools,+ } as any;+};++export const LobeMetaAI = createOpenAICompatibleRuntime({+ baseURL: 'https://api.meta.ai/v1',+ chatCompletion: {+ handlePayload: handleMetaChatCompletionPayload,+ useResponse: true,+ },+ debug: {+ chatCompletion: () => process.env.DEBUG_META_CHAT_COMPLETION === '1',+ responses: () => process.env.DEBUG_META_RESPONSES === '1',+ },+ /**+ * Structured generation resolves its API mode from `generateObject.useResponse` alone — the+ * `chatCompletion` flag above does not reach it — so it has to opt in separately, otherwise+ * `outputJSON` would silently fall back to the Chat Completions endpoint.+ */+ generateObject: {+ useResponse: true,+ },+ provider: ModelProvider.Meta,+ responses: {+ handlePayload: handleMetaResponsesPayload,+ },+});diff --git a/packages/model-runtime/src/runtimeMap.ts b/packages/model-runtime/src/runtimeMap.tsindex ba57c7f5b1e..178f717726b 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 { LobeMetaAI } from './providers/meta';import { LobeMinimaxAI } from './providers/minimax';import { LobeMinimaxCodingPlanAI } from './providers/minimaxCodingPlan';import { LobeMistralAI } from './providers/mistral';@@ -121,6 +122,7 @@ export const providerRuntimeMap = {lmstudio: LobeLMStudioAI,lobehub: LobeHubAI,longcat: LobeLongCatAI,+ meta: LobeMetaAI,minimax: LobeMinimaxAI,minimaxcodingplan: LobeMinimaxCodingPlanAI,mistral: LobeMistralAI,diff --git a/src/hooks/useProviderName.ts b/src/hooks/useProviderName.tsindex c3abab81359..5139db7bdf7 100644--- a/src/hooks/useProviderName.ts+++ b/src/hooks/useProviderName.ts@@ -1,7 +1,3 @@-import { DEFAULT_MODEL_PROVIDER_LIST } from 'model-bank/modelProviders';+import { getProviderDisplayName } from 'model-bank/modelProviders';-export const useProviderName = (provider: string) => {- const providerCard = DEFAULT_MODEL_PROVIDER_LIST.find((p) => p.id === provider);-- return providerCard?.name || provider;-};+export const useProviderName = (provider: string) => getProviderDisplayName(provider);diff --git a/src/utils/locale/runtimeErrorMessage.test.ts b/src/utils/locale/runtimeErrorMessage.test.tsindex 10d1b64c604..a0e533d2183 100644--- a/src/utils/locale/runtimeErrorMessage.test.ts+++ b/src/utils/locale/runtimeErrorMessage.test.ts@@ -18,6 +18,14 @@ describe('getRuntimeErrorMessage', () => {);});+ it('translates deprecated alias codes under their canonical key', () => {+ const t = createTranslator({+ 'modelRuntime:ContextEnginePipelineError': 'Localized pipeline error',+ });++ expect(getRuntimeErrorMessage(t, 'PipelineError')).toBe('Localized pipeline error');+ });+it('returns the raw fallback when a registered runtime error has no locale key', () => {const t = createTranslator({});diff --git a/src/utils/locale/runtimeErrorMessage.ts b/src/utils/locale/runtimeErrorMessage.tsindex 521f647f52e..69b3047b4dd 100644--- a/src/utils/locale/runtimeErrorMessage.ts+++ b/src/utils/locale/runtimeErrorMessage.ts@@ -1,4 +1,4 @@-import { getErrorCodeSpec } from '@lobechat/model-runtime';+import { getRuntimeErrorI18nKey } from '@lobechat/model-runtime';/*** Loose `t` shape that accepts any key / vars — the type-safe key inference in@@ -9,12 +9,9 @@ type LooseT = (key: string, vars?: Record<string, unknown>) => string;/*** Resolve the localized message for an error type, routing between the new* `modelRuntime` namespace (one key per `AgentRuntimeErrorType`) and the legacy- * `error.response.<X>` map.- *- * - If `code` is a known runtime code (present in `ERROR_CODE_SPECS`), the- * message lives under `modelRuntime:<code>`.- * - Otherwise (HTTP status code, Plugin*, Cloud-only ChatErrorType, etc.) it- * stays in the legacy `error.response.<X>` location.+ * `error.response.<X>` map. The routing rule itself lives in+ * `getRuntimeErrorI18nKey` so it stays in sync with the non-React+ * `getMessageError` in `@lobechat/fetch-sse`.** The caller should pre-load both namespaces:* `useTranslation(['error', 'modelRuntime'])`.@@ -26,9 +23,9 @@ export const getRuntimeErrorMessage = (fallbackMessage = '',): string => {if (code === undefined || code === null || code === '') return '';- const key =- typeof code === 'string' && getErrorCodeSpec(code)- ? `modelRuntime:${code}`- : `response.${code}`;- return (t as LooseT)(key, { ...vars, defaultValue: fallbackMessage });+ const { key, ns } = getRuntimeErrorI18nKey(code);+ // `error` is the default namespace for these callers, so only `modelRuntime`+ // needs an explicit prefix.+ const fullKey = ns === 'modelRuntime' ? `modelRuntime:${key}` : key;+ return (t as LooseT)(fullKey, { ...vars, defaultValue: fallbackMessage });};