AI大模型探索之路-实战篇7:Function Calling技术实战:自动生成函数

系列篇章💥

AI大模型探索之路-实战篇4:深入DB-GPT数据应用开发框架调研
AI大模型探索之路-实战篇5:探索Open Interpreter开放代码解释器调研
AI大模型探索之路-实战篇6:掌握Function Calling的详细流程



一、前言

继前文对Function Calling操作流程的详细回顾之后,本文将进一步探讨OpenAI的Function Calling技术在实际应用中的表现。通过利用大型模型的强大能力自动生成function函数,我们旨在提升代码的通用性与扩展性。这一深入分析的核心目标是为智能数据分析平台的顺利部署打下坚实的技术基础。

这种基于人工智能的Function Calling技术探索是未来软件开发和维护领域的重要发展方向,它不仅能提高开发效率,还能大幅降低维护成本,提高软件的适应性和灵活性。通过本文的深入分析,我们希望为读者提供更全面的了解和应用视角,促进技术的进一步发展和应用。

二、Function Calling函数封装

在本章节中,我们将继续深入探索大模型自动生成function函数的全过程。此技术不仅体现了人工智能领域的前沿进展,还具有实际应用的重要可行性。我们将通过具体的步骤和实践案例,分析这一技术的具体工作原理及其在实际应用中的执行效果。
1)获取函数的注释说明
首先,为了有效利用大模型生成function函数,我们需要从已有的代码中获取目标函数的注释说明。这些注释将提供函数的目的、输入参数以及预期输出等关键信息。精确而详尽的注释是确保大模型能正确理解并生成符合需求的函数定义的前提。
2)将注释说明提供给大模型,由大模型生成相应的JSON Schema
获得注释后,我们将其提供给大模型。模型将根据这些注释自动生成一个对应的JSON Schema。这一步骤是自动化过程中的关键,因为它直接关系到最终生成的function函数是否能满足实际的业务需求。
3) 对大模型生成的JSON Schema进行检查和补充
虽然大模型能够根据注释生成JSON Schema,但手动检查和补充这一环节仍然不可或缺。我们需确保生成的JSON Schema与手工创建的完全一致,包括所有细节和特定条件。这一过程可能需要开发者与模型之间的多次迭代,直到达到最优的输出结果。

通过这一系列的步骤,我们将能够有效地利用大模型自动生成function函数,从而提升开发效率并减少人为错误。

1、定义客户端

import openai
import os
import numpy as np
import pandas as pd
import json
import io
from openai import OpenAI
#获取API KEY
openai.api_key = os.getenv("OPENAI_API_KEY")
#创建客户端
client = OpenAI(api_key=openai.api_key)

2、API调用测试

response = client.chat.completions.create(
  #model="gpt-4-0613",
  model="gpt-3.5-turbo",# 这里最好使用gpt4
  messages=[
    {"role": "user", "content": "什么是JSON Schema?"}
  ]
)

response.choices[0].message.content

输出:

'JSON Schema是一种用于描述和验证JSON数据结构的规范。它定义了数据的类型、格式、约束和关系,使得可以对JSON数据进行验证和验证。通过JSON Schema,开发人员可以确保数据的完整性、准确性和一致性,以及在不同应用程序和平台之间的数据交换的有效性。JSON Schema可以被用来验证输入数据、生成文档和测试数据等各种用途。'

3、定义函数

def sunwukong_function(data):
    """
    孙悟空算法函数,该函数定义了数据集计算过程
    :param data: 必要参数,表示带入计算的数据表,用字符串进行表示
    :return:sunwukong_function函数计算后的结果,返回结果为表示为JSON格式的Dataframe类型对象
    """
    data = io.StringIO(data)
    df_new = pd.read_csv(data, sep='\s+', index_col=0)
    res = df_new * 10
    return json.dumps(res.to_string())

4、定义参数数据格式

# 创建一个DataFrame
df = pd.DataFrame({'x1':[1, 2], 'x2':[3, 4]})

df_str = df.to_string()

data = io.StringIO(df_str)

df_new = pd.read_csv(data, sep='\s+', index_col=0)

5、定义一个标准的funcation call函数

# 定义工具函数
sunwukong={
        "type": "function",
        "function": {"name": "sunwukong_function",
                      "description": "用于执行孙悟空算法函数,定义了一种特殊的数据集计算过程",
                      "parameters": {"type": "object",
                                     "properties": {"data": {"type": "string",
                                                             "description": "执行孙悟空算法的数据集"},
                                                   },
                                     "required": ["data"],
                                    },
                     }
        }
        
