{
"sentiment":"positive",
"confidence":0.93
}ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;font-size: 14px;letter-spacing: 0.1em;color: rgb(63, 63, 63);"> 那就可以直接ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;font-feature-settings: normal;font-variation-settings: normal;font-size: 12.6px;text-align: left;line-height: 1.75;color: rgb(221, 17, 68);background: rgba(27, 31, 35, 0.05);padding: 3px 5px;border-radius: 4px;">json.loads()进程序,省时省力。ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;padding-left: 8px;color: rgb(63, 63, 63);">如何引导模型输出 JSON?关键在于提示词设计(prompt engineering)。我们需要在 prompt 中明确告诉模型两点:
下面是一个典型的 prompt 示例:
请根据以下用户评论判断其情感倾向,并以 JSON 格式返回结果,包含两个字段:"sentiment"(取值为 "positive"、"negative" 或 "neutral")和 "confidence"(0 到 1 之间的浮点数)。只输出 JSON,不要添加其他说明。
评论内容:这个产品真的很不错,用起来很顺手。
注意这里的几个关键词:“以 JSON 格式返回”、“包含两个字段”、“只输出 JSON”。这些约束条件能有效引导模型进入“结构化输出”模式。
我们来看一个简单的 Python 脚本,调用 OpenAI 的 API 实现上述功能(当然,也可以适配其他支持 function calling 或结构化输出的模型,如 Anthropic、通义千问等)。
importopenai
importjson
# 设置 API Key(请替换为你的实际密钥)
openai.api_key ="your-api-key"
defget_sentiment(text):
prompt =f"""
请分析以下评论的情感倾向,并返回 JSON 格式的结果,字段包括:
- "sentiment": 取值为 "positive", "negative", 或 "neutral"
- "confidence": 浮点数,表示判断的置信度(0-1)
要求:
1. 输出必须是合法的 JSON
2. 不要包含任何额外说明或格式符号
3. 只返回 JSON 对象
评论内容:{text}
"""
response = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role":"user","content": prompt}
],
temperature=0.3# 降低随机性,提高输出稳定性
)
raw_output = response.choices[0].message.content.strip()
try:
result = json.loads(raw_output)
returnresult
exceptjson.JSONDecodeError:
print(f"JSON 解析失败:{raw_output}")
returnNone
# 测试
comment ="这个手机电池很耐用,拍照也清楚。"
result = get_sentiment(comment)
print(result)
# 输出示例:{'sentiment': 'positive', 'confidence': 0.95} 这段代码虽然简单,但在实际项目中非常实用。通过控制temperature参数,我们可以进一步提升 JSON 输出的稳定性。
在实际使用中,我们发现模型偶尔会输出非法 JSON,比如缺少引号、使用单引号、或多出解释文字。对此,有几种缓解方法:
json.loads()包裹,并配合正则或第三方库(如json-repair)尝试自动修复。response_format={"type": "json_object"}参数(需启用gpt-4-turbo或更新模型),能强制模型输出合法 JSON。例如:
评论:服务态度很差,等了两个小时。
{"sentiment": "negative", "confidence": 0.98}
评论:还可以吧,不算好也不算差。
{"sentiment": "neutral", "confidence": 0.75}
评论:这个功能太棒了,完全超出预期!模型往往会模仿这种格式继续输出。
JSON 提示特别适合以下场景:
但也有一些局限需要注意:
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |