You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

@azure/openai npm包问题:请求含工具但响应toolCalls为空

@azure/openai调用GPT-4时toolCalls为空的解决方法

问题概述

使用Node.js的@azure/openai包(版本1.0.0-beta.10、1.0.0-alpha.20240104.1)调用GPT-4/GPT-4 Turbo/GPT-35-Turbo模型,请求中已传入工具定义,但响应返回的toolCalls为空数组,尽管finishReason显示为tool_calls。

原代码示例

const getCurrentWeather = {
  name: 'get_current_weather',
  description: 'Get the current weather in a given location',
  parameters: {
    type: 'object',
    properties: {
      location: {
        type: 'string',
        description: 'The city and state, e.g. San Francisco, CA',
      },
      unit: {
        type: 'string',
        enum: ['celsius', 'fahrenheit'],
      },
    },
    required: ['location'],
  },
};

const messages = [{ role: 'user', content: 'What is the weather like in Glasgow Scotland?' }];
const options = {
  tools: [
    {
      type: 'function',
      function: getCurrentWeather,
    },
  ],
};
client.getChatCompletions(deploymentIdBest, messages, options).then((res) => console.log(res));

预期响应

响应应包含有效toolCalls:

{
  "role": "assistant",
  "content": null,
  "tool_calls": [
    {
      "id": "call_o7uyztQLeVIoRdjcDkDJY3ni",
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "arguments": "{\"location\": \"Glasgow, Scotland\", \"unit\": \"celsius\"}"
      }
    }
  ]
}

实际响应

返回的toolCalls为空数组:

{
  "id": "chatcmpl-8fr5PAthe2uTIHVjd8mcy7pOMkrx5",
  "object": "chat.completion",
  "model": "gpt-4",
  "usage": {
    "promptTokens": 172,
    "completionTokens": 22,
    "totalTokens": 194
  },
  "created": "1970-01-20T17:36:26.203Z",
  "promptFilterResults": [
    {
      "promptIndex": 0,
      "contentFilterResults": {}
    }
  ],
  "choices": [
    {
      "index": 0,
      "finishReason": "tool_calls",
      "contentFilterResult": {
        "error": {
          "code": "content_filter_error",
          "message": "The contents are not filtered"
        }
      },
      "message": {
        "role": "assistant",
        "toolCalls": []
      },
      "contentFilterResults": {}
    }
  ]
}

解决方案

1. 显式设置tool_choice参数

在请求选项中添加tool_choice: "auto",强制模型判断是否调用工具。修改后的代码:

const options = {
  tools: [
    {
      type: 'function',
      function: getCurrentWeather,
    },
  ],
  tool_choice: "auto" // 新增该行
};

2. 检查API版本兼容性

确保Azure OpenAI的API版本为2024-02-15-preview或更高,旧版本不支持tools参数的新格式。可手动指定API版本:

const client = new OpenAIClient(process.env.AZURE_OPENAI_API_KEY, process.env.AZURE_OPENAI_ENDPOINT, {
  apiVersion: "2024-02-15-preview"
});

3. 排查内容过滤异常

响应中的content_filter_error可能导致响应结构异常,需检查Azure OpenAI的内容过滤配置,或暂时关闭内容过滤用于排查。

4. 确认模型部署版本

确保Azure上部署的GPT-4 Turbo/3.5 Turbo为0613及以上版本,旧模型版本不支持工具调用功能。

验证方法

  • 发送请求后检查响应的toolCalls是否生成有效调用
  • 若仍存在问题,直接调用Azure OpenAI REST API验证,排除SDK封装问题

内容的提问来源于stack exchange,提问作者emye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 09:58:19