什么是Function Calling?AI模型Function Calling工作机制及阿里云百炼各大模型支持版本汇总

简介: Function Calling 是大模型调用外部工具(API/数据库等)的能力,突破其无法访问实时数据的限制。通过多轮交互(模型判断→调用工具→返回结果→生成回答),实现与外部系统联动。阿里云百炼平台已支持千问、DeepSeek、GLM等主流模型。在阿里云百炼官网:https://t.aliyun.com/U/fPVHqY 免费领取千万Tokens

什么是Function Calling?大模型无法访问实时数据和外部系统,Function Calling 允许模型调用外部工具(API、数据库、自定义函数等),获取信息或执行操作,突破模型自身能力的限制。模型支持Function Calling能力,使用Function Calling功能,通过引入外部工具,使得大模型可以与外部世界进行交互。在阿里云百炼平台:https://www.aliyun.com/product/bailian  调用AI大模型,并使用Function Calling功能。


工作原理

Function Calling 通过应用程序与大模型之间的多步骤交互实现:

  1. 发起第一次模型调用
    应用程序向大模型发送用户问题和可用工具清单。
  2. 接收模型的工具调用指令(工具名称与入参)
    若模型判断需要调用外部工具,返回JSON格式的指令,指定函数名称与入参。
若模型判断无需调用工具,会返回自然语言格式的回复。
  1. 在应用端运行工具
    应用程序执行指定工具,获取输出结果。
  2. 发起第二次模型调用
    将工具输出结果添加到消息数组(messages),再次调用模型。
  3. 接收来自模型的最终响应
    模型综合工具输出与用户问题,生成自然语言回复。


工作流程示意图 gongzuoliuchengtu.jpg

哪些模型支持Function Calling?

阿里云百炼千问、DeepSeek、GLM、Kimi和MiniMax支持Function Calling的模型版本如下,更多模型在阿里云百炼平台查看:https://www.aliyun.com/product/bailian

阿里云百炼模型广场.jpg

千问

文本生成模型:

  • 千问Max:Qwen3.7-Max系列、Qwen3.6-Max系列、Qwen3-Max系列、Qwen-Max系列
  • 千问Plus:Qwen3.7-Plus系列、Qwen3.6-Plus系列、Qwen3.5-Plus系列、Qwen-Plus系列
  • 千问Flash:Qwen3.6-Flash系列、Qwen3.5-Flash系列、Qwen-Flash系列
  • 千问Coder:Qwen3-Coder系列、Qwen2.5-Coder系列、Qwen-Coder系列
  • 千问Turbo:Qwen-Turbo系列
  • Qwen3.6开源系列
  • Qwen3.5开源系列
  • Qwen3开源系列
  • Qwen2.5开源系列

多模态模型:

  • 千问VL: Qwen3-VL-Plus系列、 Qwen3-VL-Flash系列
  • 千问Omni:Qwen3.5-Omni-Plus系列、Qwen3.5-Omni-Flash系列、Qwen3-Omni-Flash系列
  • 千问Omni-Realtime:Qwen3.5-Omni-Plus-Realtime系列、Qwen3.5-Omni-Flash-Realtime系列
  • Qwen3-VL 开源系列

DeepSeek

阿里云百炼部署

  • deepseek-v4-pro
  • deepseek-v4-flash
  • deepseek-v3.2
  • deepseek-v3.2-exp(非思考模式)
  • deepseek-v3.1(非思考模式)
  • deepseek-r1
  • deepseek-r1-0528
  • deepseek-v3

硅基流动部署

  • siliconflow/deepseek-v3.2
  • siliconflow/deepseek-v3.1-terminus
  • siliconflow/deepseek-r1-0528
  • siliconflow/deepseek-v3-0324

快手万擎部署

  • vanchin/deepseek-v3.2-think
  • vanchin/deepseek-v3.1-terminus
  • vanchin/deepseek-r1
  • vanchin/deepseek-v3

GLM

  • glm-5.2
  • glm-5.1
  • glm-5
  • glm-4.7
  • glm-4.6
  • glm-4.5
  • glm-4.5-air

Kimi

阿里云百炼部署

  • kimi-k2.6
  • kimi-k2.5
  • kimi-k2-thinking
  • Moonshot-Kimi-K2-Instruct

月之暗面部署

kimi/kimi-k3、kimi/kimi-k2.7-code-highspeed、kimi/kimi-k2.7-code、kimi/kimi-k2.6、kimi/kimi-k2.5

MiniMax

阿里云百炼部署

  • MiniMax-M2.5
  • MiniMax-M2.1

