个人编程网站

进销存(JXC)软件开发技术积累与分享

进销存系统智能客服与语音交互

引言

随着人工智能技术的发展,进销存系统正在从传统的图形界面交互向智能化交互方式演进。智能客服和语音交互可以让用户更高效地完成库存查询、订单处理等操作。本文将探讨智能客服与语音交互在进销存系统中的应用。

智能客服系统架构

构建企业级智能客服平台:

层次 组件 功能
接入层 Web/小程序/公众号 多端接入
理解层 NLP引擎 意图识别、实体抽取
服务层 业务能力中台 库存/订单/财务查询
输出层 对话管理、TTS 自然语言回复、语音合成

对话式库存查询

实现智能库存查询助手:

// 智能库存查询助手
class InventoryQueryAssistant {
  constructor(inventoryService) {
    this.inventoryService = inventoryService;
    this.nlpEngine = new NLPEngine();
    this.contextManager = new ContextManager();
  }

  // 处理用户查询
  async handleQuery(userQuery, userId) {
    // 1. 自然语言理解
    const understanding = await this.nlpEngine.understand(userQuery);

    // 2. 获取对话上下文
    const context = this.contextManager.getContext(userId);

    // 3. 构建查询参数
    const queryParams = this.buildQueryParams(understanding, context);

    // 4. 执行查询
    const results = await this.inventoryService.query(queryParams);

    // 5. 生成自然语言回复
    const response = this.generateResponse(understanding, results);

    // 6. 更新上下文
    this.contextManager.updateContext(userId, understanding, results);

    return response;
  }

  // 构建查询参数
  buildQueryParams(understanding, context) {
    const params = {
      sku: understanding.entities.sku || context.pendingParams.sku,
      warehouse: understanding.entities.warehouse || context.pendingParams.warehouse,
      date: understanding.entities.date || new Date()
    };

    // 处理时间表达式
    if (understanding.entities.timeExpression) {
      params.date = this.parseTimeExpression(understanding.entities.timeExpression);
    }

    return params;
  }

  // 解析时间表达式
  parseTimeExpression(expression) {
    const now = new Date();

    if (expression === '今天') return now;
    if (expression === '昨天') return new Date(now - 86400000);
    if (expression === '上周') return new Date(now - 7 * 86400000);
    if (expression === '上个月') return new Date(now.getFullYear(), now.getMonth() - 1);

    // 处理相对时间
    const match = expression.match(/(\d+)(天|周|月)前/);
    if (match) {
      const value = parseInt(match[1]);
      const unit = match[2];
      const ms = unit === '天' ? 86400000 : unit === '周' ? 604800000 : 2592000000;
      return new Date(now - value * ms);
    }

    return now;
  }

  // 生成自然语言回复
  generateResponse(understanding, results) {
    const intent = understanding.intent;

    switch (intent) {
      case 'QUERY_STOCK':
        return this.formatStockResponse(results);
      case 'QUERY_TREND':
        return this.formatTrendResponse(results);
      case 'QUERY_LOW_STOCK':
        return this.formatLowStockResponse(results);
      case 'QUERY_EXPIRY':
        return this.formatExpiryResponse(results);
      default:
        return this.formatGeneralResponse(results);
    }
  }

  // 格式化库存查询回复
  formatStockResponse(results) {
    if (results.length === 0) {
      return '未找到相关库存信息,请尝试其他查询条件。';
    }

    if (results.length === 1) {
      const item = results[0];
      return `商品【${item.skuName}】在【${item.warehouseName}】的当前库存为 ${item.quantity} ${item.unit}。` +
        (item.availableQuantity < item.quantity ?
          `其中可用库存为 ${item.availableQuantity} ${item.unit}。` : '');
    }

    // 多个结果汇总
    const total = results.reduce((sum, item) => sum + item.quantity, 0);
    const warehouses = results.map(r => r.warehouseName).join('、');

    return `商品【${results[0].skuName}】在以下仓库有库存:\n` +
      results.map(r => `  - ${r.warehouseName}: ${r.quantity}${r.unit}`).join('\n') +
      `\n合计: ${total}${results[0].unit}。`;
  }

  // 格式化库存预警回复
  formatLowStockResponse(results) {
    if (results.length === 0) {
      return '目前没有库存不足的商品,系统运行正常。';
    }

    const critical = results.filter(r => r.quantity < r.minStock * 0.5);
    const warning = results.filter(r => r.quantity >= r.minStock * 0.5 && r.quantity < r.minStock);

    let response = `发现 ${results.length} 个商品库存不足:\n`;

    if (critical.length > 0) {
      response += `\n【紧急补货】${critical.length}个:\n`;
      response += critical.map(r => `  ⚠️ ${r.skuName} (${r.warehouseName}): ${r.quantity}/${r.minStock}${r.unit}`).join('\n');
    }

    if (warning.length > 0) {
      response += `\n【建议补货】${warning.length}个:\n`;
      response += warning.map(r => `  • ${r.skuName} (${r.warehouseName}): ${r.quantity}/${r.minStock}${r.unit}`).join('\n');
    }

    return response;
  }
}

语音交互集成

实现语音控制进销存系统:

// 语音交互控制器
class VoiceInteractionController {
  constructor(config) {
    this.asr = new ASREngine(config.asr);
    this.tts = new TTSEngine(config.tts);
    this.nlpEngine = new NLPEngine();
    this.audioManager = new AudioManager();
  }