#将函数放入工具列表       
tools = [sunwukong]

#定义工具函数字典
available_tools =  {
    "sunwukong_function": sunwukong_function,
}

6、取出注释说明信息

import inspect
# 取出注释信息
print(inspect.getdoc(sunwukong_function))

输出:

孙悟空算法函数,该函数定义了数据集计算过程
:param data: 必要参数,表示带入计算的数据表,用字符串进行表示
:return:sunwukong_function函数计算后的结果,返回结果为表示为JSON格式的Dataframe类型对象

7、生成JSON Schema对象

取出注释信息,调用大模型API生成JSON Schema对象

function_description = inspect.getdoc(sunwukong_function)
response = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "以下是孙悟空函数的函数说明:%s" % function_description},
    {"role": "user", "content": "请帮我编写一个JSON Schema对象,用于说明孙悟空函数的参数输入规范。输出结果要求是JSON Schema格式的JONS类型对象,不需要任何前后修饰语句。"}
  ]
)
# 使用gpt3.5发现有时候生成正确,但是有时候生成的json信息还是有些缺少,gpt.4会更稳定
response.choices[0].message.content

输出:
在这里插入图片描述

8、清理返回对象的特殊字符

# 将变量 response.choices[0].message.content 中的字符串中的 "" 和 "json" 替换为空字符串
r=response.choices[0].message.content.replace("```","").replace("json","")

9、转换为JSON格式

json.loads(r)

输出:

{'type': 'object',
 'required': ['data'],
 'properties': {'data': {'type': 'string',
   'description': 'Represents the data table to be calculated'}}}

10、查看悟空函数信息

# 打印悟空函数的json格式,与上面模型生成的json对比
sunwukong

输出:

{'type': 'function',
 'function': {'name': 'sunwukong_function',
  'description': '用于执行孙悟空算法函数,定义了一种特殊的数据集计算过程',
  'parameters': {'type': 'object',
   'properties': {'data': {'type': 'string', 'description': '执行孙悟空算法的数据集'}},
   'required': ['data']}}}
#打印参数信息
sunwukong['function']['parameters']

输出:

{'type': 'object',
 'properties': {'data': {'type': 'string', 'description': '执行孙悟空算法的数据集'}},
 'required': ['data']}

11、调用API生成JSON格式函数信息

system_prompt = '以下是某的函数说明:%s' % function_description
user_prompt = '根据这个函数的函数说明,请帮我创建一个JSON格式的字典,这个字典有如下5点要求:\
               1.字典总共有三个键值对;\
               2.第一个键值对的Key是字符串name,value是该函数的名字:%s,也是字符串;\
               3.第二个键值对的Key是字符串description,value是该函数的函数的功能说明,也是字符串;\
               4.第三个键值对的Key是字符串parameters,value是一个JSON Schema对象,用于说明该函数的参数输入规范。\
               5.输出结果必须是一个JSON格式的字典,且不需要任何前后修饰语句' % function_name
response = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": user_prompt}
  ]
)
response.choices[0].message.content

输出:
在这里插入图片描述

清理特殊字符后,转化JSON格式输出

json_function_description=json.loads(response.choices[0].message.content.replace("```","").replace("json",""))
json_function_description

输出:

{'name': 'sunwukong_function',
 'description': '孙悟空算法函数,该函数定义了数据集计算过程',
 'parameters': {'type': 'object',
  'properties': {'data': {'type': 'string',
    'description': '必要参数,表示带入计算的数据表,用字符串进行表示'}},
  'required': ['data']}}

12、输出原始函数对比

# 输出悟空函数,和生成的函数信息对比
sunwukong

输出:

{'type': 'function',
 'function': {'name': 'sunwukong_function',
  'description': '用于执行孙悟空算法函数,定义了一种特殊的数据集计算过程',
  'parameters': {'type': 'object',
   'properties': {'data': {'type': 'string', 'description': '执行孙悟空算法的数据集'}},
   'required': ['data']}}}

补充缺少的部分信息

# 补充缺少的部分信息
json_str={"type": "function","function":json_function_description}
json_str

输出:

