import pandas as pd from openai import OpenAI from dotenv import load_dotenv load_dotenv() client = OpenAI() import json from io import StringIO
df_complex = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [55, 30, 35], 'Salary': [50000.0, 100000.5, 150000.75], 'IsMarried': [True, False, True] }) print(df_complex)
df_complex_json = df_complex.to_json(orient='split')
messages = [ {"role": "system","content": "你是一位优秀的数据分析师, 现在有这样一个数据集input_json:%s,数据集以JSON形式呈现" % df_complex_json}, {"role": "user", "content": "请在数据集input_json上执行计算所有人年龄总和函数"} ]
def calculate_total_age_from_split_json(input_json): """ 从给定的JSON格式字符串(按'split'方向排列)中解析出DataFrame,计算所有人的年龄总和,并以JSON格式返回结果。 参数: input_json (str): 包含个体数据的JSON格式字符串。 返回: str: 所有人的年龄总和,以JSON格式返回。 """ df = pd.read_json(StringIO(input_json), orient='split') total_age = df['Age'].sum() return json.dumps({"total_age": str(total_age)})
result = calculate_total_age_from_split_json(df_complex_json) print("The JSON output is:", result)
response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, tools = [{ "type": "function", "function": { "name": "calculate_total_age_from_split_json", "description": "计算年龄总和的函数,从给定的JSON格式字符串(按'split'方向排列)中解析出DataFrame,计算所有人的年龄总和,并以JSON格式返回结果。", "parameters": { "type": "object", "properties": { "input_json": { "type": "string", "description": "执行计算年龄总和的数据集", }, }, "required": ["input_json"], } } }], tool_choice="auto" ) print('message: ',messages) print('model_response_message: ',response.choices[0].message)
function_name = response.choices[0].message.tool_calls[0].function.name print('function_name: ', function_name)
function_args = json.loads(response.choices[0].message.tool_calls[0].function.arguments) print('function_args:',function_args)
tool_calls_id = response.choices[0].message.tool_calls[0].id print('tool_calls_id: ',tool_calls_id)
function_repository = { "calculate_total_age_from_split_json": calculate_total_age_from_split_json, }
local_fuction_call = function_repository[function_name] print('local_fuction_call: ',local_fuction_call) function_response = local_fuction_call(**function_args) print('function_response:',function_response)
messages.append(response.choices[0].message) print('function_messages1: ',messages)
messages.append({"role": "tool", "name": function_name, "tool_call_id": tool_calls_id, "content": function_response})
print('function_messages2: ',messages)
final_response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, )
print('answer: ',final_response.choices[0].message.content)
|