|
现如今我们已经习惯了大模型能回答问题、写代码、生成文案,但大模型本身其实“手无缚鸡之力”,它无法直接访问数据库、不能实时获取天气。 但现如今的大模型又是怎么做到这些的呢?答案就是——Function Calling(函数调用)。 什么是 Function Calling?Function Calling 是一种让大模型在理解用户自然语言后,主动调用外部工具或函数的能力。 大模型本身无法直接操作外部系统(如数据库、计算工具),但通过调用预设函数,可以完成:实时数据获取(天气、股价、新闻)、复杂计算(数学运算、代码执行)、操作外部系统(发送邮件、控制智能设备) 模型可将用户自然语言请求转化为结构化参数,传递给函数。例如:用户说“明天北京天气如何?” → 模型调用 get_weather(location="北京", date="2025-05-06") 模型可根据上下文决定是否/何时调用函数,甚至链式调用多个函数(如先查天气,再推荐穿搭)。 举个例子🌰 我将询问千问大模型北京的天气怎么样,并让千文使用我们自定义的函数查询天气信息并返回个用户天气信息。 首先我们定义一个工具函数,json格式的,是为了让大模型了解这个函数时干什么的,函数参数是什么。 importrequestsfromhttpimportHTTPStatusimportdashscopeimportos
# 设置 DashScope API Keydashscope.api_key = os.getenv("DASHSCOPE_API_KEY")# 高德天气 API 的 天气工具定义(JSON 格式)weather_tool = { "type":"function", "function": { "name":"get_current_weather", "description":"Get the current weather in a given location", "parameters": { "type":"object", "properties": { "location": { "type":"string", "description":"The city name, e.g. 北京", }, "adcode": { "type":"string", "description":"The city code, e.g. 110000 (北京)", } }, "required": ["location"], }, },}
接着编写天气条用的函数 defget_current_weather(location:str, adcode:str=None): """调用高德地图API查询天气""" gaode_api_key = os.getenv("GAOGE_API_KEY") # 替换成你的高德API Key base_url ="https://restapi.amap.com/v3/weather/weatherInfo"
params = { "key": gaode_api_key, "city": adcodeifadcodeelselocation, "extensions":"base", # 可改为 "all" 获取预报 }
response = requests.get(base_url, params=params) ifresponse.status_code ==200: returnresponse.json() else: return{"error":f"Failed to fetch weather:{response.status_code}"}
通过dashscope调用大模型回答问题,大模型会根据之前的函数定义信息构造出函数需要的参数值和参数格式,再调用函数。 """使用 Qwen3 + 查询天气"""messages = [ {"role":"system","content":"你是一个智能助手,可以查询天气信息。"}, {"role":"user","content":"北京现在天气怎么样?"}]response = dashscope.Generation.call( model="qwen-turbo-latest", # 可使用 Qwen3 最新版本 messages=messages, tools=[weather_tool], # 传入工具定义 tool_choice="auto", # 让模型决定是否调用工具)ifresponse.status_code == HTTPStatus.OK: # 检查是否需要调用工具 if"tool_calls"inresponse.output.choices[0].message: print('response=', response.output.choices[0]) tool_call = response.output.choices[0].message.tool_calls[0] print('tool_call=', tool_call) iftool_call["function"]["name"] =="get_current_weather": # 解析参数并调用高德API importjson args = json.loads(tool_call["function"]["arguments"]) location = args.get("location","北京") adcode = args.get("adcode",None)
weather_data = get_current_weather(location, adcode) print(f"查询结果:{weather_data}") else: print(response.output.choices[0].message.content)else: print(f"请求失败:{response.code}-{response.message}")
summary 怎么样,使用funcation calling是不是很简单,我们只需要将函数的具体功能实现并告诉大模型,这样大模型就会自动调用函数获取关键信息。 |