如何配置OpenAI Assistant使其默认返回JSON格式结果?
让OpenAI Assistant默认返回JSON格式结果的可行方法
问题背景
我了解到在OpenAI新版本中,可通过以下方式让ChatGPT返回JSON格式的响应:
completion = openai.chat.completions.create( model="gpt-4-1106-preview", response_format={"type": "json_object"}, messages=[ {"role": "user", "content": "translate this message to french, italian, spanish, greek: Hello, nice to meet you, reply in json object with key is the language code"} ] )
但我希望让Assistant默认返回JSON格式的结果,原本期望通过以下方式实现:
assistant = client.beta.assistants.create( name="DocRetrievalAssistantJson", response_format={ "type": "json_object" }, instructions=model_instructions, model="gpt-4-1106-preview", tools=[{"type": "retrieval"}] )
然而assistant.create API并不支持response_format参数,请问有什么可行的实现方法?
可行解决方案
在Assistant指令中强制要求JSON输出
直接在instructions字段里明确说明必须始终以严格JSON格式返回内容,示例代码:model_instructions = """ 你是文档检索助手,所有回答必须以严格的JSON格式返回,不得包含任何JSON以外的文本。 """ assistant = client.beta.assistants.create( name="DocRetrievalAssistantJson", instructions=model_instructions, model="gpt-4-1106-preview", tools=[{"type": "retrieval"}] )这种方式依赖模型遵循指令,GPT-4系列模型的遵循度较高,但无法像
response_format那样强制约束,仍有极小概率出现非JSON输出。创建线程运行时指定响应格式
在调用run.create方法时传入response_format参数,这是官方支持的强制约束方式,和Chat Completions API的效果一致:# 创建线程 thread = client.beta.threads.create() # 运行线程时指定JSON响应格式 run = client.beta.threads.runs.create( thread_id=thread.id, assistant_id=assistant.id, response_format={"type": "json_object"} )该方案可靠性最高,适合需要严格JSON输出的场景。
后续校验并修复格式
如果前两种方法仍出现非JSON输出,可以在获取响应后做解析校验,失败则引导模型重新生成:import json # 获取助手响应内容 message_response = client.beta.threads.messages.list(thread_id=thread.id) content = message_response.data[0].content[0].text.value try: result = json.loads(content) except json.JSONDecodeError: # 发送消息要求重新返回JSON格式内容 client.beta.threads.messages.create( thread_id=thread.id, role="user", content="请将之前的回答以严格的JSON格式重新返回,不要添加任何额外文本" ) # 重新运行线程并指定格式 new_run = client.beta.threads.runs.create( thread_id=thread.id, assistant_id=assistant.id, response_format={"type": "json_object"} )
内容的提问来源于stack exchange,提问作者DarioB
相关产品推荐
相关产品推荐

