JSON Output
在很多场景下,用户需要让模型严格按照 JSON 格式来输出,以实现输出的结构化,便于后续逻辑进行解析。
SpAk API 支持 JSON Output,但默认模型不一定会输出合法的 JSON。在 API 中设置 response_format 为 {'type': 'json_object'},将启用 JSON 模式,以确保模型输出合法的 JSON。
注意事项
- 设置
response_format为{'type': 'json_object'},将启用 JSON 模式。 - 在提示词中必须包含 "json" 这个单词,否则 API 会返回 400 错误,并提示参数
response_format无效。 - 若
finish_reason=length,则表明生成超过了max_tokens或对话超过了最大上下文长度,此时响应的content可能是不完整的 JSON,需要进行校验。
参数详情见 对话补全。
样例代码
import json
from openai import OpenAI
client = OpenAI(
api_key="<your api key>",
base_url="https://yuansuo.top",
)
system_prompt = """
The user will provide some exam text. 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"
}
"""
user_prompt = "Which is the longest river in the world? The Nile River."
messages = [{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}]
response = client.chat.completions.create(
model="SpAk-Aster-V1-MOE",
messages=messages,
response_format={
'type': 'json_object'
}
)
print(json.loads(response.choices[0].message.content))