{'type': 'function',
 'function': {'name': 'sunwukong_function',
  'description': '孙悟空算法函数,该函数定义了数据集计算过程',
  'parameters': {'type': 'object',
   'properties': {'data': {'type': 'string',
     'description': '必要参数,表示带入计算的数据表,用字符串进行表示'}},
   'required': ['data']}}}

再次输出悟空函数,进行对比,基本上已经一摸一样了

三、定义自动输出function 参数的函数

继前文的探讨和实验验证了利用大模型自动生成function参数的函数的可行性之后,本章节将专注于如何有效地封装这一功能,并通过提供多个函数工具,进行具体的调用测试来展示其实用性。

1、自动输出funcation的函数

def auto_functions(functions_list):
    """
    Chat模型的functions参数编写函数
    :param functions_list: 包含一个或者多个函数对象的列表;
    :return:满足Chat模型functions参数要求的functions对象
    """
    def functions_generate(functions_list):
        # 创建空列表,用于保存每个函数的描述字典
        functions = []
        # 对每个外部函数进行循环
        for function in functions_list:
            # 读取函数对象的函数说明
            function_description = inspect.getdoc(function)
            # 读取函数的函数名字符串
            function_name = function.__name__

            system_prompt = '以下是某的函数说明:%s' % function_description
            user_prompt = '根据这个函数的函数说明,请帮我创建一个JSON格式的字典,这个字典有如下5点要求:\
               1.字典总共有三个键值对;\
               2.第一个键值对的Key是字符串name,value是该函数的名字:%s,也是字符串;\
               3.第二个键值对的Key是字符串description,value是该函数的函数的功能说明,也是字符串;\
               4.第三个键值对的Key是字符串parameters,value是一个JSON Schema对象,用于说明该函数的参数输入规范。\
               5.输出结果必须是一个JSON格式的字典,且不需要任何前后修饰语句' % function_name

            response = client.chat.completions.create(
                              model="gpt-3.5-turbo",
                              messages=[
                                {"role": "system", "content": system_prompt},
                                {"role": "user", "content": user_prompt}
                              ]
                            )
            json_function_description=json.loads(response.choices[0].message.content.replace("```","").replace("json",""))
            json_str={"type": "function","function":json_function_description}
            functions.append(json_str)
        return functions
    ## 最大可以尝试4次
    max_attempts = 4
    attempts = 0

    while attempts < max_attempts:
        try:
            functions = functions_generate(functions_list)
            break  # 如果代码成功执行,跳出循环
        except Exception as e:
            attempts += 1  # 增加尝试次数
            print("发生错误:", e)
            if attempts == max_attempts:
                print("已达到最大尝试次数,程序终止。")
                raise  # 重新引发最后一个异常
            else:
                print("正在重新运行...")
    return functions

定义函数列表

functions_list = [sunwukong_function]

2、自动生成funcation函数调用测试

tools = auto_functions(functions_list)

查看生成后的工具函数

tools
 'description': '孙悟空算法函数,该函数定义了数据集计算过程',
   'parameters': {'type': 'object',
    'properties': {'data': {'type': 'string',
      'description': '表示带入计算的数据表,用字符串进行表示'}},
    'required': ['data']}}}]

3、定义参数数据

df_str = pd.DataFrame({'x1':[1, 2], 'x2':[3, 4]}).to_string()
df_str

在这里插入图片描述

4、调用API测试

使用自动生成的funcation call函数,调用OpenAI测试,看大模型能否找到函数

messages=[
    {"role": "system", "content": "数据集data:%s,数据集以字符串形式呈现" % df_str},
    {"role": "user", "content": "请在数据集data上执行孙悟空算法"}
]
response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=messages,
        tools=tools,
        tool_choice="auto",  
    )
response.choices[0].message

输出:从输出结构中可以看到,已经正常找到生成的工具函数
在这里插入图片描述

5、定义第二个函数

#在定义一个工具函数,一起测试
def tangseng_function(data):
    """
    唐僧算法函数,该函数定义了数据集计算过程
    :param data: 必要参数,表示带入计算的数据表,用字符串进行表示
    :return:tangseng_function函数计算后的结果,返回结果为表示为JSON格式的Dataframe类型对象
    """
    data = io.StringIO(data)
    df_new = pd.read_csv(data, sep='\s+', index_col=0)
    res = df_new * 1000000
    return json.dumps(res.to_string())
#两个函数一起放入工具列表
functions_list=[sunwukong_function,tangseng_function]

