Skip to content

AI 智能辅助功能

AI 能力说明

JitWord 深度集成多种主流大模型,提供智能写作、内容改写、语法检查等全方位 AI 辅助功能,大幅提升文档创作效率。

🧠 AI 功能概览

JitWord 的 AI 智能辅助系统基于先进的大语言模型技术,为用户提供全方位的文档创作支持:

核心 AI 能力

  • 智能写作生成:根据主题、大纲或关键词快速生成高质量文档内容
  • 内容智能改写:一键改写、润色、扩展现有内容,支持多种写作风格
  • 智能总结提取:自动提取文档要点和摘要,生成执行摘要
  • 语法智能检查:实时语法和拼写检查,提升文档质量
  • 上下文理解:基于文档上下文的智能内容建议和补全
  • 多语言支持:支持中英文等多语言的智能处理和翻译

AI 技术架构

🎯 AI 功能详解

智能写作生成

功能特点

  • 支持多种写作场景:报告、方案、总结、创意文案等
  • 可根据用户提供的主题、大纲或关键词生成内容
  • 支持指定文档长度、写作风格和语言风格
  • 实时流式生成,边生成边显示,提升用户体验

使用场景

javascript
// AI 写作示例
const aiWriter = new AIWriter();

// 根据主题生成内容
const content = await aiWriter.generate({
  prompt: "写一份关于人工智能在教育领域应用的报告",
  style: "professional", // 专业风格
  length: "medium",      // 中等长度
  language: "zh-CN"      // 中文
});

// 根据大纲生成内容
const outlineContent = await aiWriter.generateFromOutline({
  title: "项目管理最佳实践",
  outline: [
    "项目规划阶段",
    "执行监控阶段", 
    "风险管理",
    "团队协作"
  ]
});

内容智能改写

改写类型

  • 润色优化:提升文档的表达质量和可读性
  • 风格转换:在正式、非正式、学术、商务等风格间转换
  • 长度调整:扩展或压缩内容长度
  • 语言翻译:支持中英文等多语言翻译
  • 专业术语:根据行业特点调整专业术语使用

使用示例

javascript
// 内容改写示例
const aiRewriter = new AIRewriter();

// 润色文本
const polishedText = await aiRewriter.polish({
  content: "这个项目很重要,我们需要认真对待。",
  instruction: "请将这段话改写得更加正式和专业"
});

// 风格转换
const formalText = await aiRewriter.changeStyle({
  content: "咱们开个会讨论一下这个问题吧",
  fromStyle: "casual",
  toStyle: "formal"
});

// 扩展内容
const expandedText = await aiRewriter.expand({
  content: "AI技术发展迅速",
  targetLength: "detailed",
  focus: "技术细节和应用场景"
});

智能总结功能

总结类型

  • 要点提取:提取文档的关键要点和核心信息
  • 执行摘要:生成适合管理层阅读的执行摘要
  • 章节总结:为长文档的各个章节生成小结
  • 关键词提取:自动提取文档的关键词和标签

实现示例

javascript
// 智能总结功能
const aiSummarizer = new AISummarizer();

// 生成执行摘要
const executiveSummary = await aiSummarizer.generateExecutiveSummary({
  content: documentContent,
  maxLength: 200,
  focus: "关键决策点和行动项"
});

// 提取要点
const keyPoints = await aiSummarizer.extractKeyPoints({
  content: documentContent,
  maxPoints: 5,
  format: "bullet_list"
});

// 生成关键词
const keywords = await aiSummarizer.extractKeywords({
  content: documentContent,
  maxKeywords: 10,
  includeScore: true
});

🔧 AI 模型配置

支持的 AI 模型

提供商模型名称特点适用场景
DeepSeekdeepseek-chat高质量中文生成,推理能力强通用写作、内容改写
DeepSeekdeepseek-reasoner逻辑推理能力突出分析报告、逻辑梳理
Kimikimi-k2-0905-preview长文本处理能力强长文档总结、大纲生成
Kimikimi-k2-0711稳定版本,响应快速日常写作、快速改写
Qwenqwen-turbo响应速度快,成本低高频使用场景
Qwenqwen-plus能力均衡,质量高专业文档写作
自定义企业私有模型支持 OpenAI 兼容接口企业定制化需求

