什么是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

相关文章
408王道计算机组成原理强化——输入输出系统大题(I/O)
408王道计算机组成原理强化——输入输出系统大题(I/O)
937 1
408王道计算机组成原理强化——输入输出系统大题(I/O)
|
4月前
|
人工智能 安全 JavaScript
OpenClaw 2026 Mac安装教程:官网命令安装及Homebrew + Python + Ollama一键配置
OpenClaw 2026 Mac安装教程:支持官网一键脚本(5分钟完成)及Homebrew+Ollama手动配置,兼容Intel/M芯片、macOS 12+。含环境验证、模型对接与网关启动全流程。新手更推荐阿里云轻量服务器一键部署(38元/年),安全省心。
1822 8
|
1天前
|
人工智能 监控 C++
技能架构设计:208个金融AI Skill的分类体系
银行智能体架构:7个Skill如何协同工作 实战代码:基于 financial-ai-skills 项目 | 架构设计 | Skill协同 | 数据流 单体架构 vs 微服务架构 银行系统常见的两种架构: `` 单体架构: 微服务架构: ┌─────────────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ 核心系统 │ │信贷 │ │风控 │ │营销 │ │ ├─信贷
|
1天前
|
人工智能 算法 Python
贷款计算器AI:从利率测算到还款方案优化
等额本息算法揭秘:信贷审批背后的数学 实战代码:基于 credit-approval Skill | 还款计算 | 利率定价 | 月供公式 信贷审批的核心:还款能力评估 银行审批贷款时,最核心的问题是:客户还得起吗? 这需要计算: 1. 月供金额:每月还多少 2. 还款能力:收入能否覆盖 3. 总利息:贷款成本多少 等额本息公式 等额本息是最常见的还款方式:每月还款额相同。 `` 月
|
1天前
|
人工智能 自然语言处理 监控
开源生态构建:从6个GitHub仓库到金融AI工具链
开源金融AI技能库:56个场景全覆盖 实战代码:基于 financial-ai-skills 项目 | 开源生态 | 场景覆盖 | 贡献指南 项目概览 `` financial-ai-skills/ ├── README.md ├── LICENSE (MIT) ├── skills/ │ ├── financial-intelligence/ # 财务智能 (8个场景) │ ├──
|
1天前
|
运维 资源调度 监控
2026年客户健康度经营看板指南:续费风险、活跃回升与关键人覆盖字段设计
2026年,SaaS客户经营转向存量深耕,传统汇总式看板已失效。本文提出“客户健康度分层经营看板”新范式:聚焦续费风险预警、活跃回升真伪识别、关键人关系网络监控三大核心,打通CRM/产品/服务数据,统一字段口径与时间窗口,推动看板从“复盘工具”升级为支撑日常指挥的经营操作系统。
|
1天前
|
人工智能 监控
工作流自动化AI:从审批流到合规检查的Skill编排
从工单到闭环:银行运营自动化完整方案 实战代码:基于 operations-automation Skill | 工单系统 | 流程编排 | SLA监控 痛点:银行运营的"人肉接力" 银行运营流程的典型场景: `` 客户投诉 → 客服记录 → 转运营 → 转技术 → 转合规 → 回复客户 ↑___________________________________________↓ (平
|
5月前
|
缓存 NoSQL 网络协议
Redis Pipeline 实战指南:提升 Go 后端性能的利器
Redis Pipeline 是一种批量命令优化机制,通过一次网络往返执行多条命令,显著降低RTT开销、提升吞吐(实测快50倍)。它非事务,无原子性保证,适用于批量写入、排行榜更新等场景;强一致性需求应选MULTI/EXEC或Lua脚本。(239字)
387 1
|
11月前
|
JSON 大数据 API
巧用苏宁易购 API,精准分析苏宁易购家电销售大数据
在数据驱动的电商时代,精准分析销售数据能助力企业优化库存、提升营销效果。本文详解如何利用苏宁易购API获取家电销售数据,结合Python进行数据清洗与统计分析,实现销量预测与洞察提取,帮助企业降本增效。