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

Python调用OpenAI Assistant:如何在会话中修改响应JSON Schema格式?

OpenAI Assistant 响应格式问题解决方案

一、为什么本地设置assistant.response_format不生效?

直接修改本地assistant对象的属性不会同步到OpenAI服务器,助手的配置(包括响应格式)是存储在云端的,必须通过API操作才能更新。你之前在Playground设置的Schema是助手的默认配置,所以本地修改无效。

二、获取期望格式数据的两种方法

方法1:在Run级别临时指定格式(推荐)

不需要修改助手的全局配置,每次创建Run时单独传入response_format参数,仅对当前提问生效,适合同一会话中不同问题用不同格式的场景:

from openai import OpenAI
client = OpenAI(api_key="你的API密钥")

# 替换为你的助手ID和会话线程ID
assistant_id = "your-assistant-id"
thread_id = "your-thread-id"

# 定义目标输出格式
output_format = {
  "name": "mySchema",
  "strict": False,
  "schema": {
    "type": "object",
    "properties": {
      "text": {"type": "string"}
    },
    "required": []
  }
}

# 创建Run时指定响应格式
run = client.beta.threads.runs.create(
  thread_id=thread_id,
  assistant_id=assistant_id,
  response_format={"type": "json_schema", "json_schema": output_format}
)

# 等待Run执行完成
while run.status not in ["completed", "failed"]:
    run = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)

# 获取最新响应
messages = client.beta.threads.messages.list(thread_id=thread_id)
latest_response = messages.data[0].content[0].text.value
print(latest_response)

方法2:永久更新助手的默认格式

如果希望所有后续会话都使用新格式,可以调用Update Assistant API修改云端的助手配置:

from openai import OpenAI
client = OpenAI(api_key="你的API密钥")

assistant_id = "your-assistant-id"
output_format = {
  "name": "mySchema",
  "strict": False,
  "schema": {
    "type": "object",
    "properties": {
      "text": {"type": "string"}
    },
    "required": []
  }
}

# 更新助手的响应格式配置
updated_assistant = client.beta.assistants.update(
  assistant_id=assistant_id,
  response_format={"type": "json_schema", "json_schema": output_format}
)

# 验证更新结果
print(updated_assistant.response_format)

三、会话过程中能否修改响应JSON Schema?

可以,两种实现方式:

  • 单Run临时修改:每次创建新Run时传入不同的response_format,同一会话线程的上下文会被保留,不同提问可以用不同输出格式。
  • 全局默认修改:调用Update Assistant API修改助手的云端配置,之后所有新创建的Run都会自动使用新格式。

注意:Playground的设置会直接覆盖助手的云端默认配置,所以如果之前在Playground设置过Schema,必须通过上述API操作才能替换成你需要的格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 11:57:03