Hotdry.
ai-systems

DeepChat 中集成本地日历、邮件和文件 API:TypeScript 隐私保护个人 AI 助手集成

探索在 DeepChat TypeScript 框架下集成本地 API,实现 AI 助手对日历、邮件和文件的隐私访问,无需云服务。提供配置、代码示例和安全实践。

在当今数据隐私日益重要的时代,构建个人 AI 助手时,避免依赖外部云服务成为关键需求。DeepChat 作为一个开源的 TypeScript 构建的 AI 聊天平台,支持多模型集成和工具调用,正是实现这一目标的理想选择。通过集成本地 API,AI 助手可以直接访问用户的日历、邮件和文件,实现隐私保护的个性化服务,而无需传输敏感数据到远程服务器。这种方法不仅降低了数据泄露风险,还提升了响应速度和自定义灵活性。本文将聚焦于在 DeepChat 中使用 TypeScript 实现这些本地集成的具体步骤和最佳实践,帮助开发者构建安全的个人 AI 系统。

首先,理解 DeepChat 的核心优势。它基于 Electron 和 Vue.js,支持本地模型如 Ollama,并通过 MCP(Model Context Protocol)协议启用工具调用。这允许 AI 模型在对话中智能调用自定义函数,例如读取本地文件或查询日历事件,而所有操作均在用户设备上完成。DeepChat 的隐私导向设计,包括本地数据存储和网络代理支持,进一步强化了其在个人 AI 场景中的适用性。根据官方文档,DeepChat 支持 MCP 的 Resources、Prompts 和 Tools 三种核心能力,其中 Tools 特别适合本地 API 集成。

准备工作:环境配置

要开始集成,首先需要安装 DeepChat。从 GitHub 仓库克隆项目并构建:

git clone https://github.com/ThinkInAIXYZ/deepchat.git
cd deepchat
pnpm install
pnpm run build:win  # 或对应平台

DeepChat 使用 pnpm 作为包管理器,确保 Node.js 版本 ≥18。接下来,安装本地 API 所需的依赖。对于日历,使用 node-ical 解析 ICS 文件;对于邮件,使用 nodemailer 发送和 imap 读取(假设本地 SMTP/IMAP 服务器如 Postfix 或 Dovecot);文件使用内置 fs 模块。

pnpm add node-ical nodemailer imap fs-extra
pnpm add -D @types/node-ical @types/nodemailer @types/imap

定义一个 TypeScript 接口来规范工具函数,确保类型安全:

interface LocalTool {
  name: string;
  description: string;
  parameters: {
    type: 'object';
    properties: Record<string, { type: string; description: string }>;
    required: string[];
  };
  execute: (params: any) => Promise<any>;
}

这些准备确保了集成过程的顺利进行,无需任何外部 API 密钥。

集成本地日历 API

本地日历集成通常涉及解析用户的 ICS 文件,这些文件可从本地应用如 Thunderbird 或手动导出生成。使用 node-ical 库,可以轻松读取和解析事件。

首先,定义 MCP Tool 函数:

import ical from 'node-ical';

const calendarTool: LocalTool = {
  name: 'read_calendar',
  description: '读取本地 ICS 日历文件中的事件,支持日期范围查询',
  parameters: {
    type: 'object',
    properties: {
      filePath: { type: 'string', description: 'ICS 文件路径' },
      startDate: { type: 'string', description: '开始日期 (YYYY-MM-DD)' },
      endDate: { type: 'string', description: '结束日期 (YYYY-MM-DD)' }
    },
    required: ['filePath']
  },
  async execute({ filePath, startDate, endDate }) {
    const data = await ical.async.parseFile(filePath);
    const events = Object.values(data)
      .filter((event: any) => event.type === 'VEVENT')
      .filter((event: any) => {
        const eventDate = new Date(event.start);
        return !startDate || eventDate >= new Date(startDate)) &&
               (!endDate || eventDate <= new Date(endDate));
      })
      .map((event: any) => ({
        summary: event.summary,
        start: event.start.toISOString(),
        end: event.end.toISOString(),
        description: event.description
      }));
    return { events };
  }
};

在 DeepChat 的 MCP 服务中注册此工具。通过内置的 inMemory 服务,AI 模型可以在对话中调用如 “今天有什么会议?” 时,自动执行此函数并返回结果。参数配置建议:限制 filePath 到用户主目录下的子路径,避免跨盘访问;超时阈值设为 5 秒,防止长时间阻塞。

