问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

大模型Function Call功能详解:原理、应用场景及实现方法

创作时间:
作者:
@小白创作中心

大模型Function Call功能详解:原理、应用场景及实现方法

引用
简书
1.
https://www.jianshu.com/p/9fabf700c6f8

大模型的Function Call功能允许用户通过自然语言与大模型交互,让大模型调用外部函数并获取结果。这一功能不仅弥补了大模型在实时性和逻辑推理方面的不足,还大大增强了其扩展性和实用性。本文将详细介绍Function Call的工作原理、应用场景以及具体实现方法。

什么是Function Call

简单来说,就是大模型函数调用,不是你直接调用大模型函数,而是你告诉大模型一个函数,大模型根据你喂给它的数据和参数执行函数调用返回给你想要的函数执行结果。

你可以借助大模型的自然语言理解能力实现自然语言的函数调用。大模型这一能力大大增加了私有定制模型的扩展性!

为什么有Function Call

  1. 大模型的缺陷:
  • 有所不知
    a.训练数据不可能什么都有;垂直、非公开数据必有欠缺。
    b.不知道最新信息;大模型的训练周期很长,且更新一次耗资巨大,还有越训越傻的风险。所以它不可能实时训练。
  • 没有"真逻辑"
    它表现出的逻辑、推理,是训练文本的统计规律,而不是真正的逻辑,所以有幻觉。
  1. 大模型的优势:
  • 强大的语义泛化能力,能根据所说的话,识别出意图
  • 希望通过大模型来做更多的事,而不仅是简单的搜索和闲聊

因为:大模型需要连接真实世界,并对接真逻辑系统。

Function Call 技术可以把大模型和业务系统连接,实现更丰富的功能

Function call工作流程

  1. 用户提出functions需求: 用户用自然语言描述他们想要完成的任务。
  2. LLM理解意图: 大模型分析用户的语言,理解其意图,并将其转化为结构化的请求。
  3. 选择合适的function: 根据用户的需求,从预先定义好的functions中选择合适的function。
  4. 参数转换与执行: 将用户的需求转化为function能够理解的参数,并调用外部工具执行操作。
  5. 结果处理与呈现: 接收外部工具返回的结果, 由LLM将其转化为用户友好的自然语言回应。


Function call.png

对大模型的要求

  • 好的语义理解能力,能够正确识别是否调用function、调用哪个function 以及对应参数;
  • 对于缺失的参数要能主动提问;

langchain实现

当今大部分模型厂商都有支持function call的模型,需要选择对应的正确模型,定义好模型厂商对应的functions书写规范,function描述的必备要素:

  • 函数名
  • 函数的功能描述
  • 函数的请求参数说明
  • 函数的响应参数说明(可选)

实例如下:

1. 定义functions

functions = [
    {
        "type":"function",
        "function":{
            "name": "get_current_speed",
            "description": "Gets current speed of a given car",
            "parameters": {
                "type": "object",
                "properties": {
                    "car_name": {
                        "type": "string",
                        "description": "The name of the car"
                    }
                },
                "required": ["car_name"]
            }
        }
    },
    {
        "type":"function",
        "function":{
            "name": "get_interior_temperature",
            "description": "Gets the interior temperature of a given car",
            "parameters": {
                "type": "object",
                "properties": {
                    "car_name": {
                        "type": "string",
                        "description": "The name of the car"
                    }
                },
                "required": ["car_name"]
            }
        } 
    },
    {
        "type":"function",
       "function":{
            "name": "get_remaining_battery",
            "description": "Gets the remaining battery of a given car",
            "parameters": {
                "type": "object",
                "properties": {
                    "car_name": {
                        "type": "string",
                        "description": "The name of the car"
                    }
                },
                "required": ["car_name"]
            }
       }
    }
]

2. 创建llm client

import os
import openai
import numpy as np
import json
import tenacity
from openai import OpenAI
client = OpenAI(
    api_key='sk-xxxxxxxxxxxx',
    base_url='https://api.chatanywhere.tech/v1'
)
GPT_MODEL = "gpt-3.5-turbo"

3. 定义Api调用接口

def generate_response_with_function_call(messages):
    try:
        response = client.chat.completions.create(
            model= GPT_MODEL,
            messages= messages,
            max_tokens=100,  # 生成的最大token数
            temperature=0.7,  # 生成的随机性
            tools=functions,  # 定义的函数调用规范
            tool_choice="auto",
        )
        return response.choices[0].message
    except Exception as e:
        print(f"Error generating response: {str(e)}")
        return None

4. 调用函数及结果处理

  • 封装messages
messages= [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Car A 当前速度是多少"}
]
  • 定义本地function
def get_current_speed(car_name):
   //调用其他接口来获取speed
def get_interior_temperature(car_name):
     //调用其他接口来获取interior temperature
def get_remaining_battery(car_name): 
    //调用其他接口来获取remaining battery
  • 执行Api调用及结果处理
first_response_message = generate_response_with_function_call(messages)

//获取function name
response_function_name = first_response_message.tool_calls[0].function.name
//获取function arguments
response_function_argu = json.loads(first_response_message.tool_calls[0].function.arguments)

# 定义一个函数来基于大模型的调用结果,来执行函数
def call_function(function_name, arguments):
        if function_name == "get_interior_temperature":
            car_name = arguments.get("car_name")
            return get_interior_temperature(car_name)
        elif function_name == "get_current_speed":
            car_name = arguments.get("car_name")
            return get_current_speed(car_name)
        elif function_name == "get_remaining_battery":
            car_name = arguments.get("car_name")
            return get_remaining_battery(car_name)
        return "Function not found"
# 执行本地函数
function_response = call_function(response_function_name, response_function_argu)

将获得的函数执行结果补充进messages,再次调用API:

messages.append(first_response_message)
messages.append({
    "role":"tool",
    "content":function_response,
    "tool_call_id":response_message.tool_calls[0].id,
})
second_response = generate_response_with_function_call(messages)
# 读取二次调用得到的content
final_message = second_response.content
print("最终输出: " + str(final_message))

最终输出: Car A当前车速为70.0km/h

经过两次大模型的API调用,得到了合理的结果;

  • 第一次大模型调用:根据用户的query及定义的functions,得到对应的function name及arguments
  • 第二次大模型调用:结合外部请求结果,大模型进行总结给出合理的回答
© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号