AI Provider 配置

配置文件utils/ai/providers.ts):

typescript
export interface ProviderConfig {
  key: string;
  label: string;
  baseUrl: string;
  models: ModelConfig[];
  buildHeaders?: (apiKey: string) => Record<string, string>;
  rateLimit?: {
    requestsPerMinute: number;
    tokensPerMinute: number;
  };
}

export const PROVIDERS: Record<string, ProviderConfig> = {
  deepseek: {
    key: 'deepseek',
    label: 'DeepSeek',
    baseUrl: 'https://api.deepseek.com/v1',
    models: [
      { 
        label: 'DeepSeek Chat', 
        value: 'deepseek-chat',
        maxTokens: 4096,
        supportStream: true,
        costPerToken: 0.0001
      },
      { 
        label: 'DeepSeek Reasoner', 
        value: 'deepseek-reasoner',
        maxTokens: 8192,
        supportStream: true,
        costPerToken: 0.0002
      }
    ],
    rateLimit: {
      requestsPerMinute: 60,
      tokensPerMinute: 100000
    }
  },
  
  kimi: {
    key: 'kimi',
    label: 'Kimi (Moonshot)',
    baseUrl: 'https://api.moonshot.cn/v1',
    models: [
      { 
        label: 'Kimi K2 0905 Preview', 
        value: 'kimi-k2-0905-preview',
        maxTokens: 16384,
        supportStream: true
      },
      { 
        label: 'Kimi K2 0711', 
        value: 'kimi-k2-0711',
        maxTokens: 8192,
        supportStream: true
      }
    ]
  },
  
  custom: {
    key: 'custom',
    label: '企业自定义模型',
    baseUrl: '', // 企业自定义
    models: [
      { label: 'GPT-4o Mini', value: 'gpt-4o-mini' },
      { label: 'GLM-4 Air', value: 'glm-4-air' }
    ]
  }
};

AI 配置管理

配置存储utils/ai/config.ts):

typescript
export interface AISettings {
  provider: string;
  model: string;
  apiKey: string;
  temperature: number;
  maxTokens: number;
  enableStream: boolean;
  customPrompts: Record<string, string>;
}

export class AIConfigManager {
  private static readonly STORAGE_KEY = 'jitword_ai_settings';
  
  // 获取 AI 配置
  static getSettings(): AISettings {
    const stored = localStorage.getItem(this.STORAGE_KEY);
    if (stored) {
      return JSON.parse(stored);
    }
    
    return this.getDefaultSettings();
  }
  
  // 保存 AI 配置
  static saveSettings(settings: Partial<AISettings>) {
    const current = this.getSettings();
    const updated = { ...current, ...settings };
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(updated));
  }
  
  // 默认配置
  static getDefaultSettings(): AISettings {
    return {
      provider: 'deepseek',
      model: 'deepseek-chat',
      apiKey: '',
      temperature: 0.7,
      maxTokens: 2000,
      enableStream: true,
      customPrompts: {}
    };
  }
}

🌊 流式处理系统

流式生成实现

核心流式处理utils/ai/openaiStream.ts):