这种集成允许 AI 助手如 “帮我安排下午会议” 时,查询可用时段,而所有数据本地处理,确保隐私。

集成本地邮件 API

邮件集成更注重读取和发送本地服务器上的邮件。假设用户运行本地 IMAP/SMTP 服务器,使用 imap 库读取收件箱,nodemailer 发送。

定义读取邮件工具:

import Imap from 'imap';
import { simpleParser } from 'mailparser';

const emailTool: LocalTool = {
  name: 'read_emails',
  description: '从本地 IMAP 服务器读取邮件,支持主题和发件人过滤',
  parameters: {
    type: 'object',
    properties: {
      host: { type: 'string', description: 'IMAP 主机,默认 localhost' },
      port: { type: 'number', description: '端口,默认 143' },
      username: { type: 'string', description: '用户名' },
      password: { type: 'string', description: '密码' },
      subject: { type: 'string', description: '主题过滤' }
    },
    required: ['username', 'password']
  },
  async execute({ host = 'localhost', port = 143, username, password, subject }) {
    return new Promise((resolve, reject) => {
      const imap = new Imap({ user: username, password, host, port, tls: false });
      imap.once('ready', () => {
        imap.openBox('INBOX', true, (err, box) => {
          if (err) return reject(err);
          imap.search([['SUBJECT', subject || '']], (err, results) => {
            if (err) return reject(err);
            const fetch = imap.fetch(results, { bodies: '' });
            fetch.on('message', (msg) => {
              msg.on('body', (stream) => {
                simpleParser(stream, (err, parsed) => {
                  if (!err && parsed) resolve({ from: parsed.from?.text, subject: parsed.subject, text: parsed.text });
                });
              });
            });
            imap.end();
          });
        });
      });
      imap.once('error', reject);
    });
  }
};

对于发送,使用 nodemailer 配置本地 SMTP。安全参数:使用环境变量存储凭证;限制查询结果到最近 10 封邮件;集成加密传输,即使本地也建议 TLS。

AI 可以调用此工具响应 “回复最新邮件”,本地生成并发送内容。

集成本地文件 API

文件访问最简单,使用 Node.js fs 模块。DeepChat 的 Electron 环境天然支持文件系统操作。

import fs from 'fs-extra';

const fileTool: LocalTool = {
  name: 'read_file',
  description: '读取本地文件内容,支持路径和编码指定',
  parameters: {
    type: 'object',
    properties: {
      path: { type: 'string', description: '文件路径' },
      encoding: { type: 'string', description: '编码,默认 utf8' }
    },
    required: ['path']
  },
  async execute({ path, encoding = 'utf8' }) {
    if (!path.startsWith(process.env.HOME || '/')) throw new Error('路径限制');
    const content = await fs.readFile(path, encoding);
    return { content: content.toString().substring(0, 10000) };  // 限制长度
  }
};

引用 Node.js 文档:“Node.js fs 模块提供文件系统访问。” 此工具允许 AI 如 “总结我的笔记” 时读取~/Documents/notes.txt。

在 DeepChat 中配置和使用

在 DeepChat 的开发者模式下,编辑 MCP 服务配置。将以上工具添加到 inMemory services:

// 在 src/services/mcp.ts 或类似文件中
const localTools = [calendarTool, emailTool, fileTool];
export const mcpServices = {
  inMemory: {
    tools: localTools
  }
};

重启 DeepChat,选择本地 Ollama 模型。AI 在对话中会根据提示自动调用工具,例如 “检查我的日历并回复邮件”。监控点:日志工具调用次数,阈值 >50 次 / 小时 则警报潜在滥用。

最佳实践与风险控制

隐私是核心:使用沙箱如 Electron 的 contextIsolation 隔离工具执行;权限清单:用户手动批准每个工具首次调用;回滚策略:如果工具失败,fallback 到简单提示。参数优化:日历查询限 7 天窗口;邮件限 5 封 / 次;文件限 10KB。风险包括本地权限提升,使用 chroot 或 Docker 容器化 DeepChat 实例。测试中,确保无数据外泄:使用 Wireshark 验证无网络流量。

通过这些集成,DeepChat 转变为强大的个人 AI 助手,处理日常任务如日程提醒、邮件自动化和文件搜索,全程本地隐私保护。开发者可进一步扩展到语音或图像工具,构建完整生态。未来,随着本地模型进步,这种范式将更普及。

(字数约 1250)

查看归档