6、两个函数生成测试

# 使用gpt3.5发现有时候生成正确,但是有时候生成的json信息还是有些缺少,gpt.4会更稳定
tools = auto_functions(functions_list)
tools

输出:

[{'type': 'function',
  'function': {'name': 'sunwukong_function',
   'description': '孙悟空算法函数,该函数定义了数据集计算过程',
   'parameters': {'type': 'object',
    'properties': {'data': {'type': 'string', 'description': '表示带入计算的数据表'}},
    'required': ['data']}}},
 {'type': 'function',
  'function': {'name': 'tangseng_function',
   'description': '唐僧算法函数,该函数定义了数据集计算过程',
   'parameters': {'type': 'object',
    'properties': {'data': {'type': 'string',
      'description': '必要参数,表示带入计算的数据表,用字符串进行表示'}},
    'required': ['data']}}}]

7、两个工具函数一起调用API测试

messages=[
    {"role": "system", "content": "数据集data:%s,数据集以字符串形式呈现" % df_str},
    {"role": "user", "content": "请在数据集data上执行唐僧算法函数"}
]
response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=messages,
        tools=tools,
        tool_choice="auto", 
    )
response.choices[0].message

输出:根据输出可以看到,已经成功找到工具函数
在这里插入图片描述

四、结语

在本文的探讨和实践过程中,我们深入探索了利用大规模语言模型的生成能力来自动构建function函数的可能性和方法。通过精心设计的实验和不断的调优,我们成功实现了利用这些先进模型自动生成高质量的function函数,这不仅大大提高了开发效率,还为函数的多样性和创新性打开了新的大门。
此外,我们还专注于提高这些自动生成的函数在实际应用中的通用性和扩展性。这意味着所开发的函数不仅适用于当前的特定任务,还能在不同的应用环境和项目中轻松调整和扩展,从而保证长远的可用性和持续的价值。这一目标的实现显著增强了代码的复用性和适应性,为软件开发行业带来了新的工作效率和创新思路。

在这里插入图片描述

🎯🔖更多专栏系列文章:AIGC-AI大模型探索之路

如果文章内容对您有所触动,别忘了点赞、⭐关注,收藏!加入我,让我们携手同行AI的探索之旅,一起开启智能时代的大门!

  • 47
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 24
    评论