稀宇科技部署

  • MiniMax/MiniMax-M3
  • MiniMax/MiniMax-M2.7
  • MiniMax/MiniMax-M2.5
  • MiniMax/MiniMax-M2.1


Function Calling使用教程:

以下示例演示天气查询场景的完整 Function Calling 流程。

OpenAI 兼容:

Python:

from openai import OpenAI
from datetime import datetime
import json
import os
import random

# 初始化客户端
client = OpenAI(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下为华北2(北京)地域的URL,调用时请将WorkspaceId替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
# 模拟用户问题
USER_QUESTION = "北京天气咋样"
# 定义工具列表
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如北京市、杭州市、余杭区等。",
                    }
                },
                "required": ["location"],
            },
        },
    },
]

# 模拟天气查询工具
def get_current_weather(arguments):
    weather_conditions = ["晴天", "多云", "雨天"]
    random_weather = random.choice(weather_conditions)
    location = arguments["location"]
    return f"{location}今天是{random_weather}。"

# 封装模型响应函数
def get_response(messages):
    completion = client.chat.completions.create(
        model="qwen3.6-plus",
        extra_body={"enable_thinking": False},
        messages=messages,
        tools=tools,
    )
    return completion

messages = [{"role": "user", "content": USER_QUESTION}]
response = get_response(messages)
assistant_output = response.choices[0].message
if assistant_output.content is None:
    assistant_output.content = ""
messages.append(assistant_output)
# 如果不需要调用工具,直接输出内容
if assistant_output.tool_calls is None:
    print(f"无需调用天气查询工具,直接回复:{assistant_output.content}")
else:
    # 进入工具调用循环
    while assistant_output.tool_calls is not None:
        tool_call = assistant_output.tool_calls[0]
        tool_call_id = tool_call.id
        func_name = tool_call.function.name
        arguments = json.loads(tool_call.function.arguments)
        print(f"正在调用工具 [{func_name}],参数:{arguments}")
        # 执行工具
        tool_result = get_current_weather(arguments)
        # 构造工具返回信息
        tool_message = {
            "role": "tool",
            "tool_call_id": tool_call_id,
            "content": tool_result,  # 保持原始工具输出
        }
        print(f"工具返回:{tool_message['content']}")
        messages.append(tool_message)
        # 再次调用模型,获取总结后的自然语言回复
        response = get_response(messages)
        assistant_output = response.choices[0].message
        if assistant_output.content is None:
            assistant_output.content = ""
        messages.append(assistant_output)
    print(f"助手最终回复:{assistant_output.content}")

Node.js

import OpenAI from 'openai';  
  
// 初始化客户端  
const openai = new OpenAI({  
  // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:apiKey: "sk-xxx",
  // 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
  apiKey: process.env.DASHSCOPE_API_KEY,  
  // 以下为华北2(北京)地域的URL,调用时请将WorkspaceId替换为真实的业务空间ID,各地域的URL不同。
  baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",  
});  
  
// 定义工具列表  
const tools = [  
  {  
    type: "function",  
    function: {  
      name: "get_current_weather",  
      description: "当你想查询指定城市的天气时非常有用。",  
      parameters: {  
        type: "object",  
        properties: {  
          location: {  
            type: "string",  
            description: "城市或县区,比如北京市、杭州市、余杭区等。",  
          },  
        },  
        required: ["location"],  
      },  
    },  
  },  
];  
  
// 模拟天气查询工具  
const getCurrentWeather = (args) => {  
  const weatherConditions = ["晴天", "多云", "雨天"];  
  const randomWeather = weatherConditions[Math.floor(Math.random() * weatherConditions.length)];  
  const location = args.location;  
  return `${location}今天是${randomWeather}。`;  
};  
  
// 封装模型响应函数  
const getResponse = async (messages) => {  
  const response = await openai.chat.completions.create({  
    model: "qwen3.6-plus",  
    enable_thinking: false,
    messages: messages,  
    tools: tools,  
  });  
  return response;  
};  

