钉钉 AI 客服:Serverless 部署方案

5 阅读1分钟

钉钉 AI 客服:Serverless 部署方案

Serverless 适合低成本启动 AI 客服。


一、为什么选择 Serverless?

优势说明
零运维无需管理服务器
按量付费用多少付多少
自动扩缩流量高峰自动扩容
快速部署分钟级上线

二、云函数实现

2.1 阿里云函数计算

// index.js
exports.handler = async (event) => {
  const message = JSON.parse(event.toString()).message;
  
  const response = await ai.chat(message);
  
  return {
    statusCode: 200,
    body: JSON.stringify({ response })
  };
};

2.2 腾讯云函数

exports.main = async (event, context) => {
  const { message } = event;
  
  const response = await ai.chat(message);
  
  return {
    code: 0,
    data: { response }
  };
};

三、API 网关配置

3.1 触发器配置

# 阿里云 API 网关
triggers:
  - name: chat-api
    type: http
    config:
      authType: anonymous
      methods:
        - POST
      path: /api/chat

四、数据库方案

4.1 云数据库

// 阿里云 TableStore
const TableStore = require('tablestore');

const client = new TableStore.Client({
  accessKeyId: process.env.ALIYUN_ACCESS_KEY,
  secretAccessKey: process.env.ALIYUN_SECRET_KEY,
  endpoint: 'https://xxx.cn-hangzhou.ots.aliyuncs.com'
});

async function saveChat(userId, message) {
  await client.putRow({
    tableName: 'chats',
    condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
    primaryKey: [{ userId }, { timestamp: Date.now() }],
    attributeColumns: [{ message }]
  });
}

4.2 云缓存

// 阿里云 Redis
const Redis = require('ioredis');

const redis = new Redis({
  host: 'xxx.redis.rds.aliyuncs.com',
  port: 6379,
  password: process.env.REDIS_PASSWORD
});

async function cacheContext(userId, context) {
  await redis.set(`ctx:${userId}`, JSON.stringify(context), 'EX', 3600);
}

五、成本分析

5.1 费用估算(月)

项目数量费用
函数调用10 万次¥1.5
执行时间1000 秒¥0.03
API 网关10 万次¥1.0
数据库1 GB¥0.5
合计-¥3/月

六、冷启动优化

6.1 预留实例

# 阿里云预留实例
provision:
  - qualifier: LATEST
    functionName: chat
    target: 1  # 预留 1 个实例

6.2 预热策略

// 定时预热
exports.warmup = async (event) => {
  await fetch('https://api.example.com/api/chat', {
    method: 'POST',
    body: JSON.stringify({ message: 'ping' })
  });
};

// 配置定时触发器(每 5 分钟)

七、部署流程

7.1 阿里云部署

# 安装工具
npm install -g @alicloud/fcli

# 配置
fcli config set --account-id xxx --access-key-id xxx --access-key-secret xxx

# 部署函数
fcli function create --name chat --runtime nodejs18 --handler index.handler

7.2 腾讯云部署

# 安装工具
npm install -g serverless

# 部署
sls deploy

八、监控告警

8.1 云监控配置

// 函数执行时间告警
{
  "metric": "FunctionDuration",
  "threshold": 3000,  // 3 秒
  "operator": ">",
  "actions": ["钉钉通知"]
}

项目地址:GitHub - dingtalk-connector-pro 有问题欢迎 Issue 或评论区交流