You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GPT-4o-mini/GPT-3.5/GPT-4-0613模型函数调用API报错Error 400: Missing 'functions[0].name' Parameter的求助

GPT-4o-mini/GPT-3.5/GPT-4-0613模型函数调用API报错Error 400: Missing 'functions[0].name' Parameter的求助

嘿,我看到你在开发笔记本购物助手聊天机器人时遇到这个烦人的报错了,咱们一步步拆解问题,把它搞定!

问题根源分析

你拿到的400错误核心原因是工具定义格式和API调用参数不匹配,结合你的代码来看有两个关键问题:

  1. 你定义的tools数组是新版工具规范(带type: "function"和嵌套的function对象),但调用API时却用了旧版的functions=tools参数,导致OpenAI无法识别函数名称;
  2. 你代码里重复初始化了OpenAI客户端,还有一些属性访问的语法错误(比如用字典索引访问对象属性),也会触发异常。

另外,你的initialize_conversation函数其实是用来生成系统消息的,完全不需要放到工具列表里让AI调用——这个逻辑应该由你自己的代码初始化,不是AI该做的事,反而会混淆模型的判断。

针对性修复方案

根据你使用的模型(gpt-4o-mini更推荐新版工具规范),我给你整理了两种修复方式:

方案一:适配新版tools参数(推荐给gpt-4o-mini)

新版规范用tools参数传递工具列表,搭配tool_choice="auto"让模型自动判断是否调用工具,同时响应处理要适配tool_calls字段:

from openai import OpenAI
import json

# 只初始化一次OpenAI客户端
client = OpenAI()

# 定义符合新版规范的工具列表
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_laptop_recommendations",
            "description": "根据用户的需求返回合适的笔记本推荐,数据来自本地CSV文件",
            "parameters": {
                "type": "object",
                "properties": {
                    "user_requirement": {
                        "type": "string",
                        "description": "用户的笔记本需求描述,比如预算、用途、偏好品牌等"
                    },
                    "return_json": {
                        "type": "boolean",
                        "description": "是否以JSON格式返回结果,默认False"
                    },
                },
                "required": ["user_requirement"],
                "additionalProperties": False,
            },
        },
    },
]

# 初始化对话历史(直接在代码中处理,无需做成工具)
def initialize_conversation():
    return [{"role": "system", "content": "你是专业的笔记本购物助手,会根据用户需求调用工具获取推荐,并给出清晰易懂的建议"}]

# 实现工具对应的函数(这里替换成你读取CSV的实际逻辑)
def get_laptop_recommendations(user_requirement, return_json=False):
    # 示例:模拟从CSV读取数据并生成推荐
    sample_data = [
        {"型号": "MacBook Air M2", "价格": "9999元", "配置": "8G内存+256G固态,适合办公"},
        {"型号": "戴尔XPS 13", "价格": "11999元", "配置": "16G内存+512G固态,适合设计"}
    ]
    if return_json:
        return json.dumps(sample_data, ensure_ascii=False)
    else:
        return "\n".join([f"- {item['型号']}: {item['价格']},{item['配置']}" for item in sample_data])

# 主对话逻辑
def dialogue_mgmt_system():
    conversation = initialize_conversation()
    print("欢迎来到笔记本购物助手!输入'exit'结束对话。\n")
    
    while True:
        user_input = input("你: ")
        if user_input.lower() == "exit":
            print("再见!祝你购物愉快!")
            break
        
        conversation.append({"role": "user", "content": user_input})
        
        try:
            # 调用API,使用新版tools参数
            response = client.chat_completions.create(
                model="gpt-4o-mini",
                messages=conversation,
                tools=tools,
                tool_choice="auto"
            )
            
            assistant_msg = response.choices[0].message
            # 检查是否需要调用工具
            if assistant_msg.tool_calls:
                # 处理工具调用(这里以第一个调用为例,支持多工具调用可循环处理)
                tool_call = assistant_msg.tool_calls[0]
                func_name = tool_call.function.name
                func_args = json.loads(tool_call.function.arguments)
                
                # 执行对应的函数
                if func_name in globals():
                    func_output = globals()[func_name](**func_args)
                    # 将工具结果加入对话历史
                    conversation.append({
                        "role": "tool",
                        "tool_call_id": tool_call.id,
                        "name": func_name,
                        "content": func_output
                    })
                    # 再次调用API,让AI基于工具结果生成自然回答
                    final_response = client.chat_completions.create(
                        model="gpt-4o-mini",
                        messages=conversation
                    )
                    print(f"助手: {final_response.choices[0].message.content}")
                    conversation.append({"role": "assistant", "content": final_response.choices[0].message.content})
                else:
                    print(f"错误:未找到函数'{func_name}'")
            else:
                # 直接返回AI的自然回答
                print(f"助手: {assistant_msg.content}")
                conversation.append({"role": "assistant", "content": assistant_msg.content})
        
        except Exception as e:
            print(f"发生错误: {e}")

# 启动聊天机器人
if __name__ == "__main__":
    dialogue_mgmt_system()

方案二:适配旧版functions参数(适合GPT-4-0613)

如果要兼容旧模型,需要简化工具定义格式,去掉外层的type和function嵌套:

# 旧版函数定义格式
functions = [
    {
        "name": "get_laptop_recommendations",
        "description": "根据用户需求返回笔记本推荐",
        "parameters": {
            "type": "object",
            "properties": {
                "user_requirement": {"type": "string", "description": "用户需求描述"},
                "return_json": {"type": "boolean", "description": "是否返回JSON格式"}
            },
            "required": ["user_requirement"]
        }
    }
]

# API调用时用旧版参数
response = client.chat_completions.create(
    model="gpt-4-0613",
    messages=conversation,
    functions=functions,
    function_call="auto"
)

修复关键点总结

  1. 新版模型(gpt-4o-mini、gpt-4o)用tools参数传递工具,旧模型(GPT-4-0613、gpt-3.5-turbo-0613)用functions参数;
  2. 不要把代码初始化逻辑做成工具让AI调用,避免模型混淆;
  3. 访问API返回的消息属性时用点语法(比如assistant_msg.tool_calls),不要用字典索引;
  4. 工具调用后需要再次调用API,让模型基于工具结果生成自然回答,而不是直接返回工具输出。

备注:内容来源于stack exchange,提问作者SubathraKishore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 13:49:51