Function Call 是什么
大模型的 Function Call(函数调用) 属于一种使大语言模型(LLM)依据用户指令调用外部函数或工具的技术,借助模型的理解能力与外部工具的精确性相结合,达成更为繁杂、更具动态性的任务处置。其核心要点如下: 
定义
Function Call可让大模型基于用户的自然语言输入,识别意图并触发预先设定的外部函数或工具,把自然语言转化为结构化的参数传送给函数,最后整合函数返回的结果以生成用户能够理解的回应。 
原理
- 语义理解:模型解析用户输入,判定是否有调用函数的必要。 
 
- 函数匹配:从预先定义的函数库中选取适宜的工具(诸如天气查询、数学计算等)。 
 
- 参数生成:把用户描述转换为函数所需的参数格式(例如 
{num:1.4})。  
- 执行整合:调用外部工具获取结果,进而生成自然语言的答复。 
 
作用
突破大模型原生限制
- 实时数据获取:例如查询天气、股票等动态信息(大模型自身知识库为静态的)。 
 
- 精准计算:处理像数学运算、数据分析这类需要高度准确性的任务(如计算平方、绝对值)。 
 
- 私域知识扩展:连接数据库、知识图谱等私有数据源,以解决特定领域的问题。 
 
增强功能多样性
- 支持复杂操作:像发送邮件、控制智能设备、自动化办公任务等。 
 
- 提升交互效率:用户无需学习特定的命令语法,使用自然语言就能触发复杂功能。 
 
提升安全性与合规性
- 敏感数据隔离:由外部工具处理隐私信息(如支付、身份验证),防止暴露给大模型。 
 
使用方法
步骤一:定义外部函数
依据需求编写函数,例如: 
1 2 3
   |  def calculator_square(num: float) -> float:      return num ** 2 
 
  | 
 
步骤二:注册函数给大模型
向模型阐述函数的功能、参数以及使用场景(需符合模型要求的格式,如JSON Schema): 
1 2 3 4 5 6 7 8 9
   | {   "name": "calculator_square",    "description": "计算一个数的平方",    "parameters": {     "type": "object",      "properties": {"num": {"type": "number"}},      "required": ["num"]   } }
  | 
 
步骤三:用户提问触发函数调用
用户输入自然语言指令(如“计算1.4的平方”),模型判定需调用函数后,生成参数并返回: 
1 2 3 4 5 6
   | {   "function_call": {     "name": "calculator_square",      "arguments": "{num: 1.4}"   } }
  | 
 
步骤四:执行函数并返回结果
开发者解析参数,执行函数后将结果返回给模型,最终生成用户友好的回答: 
案例
下面使用 OpenAI Python 客户端实现 Function Call,通过一个简单的场景来演示:查询某个城市的天气情况。假设我们有一个外部函数 get_current_weather,它会调用一个天气 API 并返回结果。
注意事项
- 函数安全性:需要对参数进行严格校验,防止恶意输入(如SQL注入)。 
 
- 模型适配:不同模型(如GPT - 4、GLM - 4)的Function Call接口可能存在差异,需参照官方文档。 
 
- 错误处理:模型可能会误选函数或者生成错误参数,需要设计容错机制(如重试或者提示用户澄清)。 
 
依赖
函数定义
先定义一个外部函数 get_current_weather,它将调用一个天气 API(例如 OpenWeatherMap API)来获取实时天气数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
   | import requests
  def get_current_weather(location: str, unit: str = "metric"):     """     调用天气 API 获取当前天气     :param location: 城市名称     :param unit: 温度单位(metric 表示摄氏度,imperial 表示华氏度)     :return: 天气数据     """     api_key = "YOUR_OPENWEATHERMAP_API_KEY"     url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&units={unit}&appid={api_key}"     response = requests.get(url)     data = response.json()     return {         "temperature": data["main"]["temp"],         "description": data["weather"][0]["description"]     }
   | 
 
使用 OpenAI 的 Function Call
接下来,我们将使用 OpenAI 的 Python 客户端来实现 Function Call。假设我们已经有一个 OpenAI 的 API 密钥,并且启用了 Function Call 功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
   | import openai
 
  openai.api_key = "YOUR_OPENAI_API_KEY"
 
  def get_current_weather(location: str, unit: str = "metric"):     """     调用天气 API 获取当前天气     :param location: 城市名称     :param unit: 温度单位(metric 表示摄氏度,imperial 表示华氏度)     :return: 天气数据     """     api_key = "YOUR_OPENWEATHERMAP_API_KEY"     url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&units={unit}&appid={api_key}"     response = requests.get(url)     data = response.json()     return {         "temperature": data["main"]["temp"],         "description": data["weather"][0]["description"]     }
 
  functions = [     {         "name": "get_current_weather",         "description": "获取指定城市的当前天气",         "parameters": {             "type": "object",             "properties": {                 "location": {                     "type": "string",                     "description": "城市名称"                 },                 "unit": {                     "type": "string",                     "description": "温度单位(metric 或 imperial)",                     "default": "metric"                 }             },             "required": ["location"]         }     } ]
 
  user_input = "北京今天的天气如何?"
 
  response = openai.ChatCompletion.create(     model="gpt-4",     messages=[         {"role": "user", "content": user_input}     ],     functions=functions,     function_call="auto"   )
 
  if response.choices[0].finish_reason == "function_call":     function_args = response.choices[0].message.function_call.arguments     function_name = response.choices[0].message.function_call.name
           if function_name == "get_current_weather":         weather_result = get_current_weather(             location=function_args["location"],             unit=function_args.get("unit", "metric")         )
                   second_response = openai.ChatCompletion.create(             model="gpt-4",             messages=[                 {"role": "user", "content": user_input},                 {"role": "assistant", "content": response.choices[0].message.content},                 {"role": "function", "name": function_name, "arguments": function_args},                 {"role": "function", "name": function_name, "content": weather_result}             ]         )         print(second_response.choices[0].message.content) else:     print(response.choices[0].message.content)
   | 
 
通过Function Call,大模型从“纯文本生成器”晋升为“智能调度中心”,极大地拓展了应用范围。开发者可借助开源框架(如LangChain)快速集成此功能。