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

OpenAI函数调用报错求助及tools/functions参数疑问

问题解决与参数说明

错误修正

你遇到的'type' is a required property - 'tools.0'错误,是因为使用tools参数时,每个工具对象必须明确指定type字段(当前函数调用场景下固定为"function"),同时原函数定义需要嵌套在function子字段中。另外,建议补充参数的required列表,帮助模型明确必填参数。修正后的完整代码如下:

import openai

# 假设llm_config已提前定义,示例:
# llm_config = {
#     "model_name": "gpt-3.5-turbo-1106",
#     "deployment_name": "your-deployment-id"  # Azure OpenAI需指定该参数
# }

def fetch_weather_with_openai(location, unit='celsius'):
    """
    Fetch weather using OpenAI's ChatCompletion.create with a simulated function call.

    Args:
    location (str): The location for which weather information is requested.
    unit (str): The unit of temperature (celsius or fahrenheit).

    Returns:
    str: The generated response or function call details.
    """

    function_payload = {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"]
                    }
                },
                "required": ["location"]  # 明确必填参数
            }
        }
    }

    # 定义输入消息
    messages = [
        {"role": "user", "content": f"What's the weather like in {location}?"}
    ]

    response = openai.ChatCompletion.create(
        model=llm_config['model_name'],
        deployment_id=llm_config.get('deployment_name'),  # 用get避免未定义时出错
        messages=messages,
        tools=[function_payload],
        tool_choice="auto"  # 让模型自动决定是否调用函数
    )

    response_message = response.choices[0].message
    # 检查模型是否返回函数调用请求
    if response_message.get("tool_calls"):
        function_call = response_message["tool_calls"][0]["function"]
        return f"模型请求调用函数:{function_call['name']},参数:{function_call['arguments']}"
    else:
        # 模型直接返回自然语言回答
        return response_message.get("content", "无返回内容")

# 示例调用
response = fetch_weather_with_openai("Paris, France")
print(response)

tools与functions参数的差异

  • functions参数:旧版API参数,仅支持函数调用这一种交互类型,参数值直接是函数元数据的数组。
  • tools参数:新版API扩展参数,设计目的是支持更多工具类型(未来可能包含检索、代码执行等)。当前函数调用场景下,每个工具对象必须包含type字段(固定为"function"),并将原函数元数据嵌套在function子字段中。

建议优先使用tools参数,它是API的未来演进方向,兼容性更好。

内容的提问来源于stack exchange,提问作者user3104352

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:50:23