
● 将 response_format 参数设置为 {'type': 'json_object'}。
● 用户传入的 system 或 user prompt 中必须含有 json 字样,并给出希望模型输出的 JSON 格式的样例。
import jsonfrom openai import OpenAIclient = OpenAI(api_key="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",base_url="https://openapi.coreshub.cn/v1")user_prompt = """Which is the longest river in the world? The Nile River.Please parse the "question" and "answer" and output them in JSON format.EXAMPLE INPUT:Which is the highest mountain in the world? Mount Everest.EXAMPLE JSON OUTPUT:{"question": "Which is the highest mountain in the world?","answer": "Mount Everest"}Don't output begin "```json" and end "```""""messages = [{"role": "user", "content": user_prompt}]response = client.chat.completions.create(model="DeepSeek-V3",messages=messages,response_format={'type': 'json_object'})print(json.loads(response.choices[0].message.content))
{'question': 'Which is the longest river in the world?', 'answer': 'The Nile River'}
import jsonfrom openai import OpenAIclient = OpenAI(api_key="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",base_url="https://openapi.coreshub.cn/v1")response = client.chat.completions.create(model="DeepSeek-V3",messages=[{"role": "system", "content": "You are a helpful assistant designed to output JSON."},{"role": "user", "content": """? 2020 年世界奥运会乒乓球男子和女子单打冠军分别是谁?Please respond in the format {\"男子冠军\": ..., \"女子冠军\": ...}Don't output begin "```json" and end "```" """}],response_format={'type': 'json_object'})print(json.loads(response.choices[0].message.content))
代码运行回显示例:
{'男子冠军': '马龙', '女子冠军': '陈梦'}
更多推荐





点击“阅读原文”了解更多文章转载自青云QingCloud,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。





