
先忽略Function Calling的名称,看看“解锁大语言模型的实际行动力”,为什么有此一说?难道大模型也会有到达不了的彼岸?如果接触过DeepSeek,我们都会惊叹于大语言模型(LLM)对答如流、才华横溢以及解答问题的能力。然而它本质上是一个知识丰富的聊天者,能让人惊叹的做出完美的解决方案,唯一缺陷的是没有办法做真正的事情处理,好比能告诉我们最优秀完美的旅游方案,却没有办法去定一张机票,鉴于此,Function Calling(函数调用)完美登场,助力解锁大语言模型的实际行动力,让AI不只是“说”,更能“做”,让我们今天就好好了解Function Calling原理与应用指南!
Function Calling 是大模型提供的一项革新能力。它充当了模型思考与外部行动之间的关键桥梁。它允许开发者告诉模型:‘你拥有这些可用的工具(函数)’,模型则能在理解用户意图后,聪明地决定是否需要使用某个工具,并以结构化格式请求调用它。开发者收到请求后,执行实际的操作(如查询数据库、发送邮件、调用API),并将结果反馈给模型,模型最终整合信息,生成自然语言回复给用户。
函数(function)是用来组织和执行代码逻辑的基本单元,它们都封装了一段可重复使用的代码块,接收输入参数并可能返回结果;
每个函数有:名称、清晰描述、参数(名称、类型、描述);
function_call 信息(name - 函数名,arguments - 符合函数参数定义的JSON字符串)。
 下面是即将调试的一个用例,可以先看看初步流程,稍后可以看看具体执行过程!

图示说明:
基于Qwen-Plus的大模型创建一个指定城市的天气查询对话系统,利用大模型的函数调用(Function Calling)能力实现智能交互,看看整个流程的执行!
import json
import os
import dashscope
from dashscope.api_entities.dashscope_response import Role
# 从环境变量中,获取 DASHSCOPE_API_KEY
api_key = os.environ.get('DASHSCOPE_API_KEY')
dashscope.api_key = api_key
# 编写天气函数,调用本地的函数看看Function Call的效果,此处可替换为天气的接口看真实数据
def get_current_weather(location, unit="摄氏度"):
    # 获取指定地点的天气
    temperature = -1
    if '杭州' in location or 'Hangzhou' in location:
        temperature = 10
    if '上海' in location or 'Shanghai' in location:
        temperature = 36
    if '深圳' in location or 'Shenzhen' in location:
        temperature = 37
    weather_info = {
        "location": location,
        "temperature": temperature,
        "unit": unit,
        "forecast": ["晴天", "微风"],
    }
    return json.dumps(weather_info)
# 封装模型响应函数
def get_response(messages):
    try:
        response = dashscope.Generation.call(
            model='qwen-plus',
            messages=messages,
            functions=functions,
            result_format='message'
        )
        return response
    except Exception as e:
        print(f"API调用出错: {str(e)}")
        return None
# 使用function call进行QA
def run_conversation():
    query = "杭州的天气怎样"
    messages=[{"role": "user", "content": query}]
    # 得到第一次响应
    response = get_response(messages)
    if not response or not response.output:
        print("获取响应失败")
        return None
    print('response=', response)
    message = response.output.choices[0].message
    messages.append(message)
    print('message=', message)
    # Step 2, 判断用户是否要call function
    if hasattr(message, 'function_call') and message.function_call:
        function_call = message.function_call
        tool_name = function_call['name']
        # Step 3, 执行function call
        arguments = json.loads(function_call['arguments'])
        print('arguments=', arguments)
        tool_response = get_current_weather(
            location=arguments.get('location'),
            unit=arguments.get('unit'),
        )
        tool_info = {"role": "function", "name": tool_name, "content": tool_response}
        print('tool_info=', tool_info)
        messages.append(tool_info)
        print('messages=', messages)
        #Step 4, 得到第二次响应
        response = get_response(messages)
        if not response or not response.output:
            print("获取第二次响应失败")
            return None
        print('response=', response)
        message = response.output.choices[0].message
        return message
    return message
functions = [
    {
      'name': 'get_current_weather',
      'description': '获取指定地点,指定温度单位的天气信息',
      'parameters': {
            'type': 'object',
            'properties': {
                'location': {
                    'type': 'string',
                    'description': '城市名称,例如:杭州,上海,深圳。'
                },
                'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}
            },
        'required': ['location']
      }
    }
]
if __name__ == "__main__":
    result = run_conversation()
    if result:
        print("最终结果:", result)
    else:
        print("对话执行失败")最终结果:
 最终结果: {"role": "assistant", "content": "杭州当前的温度是10摄氏度,天气晴朗,微风。"}
{
  "function_call": {
    "name": "get_current_weather",
    "arguments": "{\"location\":\"杭州\"}"
  }
} 3.执行函数:get_current_weather(location="杭州")
4.函数返回:
 {   "location": "杭州",   "temperature": 10,   "unit": "摄氏度",   "forecast": ["晴天", "微风"] }5.大模型最终回复:
 "杭州当前气温10摄氏度,天气晴,微风"get_current_weather)def get_current_weather(location, unit="摄氏度"):
    # 模拟真实天气API(根据城市返回预设温度)
    temperature = -1
    if '杭州' in location: temperature = 10
    if '上海' in location: temperature = 36
    if '深圳' in location: temperature = 37
    return json.dumps({
        "location": location,
        "temperature": temperature,
        "unit": unit,
        "forecast": ["晴天", "微风"]
    })functions)functions = [{
    'name': 'get_current_weather',
    'description': '获取指定地点,指定温度单位的天气信息',
    'parameters': {
        'type': 'object',
        'properties': {
            'location': {
                'type': 'string',
                'description': '城市名称,例如:杭州,上海,深圳。'
            },
            'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}
        },
        'required': ['location']
    }
}]description:中文描述提升中文场景准确性enum:限制unit参数的可选值(摄氏度/华氏度)required:强制要求location参数run_conversation)def run_conversation():
    # 1. 用户输入
    query = "杭州的天气怎样"
    messages = [{"role": "user", "content": query}]
    # 2. 首次模型调用
    response = get_response(messages)
    message = response.output.choices[0].message
    # 3. 检测函数调用
    if hasattr(message, 'function_call'):
        # 解析参数
        arguments = json.loads(message.function_call['arguments'])
        # 4. 执行天气函数
        tool_response = get_current_weather(**arguments)
        # 5. 将结果加入上下文
        messages.append({
            "role": "function", 
            "name": "get_current_weather",
            "content": tool_response
        })
        # 6. 二次模型调用生成最终回复
        final_response = get_response(messages)
        return final_response.output.choices[0].message{"location": "杭州"})以上完整的阐述了此示例整个流程执行的各个节点细节,更好的帮助大家理解!
required 的参数);
 检查参数类型是否正确(传进来的字符串能否转成需要的数字/日期?);
 检查参数值是否在有效范围内(日期是否合理?ID是否存在?);
 进行必要的清理和转换(防止SQL注入、命令注入等)。
 原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。