🤯 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
🔨 chore: Update HF provider support (#9751)
sxjeru1b3f88346b2f
diff --git a/package.json b/package.jsonindex 4a6d7059d4f..d181e3369dd 100644--- a/package.json+++ b/package.json@@ -143,7 +143,7 @@"@fal-ai/client": "^1.6.2","@formkit/auto-animate": "^0.9.0","@google/genai": "^1.24.0",- "@huggingface/inference": "^2.8.1",+ "@huggingface/inference": "^4.11.3","@icons-pack/react-simple-icons": "^13.8.0","@khmyznikov/pwa-install": "0.3.9","@langchain/community": "^0.3.57",diff --git a/packages/model-bank/src/aiModels/akashchat.ts b/packages/model-bank/src/aiModels/akashchat.tsindex ca075ee6f8a..44ff7cdc09f 100644--- a/packages/model-bank/src/aiModels/akashchat.ts+++ b/packages/model-bank/src/aiModels/akashchat.ts@@ -3,7 +3,6 @@ import { AIChatModelCard } from '../types/aiModel';const akashChatModels: AIChatModelCard[] = [{abilities: {- functionCall: true,reasoning: true,},contextWindowTokens: 65_536,diff --git a/packages/model-bank/src/aiModels/groq.ts b/packages/model-bank/src/aiModels/groq.tsindex 2d5d9f72789..f73dabd74cb 100644--- a/packages/model-bank/src/aiModels/groq.ts+++ b/packages/model-bank/src/aiModels/groq.ts@@ -37,7 +37,7 @@ const groqChatModels: AIChatModelCard[] = [pricing: {units: [{ name: 'textInput', rate: 0.15, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textOutput', rate: 0.75, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 0.6, strategy: 'fixed', unit: 'millionTokens' },],},releasedAt: '2025-08-06',@@ -56,8 +56,8 @@ const groqChatModels: AIChatModelCard[] = [maxOutput: 65_536,pricing: {units: [- { name: 'textInput', rate: 0.1, strategy: 'fixed', unit: 'millionTokens' },- { name: 'textOutput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput', rate: 0.075, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },],},releasedAt: '2025-08-06',diff --git a/packages/model-bank/src/aiModels/huggingface.ts b/packages/model-bank/src/aiModels/huggingface.tsindex cfe1650a229..ce7fa8e8f45 100644--- a/packages/model-bank/src/aiModels/huggingface.ts+++ b/packages/model-bank/src/aiModels/huggingface.ts@@ -36,7 +36,6 @@ const huggingfaceChatModels: AIChatModelCard[] = [contextWindowTokens: 32_768,description: 'Qwen QwQ 是由 Qwen 团队开发的实验研究模型,专注于提升AI推理能力。',displayName: 'QwQ 32B Preview',- enabled: true,id: 'Qwen/QwQ-32B-Preview',type: 'chat',},@@ -67,7 +66,6 @@ const huggingfaceChatModels: AIChatModelCard[] = [},contextWindowTokens: 128_000,displayName: 'DeepSeek R1',- enabled: true,id: 'deepseek-ai/DeepSeek-R1',type: 'chat',},diff --git a/packages/model-bank/src/aiModels/siliconcloud.ts b/packages/model-bank/src/aiModels/siliconcloud.tsindex 4bcb04e1441..95e50098165 100644--- a/packages/model-bank/src/aiModels/siliconcloud.ts+++ b/packages/model-bank/src/aiModels/siliconcloud.ts@@ -195,6 +195,52 @@ const siliconcloudChatModels: AIChatModelCard[] = [},type: 'chat',},+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 256_000,+ description:+ 'Qwen3-VL-8B-Instruct 是 Qwen3 系列的视觉语言模型,基于 Qwen3-8B-Instruct 开发并在大量图文数据上训练,擅长通用视觉理解、以视觉为中心的对话以及图像中的多语言文本识别。适用于视觉问答、图像描述、多模态指令跟随与工具调用场景。',+ displayName: 'Qwen3 VL 8B Instruct',+ id: 'Qwen/Qwen3-VL-8B-Instruct',+ organization: 'Qwen',+ pricing: {+ currency: 'CNY',+ units: [+ { name: 'textInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 2, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2025-10-15',+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ reasoning: true,+ vision: true,+ },+ contextWindowTokens: 256_000,+ description:+ 'Qwen3-VL-8B-Thinking 是 Qwen3 系列的视觉思考版本,针对复杂多步推理任务优化,默认在回答前生成逐步思考(thinking chain)以提高推理准确性。适合需要深度推理的视觉问答、审阅图像内容并给出详细分析的场景。',+ displayName: 'Qwen3 VL 8B Thinking',+ id: 'Qwen/Qwen3-VL-8B-Thinking',+ organization: 'Qwen',+ pricing: {+ currency: 'CNY',+ units: [+ { name: 'textInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 5, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2025-10-15',+ settings: {+ extendParams: ['reasoningBudgetToken'],+ },+ type: 'chat',+ },{abilities: {functionCall: true,diff --git a/packages/model-runtime/src/core/contextBuilders/huggingface.test.ts b/packages/model-runtime/src/core/contextBuilders/huggingface.test.tsnew file mode 100644index 00000000000..c9b0b45e0d8--- /dev/null+++ b/packages/model-runtime/src/core/contextBuilders/huggingface.test.ts@@ -0,0 +1,325 @@+import { describe, expect, it } from 'vitest';++import type { OpenAIChatMessage } from '../../types';+import { convertOpenAIMessagesToHFFormat } from './huggingface';++describe('convertOpenAIMessagesToHFFormat', () => {+ it('should convert simple text messages', () => {+ const messages: OpenAIChatMessage[] = [+ { role: 'user', content: 'Hello' },+ { role: 'assistant', content: 'Hi there' },+ ];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result).toEqual([+ { role: 'user', content: 'Hello' },+ { role: 'assistant', content: 'Hi there' },+ ]);+ });++ it('should convert messages with name property', () => {+ const messages: OpenAIChatMessage[] = [{ role: 'user', content: 'Hello', name: 'John' }];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result).toEqual([{ role: 'user', content: 'Hello', name: 'John' }]);+ });++ it('should convert text content array to HF format', () => {+ const messages: OpenAIChatMessage[] = [+ {+ role: 'user',+ content: [{ type: 'text', text: 'Hello' }],+ },+ ];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result).toEqual([+ {+ role: 'user',+ content: [{ type: 'text', text: 'Hello' }],+ },+ ]);+ });++ it('should convert image_url content array to HF format', () => {+ const messages: OpenAIChatMessage[] = [+ {+ role: 'user',+ content: [+ {+ type: 'image_url',+ image_url: {+ url: 'https://example.com/image.jpg',+ detail: 'high',+ },+ },+ ],+ },+ ];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result).toEqual([+ {+ role: 'user',+ content: [+ {+ type: 'image_url',+ image_url: {+ url: 'https://example.com/image.jpg',+ detail: 'high',+ },+ },+ ],+ },+ ]);+ });++ it('should convert mixed content array', () => {+ const messages: OpenAIChatMessage[] = [+ {+ role: 'user',+ content: [+ { type: 'text', text: 'Check this image' },+ {+ type: 'image_url',+ image_url: {+ url: 'https://example.com/image.jpg',+ detail: 'low',+ },+ },+ ],+ },+ ];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result).toEqual([+ {+ role: 'user',+ content: [+ { type: 'text', text: 'Check this image' },+ {+ type: 'image_url',+ image_url: {+ url: 'https://example.com/image.jpg',+ detail: 'low',+ },+ },+ ],+ },+ ]);+ });++ it('should convert messages with tool_calls', () => {+ const messages: OpenAIChatMessage[] = [+ {+ role: 'assistant',+ content: 'I will call a tool',+ tool_calls: [+ {+ id: 'call_123',+ type: 'function',+ function: {+ name: 'get_weather',+ arguments: '{"city": "New York"}',+ },+ },+ ],+ },+ ];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result).toEqual([+ {+ role: 'assistant',+ content: 'I will call a tool',+ tool_calls: [+ {+ id: 'call_123',+ type: 'function',+ function: {+ name: 'get_weather',+ arguments: '{"city": "New York"}',+ },+ },+ ],+ },+ ]);+ });++ it('should convert messages with tool_call_id', () => {+ const messages: OpenAIChatMessage[] = [+ {+ role: 'tool',+ content: 'Weather data',+ tool_call_id: 'call_123',+ },+ ];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result).toEqual([+ {+ role: 'tool',+ content: 'Weather data',+ tool_call_id: 'call_123',+ },+ ]);+ });++ it('should handle undefined image_url detail', () => {+ const messages: OpenAIChatMessage[] = [+ {+ role: 'user',+ content: [+ {+ type: 'image_url',+ image_url: {+ url: 'https://example.com/image.jpg',+ },+ },+ ],+ },+ ];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result).toEqual([+ {+ role: 'user',+ content: [+ {+ type: 'image_url',+ image_url: {+ url: 'https://example.com/image.jpg',+ detail: undefined,+ },+ },+ ],+ },+ ]);+ });++ it('should handle unknown content types with fallback', () => {+ const messages: OpenAIChatMessage[] = [+ {+ role: 'user',+ content: [+ { type: 'text', text: 'Hello' },+ // @ts-ignore - Testing unknown content type+ { type: 'unknown', data: 'some data' },+ ],+ },+ ];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result).toEqual([+ {+ role: 'user',+ content: [+ { type: 'text', text: 'Hello' },+ { text: '', type: 'text' },+ ],+ },+ ]);+ });++ it('should handle empty content array', () => {+ const messages: OpenAIChatMessage[] = [+ {+ role: 'user',+ content: [],+ },+ ];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result).toEqual([+ {+ role: 'user',+ content: [],+ },+ ]);+ });++ it('should convert multiple messages with different content types', () => {+ const messages: OpenAIChatMessage[] = [+ { role: 'user', content: 'Simple text' },+ {+ role: 'assistant',+ content: [+ { type: 'text', text: 'Response with image' },+ {+ type: 'image_url',+ image_url: {+ url: 'https://example.com/response.jpg',+ detail: 'auto',+ },+ },+ ],+ },+ {+ role: 'user',+ content: [+ {+ type: 'image_url',+ image_url: {+ url: 'https://example.com/input.jpg',+ },+ },+ ],+ },+ ];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result).toHaveLength(3);+ expect(result[0].content).toBe('Simple text');+ expect(Array.isArray(result[1].content)).toBe(true);+ expect(Array.isArray(result[2].content)).toBe(true);+ });++ it('should preserve all message properties', () => {+ const messages: OpenAIChatMessage[] = [+ {+ role: 'assistant',+ content: 'Test message',+ name: 'assistant_name',+ tool_calls: [+ {+ id: 'call_456',+ type: 'function',+ function: {+ name: 'test_function',+ arguments: '{}',+ },+ },+ ],+ },+ ];++ const result = convertOpenAIMessagesToHFFormat(messages);++ expect(result[0]).toEqual({+ role: 'assistant',+ content: 'Test message',+ name: 'assistant_name',+ tool_calls: [+ {+ id: 'call_456',+ type: 'function',+ function: {+ name: 'test_function',+ arguments: '{}',+ },+ },+ ],+ });+ });+});diff --git a/packages/model-runtime/src/core/contextBuilders/huggingface.ts b/packages/model-runtime/src/core/contextBuilders/huggingface.tsnew file mode 100644index 00000000000..074aeb1e686--- /dev/null+++ b/packages/model-runtime/src/core/contextBuilders/huggingface.ts@@ -0,0 +1,69 @@+import type { OpenAIChatMessage, UserMessageContentPart } from '../../types';++/**+ * Converts OpenAI-style chat messages to Hugging Face chat completion format.+ *+ * @param messages - Array of OpenAI chat messages+ * @returns Array of messages compatible with HuggingFace ChatCompletionInput+ */+export function convertOpenAIMessagesToHFFormat(messages: OpenAIChatMessage[]): Array<{+ content?:+ | string+ | Array<+ | { text: string; type: 'text' }+ | { image_url: { detail?: 'auto' | 'low' | 'high'; url: string }; type: 'image_url' }+ >;+ name?: string;+ role: string;+ tool_call_id?: string;+ tool_calls?: Array<{ function: { arguments?: string; name: string }; id: string; type: string }>;+}> {+ return messages.map((message) => {+ // Handle content conversion: string stays as string, content parts get converted+ let convertedContent:+ | string+ | Array<+ | { text: string; type: 'text' }+ | { image_url: { detail?: 'auto' | 'low' | 'high'; url: string }; type: 'image_url' }+ >+ | undefined;++ if (typeof message.content === 'string') {+ convertedContent = message.content;+ } else if (Array.isArray(message.content)) {+ convertedContent = message.content.map((part: UserMessageContentPart) => {+ if (part.type === 'text') {+ return {+ text: part.text,+ type: 'text' as const,+ };+ } else if (part.type === 'image_url') {+ return {+ image_url: {+ detail: part.image_url.detail,+ url: part.image_url.url,+ },+ type: 'image_url' as const,+ };+ }+ // Fallback for unknown content types+ return { text: '', type: 'text' as const };+ });+ }++ return {+ content: convertedContent,+ name: message.name,+ role: message.role,+ tool_call_id: message.tool_call_id,+ tool_calls: message.tool_calls?.map((tc) => ({+ function: {+ arguments: tc.function.arguments,+ name: tc.function.name,+ },+ id: tc.id,+ type: 'function',+ })),+ };+ });+}diff --git a/packages/model-runtime/src/providers/huggingface/index.test.ts b/packages/model-runtime/src/providers/huggingface/index.test.tsindex 95d0da24a6e..92e2b86317a 100644--- a/packages/model-runtime/src/providers/huggingface/index.test.ts+++ b/packages/model-runtime/src/providers/huggingface/index.test.ts@@ -168,33 +168,6 @@ describe('LobeHuggingFaceAI', () => {});});- it('should use default max_tokens of 4096 when not provided', () => {- const mockClient = {- chatCompletionStream: vi.fn().mockReturnValue({- async *[Symbol.asyncIterator]() {- yield { choices: [] } as any;- },- }),- } as any;-- const mockInstance = {- baseURL: 'https://api.example.com',- };-- const payload = {- messages: [{ role: 'user', content: 'test' }],- model: 'test-model',- };-- params.customClient!.createChatCompletionStream(mockClient, payload as any, mockInstance);-- expect(mockClient.chatCompletionStream).toHaveBeenCalledWith(- expect.objectContaining({- max_tokens: 4096,- }),- );- });-it('should handle undefined baseURL', () => {const mockClient = {chatCompletionStream: vi.fn().mockReturnValue({@@ -385,129 +358,180 @@ describe('LobeHuggingFaceAI', () => {});it('should fetch and process models from HuggingFace API', async () => {- const mockModels = [- {- id: 'meta-llama/Meta-Llama-3.1-8B-Instruct',- tags: ['text-generation', 'llama'],- },- {- id: 'microsoft/Phi-3-mini-4k-instruct',- tags: ['text-generation'],- },- ];+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'meta-llama/Meta-Llama-3.1-8B-Instruct',+ object: 'model',+ created: 1759170171,+ owned_by: 'meta-llama',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'huggingface',+ status: 'live',+ context_length: 8192,+ supports_tools: false,+ supports_structured_output: false,+ is_model_author: true,+ },+ ],+ },+ {+ id: 'microsoft/Phi-3-mini-4k-instruct',+ object: 'model',+ created: 1759170171,+ owned_by: 'microsoft',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'huggingface',+ status: 'live',+ context_length: 4096,+ supports_tools: false,+ supports_structured_output: false,+ is_model_author: true,+ },+ ],+ },+ ],+ };global.fetch = vi.fn().mockResolvedValue({- json: async () => mockModels,+ ok: true,+ json: async () => mockResponse,} as Response);const models = await params.models!();- expect(fetch).toHaveBeenCalledWith('https://huggingface.co/api/models', {- method: 'GET',- });- expect(models).toHaveLength(2);- expect(models[0].id).toBe('meta-llama/Meta-Llama-3.1-8B-Instruct');- expect(models[1].id).toBe('microsoft/Phi-3-mini-4k-instruct');+ expect(fetch).toHaveBeenCalledWith('https://router.huggingface.co/v1/models');+ expect(models.length).toBeGreaterThan(0);});- it('should detect function-calling ability from tags', async () => {- const mockModels = [- {- id: 'test-model',- tags: ['function-calling', 'text-generation'],- },- ];+ it('should detect function-calling ability from provider info', async () => {+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'test-model',+ object: 'model',+ created: 1759170171,+ owned_by: 'test',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'test',+ status: 'live',+ supports_tools: true,+ is_model_author: true,+ },+ ],+ },+ ],+ };global.fetch = vi.fn().mockResolvedValue({- json: async () => mockModels,+ ok: true,+ json: async () => mockResponse,} as Response);const models = await params.models!();+ expect(models.length).toBeGreaterThan(0);expect(models[0].functionCall).toBe(true);});- it('should detect vision ability from vision keywords in tags', async () => {- const mockModels = [- {- id: 'vision-model-1',- tags: ['image-text-to-text', 'text-generation'],- },- {- id: 'vision-model-2',- tags: ['multimodal', 'text-generation'],- },- {- id: 'vision-model-3',- tags: ['vision', 'text-generation'],- },- ];-- global.fetch = vi.fn().mockResolvedValue({- json: async () => mockModels,- } as Response);-- const models = await params.models!();-- expect(models[0].vision).toBe(true);- expect(models[1].vision).toBe(true);- expect(models[2].vision).toBe(true);- });-- it('should detect reasoning ability from reasoning tag', async () => {- const mockModels = [- {- id: 'reasoning-model',- tags: ['reasoning', 'text-generation'],- },- ];-- global.fetch = vi.fn().mockResolvedValue({- json: async () => mockModels,- } as Response);-- const models = await params.models!();-- expect(models[0].reasoning).toBe(true);- });-- it('should detect reasoning ability from reasoning keywords in model id', async () => {- const mockModels = [- {- id: 'deepseek-r1-model',- tags: ['text-generation'],- },- {- id: 'qvq-model',- tags: ['text-generation'],- },- {- id: 'qwq-model',- tags: ['text-generation'],- },- ];+ it('should detect vision ability from input_modalities', async () => {+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'vision-model-1',+ object: 'model',+ created: 1759170171,+ owned_by: 'test',+ architecture: {+ input_modalities: ['image', 'text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'test',+ status: 'live',+ is_model_author: true,+ },+ ],+ },+ {+ id: 'vision-model-2',+ object: 'model',+ created: 1759170171,+ owned_by: 'test',+ architecture: {+ input_modalities: ['image'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'test',+ status: 'live',+ is_model_author: true,+ },+ ],+ },+ ],+ };global.fetch = vi.fn().mockResolvedValue({- json: async () => mockModels,+ ok: true,+ json: async () => mockResponse,} as Response);const models = await params.models!();- expect(models[0].reasoning).toBe(true);- expect(models[1].reasoning).toBe(true);- expect(models[2].reasoning).toBe(true);+ expect(models.length).toBeGreaterThan(0);+ const visionModels = models.filter((m) => m.vision);+ expect(visionModels.length).toBeGreaterThan(0);});it('should merge with LOBE_DEFAULT_MODEL_LIST when model is known', async () => {- const mockModels = [- {- id: 'meta-llama/llama-3.3-70b-instruct',- tags: ['text-generation'],- },- ];+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'meta-llama/llama-3.3-70b-instruct',+ object: 'model',+ created: 1759170171,+ owned_by: 'meta-llama',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'huggingface',+ status: 'live',+ context_length: 8192,+ is_model_author: true,+ },+ ],+ },+ ],+ };global.fetch = vi.fn().mockResolvedValue({- json: async () => mockModels,+ ok: true,+ json: async () => mockResponse,} as Response);const models = await params.models!();@@ -522,67 +546,126 @@ describe('LobeHuggingFaceAI', () => {});it('should handle models with case-insensitive matching', async () => {- const mockModels = [- {- id: 'META-LLAMA/LLAMA-3.3-70B-INSTRUCT',- tags: ['text-generation'],- },- ];+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'META-LLAMA/LLAMA-3.3-70B-INSTRUCT',+ object: 'model',+ created: 1759170171,+ owned_by: 'meta-llama',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'huggingface',+ status: 'live',+ is_model_author: true,+ },+ ],+ },+ ],+ };global.fetch = vi.fn().mockResolvedValue({- json: async () => mockModels,+ ok: true,+ json: async () => mockResponse,} as Response);const models = await params.models!();+ expect(models.length).toBeGreaterThan(0);expect(models[0].id).toBe('META-LLAMA/LLAMA-3.3-70B-INSTRUCT');});it('should set default values for unknown models', async () => {- const mockModels = [- {- id: 'unknown/unknown-model',- tags: ['text-generation'],- },- ];+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'unknown/unknown-model',+ object: 'model',+ created: 1759170171,+ owned_by: 'unknown',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'unknown',+ status: 'live',+ is_model_author: true,+ },+ ],+ },+ ],+ };global.fetch = vi.fn().mockResolvedValue({- json: async () => mockModels,+ ok: true,+ json: async () => mockResponse,} as Response);const models = await params.models!();+ expect(models.length).toBeGreaterThan(0);expect(models[0].enabled).toBe(false);expect(models[0].functionCall).toBe(false);expect(models[0].reasoning).toBe(false);expect(models[0].vision).toBe(false);});- it('should combine tag-based and model-list-based abilities', async () => {- const mockModels = [- {- id: 'meta-llama/llama-3.3-70b-instruct',- tags: ['function-calling', 'reasoning'],- },- ];+ it('should combine provider-based and model-list-based abilities', async () => {+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'meta-llama/llama-3.3-70b-instruct',+ object: 'model',+ created: 1759170171,+ owned_by: 'meta-llama',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'huggingface',+ status: 'live',+ supports_tools: true,+ is_model_author: true,+ },+ ],+ },+ ],+ };global.fetch = vi.fn().mockResolvedValue({- json: async () => mockModels,+ ok: true,+ json: async () => mockResponse,} as Response);const models = await params.models!();const model = models.find((m) => m.id === 'meta-llama/llama-3.3-70b-instruct');if (model) {- // Should have true if either tag or model list has the ability+ // Should have true if either provider info or model list has the abilityexpect(typeof model.functionCall).toBe('boolean');- expect(typeof model.reasoning).toBe('boolean');}});it('should handle empty model list', async () => {+ const mockResponse = {+ object: 'list',+ data: [],+ };+global.fetch = vi.fn().mockResolvedValue({- json: async () => [],+ ok: true,+ json: async () => mockResponse,} as Response);const models = await params.models!();@@ -593,50 +676,88 @@ describe('LobeHuggingFaceAI', () => {it('should handle API errors gracefully', async () => {global.fetch = vi.fn().mockRejectedValue(new Error('API Error'));- await expect(params.models!()).rejects.toThrow('API Error');+ const result = await params.models!();+ expect(result).toEqual([]);});it('should handle invalid JSON response', async () => {global.fetch = vi.fn().mockResolvedValue({+ ok: true,json: async () => {throw new Error('Invalid JSON');},} as unknown as Response);- await expect(params.models!()).rejects.toThrow('Invalid JSON');+ const result = await params.models!();+ expect(result).toEqual([]);});- it('should preserve contextWindowTokens from known models', async () => {- const mockModels = [- {- id: 'meta-llama/llama-3.3-70b-instruct',- tags: [],- },- ];+ it('should preserve contextWindowTokens from provider info', async () => {+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'meta-llama/llama-3.3-70b-instruct',+ object: 'model',+ created: 1759170171,+ owned_by: 'meta-llama',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'huggingface',+ status: 'live',+ context_length: 8192,+ is_model_author: true,+ },+ ],+ },+ ],+ };global.fetch = vi.fn().mockResolvedValue({- json: async () => mockModels,+ ok: true,+ json: async () => mockResponse,} as Response);const models = await params.models!();const model = models.find((m) => m.id === 'meta-llama/llama-3.3-70b-instruct');if (model) {- // contextWindowTokens should be preserved from LOBE_DEFAULT_MODEL_LIST if available- expect(model.contextWindowTokens).toBeDefined();+ // contextWindowTokens should be preserved from provider info+ expect(model.contextWindowTokens).toBe(8192);}});it('should preserve displayName from known models', async () => {- const mockModels = [- {- id: 'meta-llama/llama-3.3-70b-instruct',- tags: [],- },- ];+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'meta-llama/llama-3.3-70b-instruct',+ object: 'model',+ created: 1759170171,+ owned_by: 'meta-llama',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'huggingface',+ status: 'live',+ is_model_author: true,+ },+ ],+ },+ ],+ };global.fetch = vi.fn().mockResolvedValue({- json: async () => mockModels,+ ok: true,+ json: async () => mockResponse,} as Response);const models = await params.models!();@@ -647,5 +768,384 @@ describe('LobeHuggingFaceAI', () => {expect(model.displayName).toBeDefined();}});++ it('should fallback to other providers when model_author has missing context_length', async () => {+ // 场景:zai-org 是 is_model_author 但没有 context_length,novita provider 有完整信息+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'zai-org/GLM-4.6',+ object: 'model',+ created: 1759170171,+ owned_by: 'zai-org',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'novita',+ status: 'live',+ context_length: 204800,+ pricing: {+ input: 0.6,+ output: 2.2,+ },+ supports_tools: true,+ supports_structured_output: false,+ is_model_author: false,+ },+ {+ provider: 'zai-org',+ status: 'live',+ supports_tools: true,+ supports_structured_output: false,+ is_model_author: true,+ // context_length 缺失+ },+ ],+ },+ ],+ };++ global.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => mockResponse,+ } as Response);++ const models = await params.models!();+ expect(models.length).toBeGreaterThan(0);++ const model = models[0];+ // 应该从 novita provider 回退获取到 context_length+ expect(model.contextWindowTokens).toBe(204800);+ // 应该从 zai-org provider 获取到 supports_tools+ expect(model.functionCall).toBe(true);+ });++ it('should fallback to other providers when model_author has missing supports_tools', async () => {+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'test/model',+ object: 'model',+ created: 1759170171,+ owned_by: 'test',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'provider-with-tools',+ status: 'live',+ context_length: 2048,+ supports_tools: true,+ is_model_author: false,+ },+ {+ provider: 'author',+ status: 'live',+ context_length: 2048,+ is_model_author: true,+ // supports_tools 缺失+ },+ ],+ },+ ],+ };++ global.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => mockResponse,+ } as Response);++ const models = await params.models!();+ expect(models.length).toBeGreaterThan(0);++ const model = models[0];+ // 应该从 author provider 获取到 context_length+ expect(model.contextWindowTokens).toBe(2048);+ // 应该从 provider-with-tools 回退获取到 supports_tools+ expect(model.functionCall).toBe(true);+ });++ it('should use model_author provider data when all fields are present', async () => {+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'author/complete-model',+ object: 'model',+ created: 1759170171,+ owned_by: 'author',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'other',+ status: 'live',+ context_length: 1024,+ supports_tools: false,+ is_model_author: false,+ },+ {+ provider: 'author',+ status: 'live',+ context_length: 8192,+ supports_tools: true,+ is_model_author: true,+ },+ ],+ },+ ],+ };++ global.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => mockResponse,+ } as Response);++ const models = await params.models!();+ expect(models.length).toBeGreaterThan(0);++ const model = models[0];+ // 应该使用 author provider 的完整数据,而不是 other provider+ expect(model.contextWindowTokens).toBe(8192);+ expect(model.functionCall).toBe(true);+ });++ it('should select provider with most complete information when no model_author', async () => {+ // 场景:没有 is_model_author,但 novita provider 信息更完整+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'deepseek-ai/DeepSeek-V3.2-Exp',+ object: 'model',+ created: 1759126046,+ owned_by: 'deepseek-ai',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'novita',+ status: 'live',+ context_length: 163840,+ pricing: {+ input: 0.27,+ output: 0.41,+ },+ supports_tools: true,+ supports_structured_output: true,+ is_model_author: false,+ },+ ],+ },+ ],+ };++ global.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => mockResponse,+ } as Response);++ const models = await params.models!();+ expect(models.length).toBeGreaterThan(0);++ const model = models[0];+ // 应该从 novita provider 获取完整信息+ expect(model.contextWindowTokens).toBe(163840);+ expect(model.functionCall).toBe(true);+ expect(model.id).toBe('deepseek-ai/DeepSeek-V3.2-Exp');+ });++ it('should prefer provider with more fields when is_model_author is absent', async () => {+ // 场景:两个非作者 provider,选择信息更完整的+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'test/model',+ object: 'model',+ created: 1759170171,+ owned_by: 'test',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'provider-incomplete',+ status: 'live',+ context_length: 2048,+ // 只有 3 个字段+ is_model_author: false,+ },+ {+ provider: 'provider-complete',+ status: 'live',+ context_length: 4096,+ supports_tools: true,+ supports_structured_output: true,+ pricing: {+ input: 0.1,+ output: 0.2,+ },+ // 5 个字段,更完整+ is_model_author: false,+ },+ ],+ },+ ],+ };++ global.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => mockResponse,+ } as Response);++ const models = await params.models!();+ expect(models.length).toBeGreaterThan(0);++ const model = models[0];+ // 应该选择 provider-complete(信息更完整)而不是 provider-incomplete+ expect(model.contextWindowTokens).toBe(4096);+ expect(model.functionCall).toBe(true);+ });++ it('should extract pricing information from provider', async () => {+ // 场景:pricing 存在于 provider 中+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'zai-org/GLM-4.6',+ object: 'model',+ created: 1759170171,+ owned_by: 'zai-org',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'novita',+ status: 'live',+ context_length: 204800,+ pricing: {+ input: 0.6,+ output: 2.2,+ },+ supports_tools: true,+ is_model_author: false,+ },+ {+ provider: 'zai-org',+ status: 'live',+ supports_tools: true,+ is_model_author: true,+ // pricing 缺失+ },+ ],+ },+ ],+ };++ global.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => mockResponse,+ } as Response);++ const models = await params.models!();+ expect(models.length).toBeGreaterThan(0);++ const model = models[0];+ // 应该从 novita 回退获取到 pricing+ // 注意:processMultiProviderModelList 会转换 pricing 格式+ expect(model.pricing).toBeDefined();+ if (model.pricing && typeof model.pricing === 'object' && 'units' in model.pricing) {+ // 经过转换的格式+ expect((model.pricing as any).units).toHaveLength(2);+ } else {+ // 原始格式+ expect(model.pricing).toEqual({+ input: 0.6,+ output: 2.2,+ });+ }+ });++ it('should use pricing from model_author when available', async () => {+ const mockResponse = {+ object: 'list',+ data: [+ {+ id: 'author/model',+ object: 'model',+ created: 1759170171,+ owned_by: 'author',+ architecture: {+ input_modalities: ['text'],+ output_modalities: ['text'],+ },+ providers: [+ {+ provider: 'other',+ status: 'live',+ pricing: {+ input: 0.1,+ output: 0.1,+ },+ is_model_author: false,+ },+ {+ provider: 'author',+ status: 'live',+ pricing: {+ input: 0.05,+ output: 0.15,+ },+ is_model_author: true,+ },+ ],+ },+ ],+ };++ global.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => mockResponse,+ } as Response);++ const models = await params.models!();+ expect(models.length).toBeGreaterThan(0);++ const model = models[0];+ // 应该优先使用 author provider 的定价+ // 注意:processMultiProviderModelList 会转换 pricing 格式+ expect(model.pricing).toBeDefined();+ if (model.pricing && typeof model.pricing === 'object' && 'units' in model.pricing) {+ // 经过转换的格式,检查 rate 值+ const pricingUnits = (model.pricing as any).units;+ expect(pricingUnits).toHaveLength(2);+ const inputUnit = pricingUnits.find((u: any) => u.name === 'textInput');+ const outputUnit = pricingUnits.find((u: any) => u.name === 'textOutput');+ expect(inputUnit?.rate).toBe(0.05);+ expect(outputUnit?.rate).toBe(0.15);+ } else {+ // 原始格式+ expect(model.pricing).toEqual({+ input: 0.05,+ output: 0.15,+ });+ }+ });});});diff --git a/packages/model-runtime/src/providers/huggingface/index.ts b/packages/model-runtime/src/providers/huggingface/index.tsindex 6ce32c657d6..3808763deaf 100644--- a/packages/model-runtime/src/providers/huggingface/index.ts+++ b/packages/model-runtime/src/providers/huggingface/index.ts@@ -1,19 +1,16 @@-import { HfInference } from '@huggingface/inference';-import type { ChatModelCard } from '@lobechat/types';+import { InferenceClient } from '@huggingface/inference';import { ModelProvider } from 'model-bank';import urlJoin from 'url-join';+import { convertOpenAIMessagesToHFFormat } from '../../core/contextBuilders/huggingface';import {OpenAICompatibleFactoryOptions,createOpenAICompatibleRuntime,} from '../../core/openaiCompatibleFactory';import { convertIterableToStream } from '../../core/streams';import { AgentRuntimeErrorType } from '../../types/error';--export interface HuggingFaceModelCard {- id: string;- tags: string[];-}+import { processMultiProviderModelList } from '../../utils/modelParse';+import type { HuggingFaceRouterModelCard, HuggingFaceRouterResponse } from './type';export const params = {chatCompletion: {@@ -30,12 +27,11 @@ export const params = {},},customClient: {- createChatCompletionStream: (client: HfInference, payload, instance) => {- const { max_tokens = 4096 } = payload;+ createChatCompletionStream: (client: InferenceClient, payload, instance) => {const hfRes = client.chatCompletionStream({endpointUrl: instance.baseURL ? urlJoin(instance.baseURL, payload.model) : instance.baseURL,- max_tokens: max_tokens,- messages: payload.messages,+ max_tokens: payload.max_tokens,+ messages: convertOpenAIMessagesToHFFormat(payload.messages),model: payload.model,stream: true,temperature: payload.temperature,@@ -51,56 +47,91 @@ export const params = {return convertIterableToStream(hfRes);},- createClient: (options) => new HfInference(options.apiKey),+ createClient: (options) =>+ new InferenceClient(options.apiKey ?? '', {+ endpointUrl: options.baseURL ?? undefined,+ }),},debug: {chatCompletion: () => process.env.DEBUG_HUGGINGFACE_CHAT_COMPLETION === '1',},models: async () => {- const { LOBE_DEFAULT_MODEL_LIST } = await import('model-bank');+ let modelList: HuggingFaceRouterModelCard[] = [];- const visionKeywords = ['image-text-to-text', 'multimodal', 'vision'];+ try {+ const response = await fetch('https://router.huggingface.co/v1/models');+ if (response.ok) {+ const data: HuggingFaceRouterResponse = await response.json();+ modelList = data.data;+ }+ } catch (error) {+ console.error('Failed to fetch HuggingFace router models:', error);+ return [];+ }- const reasoningKeywords = ['deepseek-r1', 'qvq', 'qwq'];+ const formattedModels = modelList+ .map((model) => {+ const { architecture, providers } = model;- // ref: https://huggingface.co/api/models- const url = 'https://huggingface.co/api/models';- const response = await fetch(url, {- method: 'GET',- });- const json = await response.json();+ // 选择提供商信息的优先级:is_model_author > 信息完整度 > 默认首个+ const mainProvider =+ providers.find((p) => p.is_model_author) ||+ providers.reduce((prev, curr) => {+ // 计算每个 provider 非 undefined 的字段数+ const prevFieldCount = Object.values(prev).filter(+ (v) => v !== undefined && v !== null,+ ).length;+ const currFieldCount = Object.values(curr).filter(+ (v) => v !== undefined && v !== null,+ ).length;+ return currFieldCount > prevFieldCount ? curr : prev;+ }) ||+ providers[0];- const modelList: HuggingFaceModelCard[] = json;+ if (!mainProvider) {+ return undefined;+ }- return modelList- .map((model) => {- const knownModel = LOBE_DEFAULT_MODEL_LIST.find(- (m) => model.id.toLowerCase() === m.id.toLowerCase(),- );+ // 多 provider 回退策略:先从主 provider 获取,缺失时查其他 provider+ const getFieldFromProviders = (field: keyof typeof mainProvider) => {+ const value = mainProvider[field];+ if (value !== undefined && value !== null) {+ return value;+ }+ // 缺失时遍历其他 provider+ return providers.find(+ (p) => p !== mainProvider && p[field] !== undefined && p[field] !== null,+ )?.[field];+ };++ const inputModalities = architecture?.input_modalities || [];+ const contextWindowTokens = getFieldFromProviders('context_length') as number | undefined;+ const supportsTools = getFieldFromProviders('supports_tools') as boolean | undefined;+ // const supportsStructuredOutput = getFieldFromProviders('supports_structured_output') as boolean | undefined;++ // displayName 使用 id 去除斜杠左侧内容(例如 'zai-org/GLM-4.6' -> 'GLM-4.6')+ const displayName =+ typeof model.id === 'string' && model.id.includes('/')+ ? model.id.split('/').slice(1).join('/').trim()+ : model.id;++ const pricing = getFieldFromProviders('pricing') as+ | { input?: number; output?: number }+ | undefined;return {- contextWindowTokens: knownModel?.contextWindowTokens ?? undefined,- displayName: knownModel?.displayName ?? undefined,- enabled: knownModel?.enabled || false,- functionCall:- model.tags.some((tag) => tag.toLowerCase().includes('function-calling')) ||- knownModel?.abilities?.functionCall ||- false,+ contextWindowTokens,+ created: model.created,+ displayName,+ functionCall: supportsTools ?? false,id: model.id,- reasoning:- model.tags.some((tag) => tag.toLowerCase().includes('reasoning')) ||- reasoningKeywords.some((keyword) => model.id.toLowerCase().includes(keyword)) ||- knownModel?.abilities?.reasoning ||- false,- vision:- model.tags.some((tag) =>- visionKeywords.some((keyword) => tag.toLowerCase().includes(keyword)),- ) ||- knownModel?.abilities?.vision ||- false,+ pricing,+ vision: inputModalities.includes('image') ?? false,};})- .filter(Boolean) as ChatModelCard[];+ .filter((m): m is Exclude<typeof m, undefined> => m !== undefined);++ return await processMultiProviderModelList(formattedModels, 'huggingface');},provider: ModelProvider.HuggingFace,} satisfies OpenAICompatibleFactoryOptions;diff --git a/packages/model-runtime/src/providers/huggingface/type.ts b/packages/model-runtime/src/providers/huggingface/type.tsnew file mode 100644index 00000000000..a303f96950c--- /dev/null+++ b/packages/model-runtime/src/providers/huggingface/type.ts@@ -0,0 +1,31 @@+interface HFArchitecture {+ input_modalities: string[];+ output_modalities: string[];+}++interface HFProviderInfo {+ context_length?: number;+ is_model_author?: boolean;+ pricing?: {+ input?: number;+ output?: number;+ };+ provider: string;+ status: string;+ supports_structured_output?: boolean;+ supports_tools?: boolean;+}++export interface HuggingFaceRouterModelCard {+ architecture: HFArchitecture;+ created: number;+ id: string;+ object: string;+ owned_by: string;+ providers: HFProviderInfo[];+}++export interface HuggingFaceRouterResponse {+ data: HuggingFaceRouterModelCard[];+ object: string;+}diff --git a/src/app/(backend)/webapi/stt/openai/route.ts b/src/app/(backend)/webapi/stt/openai/route.tsindex f82dc28423a..26ff12a9031 100644--- a/src/app/(backend)/webapi/stt/openai/route.ts+++ b/src/app/(backend)/webapi/stt/openai/route.ts@@ -39,7 +39,10 @@ export const POST = async (req: Request) => {// if resOrOpenAI is a Response, it means there is an error,just return itif (openaiOrErrResponse instanceof Response) return openaiOrErrResponse;- const res = await createOpenaiAudioTranscriptions({ openai: openaiOrErrResponse, payload });+ const res = await createOpenaiAudioTranscriptions({+ openai: openaiOrErrResponse as any,+ payload,+ });return new Response(JSON.stringify(res), {headers: {diff --git a/src/app/(backend)/webapi/tts/openai/route.ts b/src/app/(backend)/webapi/tts/openai/route.tsindex fddfc92563e..d9d6b9c6702 100644--- a/src/app/(backend)/webapi/tts/openai/route.ts+++ b/src/app/(backend)/webapi/tts/openai/route.ts@@ -34,5 +34,5 @@ export const POST = async (req: Request) => {// if resOrOpenAI is a Response, it means there is an error,just return itif (openaiOrErrResponse instanceof Response) return openaiOrErrResponse;- return await createOpenaiAudioSpeech({ openai: openaiOrErrResponse, payload });+ return await createOpenaiAudioSpeech({ openai: openaiOrErrResponse as any, payload });};