大模型 Function Call介绍

什么是Function Call

        简单来说,就是大模型函数调用,不是你直接调用大模型函数,而是你告诉大模型一个函数,大模型根据你喂给它的数据和参数执行函数调用返回给你想要的函数执行结果。
        你可以借助大模型的自然语言理解能力实现自然语言的函数调用。大模型这一能力大大增加了私有定制模型的扩展性!

为什么有Function Call

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

因为:大模型需要连接真实世界,并对接真逻辑系统。
Function Call 技术可以把大模型和业务系统连接,实现更丰富的功能

Function call工作流程

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

        第一次请求大模型接口后,会从定义的functions里面输出对应的function信息:

//获取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)

        根据function name及arguments选择调用对应的本地function来获取到当前结果:

# 定义一个函数来基于大模型的调用结果,来执行函数
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
  • 第二次大模型调用:结合外部请求结果,大模型进行总结给出合理的回答
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容