错误 400:GPT-4o-mini、GPT-3.5 和 GPT-4-0613 型号的函数调用 API 中缺少“functions[0].name”参数

问题描述 投票:0回答:1

我正在开发一个购物助理聊天机器人。在使用函数调用 API 时,出现错误。 “自动”似乎没有获取任何功能。我使用“gpt-4o-mini”型号。

我尝试了以下代码。我期望聊天过程能够顺利进行,并从 .csv 文件中可用的笔记本电脑列表中获得最终推荐。但我收到错误,该错误也发布在这里。

from openai import OpenAI
import json

client = OpenAI()

# Define functions (tools)
tools = [
    {
        "type": "function",
        "function": {
            "name": "initialize_conversation",
            "description": "Initialize the conversation for the shopping assistant chatbot.",
            "parameters": {
                "type": "object",
                "properties": {},
                "required": [],
                "additionalProperties": False,
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_chat_completions",
            "description": "Fetch chat completions based on the user’s input.",
            "parameters": {
                "type": "object",
                "properties": {
                    "input": {
                        "type": "string",
                        "description": "The user’s input or query to process."
                    },
                    "json_format": {
                        "type": "boolean",
                        "description": "Flag to determine if the output should be in JSON format."
                    },
                },
                "required": ["input"],
                "additionalProperties": False,
            },
        },
    },

]
import openai
import json

# Initialize OpenAI client
client = openai.OpenAI()

# Step 1: Initialize conversation (I have used a more detailed function here
def initialize_conversation():
    return [{"role": "system", "content": "You are a shopping assistant expert for laptops."}]

# Main function
def dialogue_mgmt_system_v2(tools):
    conversation = initialize_conversation()  # Start with system message. 
    
    print("Welcome to the Shopping Assistant! Type 'exit' to end the chat.\n")
    
    while True:
        # Step 3: Get user input
        user_input = input("You: ")
        if user_input.lower() == "exit":
            print("Goodbye! Have a great day!")
            break
        
        # Add user input to the conversation
        conversation.append({"role": "user", "content": user_input})
        
        try:
            **# Step 4: Call OpenAI API with tools**
            response = client.chat_completions.create(
                model="gpt-4-0613",
                messages=conversation,
                functions=tools,  # Pass the tools here
                function_call="auto"  # Let the AI decide if a function is needed
            )
            
            # Step 5: Check if a function call is needed
            if "function_call" in response.choices[0].message:
                function_call = response.choices[0].message["function_call"]
                function_name = function_call["name"]
                function_args = json.loads(function_call["arguments"])
                
                # Step 6: Execute the function
                if function_name in globals():
                    function_output = globals()[function_name](**function_args)
                    
                    # Add the function output to the conversation
                    conversation.append({"role": "function", "name": function_name, "content": json.dumps(function_output)})
                else:
                    print(f"Error: Function '{function_name}' not found.")
            
            # Step 7: AI-generated response
            else:
                assistant_response = response.choices[0].message["content"]
                print(f"Assistant: {assistant_response}")
                conversation.append({"role": "assistant", "content": assistant_response})
        
        except Exception as e:
            print(f"An error occurred: {e}"
)

** 当我执行时,聊天机器人会给出欢迎消息,但是当收到用户输入时,会抛出以下错误。**

执行输出和错误消息一览。

欢迎光临!输入“exit”结束聊天。

嗨! 我想买一台新笔记本电脑。你能给我推荐一个吗? 我正在执行步骤4:使用工具调用OpenAI API。

我正在执行异常部分。

发生错误:错误代码:400 - {'error':{'message':“缺少必需的参数:'functions[0].name'。”,'type':'invalid_request_error','param' : 'functions[0].name', 'code': 'missing_required_parameter'}}

python function runtime-error chatbot auto
1个回答
0
投票

问题在于

tools
参数的结构。这些函数不必要地封装在 OpenAI API 无法识别的
"function"
键中。每个函数都应该使用以下键直接在
tools
列表中定义:

  • name
    :函数的名称(API 需要识别它)。
  • description
    :该函数功能的简要说明。
  • parameters
    :定义函数预期输入的 JSON 模式。

这是更正后的结构:

tools = [
    {
        "name": "initialize_conversation",
        "description": "Initialize the conversation for the shopping assistant chatbot.",
        "parameters": {
            "type": "object",
            "properties": {},
            "required": [],
            "additionalProperties": False,
        },
    },
    {
        "name": "get_chat_completions",
        "description": "Fetch chat completions based on the user’s input.",
        "parameters": {
            "type": "object",
            "properties": {
                "input": {
                    "type": "string",
                    "description": "The user’s input or query."
                },
                "json_format": {
                    "type": "boolean",
                    "description": "Whether the output should be in JSON format."
                },
            },
            "required": ["input"],
            "additionalProperties": False,
        },
    },
]
© www.soinside.com 2019 - 2024. All rights reserved.