AI 工具(tools)集合(node.js 版)

0 阅读1分钟
  1. 计算类
class CalculatorTool extends Tool {
    name = "calculator"; // 工具名称,模型会用这个名称调用
    description = "用来计算数学问题,比如加减乘除、平方、开方等,输入格式为数学表达式(如“2+3*4”)";
    // 工具执行逻辑
    async _call(input: string): Promise<string> {
        try {
            // 用eval计算(实际项目可换更安全的计算库,如math.js)
            const result = eval(input);
            return `计算结果:${input} = ${result}`;
        } catch (err) {
            return `计算失败:${(err as Error).message},请输入正确的数学表达式(如“2+3*4”)`;
        }
    }
}
// 把计算器工具加入工具列表
export const TOOLS = [new CalculatorTool()];
  1. 数据库操作
const databaseQueryTool = {
  name: 'query_database',
  description: 'Execute a SQL query on the database',

  parameters: z.object({
    query: z.string().describe('SQL query to execute'),
    params: z.array(z.any()).optional().describe('Query parameters')
  }),

  handler: async ({ query, params = [] }) => {
    // 查询数据库
    const result = await db.query(query, params);
    return result;
  }
};
  1. 超时降级
async function queryWithTimeout(agent, prompt, timeout = 120000) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => {
    controller.abort();
  }, timeout);

  try {
    const result = await agent.query(prompt, {
      signal: controller.signal
    });
    clearTimeout(timeoutId);
    return result;
  } catch (error) {
    if (error.name === 'AbortError') {
      console.error('Query timed out');

      // 降级到快速模式
      return await agent.query(prompt + '\n\n[Quick mode]', {
        model: 'claude-3-haiku',
        maxTokens: 1000
      });
    }
    throw error;
  }
}

4.计算机信息

const myAgentTools = {
  getSystemMemory: {
    execute: async () => {
      const free = os.freemem() / 1024 / 1024 / 1024;
      const total = os.totalmem() / 1024 / 1024 / 1024;
      return { 
        free: free.toFixed(2) + 'GB', 
        total: total.toFixed(2) + 'GB',
        usage: ((total - free) / total * 100).toFixed(2) + '%'
      };
    },
  },

  listMyFiles: {
    execute: async ({ dirPath = './' }) => {
      try {
        const resolvedPath = path.resolve(dirPath);
        const files = fs.readdirSync(resolvedPath);
        return files.slice(0, 15).map(file => {
          const stats = fs.statSync(path.join(resolvedPath, file));
          return {
            name: file,
            type: stats.isDirectory() ? 'directory' : 'file'
          };
        });
      } catch (error) {
        return { error: error.message };
      }
    },
  },

  getSystemInfo: {
    execute: async () => {
      return {
        platform: os.platform(),
        arch: os.arch(),
        hostname: os.hostname(),
        cpus: os.cpus().length + ' 核心'
      };
    },
  }
};