假设你已经定义好了 NotifyInfoCCResp 类,可以使用 Gson 库将 JSON 字符串转换成 Java 对象,然后取出 data 中的值,添加到 List<NotifyInfoCCResp> 集合中。代码如下: ```java import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { String json = "{ \"code\":\"000\", \"message\":\"成功\", \"data\":[ { \"flightId\":1831011951, \"flightDate\":\"2023-05-3000:00:00\", \"flightNo\":\"5101\", \"departCode\":\"SHA\", \"arriveCode\":\"PEK\", \"carrier\":\"MU\", \"flightStatus\":\"CALLING\", \"planDepartTime\":\"2023-05-3008:00:00\", \"planArriveTime\":\"2023-05-3010:15:00\", \"createTime\":\"2023-05-2413:35:58\", \"flightType\":\"CRE\", \"source\":\"MANUAL\" } ], \"success\":true }"; Gson gson = new Gson(); Type type = new TypeToken<Response>() {}.getType(); Response response = gson.fromJson(json, type); List<NotifyInfoCCResp> notifyInfoList = new ArrayList<>(); for (NotifyInfo notifyInfo : response.getData()) { NotifyInfoCCResp notifyInfoCCResp = new NotifyInfoCCResp(); notifyInfoCCResp.setFlightId(notifyInfo.getFlightId()); notifyInfoCCResp.setFlightDate(notifyInfo.getFlightDate()); notifyInfoCCResp.setFlightNo(notifyInfo.getFlightNo()); notifyInfoCCResp.setDepartCode(notifyInfo.getDepartCode()); notifyInfoCCResp.setArriveCode(notifyInfo.getArriveCode()); notifyInfoCCResp.setCarrier(notifyInfo.getCarrier()); notifyInfoCCResp.setFlightStatus(notifyInfo.getFlightStatus()); notifyInfoCCResp.setPlanDepartTime(notifyInfo.getPlanDepartTime()); notifyInfoCCResp.setPlanArriveTime(notifyInfo.getPlanArriveTime()); notifyInfoCCResp.setCreateTime(notifyInfo.getCreateTime()); notifyInfoCCResp.setFlightType(notifyInfo.getFlightType()); notifyInfoCCResp.setSource(notifyInfo.getSource()); notifyInfoList.add(notifyInfoCCResp); } System.out.println(notifyInfoList); } private static class Response { private String code; private String message; private List<NotifyInfo> data; private boolean success; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<NotifyInfo> getData() { return data; } public void setData(List<NotifyInfo> data) { this.data = data; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } } private static class NotifyInfo { private long flightId; private String flightDate; private String flightNo; private String departCode; private String arriveCode; private String carrier; private String flightStatus; private String planDepartTime; private String planArriveTime; private String createTime; private String flightType; private String source; public long getFlightId() { return flightId; } public void setFlightId(long flightId) { this.flightId = flightId; } public String getFlightDate() { return flightDate; } public void setFlightDate(String flightDate) { this.flightDate = flightDate; } public String getFlightNo() { return flightNo; } public void setFlightNo(String flightNo) { this.flightNo = flightNo; } public String getDepartCode() { return departCode; } public void setDepartCode(String departCode) { this.departCode = departCode; } public String getArriveCode() { return arriveCode; } public void setArriveCode(String arriveCode) { this.arriveCode = arriveCode; } public String getCarrier() { return carrier; } public void setCarrier(String carrier) { this.carrier = carrier; } public String getFlightStatus() { return flightStatus; } public void setFlightStatus(String flightStatus) { this.flightStatus = flightStatus; } public String getPlanDepartTime() { return planDepartTime; } public void setPlanDepartTime(String planDepartTime) { this.planDepartTime = planDepartTime; } public String getPlanArriveTime() { return planArriveTime; } public void setPlanArriveTime(String planArriveTime) { this.planArriveTime = planArriveTime; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getFlightType() { return flightType; } public void setFlightType(String flightType) { this.flightType = flightType; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } } private static class NotifyInfoCCResp { private long flightId; private String flightDate; private String flightNo; private String departCode; private String arriveCode; private String carrier; private String flightStatus; private String planDepartTime; private String planArriveTime; private String createTime; private String flightType; private String source; public long getFlightId() { return flightId; } public void setFlightId(long flightId) { this.flightId = flightId; } public String getFlightDate() { return flightDate; } public void setFlightDate(String flightDate) { this.flightDate = flightDate; } public String getFlightNo() { return flightNo; } public void setFlightNo(String flightNo) { this.flightNo = flightNo; } public String getDepartCode() { return departCode; } public void setDepartCode(String departCode) { this.departCode = departCode; } public String getArriveCode() { return arriveCode; } public void setArriveCode(String arriveCode) { this.arriveCode = arriveCode; } public String getCarrier() { return carrier; } public void setCarrier(String carrier) { this.carrier = carrier; } public String getFlightStatus() { return flightStatus; } public void setFlightStatus(String flightStatus) { this.flightStatus = flightStatus; } public String getPlanDepartTime() { return planDepartTime; } public void setPlanDepartTime(String planDepartTime) { this.planDepartTime = planDepartTime; } public String getPlanArriveTime() { return planArriveTime; } public void setPlanArriveTime(String planArriveTime) { this.planArriveTime = planArriveTime; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getFlightType() { return flightType; } public void setFlightType(String flightType) { this.flightType = flightType; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } @Override public String toString() { return "NotifyInfoCCResp{" + "flightId=" + flightId + ", flightDate='" + flightDate + '\'' + ", flightNo='" + flightNo + '\'' + ", departCode='" + departCode + '\'' + ", arriveCode='" + arriveCode + '\'' + ", carrier='" + carrier + '\'' + ", flightStatus='" + flightStatus + '\'' + ", planDepartTime='" + planDepartTime + '\'' + ", planArriveTime='" + planArriveTime + '\'' + ", createTime='" + createTime + '\'' + ", flightType='" + flightType + '\'' + ", source='" + source + '\'' + '}'; } } } ``` 输出结果如下: ``` [NotifyInfoCCResp{flightId=1831011951, flightDate='2023-05-3000:00:00', flightNo='5101', departCode='SHA', arriveCode='PEK', carrier='MU', flightStatus='CALLING', planDepartTime='2023-05-3008:00:00', planArriveTime='2023-05-3010:15:00', createTime='2023-05-2413:35:58', flightType='CRE', source='MANUAL'}] ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值