const main = async () => {  
  const input = "北京天气咋样";

  let messages = [  
    {  
      role: "user",  
      content: input,  
    }  
  ];  
  let response = await getResponse(messages);  
  let assistantOutput = response.choices[0].message;  
  // 确保 content 不是 null  
  if (!assistantOutput.content) assistantOutput.content = "";  
  messages.push(assistantOutput);  
  // 判断是否需要调用工具  
  if (!assistantOutput.tool_calls) {  
    console.log(`无需调用天气查询工具,直接回复:${assistantOutput.content}`);  
  } else {  
    // 进入工具调用循环  
    while (assistantOutput.tool_calls) {  
      const toolCall = assistantOutput.tool_calls[0];  
      const toolCallId = toolCall.id;  
      const funcName = toolCall.function.name;  
      const funcArgs = JSON.parse(toolCall.function.arguments);  
      console.log(`正在调用工具 [${funcName}],参数:`, funcArgs);  
      // 执行工具  
      const toolResult = getCurrentWeather(funcArgs);  
      // 构造工具返回信息  
      const toolMessage = {  
        role: "tool",  
        tool_call_id: toolCallId,  
        content: toolResult,  
      };  
      console.log(`工具返回:${toolMessage.content}`);  
      messages.push(toolMessage);  
      // 再次调用模型获取自然语言总结  
      response = await getResponse(messages);  
      assistantOutput = response.choices[0].message;  
      if (!assistantOutput.content) assistantOutput.content = "";  
      messages.push(assistantOutput);  
    }  
    console.log(`助手最终回复:${assistantOutput.content}`);  
  }  
};  
  
// 启动程序  
main().catch(console.error);

运行后得到如下输出:

正在调用工具 [get_current_weather],参数:{'location': '北京'}
工具返回:北京今天是多云。
助手最终回复:北京今天是多云的天气。

如何使用Function Calling?

Function Calling 支持两种传入工具信息的方式:

  • 方式一:通过 tools 参数传入(推荐)
    参见如何使用,按照定义工具创建 messages 数组发起 Function Calling运行工具函数大模型总结工具函数输出的步骤调用。
  • 方式二:通过 System Message 传入
    通过 tools 参数传入效果最佳,服务端会自动适配最优 prompt 模板。如使用 Qwen 模型且不期望使用 tools 参数,参见通过 System Message 传入工具信息

以下以 OpenAI 兼容接口为例,通过 tools 参数分步骤介绍 Function Calling 的详细用法。

假设业务场景会收到天气查询与时间查询两类问题。

1. 定义工具

工具连接大模型与外部服务,首先需定义工具。

1.1. 创建工具函数

创建两个工具函数:天气查询工具与时间查询工具。

  • 天气查询工具
    接收arguments参数,arguments格式为{"location": "查询的地点"}。工具的输出为字符串,格式为:“{位置}今天是{天气}”
为了便于演示,此处定义的天气查询工具并不真正查询天气,会从晴天、多云、雨天随机选择。在实际业务中可使用如 高德天气查询 等工具进行替换。
  • 时间查询工具
    时间查询工具不需要输入参数。工具的输出为字符串,格式为:“当前时间:{查询到的时间}。”
如果使用 Node.js,请运行 npm install date-fns 安装获取时间的工具包 date-fns:


Python:

## 步骤1:定义工具函数

# 添加导入random模块
import random
from datetime import datetime

# 模拟天气查询工具。返回结果示例:“北京今天是雨天。”
def get_current_weather(arguments):
    # 定义备选的天气条件列表
    weather_conditions = ["晴天", "多云", "雨天"]
    # 随机选择一个天气条件
    random_weather = random.choice(weather_conditions)
    # 从 JSON 中提取位置信息
    location = arguments["location"]
    # 返回格式化的天气信息
    return f"{location}今天是{random_weather}。"

# 查询当前时间的工具。返回结果示例:“当前时间:2024-04-15 17:15:18。“
def get_current_time():
    # 获取当前日期和时间
    current_datetime = datetime.now()
    # 格式化当前日期和时间
    formatted_time = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
    # 返回格式化后的当前时间
    return f"当前时间:{formatted_time}。"

# 测试工具函数并输出结果,运行后续步骤时可以去掉以下四句测试代码
print("测试工具输出:")
print(get_current_weather({"location": "上海"}))
print(get_current_time())
print("\n")

Node.js:

// 步骤1:定义工具函数

// 导入时间查询工具
import { format } from 'date-fns';

function getCurrentWeather(args) {
    // 定义备选的天气条件列表
    const weatherConditions = ["晴天", "多云", "雨天"];
    // 随机选择一个天气条件
    const randomWeather = weatherConditions[Math.floor(Math.random() * weatherConditions.length)];
    // 从 JSON 中提取位置信息
    const location = args.location;
    // 返回格式化的天气信息
    return `${location}今天是${randomWeather}。`;
}

function getCurrentTime() {
    // 获取当前日期和时间
    const currentDatetime = new Date();
    // 格式化当前日期和时间
    const formattedTime = format(currentDatetime, 'yyyy-MM-dd HH:mm:ss');
    // 返回格式化后的当前时间
    return `当前时间:${formattedTime}。`;
}

// 测试工具函数并输出结果,运行后续步骤时可以去掉以下四句测试代码
console.log("测试工具输出:")
console.log(getCurrentWeather({location:"上海"}));
console.log(getCurrentTime());
console.log("\n")

运行工具后,得到输出:

测试工具输出:
上海今天是多云。
当前时间:2025-01-08 20:21:45。


更多详细的使用教程,请移步到官方文档:https://help.aliyun.com/zh/model-studio/qwen-function-calling

相关文章
|
3月前
|
自然语言处理 API 调度
从推理到执行:厘清大模型Skill固有能力与Function Call函数调用的定位与价值差异.148
本文深入解析大模型两大核心能力:Skill(内生技能)与Function Call(函数调用)。Skill是模型预训练获得的固有推理与生成能力,如翻译、编程、逻辑分析,具备内生性、静态性与低延迟;Function Call则通过调用外部API获取实时数据或执行操作,具备外生性、动态性与精准性。二者互补协同——Skill为“大脑”,负责理解与决策;Function Call为“手脚”,负责执行与连接现实世界,共同构建可靠AI智能体。
467 3
|
2月前
|
人工智能 监控 C++
技能架构设计:208个金融AI Skill的分类体系
银行智能体架构:7个Skill如何协同工作 实战代码:基于 financial-ai-skills 项目 | 架构设计 | Skill协同 | 数据流 单体架构 vs 微服务架构 银行系统常见的两种架构: `` 单体架构: 微服务架构: ┌─────────────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ 核心系统 │ │信贷 │ │风控 │ │营销 │ │ ├─信贷
|
2月前
|
SQL 人工智能 安全
一个文件夹 + 一个Markdown文件 = 你的第一个Skill
本文介绍如何用“Skill”(技能包)提升AI编程效率:只需新建文件夹+SKILL.md,即可封装项目规范、知识库与提示词,让AI秒懂业务上下文。5分钟上手,零代码实现精准代码审查、测试生成等专业能力,助力工程师高效抢救遗留系统。
|
3月前
|
人工智能 小程序 程序员
Skill详解(2万字详细教程),Skills是什么,如何安装并使用Skills
AI时代必备技能!Skills(智能体技能)是Anthropic提出的可复用能力包,以文件夹形式封装指令、脚本与资源,实现“按需加载”,大幅节省Token。它让大模型从聊天工具升级为专业助手——非技术岗也能零代码快速上手,真正实现人人可用、岗岗必备。
20217 20
Skill详解(2万字详细教程),Skills是什么,如何安装并使用Skills
|
2月前
|
运维 资源调度 监控
2026年客户健康度经营看板指南:续费风险、活跃回升与关键人覆盖字段设计
2026年,SaaS客户经营转向存量深耕,传统汇总式看板已失效。本文提出“客户健康度分层经营看板”新范式:聚焦续费风险预警、活跃回升真伪识别、关键人关系网络监控三大核心,打通CRM/产品/服务数据,统一字段口径与时间窗口,推动看板从“复盘工具”升级为支撑日常指挥的经营操作系统。
|
2月前
|
人工智能 缓存 自然语言处理
【新版】阿里云 入门型AI通用节省计划 介绍及配置价格表
阿里云入门型AI通用节省计划是面向个人开发者、初创团队与入门级AI用户推出的轻量化折扣权益方案,依托百炼大模型平台,以低门槛、高灵活、强通用为核心,通过承诺月度消费金额换取模型调用折扣,覆盖阿里直供全系列大模型,支持文本、图像、语音等多模态推理费用抵扣,无需复杂配置即可自动生效,在保留按量付费灵活性的同时,显著降低AI使用成本,是入门级用户规模化使用大模型的最优选择。
509 3
|
2月前
|
人工智能 自然语言处理 监控
开源生态构建:从6个GitHub仓库到金融AI工具链
开源金融AI技能库:56个场景全覆盖 实战代码:基于 financial-ai-skills 项目 | 开源生态 | 场景覆盖 | 贡献指南 项目概览 `` financial-ai-skills/ ├── README.md ├── LICENSE (MIT) ├── skills/ │ ├── financial-intelligence/ # 财务智能 (8个场景) │ ├──
|
2月前
|
人工智能 测试技术
MCP 到底是什么?
MCP(Model Context Protocol)是AI连接外部世界的通用接口协议,非模型也非框架,旨在统一打通数据、工具与业务系统。它有望成为AI应用开发的基础能力。