Tool调用

NavTalk 支持通过 Function Calling 实现数字人与外部系统的集成,如天气查询、知识库检索、业务系统触发等。

🔹 Step 1:定义函数工具(tools)

在建立 WebSocket 会话时,发送 session.update 请求体中配置 tools:

tools: [
  {
    type: "function",
    name: "function_call_judge",
    description: "当用户请求超出当前对话能力范围时,自动触发功能扩展调用",
    parameters: {
      type: "object",
      properties: {
        userInput: {
          type: "string",
          description: "需要处理的用户原始请求内容"
        }
      },
      required: ["userInput"]
    }
  }
]

说明:无需用户明确调用,AI 在会话中识别到指令意图后将自动触发。

🔹 Step 2:接收回调事件

当函数被触发后,WebSocket 会接收到如下类型的消息:

if (data.type === "response.function_call_arguments.done") {
  handleFunctionCall(data);
}
字段
含义

type

固定为 response.function_call_arguments.done

arguments

函数调用的参数(字符串格式 JSON)

call_id

当前函数调用的唯一标识

🔹 Step 3:处理函数调用

function handleFunctionCall(eventJson) {
  try {
    const functionCallArgs = JSON.parse(eventJson.arguments);
    const userInput = functionCallArgs.userInput;
    const callId = eventJson.call_id;

    handleWithMemAgent(userInput)
      .then(result => {
        sendFunctionCallResult(result, callId);
      })
      .catch(error => {
        console.error("Function调用失败:", error);
      });

  } catch (error) {
    console.error("解析参数失败: ", error);
  }
}

🔹 Step 4:调用后端接口处理业务逻辑

你可以将 userInput 传给业务系统或中台接口处理,如调用天气接口、CRM系统等:

function handleWithMemAgent(userInput) {
  return new Promise(async (resolve, reject) => {
    const chatId = await getFromChromeStorage("chatId");

    fetch(`${baseUrl}/api/realtime_function_call`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        userInput,
        license,
        chatId
      }),
    })
    .then(response => response.text())
    .then(result => resolve(result))
    .catch(error => reject(error));
  });
}

🔹 Step 5:返回结果至 AI 会话

结果处理完成后,需要将结果推送回 WebSocket,并触发 AI 继续响应:

function sendFunctionCallResult(result, callId) {
  const resultJson = {
    type: "conversation.item.create",
    item: {
      type: "function_call_output",
      output: result,
      call_id: callId
    }
  };

  socket.send(JSON.stringify(resultJson));

  // 主动触发 AI 响应
  socket.send(JSON.stringify({ type: "response.create" }));
}

🎯 常见应用场景示例

场景
用户输入
系统行为

查询天气

“明天北京天气如何?”

调用天气API并返回天气预报

查询知识库

“NavTalk 如何接入 Function Calling?”

接入内部知识系统返回答案

控制设备

“打开会议室灯光”

调用 IoT 接口控制硬件设备

Last updated