  // 启动语音交互
  async startSession(userId) {
    const session = new VoiceSession({
      userId: userId,
      startTime: Date.now(),
      state: 'LISTENING'
    });

    // 开始监听
    await this.startListening(session);

    return session;
  }

  // 开始监听用户语音
  async startListening(session) {
    session.state = 'LISTENING';

    // 播放提示音
    await this.audioManager.playTone(800, 100);

    // 持续音频采集
    const audioStream = await this.audioManager.startCapture();

    // 实时语音识别
    const recognition = this.asr.createRecognition();

    recognition.on('result', async (event) => {
      if (event.isFinal) {
        const text = event.transcript;

        // 意图识别
        const intent = await this.nlpEngine.understand(text);

        // 执行相应操作
        await this.handleIntent(session, intent, text);
      }
    });

    recognition.on('error', (error) => {
      this.handleError(session, error);
    });

    // 处理音频流
    await recognition.start(audioStream);
  }

  // 处理识别到的意图
  async handleIntent(session, intent, rawText) {
    session.state = 'PROCESSING';

    let response;

    try {
      switch (intent.intent) {
        case 'QUERY_INVENTORY':
          response = await this.handleInventoryQuery(intent);
          break;
        case 'CREATE_ORDER':
          response = await this.handleOrderCreation(intent);
          break;
        case 'QUERY_ORDER':
          response = await this.handleOrderQuery(intent);
          break;
        case 'CONFIRM_ACTION':
          response = await this.handleConfirmation(session, intent);
          break;
        default:
          response = '抱歉,我没有理解您的意思,请再说一次。';
      }
    } catch (error) {
      response = `处理出错:${error.message}`;
    }

    // 语音合成回复
    await this.speakResponse(session, response);
  }

  // 处理库存查询
  async handleInventoryQuery(intent) {
    const sku = intent.entities.sku;
    const warehouse = intent.entities.warehouse;

    const results = await this.inventoryService.query({
      sku: sku,
      warehouse: warehouse
    });

    return this.formatResponse(results, '库存查询');
  }

  // 处理订单创建
  async handleOrderCreation(intent) {
    // 提取订单信息
    const orderInfo = {
      type: intent.entities.orderType || '销售',
      customer: intent.entities.customer,
      items: intent.entities.items,
      quantity: intent.entities.quantity
    };

    // 创建订单
    const order = await this.orderService.create(orderInfo);

    // 需要用户确认
    return {
      type: 'CONFIRMATION_NEEDED',
      message: `确认创建${orderInfo.type}订单:\n商品:${orderInfo.items}\n数量:${orderInfo.quantity}\n客户:${orderInfo.customer}\n\n请回复"确认"或"取消"。`,
      orderId: order.id
    };
  }

  // 语音合成回复
  async speakResponse(session, response) {
    // 将文本转为语音
    const audioData = await this.tts.synthesize(response);

    // 播放音频
    await this.audioManager.play(audioData);

    // 继续监听
    if (session.state !== 'COMPLETED') {
      await this.startListening(session);
    }
  }
}

多轮对话管理

复杂业务场景的多轮交互:

// 多轮对话管理器
class DialogueManager {
  constructor() {
    this.sessions = new Map();
  }

  // 开始新对话
  startDialogue(userId, initialIntent) {
    const session = {
      userId: userId,
      intent: initialIntent,
      slots: {},
      requiredSlots: this.getRequiredSlots(initialIntent),
      status: 'SLOT_FILLING',
      history: []
    };

    this.sessions.set(userId, session);

    // 返回需要补充的信息
    return this.askForNextSlot(session);
  }

  // 获取意图所需的槽位
  getRequiredSlots(intent) {
    const slotConfig = {
      'create_order': ['customer', 'items', 'quantity'],
      'query_inventory': ['sku'],
      'return_goods': ['orderId', 'reason', 'items']
    };

    return (slotConfig[intent] || []).map(slotName => ({
      name: slotName,
      ask: this.getSlotQuestion(slotName)
    }));
  }

  // 获取槽位提问文案
  getSlotQuestion(slotName) {
    const questions = {
      customer: '请告诉我客户名称?',
      items: '请告诉我商品名称或编号?',
      quantity: '请告诉我数量?',
      orderId: '请告诉我订单编号?',
      reason: '请告诉我退货原因?',
      sku: '请告诉我商品名称或编号?'
    };

    return questions[slotName] || `请提供${slotName}?`;
  }

  // 处理用户输入
  processInput(userId, userInput) {
    const session = this.sessions.get(userId);

    if (!session) {
      return { error: '对话已过期,请重新开始' };
    }

    // 解析用户输入
    const extracted = this.extractSlots(session.requiredSlots[0], userInput);
    session.slots[extracted.slot] = extracted.value;

    // 移除已填写的槽位
    session.requiredSlots.shift();

    // 检查是否所有必需槽位都已填写
    if (session.requiredSlots.length === 0) {
      session.status = 'COMPLETED';
      return { status: 'COMPLETED', slots: session.slots };
    }

    // 返回下一个需要填写的槽位
    return this.askForNextSlot(session);
  }

  // 询问下一个槽位
  askForNextSlot(session) {
    const nextSlot = session.requiredSlots[0];

    return {
      status: 'SLOT_FILLING',
      question: nextSlot.ask,
      filled: Object.keys(session.slots),
      remaining: session.requiredSlots.length
    };
  }
}

最佳实践建议

总结

智能客服与语音交互提升进销存系统用户体验:

通过智能交互技术,让进销存系统更易于使用。

← 下一篇:进销存系统自动化立体仓库管理