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

OpenAI Assistant工具调用返回结果时400错误求助

解决OpenAI Assistant工具调用返回400 Bad Request错误

你遇到的400错误核心原因是用错了API接口——返回工具执行结果不能调用threads.messages.create(这个接口只接受user角色),必须通过threads.runs.submit_tool_outputs接口提交,这是OpenAI Assistant工具调用的标准流程。

错误代码替换

把你代码中报错的这段:

message = client.beta.threads.messages.create( # ERROR POPS UP ON THIS LINE
    thread_id=thread.id,
    role="tool", # THIS DOES NOT WORK
    content=ret,
)

替换为以下代码:

# 提交工具输出到当前运行的run
run = client.beta.threads.runs.submit_tool_outputs(
    thread_id=thread.id,
    run_id=run.id,
    tool_outputs=[
        {
            "tool_call_id": tool_call_id,
            "output": ret
        }
    ]
)

修改后完整的askQuestion函数

def askQuestion(question):
    message = client.beta.threads.messages.create(
        thread_id=thread.id,
        role="user",
        content=question,
    )
    run = client.beta.threads.runs.create(
        thread_id=thread.id,
        assistant_id=assistant.id,
    )
    run = wait_on_run(run, thread)
    while run.status == 'requires_action':
        if run.required_action.type == 'submit_tool_outputs':
            tool_call = run.required_action.submit_tool_outputs.tool_calls[0]
            if tool_call.function.name == 'funnyfunc':
                ret = "five"
                tool_call_id = tool_call.id
                # 正确提交工具输出
                run = client.beta.threads.runs.submit_tool_outputs(
                    thread_id=thread.id,
                    run_id=run.id,
                    tool_outputs=[
                        {
                            "tool_call_id": tool_call_id,
                            "output": ret
                        }
                    ]
                )
            else:
                raise NotImplementedError(tool_call.function.name)
            run = wait_on_run(run, thread)
        else:
            raise NotImplementedError(run.required_action.type)
    messages = client.beta.threads.messages.list(
        thread_id=thread.id
    )
    return messages.data[0].content[0].text.value

关键说明

  • submit_tool_outputs接口专门用于提交工具调用的结果,需要关联当前的run_id和对应的tool_call_id(从required_action中获取)
  • 提交后,run会继续执行,处理工具返回的结果并生成最终回复
  • 不需要手动创建tool角色的消息,OpenAI会自动将工具输出纳入线程上下文

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:16:04