0

I am developing a shopping assistant Chatbot. While using function calling APIs, I get an error. The "auto" does not seem to fetch any function. I use "gpt-4o-mini" model.

I attempted the following code. I expected a smooth flow of the chat process and a final recommendation from the list of laptops available in a .csv file. But I get error which is also posted here.

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}"
)

** When I execute, The Chatbot gives the welcome message but when user input is received, the following error is thrown.**

A glimpse of the execution output and error message.

<Chatbot> Welcome! Type 'exit' to end the chat.

<User> Hi! I would like to buy a new laptop. Can you suggest me one please? <Chatbot> I am executing Step 4: Call OpenAI API with tools .

<Chatbot> I am executing Exception part .

<Chatbot> An error occurred: Error code: 400 - {'error': {'message': "Missing required parameter: 'functions[0].name'.", 'type': 'invalid_request_error', 'param': 'functions[0].name', 'code': 'missing_required_parameter'}}

1 Answer 1

0

The issue lies in the structure of the tools parameter. The functions were unnecessarily wrapped in a "function" key, which the OpenAI API does not recognize. Each function should be defined directly in the tools list with the following keys:

  • name: The function's name (required for the API to identify it).
  • description: A brief explanation of what the function does.
  • parameters: A JSON Schema that defines the expected input for the function.

Here’s the corrected structure:

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,
        },
    },
]

Give a look at this: https://platform.openai.com/docs/guides/function-calling

Sign up to request clarification or add additional context in comments.

2 Comments

Confusingly enough, the link you gave has examples with the "type": "function" and "function": {...} format as written in OP's question. Mind clearing this up?
The "type": "function" wrapper is required for multi-tool setups (e.g., mixing functions with code interpreters). For functions-only, OpenAI infers it automatically. Both formats work, but the docs use the explicit style for clarity @Arc_Angle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.