🤯 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
🐛 fix: refactor tools-engine and fix search token count (#9448)
Arvin Xue82d4b727447
diff --git a/package.json b/package.jsonindex 7460b78138d..0b4cffc638e 100644--- a/package.json+++ b/package.json@@ -360,6 +360,7 @@"remark-frontmatter": "^5.0.0","remark-mdx": "^3.1.1","remark-parse": "^11.0.0",+ "require-in-the-middle": "^7.5.2","semantic-release": "^21.1.2","serwist": "^9.2.1","stylelint": "^15.11.0",diff --git a/packages/context-engine/src/index.ts b/packages/context-engine/src/index.tsindex 805cf728d94..6c2b006b510 100644--- a/packages/context-engine/src/index.ts+++ b/packages/context-engine/src/index.ts@@ -1,5 +1,5 @@// Core types and interfaces-export type * from './types';+export * from './types';// Base classesexport { BaseProcessor } from './base/BaseProcessor';@@ -28,5 +28,14 @@ export {ToolMessageReorder,} from './processors';-// Constants-export { PipelineError, ProcessorError, ProcessorType } from './types';+// Tools Engine+export type {+ FunctionCallChecker,+ GenerateToolsParams,+ PluginEnableChecker,+ ToolNameGenerator,+ ToolsEngineOptions,+ ToolsGenerationContext,+ ToolsGenerationResult,+} from './tools';+export { filterValidManifests, ToolsEngine, validateManifest } from './tools';diff --git a/packages/context-engine/src/tools/ToolsEngine.ts b/packages/context-engine/src/tools/ToolsEngine.tsnew file mode 100644index 00000000000..dfb914c1e98--- /dev/null+++ b/packages/context-engine/src/tools/ToolsEngine.ts@@ -0,0 +1,298 @@+import debug from 'debug';++import {+ FunctionCallChecker,+ GenerateToolsParams,+ LobeChatPluginManifest,+ PluginEnableChecker,+ ToolsEngineOptions,+ ToolsGenerationContext,+ ToolsGenerationResult,+ UniformTool,+} from './types';+import { generateToolName } from './utils';++const log = debug('context-engine:tools-engine');++/**+ * Tools Engine - Unified processing of tools array construction and transformation+ */+export class ToolsEngine {+ private manifestSchemas: Map<string, LobeChatPluginManifest>;+ private enableChecker?: PluginEnableChecker;+ private functionCallChecker?: FunctionCallChecker;+ private defaultToolIds: string[];+ private options: ToolsEngineOptions;++ constructor(options: ToolsEngineOptions) {+ this.options = options;+ this.defaultToolIds = options.defaultToolIds || [];+ log(+ 'Initializing ToolsEngine with %d manifest schemas and %d default tools',+ options.manifestSchemas.length,+ this.defaultToolIds.length,+ );++ // Convert manifest schemas to Map for improved lookup performance+ this.manifestSchemas = new Map(+ options.manifestSchemas.map((schema) => [schema.identifier, schema]),+ );+ this.enableChecker = options.enableChecker;+ this.functionCallChecker = options.functionCallChecker;++ log(+ 'ToolsEngine initialized with plugins: %o, default tools: %o',+ Array.from(this.manifestSchemas.keys()),+ this.defaultToolIds,+ );+ }++ /**+ * Generate tools array+ * @param params Tools generation parameters+ * @returns Processed tools array, or undefined if tools should not be enabled+ */+ generateTools(params: GenerateToolsParams): UniformTool[] | undefined {+ const { toolIds = [], model, provider, context } = params;++ // Merge user-provided tool IDs with default tool IDs+ const allToolIds = [...toolIds, ...this.defaultToolIds];++ log(+ 'Generating tools for model=%s, provider=%s, pluginIds=%o (includes %d default tools)',+ model,+ provider,+ allToolIds,+ this.defaultToolIds.length,+ );++ // 1. Check if model supports Function Calling+ if (!this.checkFunctionCallSupport(model, provider)) {+ log('Function calling not supported for model=%s, provider=%s', model, provider);+ return undefined;+ }++ // 2. Filter and validate plugins+ const { enabledManifests } = this.filterEnabledPlugins(allToolIds, model, provider, context);++ // 3. If no tools available, return undefined+ if (enabledManifests.length === 0) {+ log('No enabled manifests found, returning undefined');+ return undefined;+ }++ // 4. Convert to UniformTool format+ const tools = this.convertManifestsToTools(enabledManifests);+ log('Generated %d tools from %d manifests', tools.length, enabledManifests.length);++ return tools;+ }++ /**+ * Generate tools array (detailed version)+ * @param params Tools generation parameters+ * @returns Detailed tools generation result+ */+ generateToolsDetailed(params: GenerateToolsParams): ToolsGenerationResult {+ const { toolIds = [], model, provider, context } = params;++ // Merge user-provided tool IDs with default tool IDs+ const allToolIds = [...toolIds, ...this.defaultToolIds];++ log(+ 'Generating detailed tools for model=%s, provider=%s, pluginIds=%o (includes %d default tools)',+ model,+ provider,+ allToolIds,+ this.defaultToolIds.length,+ );++ // Filter and validate plugins+ const { enabledManifests, filteredPlugins } = this.filterEnabledPlugins(+ allToolIds,+ model,+ provider,+ context,+ );++ // Convert to UniformTool format+ const tools = this.convertManifestsToTools(enabledManifests);++ log(+ 'Generated detailed result: enabled=%d, filtered=%d, tools=%d',+ enabledManifests.length,+ filteredPlugins.length,+ tools.length,+ );++ return {+ enabledToolIds: enabledManifests.map((m) => m.identifier),+ filteredTools: filteredPlugins,+ tools: tools.length > 0 ? tools : undefined,+ };+ }++ /**+ * Check if model supports Function Calling+ */+ private checkFunctionCallSupport(model: string, provider: string): boolean {+ if (this.functionCallChecker) {+ const result = this.functionCallChecker(model, provider);+ log('Function calling check result for %s/%s: %s', model, provider, result);+ return result;+ }++ // Default to assuming Function Calling is supported+ log('No function calling checker provided, defaulting to true');+ return true;+ }++ /**+ * Filter enabled plugins+ */+ private filterEnabledPlugins(+ pluginIds: string[],+ model: string,+ provider: string,+ context?: ToolsGenerationContext,+ ): {+ enabledManifests: LobeChatPluginManifest[];+ filteredPlugins: Array<{+ id: string;+ reason: 'not_found' | 'disabled' | 'incompatible';+ }>;+ } {+ const enabledManifests: LobeChatPluginManifest[] = [];+ const filteredPlugins: Array<{+ id: string;+ reason: 'not_found' | 'disabled' | 'incompatible';+ }> = [];++ log('Filtering plugins: %o', pluginIds);++ for (const pluginId of pluginIds) {+ const manifest = this.manifestSchemas.get(pluginId);++ if (!manifest) {+ log('Plugin not found: %s', pluginId);+ filteredPlugins.push({ id: pluginId, reason: 'not_found' });+ continue;+ }++ // Use injected checker function or default check logic+ const isEnabled = this.enableChecker+ ? this.enableChecker({+ context,+ manifest,+ model,+ pluginId,+ provider,+ })+ : this.defaultEnabledCheck();++ if (isEnabled) {+ log('Plugin enabled: %s', pluginId);+ enabledManifests.push(manifest);+ } else {+ log('Plugin disabled: %s', pluginId);+ filteredPlugins.push({ id: pluginId, reason: 'disabled' });+ }+ }++ log(+ 'Filtering complete: enabled=%d, filtered=%d',+ enabledManifests.length,+ filteredPlugins.length,+ );+ return { enabledManifests, filteredPlugins };+ }++ /**+ * Default enabled check logic+ */+ private defaultEnabledCheck(): boolean {+ // Default to enabling all tools+ return true;+ }++ /**+ * Convert manifests to UniformTool array+ */+ private convertManifestsToTools(manifests: LobeChatPluginManifest[]): UniformTool[] {+ log('Converting %d manifests to tools', manifests.length);++ // Use simplified conversion logic to avoid external package dependencies+ const tools = manifests.flatMap((manifest) =>+ manifest.api.map((api) => ({+ function: {+ description: api.description,+ name: this.generateToolName(manifest.identifier, api.name, manifest.type),+ parameters: api.parameters,+ },+ type: 'function' as const,+ })),+ );++ log('Converted to %d tools', tools.length);+ return tools;+ }++ /**+ * Generate tool calling name+ * Uses external generator if provided, otherwise uses default logic from utils+ */+ private generateToolName(identifier: string, apiName: string, type?: string): string {+ // If external name generator is provided, use it+ if (this.options.generateToolName) {+ return this.options.generateToolName(identifier, apiName, type);+ }++ // Use default tool name generation logic from utils+ return generateToolName(identifier, apiName, type);+ }++ /**+ * 获取可用的插件列表(用于调试和监控)+ */+ getAvailablePlugins(): string[] {+ return Array.from(this.manifestSchemas.keys());+ }++ /**+ * 检查特定插件是否可用+ */+ hasPlugin(pluginId: string): boolean {+ return this.manifestSchemas.has(pluginId);+ }++ /**+ * 获取插件的 manifest+ */+ getPluginManifest(pluginId: string): LobeChatPluginManifest | undefined {+ return this.manifestSchemas.get(pluginId);+ }++ /**+ * 更新插件 manifest schemas(用于动态添加插件)+ */+ updateManifestSchemas(manifestSchemas: LobeChatPluginManifest[]): void {+ this.manifestSchemas.clear();+ for (const schema of manifestSchemas) {+ this.manifestSchemas.set(schema.identifier, schema);+ }+ }++ /**+ * 添加单个插件 manifest+ */+ addPluginManifest(manifest: LobeChatPluginManifest): void {+ this.manifestSchemas.set(manifest.identifier, manifest);+ }++ /**+ * 移除插件 manifest+ */+ removePluginManifest(pluginId: string): boolean {+ return this.manifestSchemas.delete(pluginId);+ }+}diff --git a/packages/context-engine/src/tools/__tests__/ToolsEngine.test.ts b/packages/context-engine/src/tools/__tests__/ToolsEngine.test.tsnew file mode 100644index 00000000000..3f9aee2f90f--- /dev/null+++ b/packages/context-engine/src/tools/__tests__/ToolsEngine.test.ts@@ -0,0 +1,814 @@+import { describe, expect, it, vi } from 'vitest';++import { ToolsEngine } from '../ToolsEngine';+import type { LobeChatPluginManifest } from '../types';++// Mock manifest schemas for testing+const mockWebBrowsingManifest: LobeChatPluginManifest = {+ api: [+ {+ description: 'Search the web',+ name: 'search',+ parameters: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Search query' },+ },+ required: ['query'],+ },+ },+ ],+ identifier: 'lobe-web-browsing',+ meta: {+ title: 'Web Browsing',+ description: 'Browse the web',+ },+ type: 'builtin',+};++const mockDalleManifest: LobeChatPluginManifest = {+ api: [+ {+ description: 'Generate images',+ name: 'generateImage',+ parameters: {+ type: 'object',+ properties: {+ prompt: { type: 'string', description: 'Image prompt' },+ },+ required: ['prompt'],+ },+ },+ ],+ identifier: 'dalle',+ meta: {+ title: 'DALL-E',+ description: 'Generate images',+ },+ type: 'builtin',+};++describe('ToolsEngine', () => {+ describe('constructor', () => {+ it('should initialize with manifest schemas', () => {+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest, mockDalleManifest],+ });++ expect(engine.hasPlugin('lobe-web-browsing')).toBe(true);+ expect(engine.hasPlugin('dalle')).toBe(true);+ expect(engine.hasPlugin('non-existent')).toBe(false);+ });++ it('should store available plugins', () => {+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest, mockDalleManifest],+ });++ const availablePlugins = engine.getAvailablePlugins();+ expect(availablePlugins).toEqual(['lobe-web-browsing', 'dalle']);+ });+ });++ describe('generateTools', () => {+ it('should return undefined when function calling is not supported', () => {+ const mockFunctionCallChecker = vi.fn().mockReturnValue(false);+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest],+ functionCallChecker: mockFunctionCallChecker,+ });++ const result = engine.generateTools({+ toolIds: ['lobe-web-browsing'],+ model: 'gpt-3.5-turbo',+ provider: 'openai',+ });++ expect(result).toBeUndefined();+ });++ it('should return undefined when no plugins are enabled', () => {+ const mockEnableChecker = vi.fn().mockReturnValue(false);+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest],+ enableChecker: mockEnableChecker,+ functionCallChecker: () => true,+ });++ const result = engine.generateTools({+ toolIds: ['lobe-web-browsing'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeUndefined();+ expect(mockEnableChecker).toHaveBeenCalledWith({+ pluginId: 'lobe-web-browsing',+ manifest: mockWebBrowsingManifest,+ model: 'gpt-4',+ provider: 'openai',+ context: undefined,+ });+ });++ it('should generate tools when plugins are enabled', () => {+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest],+ enableChecker: () => true,+ functionCallChecker: () => true,+ });++ const result = engine.generateTools({+ toolIds: ['lobe-web-browsing'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toEqual([+ {+ type: 'function',+ function: {+ name: 'lobe-web-browsing____search____builtin',+ description: 'Search the web',+ parameters: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Search query' },+ },+ required: ['query'],+ },+ },+ },+ ]);+ });++ it('should pass context to enable checker', () => {+ const mockEnableChecker = vi.fn().mockReturnValue(true);+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest],+ enableChecker: mockEnableChecker,+ functionCallChecker: () => true,+ });++ const context = { isSearchEnabled: true };+ engine.generateTools({+ toolIds: ['lobe-web-browsing'],+ model: 'gpt-4',+ provider: 'openai',+ context,+ });++ expect(mockEnableChecker).toHaveBeenCalledWith({+ pluginId: 'lobe-web-browsing',+ manifest: mockWebBrowsingManifest,+ model: 'gpt-4',+ provider: 'openai',+ context,+ });+ });++ it('should handle non-existent plugins gracefully', () => {+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest],+ enableChecker: () => true,+ functionCallChecker: () => true,+ });++ const result = engine.generateTools({+ toolIds: ['lobe-web-browsing', 'non-existent'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeDefined();+ expect(result).toHaveLength(1);+ });+ });++ describe('generateToolsDetailed', () => {+ it('should return detailed results with filtered plugins', () => {+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest, mockDalleManifest],+ enableChecker: ({ pluginId }) => pluginId === 'lobe-web-browsing',+ functionCallChecker: () => true,+ });++ const result = engine.generateToolsDetailed({+ toolIds: ['lobe-web-browsing', 'dalle', 'non-existent'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.tools).toHaveLength(1);+ expect(result.enabledToolIds).toEqual(['lobe-web-browsing']);+ expect(result.filteredTools).toEqual([+ { id: 'dalle', reason: 'disabled' },+ { id: 'non-existent', reason: 'not_found' },+ ]);+ });+ });++ describe('plugin management', () => {+ it('should allow adding new plugin manifest', () => {+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest],+ });++ expect(engine.hasPlugin('dalle')).toBe(false);++ engine.addPluginManifest(mockDalleManifest);++ expect(engine.hasPlugin('dalle')).toBe(true);+ expect(engine.getPluginManifest('dalle')).toBe(mockDalleManifest);+ });++ it('should allow removing plugin manifest', () => {+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest, mockDalleManifest],+ });++ expect(engine.hasPlugin('dalle')).toBe(true);++ const removed = engine.removePluginManifest('dalle');++ expect(removed).toBe(true);+ expect(engine.hasPlugin('dalle')).toBe(false);+ });++ it('should allow updating all manifest schemas', () => {+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest],+ });++ expect(engine.getAvailablePlugins()).toEqual(['lobe-web-browsing']);++ engine.updateManifestSchemas([mockDalleManifest]);++ expect(engine.getAvailablePlugins()).toEqual(['dalle']);+ });+ });++ describe('default behavior', () => {+ it('should use default enable checker when none provided', () => {+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest],+ functionCallChecker: () => true,+ });++ const result = engine.generateTools({+ toolIds: ['lobe-web-browsing'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeDefined();+ expect(result).toHaveLength(1);+ });++ it('should use default function call checker when none provided', () => {+ const engine = new ToolsEngine({+ manifestSchemas: [mockWebBrowsingManifest],+ enableChecker: () => true,+ });++ const result = engine.generateTools({+ toolIds: ['lobe-web-browsing'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeDefined();+ expect(result).toHaveLength(1);+ });+ });++ describe('ToolsEngine Integration Tests (migrated from enabledSchema)', () => {+ // Mock manifest data similar to the original tool selector tests+ const mockManifests: LobeChatPluginManifest[] = [+ {+ identifier: 'plugin-1',+ api: [{ name: 'api-1', description: 'API 1', parameters: {} }],+ meta: {+ title: 'Plugin 1',+ description: 'Plugin 1 description',+ avatar: '🔧',+ },+ type: 'default',+ },+ {+ identifier: 'plugin-2',+ api: [{ name: 'api-2', description: 'API 2', parameters: {} }],+ meta: {+ title: 'Plugin 2',+ description: 'Plugin 2 description',+ avatar: '⚙️',+ },+ type: 'default',+ },+ {+ identifier: 'plugin-3',+ api: [+ {+ name: 'api-3',+ description: '123123',+ parameters: {+ type: 'object',+ properties: { a: { type: 'string' } },+ },+ // This should not appear in the final result+ url: 'bac',+ },+ ],+ meta: {+ title: 'Plugin 3',+ description: 'Plugin 3 description',+ avatar: '🛠️',+ },+ type: 'default',+ },+ {+ identifier: 'plugin-4',+ api: [{ name: 'api-4', description: 'API 4', parameters: {} }],+ meta: {+ title: 'Plugin 4',+ description: 'Plugin 4 description',+ avatar: '🔩',+ },+ type: 'standalone',+ },+ {+ identifier: 'long-long-plugin-with-id',+ api: [+ {+ name: 'long-long-manifest-long-long-apiName',+ description: 'Long API',+ parameters: {},+ },+ ],+ meta: {+ title: 'Long Plugin',+ description: 'Long plugin description',+ avatar: '📏',+ },+ type: 'default',+ },+ {+ identifier: 'builtin-1',+ api: [{ name: 'builtin-api-1', description: 'Builtin API 1', parameters: {} }],+ meta: {+ title: 'Builtin 1',+ description: 'Builtin 1 description',+ avatar: '🏗️',+ },+ type: 'builtin',+ },+ ];++ const createTestEngine = () => {+ return new ToolsEngine({+ manifestSchemas: mockManifests,+ functionCallChecker: () => true, // Always allow function calls for tests+ });+ };++ describe('basic tool generation', () => {+ it('should return correct tools array for multiple plugins', () => {+ const engine = createTestEngine();+ const result = engine.generateTools({+ toolIds: ['plugin-1', 'plugin-2'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toEqual([+ {+ type: 'function',+ function: {+ name: 'plugin-1____api-1',+ description: 'API 1',+ parameters: {},+ },+ },+ {+ type: 'function',+ function: {+ name: 'plugin-2____api-2',+ description: 'API 2',+ parameters: {},+ },+ },+ ]);+ });++ it('should handle standalone plugin type correctly', () => {+ const engine = createTestEngine();+ const result = engine.generateTools({+ toolIds: ['plugin-4'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toEqual([+ {+ type: 'function',+ function: {+ name: 'plugin-4____api-4____standalone',+ description: 'API 4',+ parameters: {},+ },+ },+ ]);+ });++ it('should handle builtin plugin type correctly', () => {+ const engine = createTestEngine();+ const result = engine.generateTools({+ toolIds: ['builtin-1'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toEqual([+ {+ type: 'function',+ function: {+ name: 'builtin-1____builtin-api-1____builtin',+ description: 'Builtin API 1',+ parameters: {},+ },+ },+ ]);+ });++ it('should return empty array when no plugins match', () => {+ const engine = createTestEngine();+ const result = engine.generateTools({+ toolIds: [],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeUndefined();+ });++ it('should handle non-existent plugins gracefully', () => {+ const engine = createTestEngine();+ const result = engine.generateTools({+ toolIds: ['non-existent-plugin'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeUndefined();+ });+ });++ describe('long name handling (MD5 hash)', () => {+ it('should return MD5 hash for long API names', () => {+ const engine = createTestEngine();+ const result = engine.generateTools({+ toolIds: ['long-long-plugin-with-id'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toHaveLength(1);+ expect(result![0]).toEqual({+ type: 'function',+ function: {+ // The long action name should be hashed+ name: expect.stringMatching(/^long-long-plugin-with-id____MD5HASH_[a-f0-9]+$/),+ description: 'Long API',+ parameters: {},+ },+ });++ // Verify the specific hash matches expected value from original test+ expect(result![0].function.name).toContain('MD5HASH_');+ });+ });++ describe('parameter handling and filtering', () => {+ // fix https://github.com/lobehub/lobe-chat/issues/2036+ it('should not include URL field in function parameters', () => {+ const engine = createTestEngine();+ const result = engine.generateTools({+ toolIds: ['plugin-3'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toHaveLength(1);+ expect(result![0].function).toEqual({+ description: '123123',+ name: 'plugin-3____api-3',+ parameters: {+ properties: {+ a: {+ type: 'string',+ },+ },+ type: 'object',+ },+ });++ // Ensure URL is not included+ expect(result![0].function).not.toHaveProperty('url');+ });++ it('should preserve all other API properties correctly', () => {+ const engine = createTestEngine();+ const result = engine.generateTools({+ toolIds: ['plugin-3'],+ model: 'gpt-4',+ provider: 'openai',+ });++ const func = result![0].function;+ expect(func.description).toBe('123123');+ expect(func.name).toBe('plugin-3____api-3');+ expect(func.parameters).toEqual({+ type: 'object',+ properties: { a: { type: 'string' } },+ });+ });+ });++ describe('function calling support', () => {+ it('should return undefined when function calling is not supported', () => {+ const engine = new ToolsEngine({+ manifestSchemas: mockManifests,+ functionCallChecker: () => false, // Disable function calls+ });++ const result = engine.generateTools({+ toolIds: ['plugin-1'],+ model: 'gpt-3.5-turbo',+ provider: 'openai',+ });++ expect(result).toBeUndefined();+ });++ it('should respect function calling checker logic', () => {+ const engine = new ToolsEngine({+ manifestSchemas: mockManifests,+ functionCallChecker: (model: string) => model.includes('gpt-4'), // Only allow GPT-4+ });++ // Should work with GPT-4+ const result1 = engine.generateTools({+ toolIds: ['plugin-1'],+ model: 'gpt-4',+ provider: 'openai',+ });+ expect(result1).toBeDefined();+ expect(result1).toHaveLength(1);++ // Should not work with GPT-3.5+ const result2 = engine.generateTools({+ toolIds: ['plugin-1'],+ model: 'gpt-3.5-turbo',+ provider: 'openai',+ });+ expect(result2).toBeUndefined();+ });+ });++ describe('plugin enable filtering', () => {+ it('should respect enable checker logic', () => {+ const engine = new ToolsEngine({+ manifestSchemas: mockManifests,+ functionCallChecker: () => true,+ enableChecker: ({ pluginId }) => pluginId === 'plugin-1', // Only enable plugin-1+ });++ const result = engine.generateTools({+ toolIds: ['plugin-1', 'plugin-2'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toHaveLength(1);+ expect(result![0].function.name).toBe('plugin-1____api-1');+ });++ it('should return undefined when no plugins are enabled', () => {+ const engine = new ToolsEngine({+ manifestSchemas: mockManifests,+ functionCallChecker: () => true,+ enableChecker: () => false, // Disable all plugins+ });++ const result = engine.generateTools({+ toolIds: ['plugin-1', 'plugin-2'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeUndefined();+ });+ });++ describe('detailed generation results', () => {+ it('should provide detailed filtering information', () => {+ const engine = new ToolsEngine({+ manifestSchemas: mockManifests,+ functionCallChecker: () => true,+ enableChecker: ({ pluginId }) => pluginId === 'plugin-1',+ });++ const result = engine.generateToolsDetailed({+ toolIds: ['plugin-1', 'plugin-2', 'non-existent'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.tools).toHaveLength(1);+ expect(result.enabledToolIds).toEqual(['plugin-1']);+ expect(result.filteredTools).toEqual([+ { id: 'plugin-2', reason: 'disabled' },+ { id: 'non-existent', reason: 'not_found' },+ ]);+ });+ });+ });++ /**+ * Migration tests: Demonstrating that ToolsEngine can replace enabledSchema+ * These tests show the equivalence between the old selector-based approach+ * and the new ToolsEngine-based approach+ */+ describe('enabledSchema Migration to ToolsEngine', () => {+ // Sample manifest data that mimics the old toolSelectors test data+ const sampleManifests: LobeChatPluginManifest[] = [+ {+ identifier: 'plugin-1',+ api: [{ name: 'api-1', description: 'API 1', parameters: {} }],+ meta: {+ title: 'Plugin 1',+ description: 'Plugin 1 description',+ avatar: '🔧',+ },+ type: 'default',+ },+ {+ identifier: 'plugin-2',+ api: [{ name: 'api-2', description: 'API 2', parameters: {} }],+ meta: {+ title: 'Plugin 2',+ description: 'Plugin 2 description',+ avatar: '⚙️',+ },+ type: 'default',+ },+ {+ identifier: 'standalone-plugin',+ api: [{ name: 'standalone-api', description: 'Standalone API', parameters: {} }],+ meta: {+ title: 'Standalone Plugin',+ description: 'Standalone plugin description',+ avatar: '🔩',+ },+ type: 'standalone',+ },+ ];++ describe('basic functionality comparison', () => {+ it('should generate the same tool names as enabledSchema did', () => {+ const engine = new ToolsEngine({+ manifestSchemas: sampleManifests,+ functionCallChecker: () => true,+ });++ const result = engine.generateTools({+ toolIds: ['plugin-1', 'plugin-2'],+ model: 'gpt-4',+ provider: 'openai',+ });++ // These should match the format that enabledSchema produced+ expect(result).toEqual([+ {+ type: 'function',+ function: {+ name: 'plugin-1____api-1',+ description: 'API 1',+ parameters: {},+ },+ },+ {+ type: 'function',+ function: {+ name: 'plugin-2____api-2',+ description: 'API 2',+ parameters: {},+ },+ },+ ]);+ });++ it('should handle type suffixes the same way enabledSchema did', () => {+ const engine = new ToolsEngine({+ manifestSchemas: sampleManifests,+ functionCallChecker: () => true,+ });++ const result = engine.generateTools({+ toolIds: ['standalone-plugin'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result![0].function.name).toBe('standalone-plugin____standalone-api____standalone');+ });+ });++ describe('advantages of ToolsEngine over enabledSchema', () => {+ it('provides detailed filtering information that enabledSchema could not', () => {+ const engine = new ToolsEngine({+ manifestSchemas: sampleManifests,+ functionCallChecker: () => true,+ enableChecker: ({ pluginId }) => pluginId === 'plugin-1',+ });++ const result = engine.generateToolsDetailed({+ toolIds: ['plugin-1', 'plugin-2', 'non-existent'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toEqual({+ tools: [+ {+ type: 'function',+ function: {+ name: 'plugin-1____api-1',+ description: 'API 1',+ parameters: {},+ },+ },+ ],+ enabledToolIds: ['plugin-1'],+ filteredTools: [+ { id: 'plugin-2', reason: 'disabled' },+ { id: 'non-existent', reason: 'not_found' },+ ],+ });+ });++ it('supports function calling checks that enabledSchema relied on external logic for', () => {+ const engine = new ToolsEngine({+ manifestSchemas: sampleManifests,+ functionCallChecker: (model: string) => model.includes('gpt-4'),+ });++ // Should work with GPT-4+ const result1 = engine.generateTools({+ toolIds: ['plugin-1'],+ model: 'gpt-4',+ provider: 'openai',+ });+ expect(result1).toBeDefined();++ // Should not work with older models+ const result2 = engine.generateTools({+ toolIds: ['plugin-1'],+ model: 'gpt-3.5-turbo',+ provider: 'openai',+ });+ expect(result2).toBeUndefined();+ });++ it('encapsulates all tool generation logic in one place', () => {+ // This demonstrates that ToolsEngine combines:+ // 1. Manifest filtering (what enabledSchema did)+ // 2. Function calling support checks (what prepareTools did)+ // 3. Tool name generation (what genToolCallingName did)+ // 4. Plugin enable checking (custom logic)++ const engine = new ToolsEngine({+ manifestSchemas: sampleManifests,+ functionCallChecker: (model: string, provider: string) => {+ return model.includes('gpt') && provider === 'openai';+ },+ enableChecker: ({ pluginId, model }) => {+ // Custom business logic that was scattered before+ if (model === 'gpt-3.5-turbo') return false;+ return pluginId !== 'plugin-2'; // Skip plugin-2 for demo+ },+ });++ const result = engine.generateTools({+ toolIds: ['plugin-1', 'plugin-2'],+ model: 'gpt-4',+ provider: 'openai',+ });++ // Only plugin-1 should be enabled due to custom logic+ expect(result).toHaveLength(1);+ expect(result![0].function.name).toBe('plugin-1____api-1');+ });+ });+ });+});diff --git a/packages/context-engine/src/tools/__tests__/generateToolName.test.ts b/packages/context-engine/src/tools/__tests__/generateToolName.test.tsnew file mode 100644index 00000000000..f7465938427--- /dev/null+++ b/packages/context-engine/src/tools/__tests__/generateToolName.test.ts@@ -0,0 +1,152 @@+import { describe, expect, it } from 'vitest';++import { generateToolName } from '../utils';++describe('generateToolName', () => {+ describe('basic functionality', () => {+ it('should generate tool name with identifier and api name', () => {+ const result = generateToolName('test-plugin', 'myAction');+ expect(result).toBe('test-plugin____myAction');+ });++ it('should generate tool name with type suffix', () => {+ const result = generateToolName('test-plugin', 'myAction', 'builtin');+ expect(result).toBe('test-plugin____myAction____builtin');+ });++ it('should handle default type', () => {+ const result = generateToolName('test-plugin', 'myAction', 'default');+ expect(result).toBe('test-plugin____myAction');+ });++ it('should handle undefined type as default', () => {+ const result = generateToolName('test-plugin', 'myAction');+ expect(result).toBe('test-plugin____myAction');+ });+ });++ describe('long name handling', () => {+ it('should shorten long action names using hash', () => {+ // Create a normal identifier with a very long action name+ const identifier = 'my-plugin';+ const longActionName = 'very-long-action-name-that-will-cause-the-total-length-to-exceed-64-characters';+ const result = generateToolName(identifier, longActionName, 'builtin');++ // The result should be shorter than the original would have been+ const originalLength = `${identifier}____${longActionName}____builtin`.length;+ expect(result.length).toBeLessThan(originalLength);++ // Should contain the identifier, MD5HASH prefix, and type+ expect(result).toContain(identifier);+ expect(result).toContain('MD5HASH_');+ expect(result).toContain('____builtin');+ expect(result).toMatch(/^my-plugin____MD5HASH_[a-f0-9]+____builtin$/);+ });++ it('should handle identifier that is itself long', () => {+ // Test the original limitation - when identifier itself is very long+ const veryLongIdentifier = 'very-long-plugin-identifier-that-will-cause-overflow';+ const actionName = 'action';+ const result = generateToolName(veryLongIdentifier, actionName, 'builtin');++ // When the total length exceeds 64, even short action names get hashed+ expect(result).toContain(veryLongIdentifier);+ expect(result).toContain('MD5HASH_');+ expect(result).toContain('____builtin');++ // Verify the pattern matches the expected format+ expect(result).toMatch(new RegExp(`^${veryLongIdentifier.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}____MD5HASH_[a-f0-9]+____builtin$`));+ });++ it('should keep short names unchanged', () => {+ const result = generateToolName('short', 'action', 'type');+ expect(result).toBe('short____action____type');+ expect(result.length).toBeLessThan(64);+ });++ it('should handle edge case at exactly 64 characters', () => {+ // Create a name that's exactly 64 characters+ const identifier = 'a'.repeat(20);+ const actionName = 'b'.repeat(20);+ const type = 'c'.repeat(16); // 20 + 4 + 20 + 4 + 16 = 64++ const result = generateToolName(identifier, actionName, type);++ // Should be shortened because it's >= 64+ expect(result.length).toBeLessThan(64);+ expect(result).toContain('MD5HASH_');+ });+ });++ describe('special characters and edge cases', () => {+ it('should handle identifiers with special characters', () => {+ const result = generateToolName('my-plugin_v2', 'action-name', 'builtin');+ expect(result).toBe('my-plugin_v2____action-name____builtin');+ });++ it('should handle empty action name', () => {+ const result = generateToolName('plugin', '', 'builtin');+ expect(result).toBe('plugin________builtin');+ });++ it('should handle numeric identifiers and action names', () => {+ const result = generateToolName('plugin123', 'action456', 'type789');+ expect(result).toBe('plugin123____action456____type789');+ });++ it('should be consistent for same inputs', () => {+ const result1 = generateToolName('plugin', 'action', 'type');+ const result2 = generateToolName('plugin', 'action', 'type');+ expect(result1).toBe(result2);+ });++ it('should produce different results for different inputs', () => {+ const result1 = generateToolName('plugin1', 'action', 'type');+ const result2 = generateToolName('plugin2', 'action', 'type');+ expect(result1).not.toBe(result2);+ });+ });++ describe('hash consistency', () => {+ it('should generate consistent hash for same long action name', () => {+ const identifier = 'plugin';+ const longActionName = 'very-long-action-name-that-will-also-cause-overflow';++ const result1 = generateToolName(identifier, longActionName, 'builtin');+ const result2 = generateToolName(identifier, longActionName, 'builtin');++ expect(result1).toBe(result2);+ expect(result1).toContain('MD5HASH_');+ });++ it('should generate different hashes for different long action names', () => {+ const identifier = 'plugin';+ const longActionName1 = 'very-long-action-name-that-will-also-cause-overflow-1';+ const longActionName2 = 'very-long-action-name-that-will-also-cause-overflow-2';++ const result1 = generateToolName(identifier, longActionName1, 'builtin');+ const result2 = generateToolName(identifier, longActionName2, 'builtin');++ expect(result1).not.toBe(result2);+ expect(result1).toContain('MD5HASH_');+ expect(result2).toContain('MD5HASH_');+ });+ });++ describe('real-world examples', () => {+ it('should handle builtin tools correctly', () => {+ const result = generateToolName('lobe-image-designer', 'text2image', 'builtin');+ expect(result).toBe('lobe-image-designer____text2image____builtin');+ });++ it('should handle web browsing tools correctly', () => {+ const result = generateToolName('lobe-web-browsing', 'search');+ expect(result).toBe('lobe-web-browsing____search');+ });++ it('should handle plugin tools correctly', () => {+ const result = generateToolName('custom-plugin', 'customAction', 'plugin');+ expect(result).toBe('custom-plugin____customAction____plugin');+ });+ });+});\ No newline at end of filediff --git a/packages/context-engine/src/tools/__tests__/utils.test.ts b/packages/context-engine/src/tools/__tests__/utils.test.tsnew file mode 100644index 00000000000..5617ce119da--- /dev/null+++ b/packages/context-engine/src/tools/__tests__/utils.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';++import type { LobeChatPluginManifest } from '../types';+import { filterValidManifests, validateManifest } from '../utils';++// Mock manifest schemas+const mockBuiltinManifest: LobeChatPluginManifest = {+ api: [+ {+ description: 'Built-in tool',+ name: 'builtinAction',+ parameters: { type: 'object', properties: {} },+ },+ ],+ identifier: 'builtin-tool',+ meta: { title: 'Builtin Tool' },+ type: 'builtin',+};++describe('utils', () => {+ describe('validateManifest', () => {+ it('should validate correct manifest', () => {+ const result = validateManifest(mockBuiltinManifest);++ expect(result).toBe(true);+ });++ it('should reject manifest without identifier', () => {+ const invalidManifest = { ...mockBuiltinManifest, identifier: undefined };++ const result = validateManifest(invalidManifest);++ expect(result).toBe(false);+ });++ it('should reject manifest without api', () => {+ const invalidManifest = { ...mockBuiltinManifest, api: undefined };++ const result = validateManifest(invalidManifest);++ expect(result).toBe(false);+ });++ it('should reject manifest with empty api array', () => {+ const invalidManifest = { ...mockBuiltinManifest, api: [] };++ const result = validateManifest(invalidManifest);++ expect(result).toBe(false);+ });++ it('should reject non-object manifests', () => {+ expect(validateManifest(null)).toBe(false);+ expect(validateManifest(undefined)).toBe(false);+ expect(validateManifest('string')).toBe(false);+ expect(validateManifest(123)).toBe(false);+ });+ });++ describe('filterValidManifests', () => {+ it('should separate valid and invalid manifests', () => {+ const validManifest = mockBuiltinManifest;+ const invalidManifest = { identifier: 'invalid' }; // missing api++ const result = filterValidManifests([validManifest, invalidManifest]);++ expect(result.valid).toEqual([validManifest]);+ expect(result.invalid).toEqual([invalidManifest]);+ });+ });+});diff --git a/packages/context-engine/src/tools/index.ts b/packages/context-engine/src/tools/index.tsnew file mode 100644index 00000000000..78b3030c929--- /dev/null+++ b/packages/context-engine/src/tools/index.ts@@ -0,0 +1,16 @@+// Core ToolsEngine class+export { ToolsEngine } from './ToolsEngine';++// Types and interfaces+export type {+ FunctionCallChecker,+ GenerateToolsParams,+ PluginEnableChecker,+ ToolNameGenerator,+ ToolsEngineOptions,+ ToolsGenerationContext,+ ToolsGenerationResult,+} from './types';++// Utility functions+export { filterValidManifests, generateToolName, validateManifest } from './utils';diff --git a/packages/context-engine/src/tools/types.ts b/packages/context-engine/src/tools/types.tsnew file mode 100644index 00000000000..165fde79456--- /dev/null+++ b/packages/context-engine/src/tools/types.ts@@ -0,0 +1,130 @@+export interface LobeChatPluginApi {+ description: string;+ name: string;+ parameters: Record<string, any>;+ url?: string;+}++export interface LobeChatPluginManifest {+ api: LobeChatPluginApi[];+ identifier: string;+ meta: any;+ systemRole?: string;+ type?: 'default' | 'standalone' | 'markdown' | 'mcp' | 'builtin';+}++/**+ * Tools generation context+ */+export interface ToolsGenerationContext {+ /** Additional extension context */+ [key: string]: any;+ /** Whether image generation is allowed */+ allowImageGeneration?: boolean;+ /** Environment information */+ environment?: 'desktop' | 'web';+ /** Whether search is enabled */+ isSearchEnabled?: boolean;+ /** Model name for context-aware plugin filtering */+ model?: string;+ /** Provider name for context-aware plugin filtering */+ provider?: string;+}++/**+ * Plugin enable checker function+ */+export type PluginEnableChecker = (params: {+ context?: ToolsGenerationContext;+ manifest: LobeChatPluginManifest;+ model: string;+ pluginId: string;+ provider: string;+}) => boolean;++/**+ * Function calling support checker function+ */+export type FunctionCallChecker = (model: string, provider: string) => boolean;++/**+ * Tools generation parameters+ */+export interface GenerateToolsParams {+ /** Additional context information */+ context?: ToolsGenerationContext;+ /** Model name */+ model: string;+ /** Provider name */+ provider: string;+ /** List of tool IDs to enable */+ toolIds?: string[];+}++/**+ * Tool name generator function+ */+export type ToolNameGenerator = (identifier: string, apiName: string, type?: string) => string;++/**+ * ToolsEngine configuration options+ */+export interface ToolsEngineOptions {+ /** Default tool IDs that will always be added to the end of the tools list */+ defaultToolIds?: string[];+ /** Optional plugin enable checker function */+ enableChecker?: PluginEnableChecker;+ /** Optional function calling support checker function */+ functionCallChecker?: FunctionCallChecker;+ /** Optional tool name generator function */+ generateToolName?: ToolNameGenerator;+ /** Statically injected manifest schemas */+ manifestSchemas: LobeChatPluginManifest[];+}++/**+ * Tools generation result+ */+export interface ToolsGenerationResult {+ /** List of enabled tool IDs */+ enabledToolIds: string[];+ /** Filtered plugins and their reasons */+ filteredTools: Array<{+ id: string;+ reason: 'not_found' | 'disabled' | 'incompatible';+ }>;+ /** Generated tools array */+ tools?: UniformTool[];+}++export interface UniformFunctions {+ /**+ * The description of what the function does.+ * @type {string}+ * @memberof UniformFunctions+ */+ description?: string;+ /**+ * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.+ * @type {string}+ * @memberof UniformFunctions+ */+ name: string;+ /**+ * The parameters the functions accepts, described as a JSON Schema object. See the [guide](/docs/guides/gpt/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format.+ * @type {{ [key: string]: any }}+ * @memberof UniformFunctions+ */+ parameters?: {+ [key: string]: any;+ };+}++export interface UniformTool {+ function: UniformFunctions;++ /**+ * The type of the tool. Currently, only `function` is supported.+ */+ type: 'function';+}diff --git a/packages/context-engine/src/tools/utils.ts b/packages/context-engine/src/tools/utils.tsnew file mode 100644index 00000000000..ca3f86decb3--- /dev/null+++ b/packages/context-engine/src/tools/utils.ts@@ -0,0 +1,74 @@+import { LobeChatPluginManifest } from './types';++// Tool naming constants+const PLUGIN_SCHEMA_SEPARATOR = '____';+const PLUGIN_SCHEMA_API_MD5_PREFIX = 'MD5HASH_';++/**+ * Simple hash function for tool name shortening+ */+const genToolCallShortMD5Hash = (name: string): string => {+ // Simple hash function for tool names (fallback if no crypto available)+ let hash = 0;+ for (let i = 0; i < name.length; i++) {+ const char = name.charCodeAt(i);+ hash = ((hash << 5) - hash) + char;+ hash = hash & hash; // Convert to 32bit integer+ }+ return Math.abs(hash).toString(16).slice(0, 16);+};++/**+ * Generate tool calling name+ * Default tool name generation logic (copied from @lobechat/utils)+ */+export const generateToolName = (identifier: string, name: string, type: string = 'default'): string => {+ const pluginType = type && type !== 'default' ? `${PLUGIN_SCHEMA_SEPARATOR + type}` : '';++ // Use plugin identifier as prefix to avoid conflicts+ let apiName = identifier + PLUGIN_SCHEMA_SEPARATOR + name + pluginType;++ // OpenAI GPT function_call name can't be longer than 64 characters+ // So we need to use hash to shorten the name+ // and then find the correct apiName in response by hash+ if (apiName.length >= 64) {+ const hashContent = PLUGIN_SCHEMA_API_MD5_PREFIX + genToolCallShortMD5Hash(name);+ apiName = identifier + PLUGIN_SCHEMA_SEPARATOR + hashContent + pluginType;+ }++ return apiName;+};++/**+ * Validate manifest schema structure+ */+export function validateManifest(manifest: any): manifest is LobeChatPluginManifest {+ return Boolean(+ manifest &&+ typeof manifest === 'object' &&+ typeof manifest.identifier === 'string' &&+ Array.isArray(manifest.api) &&+ manifest.api.length > 0,+ );+}++/**+ * Filter valid manifest schemas+ */+export function filterValidManifests(manifestSchemas: any[]): {+ invalid: any[];+ valid: LobeChatPluginManifest[];+} {+ const valid: LobeChatPluginManifest[] = [];+ const invalid: any[] = [];++ for (const manifest of manifestSchemas) {+ if (validateManifest(manifest)) {+ valid.push(manifest);+ } else {+ invalid.push(manifest);+ }+ }++ return { invalid, valid };+}diff --git a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx b/src/features/ChatInput/ActionBar/Token/TokenTag.tsxindex 0371f98ef42..8bc5faa852c 100644--- a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx+++ b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx@@ -6,6 +6,7 @@ import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { Center, Flexbox } from 'react-layout-kit';+import { createChatToolsEngine } from '@/helpers/toolEngineering';import { useModelContextWindowTokens } from '@/hooks/useModelContextWindowTokens';import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';import { useTokenCount } from '@/hooks/useTokenCount';@@ -45,22 +46,31 @@ const Token = memo<TokenTagProps>(({ total: messageString }) => {const [historyCount, enableHistoryCount] = useAgentStore((s) => [agentChatConfigSelectors.historyCount(s),agentChatConfigSelectors.enableHistoryCount(s),+ // need to re-render by search mode+ agentChatConfigSelectors.isAgentEnableSearch(s),]);const maxTokens = useModelContextWindowTokens(model, provider);// Tool usage tokenconst canUseTool = useModelSupportToolUse(model, provider);- const plugins = useAgentStore(agentSelectors.currentAgentPlugins);+ const pluginIds = useAgentStore(agentSelectors.currentAgentPlugins);+const toolsString = useToolStore((s) => {- const pluginSystemRoles = toolSelectors.enabledSystemRoles(plugins)(s);- const schemaNumber = toolSelectors- .enabledSchema(plugins)(s)- .map((i) => JSON.stringify(i))- .join('');+ const toolsEngine = createChatToolsEngine({ model, provider });++ const { tools, enabledToolIds } = toolsEngine.generateToolsDetailed({+ model,+ provider,+ toolIds: pluginIds,+ });+ const schemaNumber = tools?.map((i) => JSON.stringify(i)).join('') || '';++ const pluginSystemRoles = toolSelectors.enabledSystemRoles(enabledToolIds)(s);return pluginSystemRoles + schemaNumber;});+const toolsToken = useTokenCount(canUseTool ? toolsString : '');// Chat usage tokendiff --git a/src/helpers/getSearchConfig.test.ts b/src/helpers/getSearchConfig.test.tsnew file mode 100644index 00000000000..296c3a07069--- /dev/null+++ b/src/helpers/getSearchConfig.test.ts@@ -0,0 +1,147 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import * as agentSelectors from '@/store/agent/selectors';+import * as aiInfraSelectors from '@/store/aiInfra/selectors';++import { getSearchConfig } from './getSearchConfig';++// Mock the store dependencies+vi.mock('@/store/agent', () => ({+ getAgentStoreState: () => ({}),+}));++vi.mock('@/store/agent/selectors', () => ({+ agentChatConfigSelectors: {+ currentChatConfig: vi.fn(),+ },+}));++vi.mock('@/store/aiInfra', () => ({+ getAiInfraStoreState: () => ({}),+}));++vi.mock('@/store/aiInfra/selectors', () => ({+ aiProviderSelectors: {+ isProviderHasBuiltinSearch: vi.fn(),+ },+ aiModelSelectors: {+ isModelHasBuiltinSearch: vi.fn(),+ },+}));++describe('getSearchConfig', () => {+ const model = 'gpt-4';+ const provider = 'openai';++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should return correct config when search is enabled and no builtin search', () => {+ vi.mocked(agentSelectors.agentChatConfigSelectors.currentChatConfig).mockReturnValue({+ searchMode: 'on',+ useModelBuiltinSearch: false,+ } as any);++ vi.mocked(aiInfraSelectors.aiProviderSelectors.isProviderHasBuiltinSearch).mockReturnValue(+ () => false,+ );+ vi.mocked(aiInfraSelectors.aiModelSelectors.isModelHasBuiltinSearch).mockReturnValue(+ () => false,+ );++ const result = getSearchConfig(model, provider);++ expect(result).toEqual({+ enabledSearch: true,+ isProviderHasBuiltinSearch: false,+ isModelHasBuiltinSearch: false,+ useModelSearch: false,+ useApplicationBuiltinSearchTool: true,+ });+ });++ it('should return correct config when search is disabled', () => {+ vi.mocked(agentSelectors.agentChatConfigSelectors.currentChatConfig).mockReturnValue({+ searchMode: 'off',+ useModelBuiltinSearch: false,+ } as any);++ const result = getSearchConfig(model, provider);++ expect(result.enabledSearch).toBe(false);+ expect(result.useApplicationBuiltinSearchTool).toBe(false);+ });++ it('should prefer model search when available and enabled', () => {+ vi.mocked(agentSelectors.agentChatConfigSelectors.currentChatConfig).mockReturnValue({+ searchMode: 'on',+ useModelBuiltinSearch: true,+ } as any);++ vi.mocked(aiInfraSelectors.aiProviderSelectors.isProviderHasBuiltinSearch).mockReturnValue(+ () => true,+ );+ vi.mocked(aiInfraSelectors.aiModelSelectors.isModelHasBuiltinSearch).mockReturnValue(+ () => false,+ );++ const result = getSearchConfig(model, provider);++ expect(result).toEqual({+ enabledSearch: true,+ isProviderHasBuiltinSearch: true,+ isModelHasBuiltinSearch: false,+ useModelSearch: true,+ useApplicationBuiltinSearchTool: false,+ });+ });++ it('should use model search when model has builtin search and it is enabled', () => {+ vi.mocked(agentSelectors.agentChatConfigSelectors.currentChatConfig).mockReturnValue({+ searchMode: 'on',+ useModelBuiltinSearch: true,+ } as any);++ vi.mocked(aiInfraSelectors.aiProviderSelectors.isProviderHasBuiltinSearch).mockReturnValue(+ () => false,+ );+ vi.mocked(aiInfraSelectors.aiModelSelectors.isModelHasBuiltinSearch).mockReturnValue(+ () => true,+ );++ const result = getSearchConfig(model, provider);++ expect(result).toEqual({+ enabledSearch: true,+ isProviderHasBuiltinSearch: false,+ isModelHasBuiltinSearch: true,+ useModelSearch: true,+ useApplicationBuiltinSearchTool: false,+ });+ });++ it('should not use model search when model has builtin search but preference is disabled', () => {+ vi.mocked(agentSelectors.agentChatConfigSelectors.currentChatConfig).mockReturnValue({+ searchMode: 'on',+ useModelBuiltinSearch: false,+ } as any);++ vi.mocked(aiInfraSelectors.aiProviderSelectors.isProviderHasBuiltinSearch).mockReturnValue(+ () => false,+ );+ vi.mocked(aiInfraSelectors.aiModelSelectors.isModelHasBuiltinSearch).mockReturnValue(+ () => true,+ );++ const result = getSearchConfig(model, provider);++ expect(result).toEqual({+ enabledSearch: true,+ isProviderHasBuiltinSearch: false,+ isModelHasBuiltinSearch: true,+ useModelSearch: false,+ useApplicationBuiltinSearchTool: true,+ });+ });+});diff --git a/src/helpers/getSearchConfig.ts b/src/helpers/getSearchConfig.tsnew file mode 100644index 00000000000..bbb507ecc46--- /dev/null+++ b/src/helpers/getSearchConfig.ts@@ -0,0 +1,51 @@+import { getAgentStoreState } from '@/store/agent';+import { agentChatConfigSelectors } from '@/store/agent/selectors';+import { getAiInfraStoreState } from '@/store/aiInfra';+import { aiModelSelectors, aiProviderSelectors } from '@/store/aiInfra/selectors';++/**+ * Search configuration result+ */+export interface SearchConfig {+ /** Whether search is enabled in chat config */+ enabledSearch: boolean;+ /** Whether model has builtin search capability */+ isModelHasBuiltinSearch: boolean;+ /** Whether provider has builtin search capability */+ isProviderHasBuiltinSearch: boolean;+ /** Whether to use application's builtin search tool */+ useApplicationBuiltinSearchTool: boolean;+ /** Whether to use model's builtin search */+ useModelSearch: boolean;+}++/**+ * Get search configuration for given model and provider+ * This centralizes the search logic that was duplicated across multiple places+ */+export const getSearchConfig = (model: string, provider: string): SearchConfig => {+ const chatConfig = agentChatConfigSelectors.currentChatConfig(getAgentStoreState());+ const aiInfraStoreState = getAiInfraStoreState();++ const enabledSearch = chatConfig.searchMode !== 'off';+ const isProviderHasBuiltinSearch =+ aiProviderSelectors.isProviderHasBuiltinSearch(provider)(aiInfraStoreState);+ const isModelHasBuiltinSearch = aiModelSelectors.isModelHasBuiltinSearch(+ model,+ provider,+ )(aiInfraStoreState);++ const useModelSearch =+ ((isProviderHasBuiltinSearch || isModelHasBuiltinSearch) && chatConfig.useModelBuiltinSearch) ||+ false;++ const useApplicationBuiltinSearchTool = enabledSearch && !useModelSearch;++ return {+ enabledSearch,+ isModelHasBuiltinSearch,+ isProviderHasBuiltinSearch,+ useApplicationBuiltinSearchTool,+ useModelSearch,+ };+};diff --git a/src/helpers/isCanUseFC.ts b/src/helpers/isCanUseFC.tsnew file mode 100644index 00000000000..baf3d30f532--- /dev/null+++ b/src/helpers/isCanUseFC.ts@@ -0,0 +1,13 @@+import { isDeprecatedEdition } from '@/const/version';+import { aiModelSelectors, getAiInfraStoreState } from '@/store/aiInfra';+import { getUserStoreState } from '@/store/user';+import { modelProviderSelectors } from '@/store/user/selectors';++export const isCanUseFC = (model: string, provider: string): boolean => {+ // TODO: remove isDeprecatedEdition condition in V2.0+ if (isDeprecatedEdition) {+ return modelProviderSelectors.isModelEnabledFunctionCall(model)(getUserStoreState());+ }++ return aiModelSelectors.isModelSupportToolUse(model, provider)(getAiInfraStoreState()) || false;+};diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.tsnew file mode 100644index 00000000000..debebd4c173--- /dev/null+++ b/src/helpers/toolEngineering/index.test.ts@@ -0,0 +1,197 @@+import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createChatToolsEngine, createToolsEngine, getEnabledTools } from './index';++// Mock the store and helper dependencies+vi.mock('@/store/tool', () => ({+ getToolStoreState: () => ({+ builtinTools: [+ {+ identifier: 'search',+ manifest: {+ api: [+ {+ description: 'Search the web',+ name: 'search',+ parameters: {+ properties: {+ query: { description: 'Search query', type: 'string' },+ },+ required: ['query'],+ type: 'object',+ },+ },+ ],+ identifier: 'search',+ meta: {+ title: 'Web Search',+ description: 'Search tool',+ avatar: '🔍',+ },+ type: 'builtin',+ } as unknown as LobeChatPluginManifest,+ type: 'builtin' as const,+ },+ {+ identifier: 'lobe-web-browsing',+ manifest: {+ api: [+ {+ description:+ 'a search service. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results',+ name: 'search',+ parameters: {+ properties: {+ query: { description: 'The search query', type: 'string' },+ },+ required: ['query'],+ type: 'object',+ },+ },+ ],+ identifier: 'lobe-web-browsing',+ meta: {+ title: 'Web Browsing',+ avatar: '🌐',+ },+ type: 'builtin',+ } as unknown as LobeChatPluginManifest,+ type: 'builtin' as const,+ },+ ],+ }),+}));++vi.mock('@/store/tool/selectors', () => ({+ pluginSelectors: {+ installedPluginManifestList: () => [],+ },+}));++vi.mock('../isCanUseFC', () => ({+ isCanUseFC: () => true,+}));++vi.mock('@/helpers/getSearchConfig', () => ({+ getSearchConfig: () => ({+ useApplicationBuiltinSearchTool: true,+ }),+}));++describe('toolEngineering', () => {+ describe('createToolsEngine', () => {+ it('should generate tools array for enabled plugins', () => {+ const toolsEngine = createToolsEngine();+ const result = toolsEngine.generateTools({+ toolIds: ['search'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeDefined();+ expect(result).toHaveLength(1);+ expect(result![0]).toMatchObject({+ function: {+ description: 'Search the web',+ name: 'search____search____builtin',+ parameters: {+ properties: {+ query: { description: 'Search query', type: 'string' },+ },+ required: ['query'],+ type: 'object',+ },+ },+ type: 'function',+ });+ });++ it('should return undefined when no plugins match', () => {+ const toolsEngine = createToolsEngine();+ const result = toolsEngine.generateTools({+ toolIds: ['non-existent'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeUndefined();+ });++ it('should return detailed result with correct field names', () => {+ const toolsEngine = createToolsEngine();+ const result = toolsEngine.generateToolsDetailed({+ toolIds: ['search'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toHaveProperty('enabledToolIds');+ expect(result).toHaveProperty('filteredTools');+ expect(result).toHaveProperty('tools');+ expect(result.enabledToolIds).toEqual(['search']);+ expect(result.filteredTools).toEqual([]);+ expect(result.tools).toHaveLength(1);+ });+ });++ describe('createChatToolsEngine', () => {+ it('should include web browsing tool as default when no tools are provided', () => {+ const toolsEngine = createChatToolsEngine({+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = toolsEngine.generateToolsDetailed({+ toolIds: [], // No explicitly enabled tools+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).toContain('lobe-web-browsing');+ });++ it('should include web browsing tool alongside user-provided tools', () => {+ const toolsEngine = createChatToolsEngine({+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = toolsEngine.generateToolsDetailed({+ toolIds: ['search'], // User explicitly enables search tool+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).toEqual(['search', 'lobe-web-browsing']);+ expect(result.enabledToolIds).toHaveLength(2);+ });+ });++ describe('Migration functions', () => {+ describe('getEnabledTools', () => {+ it('should return empty array when no tool IDs provided', () => {+ const result = getEnabledTools([], 'gpt-4', 'openai');+ expect(result).toEqual([]);+ });++ it('should return tools for valid tool IDs', () => {+ const result = getEnabledTools(['search'], 'gpt-4', 'openai');+ expect(result).toHaveLength(1);+ expect(result[0]).toHaveProperty('type', 'function');+ expect(result[0].function).toHaveProperty('name', 'search____search____builtin');+ });++ it('should use provided model and provider', () => {+ const result = getEnabledTools(['search'], 'gpt-3.5-turbo', 'anthropic');+ expect(result).toBeDefined();+ expect(Array.isArray(result)).toBe(true);+ });++ it('should return empty array for non-existent tools', () => {+ const result = getEnabledTools(['non-existent-tool'], 'gpt-4', 'openai');+ expect(result).toEqual([]);+ });+ });+ });+});diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.tsnew file mode 100644index 00000000000..abfb349f4fa--- /dev/null+++ b/src/helpers/toolEngineering/index.ts@@ -0,0 +1,94 @@+/**+ * Tools Engineering - Unified tools processing using ToolsEngine+ */+import { ToolsEngine } from '@lobechat/context-engine';+import type { PluginEnableChecker } from '@lobechat/context-engine';+import { ChatCompletionTool, WorkingModel } from '@lobechat/types';+import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';++import { getSearchConfig } from '@/helpers/getSearchConfig';+import { getToolStoreState } from '@/store/tool';+import { pluginSelectors } from '@/store/tool/selectors';+import { WebBrowsingManifest } from '@/tools/web-browsing';++import { isCanUseFC } from '../isCanUseFC';++/**+ * Tools engine configuration options+ */+export interface ToolsEngineConfig {+ /** Additional manifests to include beyond the standard ones */+ additionalManifests?: LobeChatPluginManifest[];+ /** Default tool IDs that will always be added to the end of the tools list */+ defaultToolIds?: string[];+ /** Custom enable checker for plugins */+ enableChecker?: PluginEnableChecker;+}++/**+ * Initialize ToolsEngine with current manifest schemas and configurable options+ */+export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine => {+ const { enableChecker, additionalManifests = [], defaultToolIds } = config;++ const toolStoreState = getToolStoreState();++ // Get all available plugin manifests+ const pluginManifests = pluginSelectors.installedPluginManifestList(toolStoreState);++ // Get all builtin tool manifests+ const builtinManifests = toolStoreState.builtinTools.map(+ (tool) => tool.manifest as LobeChatPluginManifest,+ );++ // Combine all manifests+ const allManifests = [...pluginManifests, ...builtinManifests, ...additionalManifests];++ return new ToolsEngine({+ defaultToolIds,+ enableChecker,+ functionCallChecker: isCanUseFC,+ manifestSchemas: allManifests,+ });+};++export const createChatToolsEngine = (workingModel: WorkingModel) =>+ createToolsEngine({+ // Add WebBrowsingManifest as default tool+ defaultToolIds: [WebBrowsingManifest.identifier],+ // Create search-aware enableChecker for this request+ enableChecker: ({ pluginId }) => {+ // For WebBrowsingManifest, apply search logic+ if (pluginId === WebBrowsingManifest.identifier) {+ const searchConfig = getSearchConfig(workingModel.model, workingModel.provider);+ return searchConfig.useApplicationBuiltinSearchTool;+ }++ // For all other plugins, enable by default+ return true;+ },+ });++/**+ * Provides the same functionality using ToolsEngine with enhanced capabilities+ *+ * @param toolIds - Array of tool IDs to generate tools for+ * @param model - Model name for function calling compatibility check (optional)+ * @param provider - Provider name for function calling compatibility check (optional)+ * @returns Array of ChatCompletionTool objects+ */+export const getEnabledTools = (+ toolIds: string[] = [],+ model: string,+ provider: string,+): ChatCompletionTool[] => {+ const toolsEngine = createToolsEngine();++ return (+ toolsEngine.generateTools({+ model: model, // Use provided model or fallback+ provider: provider, // Use provided provider or fallback+ toolIds,+ }) || []+ );+};diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.tsindex 62d2af8ee48..894fe63d3cf 100644--- a/src/services/chat/chat.test.ts+++ b/src/services/chat/chat.test.ts@@ -4,10 +4,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DEFAULT_USER_AVATAR } from '@/const/meta';import { DEFAULT_AGENT_CONFIG } from '@/const/settings';+import * as isCanUseFCModule from '@/helpers/isCanUseFC';+import * as toolEngineeringModule from '@/helpers/toolEngineering';import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';import { aiModelSelectors } from '@/store/aiInfra';import { useToolStore } from '@/store/tool';import { toolSelectors } from '@/store/tool/selectors';+import { modelProviderSelectors } from '@/store/user/selectors';import { DalleManifest } from '@/tools/dalle';import { WebBrowsingManifest } from '@/tools/web-browsing';import { ChatErrorType } from '@/types/index';@@ -63,6 +66,11 @@ vi.mock('../_auth', () => ({createHeaderWithAuth: vi.fn().mockResolvedValue({}),}));+// Mock isCanUseFC to control function calling behavior in tests+vi.mock('@/helpers/isCanUseFC', () => ({+ isCanUseFC: vi.fn(() => true), // Default to true, tests can override+}));+describe('ChatService', () => {describe('createAssistantMessage', () => {it('should process messages and call getChatCompletion with the right parameters', async () => {@@ -111,26 +119,6 @@ describe('ChatService', () => {);});- it('should not use tools for models in the vision model whitelist', async () => {- const getChatCompletionSpy = vi.spyOn(chatService, 'getChatCompletion');- const messages = [{ content: 'Hello', role: 'user' }] as ChatMessage[];- const modelInWhitelist = 'gpt-4-vision-preview';-- await chatService.createAssistantMessage({- messages,- model: modelInWhitelist,- plugins: ['plugin1'],- });-- expect(getChatCompletionSpy).toHaveBeenCalledWith(- expect.objectContaining({- tools: undefined,- model: modelInWhitelist,- }),- undefined,- );- });-describe('extendParams functionality', () => {it('should add reasoning parameters when model supports enableReasoning and user enables it', async () => {const getChatCompletionSpy = vi.spyOn(chatService, 'getChatCompletion');@@ -355,10 +343,12 @@ describe('ChatService', () => {expect(getChatCompletionSpy).toHaveBeenCalledWith({+ enabledSearch: undefined,messages: [{ content: 'Hello', role: 'user' },{ content: 'Hey', role: 'assistant' },],+ tools: undefined,},undefined,);@@ -870,16 +860,24 @@ describe('ChatService', () => {vi.spyOn(aiModelSelectors, 'isModelHasBuiltinSearch').mockReturnValueOnce(() => false);vi.spyOn(aiModelSelectors, 'isModelHasExtendParams').mockReturnValueOnce(() => false);- // Mock tool selectors- vi.spyOn(toolSelectors, 'enabledSchema').mockReturnValueOnce(() => [- {- type: 'function',- function: {- name: WebBrowsingManifest.identifier + '____search',- description: 'Search the web',- },- },- ]);+ // Mock createChatToolsEngine to return tools with web browsing+ const mockToolsEngine = {+ generateToolsDetailed: vi.fn().mockReturnValue({+ tools: [+ {+ type: 'function',+ function: {+ name: WebBrowsingManifest.identifier + '____search',+ description: 'Search the web',+ },+ },+ ],+ enabledToolIds: [WebBrowsingManifest.identifier],+ }),+ };+ vi.spyOn(toolEngineeringModule, 'createChatToolsEngine').mockReturnValue(+ mockToolsEngine as any,+ );await chatService.createAssistantMessage({ messages, plugins: [] });@@ -913,16 +911,24 @@ describe('ChatService', () => {vi.spyOn(aiModelSelectors, 'isModelHasBuiltinSearch').mockReturnValueOnce(() => true);vi.spyOn(aiModelSelectors, 'isModelHasExtendParams').mockReturnValueOnce(() => false);- // Mock tool selectors- vi.spyOn(toolSelectors, 'enabledSchema').mockReturnValueOnce(() => [- {- type: 'function',- function: {- name: WebBrowsingManifest.identifier + '____search',- description: 'Search the web',- },- },- ]);+ // Mock createChatToolsEngine to return tools with web browsing+ const mockToolsEngine = {+ generateToolsDetailed: vi.fn().mockReturnValue({+ tools: [+ {+ type: 'function',+ function: {+ name: WebBrowsingManifest.identifier + '____search',+ description: 'Search the web',+ },+ },+ ],+ enabledToolIds: [WebBrowsingManifest.identifier],+ }),+ };+ vi.spyOn(toolEngineeringModule, 'createChatToolsEngine').mockReturnValue(+ mockToolsEngine as any,+ );await chatService.createAssistantMessage({ messages, plugins: [] });@@ -950,16 +956,24 @@ describe('ChatService', () => {vi.spyOn(aiModelSelectors, 'isModelHasBuiltinSearch').mockReturnValueOnce(() => true);vi.spyOn(aiModelSelectors, 'isModelHasExtendParams').mockReturnValueOnce(() => false);- // Mock tool selectors- vi.spyOn(toolSelectors, 'enabledSchema').mockReturnValueOnce(() => [- {- type: 'function',- function: {- name: WebBrowsingManifest.identifier + '____search',- description: 'Search the web',- },- },- ]);+ // Mock createChatToolsEngine to return tools with web browsing+ const mockToolsEngine = {+ generateToolsDetailed: vi.fn().mockReturnValue({+ tools: [+ {+ type: 'function',+ function: {+ name: WebBrowsingManifest.identifier + '____search',+ description: 'Search the web',+ },+ },+ ],+ enabledToolIds: [WebBrowsingManifest.identifier],+ }),+ };+ vi.spyOn(toolEngineeringModule, 'createChatToolsEngine').mockReturnValue(+ mockToolsEngine as any,+ );await chatService.createAssistantMessage({ messages, plugins: [] });diff --git a/src/services/chat/contextEngineering.test.ts b/src/services/chat/contextEngineering.test.tsindex 6c565d7a026..17dce35e82d 100644--- a/src/services/chat/contextEngineering.test.ts+++ b/src/services/chat/contextEngineering.test.ts@@ -1,6 +1,8 @@import { ChatMessage } from '@lobechat/types';import { afterEach, describe, expect, it, vi } from 'vitest';+import * as isCanUseFCModule from '@/helpers/isCanUseFC';+import { contextEngineering } from './contextEngineering';import * as helpers from './helper';@@ -360,7 +362,7 @@ describe('contextEngineering', () => {it('should not include tool_calls for assistant message if model does not support tools', async () => {// Mock isCanUseFC to return false- vi.spyOn(helpers, 'isCanUseFC').mockReturnValue(false);+ vi.spyOn(isCanUseFCModule, 'isCanUseFC').mockReturnValue(false);const messages: ChatMessage[] = [{diff --git a/src/services/chat/contextEngineering.ts b/src/services/chat/contextEngineering.tsindex 052c172653d..9a0cdd1e32c 100644--- a/src/services/chat/contextEngineering.ts+++ b/src/services/chat/contextEngineering.ts@@ -18,13 +18,13 @@ import { historySummaryPrompt } from '@lobechat/prompts';import { ChatMessage, OpenAIChatMessage } from '@lobechat/types';import { INBOX_GUIDE_SYSTEMROLE } from '@/const/guide';+import { isCanUseFC } from '@/helpers/isCanUseFC';import { getToolStoreState } from '@/store/tool';import { toolSelectors } from '@/store/tool/selectors';import { VARIABLE_GENERATORS } from '@/utils/client/parserPlaceholder';import { genToolCallingName } from '@/utils/toolCall';-import { isCanUseFC, isCanUseVideo, isCanUseVision } from './helper';-+import { isCanUseVideo, isCanUseVision } from './helper';interface ContextEngineeringContext {enableHistoryCount?: boolean;diff --git a/src/services/chat/helper.ts b/src/services/chat/helper.tsindex 8037edc98db..4a5d74cf647 100644--- a/src/services/chat/helper.ts+++ b/src/services/chat/helper.ts@@ -6,15 +6,6 @@ import { aiModelSelectors, aiProviderSelectors } from '@/store/aiInfra/selectorsimport { getUserStoreState, useUserStore } from '@/store/user';import { modelConfigSelectors, modelProviderSelectors } from '@/store/user/selectors';-export const isCanUseFC = (model: string, provider: string): boolean => {- // TODO: remove isDeprecatedEdition condition in V2.0- if (isDeprecatedEdition) {- return modelProviderSelectors.isModelEnabledFunctionCall(model)(getUserStoreState());- }-- return aiModelSelectors.isModelSupportToolUse(model, provider)(getAiInfraStoreState()) || false;-};-export const isCanUseVision = (model: string, provider: string): boolean => {// TODO: remove isDeprecatedEdition condition in V2.0if (isDeprecatedEdition) {diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex ed8faf22f7b..f879e401930 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -7,21 +7,21 @@ import { ModelProvider } from 'model-bank';import { enableAuth } from '@/const/auth';import { DEFAULT_AGENT_CONFIG } from '@/const/settings';import { isDeprecatedEdition, isDesktop } from '@/const/version';+import { getSearchConfig } from '@/helpers/getSearchConfig';+import { createChatToolsEngine, createToolsEngine } from '@/helpers/toolEngineering';import { getAgentStoreState } from '@/store/agent';import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';import { aiModelSelectors, aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';import { getSessionStoreState } from '@/store/session';import { sessionMetaSelectors } from '@/store/session/selectors';import { getToolStoreState } from '@/store/tool';-import { pluginSelectors, toolSelectors } from '@/store/tool/selectors';+import { pluginSelectors } from '@/store/tool/selectors';import { getUserStoreState, useUserStore } from '@/store/user';import {preferenceSelectors,userGeneralSettingsSelectors,userProfileSelectors,} from '@/store/user/selectors';-import { WebBrowsingManifest } from '@/tools/web-browsing';-import { WorkingModel } from '@/types/agent';import { ChatMessage } from '@/types/message';import type { ChatStreamPayload } from '@/types/openai/chat';import { fetchWithInvokeStream } from '@/utils/electron/desktopRemoteRPCFetch';@@ -38,7 +38,7 @@ import { createHeaderWithAuth } from '../_auth';import { API_ENDPOINTS } from '../_url';import { initializeWithClientStore } from './clientModelRuntime';import { contextEngineering } from './contextEngineering';-import { findDeploymentName, isCanUseFC, isEnableFetchOnClient } from './helper';+import { findDeploymentName, isEnableFetchOnClient } from './helper';import { FetchOptions } from './types';interface GetChatCompletionPayload extends Partial<Omit<ChatStreamPayload, 'messages'>> {@@ -82,33 +82,28 @@ class ChatService {params,);- // =================== 0. process search =================== //- const chatConfig = agentChatConfigSelectors.currentChatConfig(getAgentStoreState());- const aiInfraStoreState = getAiInfraStoreState();- const enabledSearch = chatConfig.searchMode !== 'off';- const isProviderHasBuiltinSearch = aiProviderSelectors.isProviderHasBuiltinSearch(- payload.provider!,- )(aiInfraStoreState);- const isModelHasBuiltinSearch = aiModelSelectors.isModelHasBuiltinSearch(- payload.model,- payload.provider!,- )(aiInfraStoreState);+ const searchConfig = getSearchConfig(payload.model, payload.provider!);- const useModelSearch =- (isProviderHasBuiltinSearch || isModelHasBuiltinSearch) && chatConfig.useModelBuiltinSearch;-- const useApplicationBuiltinSearchTool = enabledSearch && !useModelSearch;+ // =================== 1. preprocess tools =================== //const pluginIds = [...(enabledPlugins || [])];- if (useApplicationBuiltinSearchTool) {- pluginIds.push(WebBrowsingManifest.identifier);- }+ const toolsEngine = createChatToolsEngine({+ model: payload.model,+ provider: payload.provider!,+ });- // ============ 1. preprocess messages ============ //+ const { tools, enabledToolIds } = toolsEngine.generateToolsDetailed({+ model: payload.model,+ provider: payload.provider!,+ toolIds: pluginIds,+ });++ // ============ 2. preprocess messages ============ //const agentStoreState = getAgentStoreState();const agentConfig = agentSelectors.currentAgentConfig(agentStoreState);+ const chatConfig = agentChatConfigSelectors.currentChatConfig(agentStoreState);// Apply context engineering with preprocessing configurationconst oaiMessages = await contextEngineering({@@ -123,19 +118,13 @@ class ChatService {provider: payload.provider!,sessionId: options?.trace?.sessionId,systemRole: agentConfig.systemRole,- tools: pluginIds,- });-- // ============ 2. preprocess tools ============ //-- const tools = this.prepareTools(pluginIds, {- model: payload.model,- provider: payload.provider!,+ tools: enabledToolIds,});// ============ 3. process extend params ============ //let extendParams: Record<string, any> = {};+ const aiInfraStoreState = getAiInfraStoreState();const isModelHasExtendParams = aiModelSelectors.isModelHasExtendParams(payload.model,@@ -209,7 +198,7 @@ class ChatService {{...params,...extendParams,- enabledSearch: enabledSearch && useModelSearch ? true : undefined,+ enabledSearch: searchConfig.enabledSearch && searchConfig.useModelSearch ? true : undefined,messages: oaiMessages,tools,},@@ -421,9 +410,12 @@ class ChatService {provider: params.provider!,tools: params.plugins,});- const tools = this.prepareTools(params.plugins || [], {+ // Use simple tools engine without complex search logic+ const toolsEngine = createToolsEngine();+ const tools = toolsEngine.generateTools({model: params.model!,provider: params.provider!,+ toolIds: params.plugins,});// remove plugins@@ -484,20 +476,6 @@ class ChatService {return agentRuntime.chat(data, { signal: params.signal });};-- private prepareTools = (pluginIds: string[], { model, provider }: WorkingModel) => {- let filterTools = toolSelectors.enabledSchema(pluginIds)(getToolStoreState());-- // check this model can use function call- const canUseFC = isCanUseFC(model, provider!);-- // the rule that model can use tools:- // 1. tools is not empty- // 2. model can use function call- const shouldUseTools = filterTools.length > 0 && canUseFC;-- return shouldUseTools ? filterTools : undefined;- };}export const chatService = new ChatService();diff --git a/src/store/tool/selectors/tool.test.ts b/src/store/tool/selectors/tool.test.tsindex ad8576960ec..b943c0f03eb 100644--- a/src/store/tool/selectors/tool.test.ts+++ b/src/store/tool/selectors/tool.test.ts@@ -59,101 +59,6 @@ const mockState = {} as ToolStoreState;describe('toolSelectors', () => {- describe('enabledSchema', () => {- it('enabledSchema should return correct ChatCompletionFunctions array', () => {- const result = toolSelectors.enabledSchema(['plugin-1', 'plugin-2'])(mockState);- expect(result).toEqual([- {- type: 'function',- function: {- name: 'plugin-1____api-1',- },- },- {- type: 'function',- function: {- name: 'plugin-2____api-2',- },- },- ]);- });-- it('enabledSchema should return with standalone plugin', () => {- const result = toolSelectors.enabledSchema(['plugin-4'])({- ...mockState,- installedPlugins: [- ...mockState.installedPlugins,- {- identifier: 'plugin-4',- manifest: {- identifier: 'plugin-4',- api: [{ name: 'api-4' }],- type: 'standalone',- },- type: 'plugin',- },- ],- } as ToolStoreState);- expect(result).toEqual([- {- type: 'function',- function: {- name: 'plugin-4____api-4____standalone',- },- },- ]);- });-- it('enabledSchema should return md5 hash apiName', () => {- const result = toolSelectors.enabledSchema(['long-long-plugin-with-id'])({- ...mockState,- installedPlugins: [- ...mockState.installedPlugins,- {- identifier: 'long-long-plugin-with-id',- manifest: {- identifier: 'long-long-plugin-with-id',- api: [{ name: 'long-long-manifest-long-long-apiName' }],- },- type: 'plugin',- },- ],- } as ToolStoreState);- expect(result).toEqual([- {- type: 'function',- function: {- name: 'long-long-plugin-with-id____MD5HASH_396eae4c671da3fb',- },- },- ]);- });-- it('enabledSchema should return empty', () => {- const result = toolSelectors.enabledSchema([])(mockState);- expect(result).toEqual([]);- });-- // fix https://github.com/lobehub/lobe-chat/issues/2036- it('should not contain url', () => {- const result = toolSelectors.enabledSchema(['plugin-3'])(mockState);- expect(result[0].function).toEqual({- description: '123123',- name: 'plugin-3____api-3',- parameters: {- properties: {- a: {- type: 'string',- },- },- type: 'object',- },- });-- expect(result[0].function).not.toHaveProperty('url');- });- });-describe('getToolManifestLoadingStatus', () => {it('should return "loading" if the plugin manifest is being loaded', () => {const result = toolSelectors.getManifestLoadingStatus('plugin-2')(mockState);diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.tsindex 49cbc7cc37a..8bf8267cacb 100644--- a/src/store/tool/selectors/tool.ts+++ b/src/store/tool/selectors/tool.ts@@ -2,30 +2,16 @@ import { pluginPrompts } from '@lobechat/prompts';import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';import { MetaData } from '@/types/meta';-import { ChatCompletionTool } from '@/types/openai/chat';import { LobeToolMeta } from '@/types/tool/tool';import { globalAgentContextManager } from '@/utils/client/GlobalAgentContextManager';import { hydrationPrompt } from '@/utils/promptTemplate';import { genToolCallingName } from '@/utils/toolCall';-import { convertPluginManifestToToolsCalling } from '@/utils/toolManifest';import { pluginHelpers } from '../helpers';import { ToolStoreState } from '../initialState';import { builtinToolSelectors } from '../slices/builtin/selectors';import { pluginSelectors } from '../slices/plugin/selectors';-const enabledSchema =- (tools: string[] = []) =>- (s: ToolStoreState): ChatCompletionTool[] => {- const manifests = pluginSelectors- .installedPluginManifestList(s)- .concat(s.builtinTools.map((b) => b.manifest as LobeChatPluginManifest))- // 如果存在 enabledPlugins,那么只启用 enabledPlugins 中的插件- .filter((m) => tools.includes(m?.identifier));-- return convertPluginManifestToToolsCalling(manifests);- };-const enabledSystemRoles =(tools: string[] = []) =>(s: ToolStoreState) => {@@ -122,7 +108,6 @@ const isToolHasUI = (id: string) => (s: ToolStoreState) => {};export const toolSelectors = {- enabledSchema,enabledSystemRoles,getManifestById,getManifestLoadingStatus,