钉钉 AI 客服:Function Calling 实战

4 阅读1分钟

钉钉 AI 客服:Function Calling 实战

Function Calling 让 AI 能调用外部工具。


一、概念介绍

Function Calling 允许 AI 调用预定义的函数,实现:

  • 查询订单
  • 获取物流
  • 执行操作

二、定义函数

const tools = [
  {
    type: 'function',
    function: {
      name: 'get_order',
      description: '查询订单状态',
      parameters: {
        type: 'object',
        properties: {
          order_id: {
            type: 'string',
            description: '订单号'
          }
        },
        required: ['order_id']
      }
    }
  },
  {
    type: 'function',
    function: {
      name: 'get_logistics',
      description: '查询物流信息',
      parameters: {
        type: 'object',
        properties: {
          tracking_number: {
            type: 'string',
            description: '快递单号'
          }
        },
        required: ['tracking_number']
      }
    }
  }
];

三、调用流程

async function chatWithTools(message) {
  // 1. 发送消息给 AI
  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: message }],
    tools
  });
  
  // 2. 检查是否需要调用函数
  const toolCalls = response.choices[0].message.tool_calls;
  
  if (toolCalls) {
    // 3. 执行函数
    const results = await Promise.all(
      toolCalls.map(call => executeFunction(call))
    );
    
    // 4. 返回结果给 AI
    const finalResponse = await openai.chat.completions.create({
      model: 'gpt-4',
      messages: [
        { role: 'user', content: message },
        response.choices[0].message,
        ...results.map(r => ({ role: 'tool', content: r }))
      ]
    });
    
    return finalResponse.choices[0].message.content;
  }
  
  return response.choices[0].message.content;
}

四、函数实现

const functions = {
  get_order: async ({ order_id }) => {
    const order = await db.query('SELECT * FROM orders WHERE id = ?', [order_id]);
    return JSON.stringify(order);
  },
  
  get_logistics: async ({ tracking_number }) => {
    const logistics = await fetch(`https://api.kuaidi.com/${tracking_number}`);
    return JSON.stringify(logistics);
  }
};

async function executeFunction(toolCall) {
  const { name, arguments: args } = toolCall.function;
  const result = await functions[name](JSON.parse(args));
  return result;
}

五、安全控制

// 权限检查
async function executeWithAuth(toolCall, user) {
  const { name } = toolCall.function;
  
  // 检查用户权限
  if (!hasPermission(user, name)) {
    return { error: '权限不足' };
  }
  
  return executeFunction(toolCall);
}

六、最佳实践

  • 函数描述清晰
  • 参数校验严格
  • 错误处理完善
  • 权限控制
  • 日志记录

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