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

如何使用Azure OpenAI JavaScript SDK实现函数调用?

Azure OpenAI JavaScript SDK 实现函数调用

正确实现代码

先确保安装对应版本的@azure/openai包,再按以下结构编写代码:

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");

// 初始化Azure OpenAI客户端
const endpoint = "https://XXXXXXXX.openai.azure.com/";
const apiKey = process.env.OPENAI_API_KEY;
const client = new OpenAIClient(endpoint, new AzureKeyCredential(apiKey));

// 定义函数描述(结构与Python的functions一致)
const functions = [
  {
    name: "目标函数名",
    description: "函数功能说明",
    parameters: {
      type: "object",
      properties: {
        参数名1: {
          type: "string",
          description: "参数1的说明"
        },
        参数名2: {
          type: "number",
          description: "参数2的说明"
        }
      },
      required: ["参数名1"]
    }
  }
];

// 对话消息列表
const messages = [
  { role: "user", content: "需要触发函数调用的用户提问内容" }
];

// 调用聊天补全接口并配置函数调用
async function fetchChatCompletion() {
  const deploymentId = "gpt-35-turbo-XXX"; // 你的模型部署ID
  const response = await client.getChatCompletions(deploymentId, messages, {
    functions: functions,
    functionCall: "auto" // 对应Python的function_call参数,可选值auto/none或指定函数对象
  });

  console.log(response.choices[0].message);
}

fetchChatCompletion().catch(err => console.error(err));

你之前写法的问题

  1. 第一种写法错误地将functions赋值给function_call属性:functionCall(JS驼峰命名)是用来指定函数调用策略的(如"auto"、"none"),而函数定义需要单独放在functions配置项中。
  2. 第二种写法直接将functions作为第三个参数:getChatCompletions的第三个参数是一个配置对象,functions和functionCall都需要作为该对象的属性传入。

关键注意事项

  • JavaScript SDK采用驼峰命名规范:Python中的function_call对应JS里的functionCall,其余参数结构和Python保持一致。
  • 确保客户端使用的API版本与Python代码匹配(2023-07-01-preview),SDK会自动适配对应版本接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 07:25:11