typescript
export async function createStreamResponse(
  provider: ProviderConfig,
  payload: any,
  apiKey: string
): Promise<AsyncIterable<{ content: string }>> {
  
  const response = await fetch(`${provider.baseUrl}/chat/completions`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`,
      ...provider.buildHeaders?.(apiKey)
    },
    body: JSON.stringify({
      ...payload,
      stream: true
    })
  });
  
  if (!response.ok) {
    throw new Error(`AI 服务请求失败: ${response.status} ${response.statusText}`);
  }
  
  if (!response.body) {
    throw new Error('响应体为空');
  }
  
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  
  return {
    async *[Symbol.asyncIterator]() {
      try {
        while (true) {
          const { done, value } = await reader.read();
          
          if (done) break;
          
          const chunk = decoder.decode(value);
          const lines = chunk.split('\n').filter(line => line.trim());
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6);
              
              if (data === '[DONE]') {
                return;
              }
              
              try {
                const parsed = JSON.parse(data);
                const content = parsed.choices?.[0]?.delta?.content;
                
                if (content) {
                  yield { content };
                }
              } catch (e) {
                console.warn('解析流式数据失败:', e);
              }
            }
          }
        }
      } finally {
        reader.releaseLock();
      }
    }
  };
}

前端流式显示

javascript
// 流式内容显示
export class StreamRenderer {
  constructor(container) {
    this.container = container;
    this.content = '';
  }
  
  async renderStream(streamGenerator) {
    this.content = '';
    this.container.innerHTML = '';
    
    try {
      for await (const chunk of streamGenerator) {
        this.content += chunk.content;
        
        // 实时更新显示
        this.updateDisplay();
        
        // 滚动到底部
        this.scrollToBottom();
      }
    } catch (error) {
      this.showError(error.message);
    }
  }
  
  updateDisplay() {
    // 使用 Markdown 渲染器实时渲染内容
    this.container.innerHTML = this.markdownToHtml(this.content);
  }
  
  scrollToBottom() {
    this.container.scrollTop = this.container.scrollHeight;
  }
}

📝 提示词管理系统

内置提示词模板

写作提示词utils/ai/prompts/writer.ts):

typescript
export const WRITER_PROMPTS = {
  // 通用写作
  general: {
    system: "你是一个专业的文档写作助手,擅长创作高质量的文档内容。",
    template: "请根据以下要求写作:\n\n主题:{topic}\n要求:{requirements}\n风格:{style}\n长度:{length}"
  },
  
  // 报告写作
  report: {
    system: "你是一个专业的报告写作专家,擅长撰写结构清晰、逻辑严密的各类报告。",
    template: "请撰写一份关于 {topic} 的{reportType}报告,要求:\n1. 结构清晰,逻辑严密\n2. 数据准确,分析深入\n3. 结论明确,建议可行\n\n具体要求:{requirements}"
  },
  
  // 方案写作
  proposal: {
    system: "你是一个专业的方案策划专家,擅长制定详细可行的解决方案。",
    template: "请制定一份 {topic} 的解决方案,包含:\n1. 现状分析\n2. 目标设定\n3. 实施步骤\n4. 资源需求\n5. 风险评估\n\n具体要求:{requirements}"
  }
};

改写提示词utils/ai/prompts/rewrite.ts):

typescript
export const REWRITE_PROMPTS = {
  // 润色优化
  polish: {
    system: "你是一个专业的文本编辑专家,擅长润色和优化文档内容。",
    template: "请对以下内容进行润色优化:\n\n原文:{content}\n\n要求:{instruction}\n\n请保持原意的基础上,提升表达质量和可读性。"
  },
  
  // 风格转换
  styleChange: {
    system: "你是一个专业的文本风格转换专家。",
    template: "请将以下内容从 {fromStyle} 风格转换为 {toStyle} 风格:\n\n原文:{content}\n\n转换要求:{requirements}"
  },
  
  // 长度调整
  lengthAdjust: {
    system: "你是一个专业的文本编辑专家,擅长调整文本长度。",
    template: "请将以下内容{action}:\n\n原文:{content}\n\n要求:{instruction}\n\n请保持核心信息不变。"
  }
};

自定义提示词

javascript
// 自定义提示词管理
export class CustomPromptManager {
  constructor() {
    this.prompts = this.loadCustomPrompts();
  }
  
  // 加载自定义提示词
  loadCustomPrompts() {
    const stored = localStorage.getItem('custom_prompts');
    return stored ? JSON.parse(stored) : {};
  }
  
  // 保存自定义提示词
  saveCustomPrompt(name, prompt) {
    this.prompts[name] = {
      ...prompt,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    
    localStorage.setItem('custom_prompts', JSON.stringify(this.prompts));
  }
  
  // 获取提示词
  getPrompt(name) {
    return this.prompts[name] || null;
  }
  
  // 删除提示词
  deletePrompt(name) {
    delete this.prompts[name];
    localStorage.setItem('custom_prompts', JSON.stringify(this.prompts));
  }
}

🎨 AI 用户界面

AI 写作弹窗

组件实现components/AIWriterModal.vue):

vue
<template>
  <a-modal
    v-model:visible="visible"
    title="AI 智能写作"
    width="800px"
    :footer="null"
    @cancel="handleClose"
  >
    <div class="ai-writer-modal">
      <!-- 写作配置 -->
      <div class="config-section">
        <a-form :model="config" layout="vertical">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="AI 模型">
                <a-select v-model:value="config.model">
                  <a-select-option 
                    v-for="model in availableModels" 
                    :key="model.value"
                    :value="model.value"
                  >
                    {{ model.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="写作风格">
                <a-select v-model:value="config.style">
                  <a-select-option value="professional">专业正式</a-select-option>
                  <a-select-option value="casual">轻松随意</a-select-option>
                  <a-select-option value="academic">学术严谨</a-select-option>
                  <a-select-option value="creative">创意活泼</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          
          <a-form-item label="写作主题">
            <a-textarea 
              v-model:value="config.topic"
              placeholder="请输入写作主题或要求..."
              :rows="3"
            />
          </a-form-item>
          
          <a-form-item label="详细要求">
            <a-textarea 
              v-model:value="config.requirements"
              placeholder="请输入具体的写作要求和期望..."
              :rows="2"
            />
          </a-form-item>
        </a-form>
      </div>
      
      <!-- 生成按钮 -->
      <div class="action-section">
        <a-button 
          type="primary" 
          :loading="generating"
          @click="handleGenerate"
        >
          {{ generating ? '生成中...' : '开始生成' }}
        </a-button>
        <a-button @click="handleClear">清空</a-button>
      </div>
      
      <!-- 生成结果 -->
      <div class="result-section" v-if="generatedContent">
        <div class="result-header">
          <span>生成结果</span>
          <a-button size="small" @click="handleInsert">插入到文档</a-button>
        </div>
        <div class="result-content" v-html="renderedContent"></div>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { AIWriter } from '@/utils/ai';

const visible = ref(false);
const generating = ref(false);
const generatedContent = ref('');

const config = ref({
  model: 'deepseek-chat',
  style: 'professional',
  topic: '',
  requirements: ''
});

// 生成内容
async function handleGenerate() {
  if (!config.value.topic.trim()) {
    message.warning('请输入写作主题');
    return;
  }
  
  generating.value = true;
  generatedContent.value = '';
  
  try {
    const aiWriter = new AIWriter();
    const stream = await aiWriter.generateStream({
      prompt: buildPrompt(config.value),
      model: config.value.model,
      stream: true
    });
    
    // 流式显示生成内容
    for await (const chunk of stream) {
      generatedContent.value += chunk;
    }
    
  } catch (error) {
    message.error(`生成失败: ${error.message}`);
  } finally {
    generating.value = false;
  }
}

// 构建提示词
function buildPrompt(config) {
  return `请根据以下要求进行写作:

主题:${config.topic}
风格:${config.style}
要求:${config.requirements || '无特殊要求'}

请生成高质量的文档内容。`;
}
</script>

AI 改写弹窗

组件实现components/AIRewriteModal.vue):

vue
<template>
  <a-modal
    v-model:visible="visible"
    title="AI 智能改写"
    width="900px"
    :footer="null"
  >
    <div class="ai-rewrite-modal">
      <!-- 原文显示 -->
      <div class="original-section">
        <div class="section-title">原文内容</div>
        <div class="original-content">{{ originalContent }}</div>
      </div>
      
      <!-- 改写配置 -->
      <div class="config-section">
        <a-form :model="rewriteConfig" layout="inline">
          <a-form-item label="改写类型">
            <a-select v-model:value="rewriteConfig.type" style="width: 120px">
              <a-select-option value="polish">润色优化</a-select-option>
              <a-select-option value="expand">扩展内容</a-select-option>
              <a-select-option value="compress">压缩精简</a-select-option>
              <a-select-option value="style">风格转换</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label="改写要求">
            <a-input 
              v-model:value="rewriteConfig.instruction"
              placeholder="请输入具体的改写要求..."
              style="width: 300px"
            />
          </a-form-item>
          
          <a-form-item>
            <a-button 
              type="primary" 
              :loading="rewriting"
              @click="handleRewrite"
            >
              开始改写
            </a-button>
          </a-form-item>
        </a-form>
      </div>
      
      <!-- 改写结果 -->
      <div class="result-section" v-if="rewrittenContent">
        <div class="section-title">
          改写结果
          <a-button size="small" type="primary" @click="handleReplace">
            替换原文
          </a-button>
        </div>
        <div class="rewritten-content" v-html="renderedRewrittenContent"></div>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref } from 'vue';
import { AIRewriter } from '@/utils/ai';

const visible = ref(false);
const rewriting = ref(false);
const originalContent = ref('');
const rewrittenContent = ref('');

const rewriteConfig = ref({
  type: 'polish',
  instruction: ''
});

// 执行改写
async function handleRewrite() {
  if (!originalContent.value.trim()) {
    message.warning('没有选中的内容');
    return;
  }
  
  rewriting.value = true;
  rewrittenContent.value = '';
  
  try {
    const aiRewriter = new AIRewriter();
    
    const result = await aiRewriter.rewrite({
      content: originalContent.value,
      type: rewriteConfig.value.type,
      instruction: rewriteConfig.value.instruction
    });
    
    rewrittenContent.value = result;
    
  } catch (error) {
    message.error(`改写失败: ${error.message}`);
  } finally {
    rewriting.value = false;
  }
}

// 替换原文
function handleReplace() {
  if (rewrittenContent.value) {
    // 替换编辑器中的选中内容
    editor.chain().focus().deleteSelection().insertContent(rewrittenContent.value).run();
    visible.value = false;
  }
}
</script>

🔧 企业级 AI 集成

企业私有模型接入

typescript
// 企业私有模型配置
export class EnterpriseAIProvider {
  constructor(config: EnterpriseAIConfig) {
    this.config = config;
    this.apiKey = config.apiKey;
    this.baseUrl = config.baseUrl;
  }
  
  // 调用企业模型
  async callModel(payload: any) {
    const response = await fetch(`${this.baseUrl}/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.apiKey}`,
        'X-Enterprise-ID': this.config.enterpriseId,
        'X-Department': this.config.department
      },
      body: JSON.stringify({
        ...payload,
        // 企业特定参数
        compliance_mode: true,
        audit_log: true,
        data_residency: this.config.dataResidency
      })
    });
    
    if (!response.ok) {
      throw new Error(`企业模型调用失败: ${response.status}`);
    }
    
    return response.json();
  }
  
  // 审计日志
  logAIUsage(operation: string, input: string, output: string) {
    const auditLog = {
      timestamp: new Date().toISOString(),
      operation: operation,
      userId: this.getCurrentUserId(),
      department: this.config.department,
      inputLength: input.length,
      outputLength: output.length,
      model: this.config.model,
      compliance: true
    };
    
    // 发送到企业审计系统
    this.sendToAuditSystem(auditLog);
  }
}

AI 成本控制

javascript
// AI 使用成本控制
export class AICostController {
  constructor() {
    this.usage = new Map(); // 用户使用统计
    this.limits = new Map(); // 用户限制配置
  }
  
  // 检查使用限制
  async checkUsageLimit(userId, operation) {
    const userUsage = this.getUserUsage(userId);
    const userLimits = this.getUserLimits(userId);
    
    // 检查日使用量
    if (userUsage.dailyTokens >= userLimits.dailyTokenLimit) {
      throw new Error('今日 AI 使用量已达上限');
    }
    
    // 检查月使用量
    if (userUsage.monthlyTokens >= userLimits.monthlyTokenLimit) {
      throw new Error('本月 AI 使用量已达上限');
    }
    
    return true;
  }
  
  // 记录使用量
  recordUsage(userId, operation, tokens, cost) {
    const usage = this.getUserUsage(userId);
    
    usage.dailyTokens += tokens;
    usage.monthlyTokens += tokens;
    usage.totalCost += cost;
    
    // 记录操作历史
    usage.operations.push({
      operation: operation,
      tokens: tokens,
      cost: cost,
      timestamp: Date.now()
    });
    
    this.saveUserUsage(userId, usage);
  }
}

📊 AI 性能监控

AI 调用监控

javascript
// AI 性能监控
export class AIPerformanceMonitor {
  constructor() {
    this.metrics = {
      totalRequests: 0,
      successfulRequests: 0,
      failedRequests: 0,
      averageResponseTime: 0,
      totalTokensUsed: 0,
      totalCost: 0
    };
  }
  
  // 记录 AI 调用
  recordAICall(provider, model, startTime, endTime, tokens, success, error) {
    const duration = endTime - startTime;
    
    this.metrics.totalRequests++;
    
    if (success) {
      this.metrics.successfulRequests++;
      this.metrics.totalTokensUsed += tokens;
      
      // 更新平均响应时间
      this.updateAverageResponseTime(duration);
      
      // 计算成本
      const cost = this.calculateCost(provider, model, tokens);
      this.metrics.totalCost += cost;
      
    } else {
      this.metrics.failedRequests++;
      
      // 记录错误
      this.recordError(provider, model, error);
    }
  }
  
  // 生成监控报告
  generateReport() {
    const successRate = this.metrics.successfulRequests / this.metrics.totalRequests;
    
    return {
      ...this.metrics,
      successRate: successRate,
      averageCostPerRequest: this.metrics.totalCost / this.metrics.successfulRequests,
      requestsPerHour: this.calculateRequestsPerHour(),
      topErrors: this.getTopErrors()
    };
  }
}

AI 质量评估

javascript
// AI 生成内容质量评估
export class AIQualityAssessment {
  // 评估生成内容质量
  assessContent(originalPrompt, generatedContent) {
    const assessment = {
      relevance: this.assessRelevance(originalPrompt, generatedContent),
      coherence: this.assessCoherence(generatedContent),
      completeness: this.assessCompleteness(originalPrompt, generatedContent),
      language: this.assessLanguageQuality(generatedContent),
      overall: 0
    };
    
    // 计算综合评分
    assessment.overall = (
      assessment.relevance * 0.3 +
      assessment.coherence * 0.25 +
      assessment.completeness * 0.25 +
      assessment.language * 0.2
    );
    
    return assessment;
  }
  
  // 评估相关性
  assessRelevance(prompt, content) {
    // 使用关键词匹配和语义相似度
    const promptKeywords = this.extractKeywords(prompt);
    const contentKeywords = this.extractKeywords(content);
    
    const overlap = this.calculateKeywordOverlap(promptKeywords, contentKeywords);
    return Math.min(overlap * 2, 1); // 归一化到 0-1
  }
  
  // 评估连贯性
  assessCoherence(content) {
    // 分析句子间的逻辑连接
    const sentences = this.splitIntoSentences(content);
    let coherenceScore = 0;
    
    for (let i = 1; i < sentences.length; i++) {
      const similarity = this.calculateSentenceSimilarity(
        sentences[i-1], 
        sentences[i]
      );
      coherenceScore += similarity;
    }
    
    return coherenceScore / (sentences.length - 1);
  }
}

🔐 AI 安全与合规

内容安全过滤

javascript
// AI 内容安全检查
export class AIContentSafety {
  constructor() {
    this.sensitiveWords = this.loadSensitiveWords();
    this.complianceRules = this.loadComplianceRules();
  }
  
  // 内容安全检查
  async checkContentSafety(content) {
    const issues = [];
    
    // 敏感词检查
    const sensitiveIssues = this.checkSensitiveWords(content);
    issues.push(...sensitiveIssues);
    
    // 合规性检查
    const complianceIssues = this.checkCompliance(content);
    issues.push(...complianceIssues);
    
    // 隐私信息检查
    const privacyIssues = this.checkPrivacyInfo(content);
    issues.push(...privacyIssues);
    
    return {
      safe: issues.length === 0,
      issues: issues,
      filteredContent: this.filterContent(content, issues)
    };
  }
  
  // 敏感词检查
  checkSensitiveWords(content) {
    const issues = [];
    
    for (const word of this.sensitiveWords) {
      if (content.includes(word)) {
        issues.push({
          type: 'sensitive_word',
          word: word,
          severity: 'high'
        });
      }
    }
    
    return issues;
  }
  
  // 隐私信息检查
  checkPrivacyInfo(content) {
    const issues = [];
    
    // 检查身份证号
    const idCardRegex = /\d{17}[\dX]/g;
    if (idCardRegex.test(content)) {
      issues.push({
        type: 'privacy_info',
        info: 'id_card',
        severity: 'high'
      });
    }
    
    // 检查手机号
    const phoneRegex = /1[3-9]\d{9}/g;
    if (phoneRegex.test(content)) {
      issues.push({
        type: 'privacy_info',
        info: 'phone_number',
        severity: 'medium'
      });
    }
    
    return issues;
  }
}

AI 使用审计

javascript
// AI 使用审计系统
export class AIAuditLogger {
  constructor() {
    this.auditLogs = [];
  }
  
  // 记录 AI 使用
  logAIUsage(operation, input, output, metadata = {}) {
    const auditEntry = {
      id: this.generateAuditId(),
      timestamp: new Date().toISOString(),
      operation: operation,
      userId: metadata.userId,
      sessionId: metadata.sessionId,
      input: {
        content: input,
        length: input.length,
        hash: this.hashContent(input)
      },
      output: {
        content: output,
        length: output.length,
        hash: this.hashContent(output)
      },
      model: metadata.model,
      provider: metadata.provider,
      tokens: metadata.tokens,
      cost: metadata.cost,
      duration: metadata.duration,
      success: metadata.success,
      error: metadata.error
    };
    
    this.auditLogs.push(auditEntry);
    
    // 发送到审计服务
    this.sendToAuditService(auditEntry);
  }
  
  // 生成审计报告
  generateAuditReport(startDate, endDate) {
    const filteredLogs = this.auditLogs.filter(log => {
      const logDate = new Date(log.timestamp);
      return logDate >= startDate && logDate <= endDate;
    });
    
    return {
      period: { startDate, endDate },
      totalOperations: filteredLogs.length,
      successfulOperations: filteredLogs.filter(log => log.success).length,
      totalTokensUsed: filteredLogs.reduce((sum, log) => sum + log.tokens, 0),
      totalCost: filteredLogs.reduce((sum, log) => sum + log.cost, 0),
      topUsers: this.getTopUsers(filteredLogs),
      topOperations: this.getTopOperations(filteredLogs),
      errorAnalysis: this.analyzeErrors(filteredLogs)
    };
  }
}

🚀 AI 功能部署

生产环境配置

bash
# AI 相关环境变量
AI_ENABLED=true
AI_DEFAULT_PROVIDER=deepseek
AI_RATE_LIMIT_ENABLED=true
AI_AUDIT_ENABLED=true
AI_CONTENT_FILTER_ENABLED=true

# 模型配置
DEEPSEEK_API_KEY=your-deepseek-api-key
KIMI_API_KEY=your-kimi-api-key
CUSTOM_MODEL_URL=https://your-enterprise-model.com/v1

# 使用限制
AI_DAILY_TOKEN_LIMIT=100000
AI_MONTHLY_TOKEN_LIMIT=1000000
AI_MAX_CONCURRENT_REQUESTS=10

Docker 部署配置

dockerfile
# AI 功能的 Docker 配置
FROM node:18-alpine

WORKDIR /app

# 安装依赖
COPY package.json pnpm-lock.yaml ./
RUN corepack enable && pnpm install --frozen-lockfile

# 复制源码
COPY . .

# 构建应用
RUN pnpm build

# 设置 AI 相关环境变量
ENV AI_ENABLED=true
ENV AI_AUDIT_ENABLED=true
ENV AI_CONTENT_FILTER_ENABLED=true

# 暴露端口
EXPOSE 3002

# 启动服务
CMD ["node", "dist/index.js"]

📞 AI 功能支持与授权

🎯 源码授权说明

  • ✅ AI 功能完全开源:包含完整的 AI 集成代码和配置
  • ✅ 支持企业模型接入:可接入企业私有化 AI 模型
  • ✅ 可商业化使用:支持基于 AI 功能的商业化部署
  • ❌ 源码不可二次分发:AI 相关源码不得再次销售或分发

🛠️ AI 技术支持

  • AI 技术咨询微信:cxzk_168(工作时间响应)
  • 企业 AI 服务:cxzk_168(微信咨询)
  • AI 功能文档:完整的 AI 集成开发指导

我们提供专业的 AI 集成服务,帮助企业基于源码快速构建智能文档协作平台。

让技术更平权,致力于高性价办公协同解决方案