LangChain 中强制让模型结构化输出

可以通过 langchain 中的 StructuredOutputParser/ResponseSchema 来在 prompt_template 中添加对应的结构化输出 Prompt 引导说明,来强制模型按要求输出。

示例代码:

from langchain.prompts import PromptTemplate
from langchain.output_parsers import StructuredOutputParser, ResponseSchema

prompt_template = """您是一位专业的鲜花店文案撰写员。\n
对于售价为 {price} 元的 {flower_name},您能提供一个吸引人的简短描述吗?

{format_instructions}
"""
response_schemas = [
    ResponseSchema(name="description", description="鲜花的描述文案"),
    ResponseSchema(name="reason", description="问为什么要这样写这个文案"),
]
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
format_instructions = output_parser.get_format_instructions()
prompt = PromptTemplate.from_template(
    prompt_template,
    partial_variables={"format_instructions": format_instructions},
)
input = prompt.format(flower_name="玫瑰", price="50")
output = model.invoke(input)
print("原始输出: \n{output}\n".format(output=output.content))
parsed_output = output_parser.parse(output.content)
print("结构化输出:\n{output}\n".format(output=json.dumps(parsed_output, ensure_ascii=False, indent=4)))

运行结果:

原始输出: 
```json
{
    "description": "这束由绚丽玫瑰组成的花束,每一朵花瓣都承载着浓烈而纯粹的爱意,适合表达最真挚的情感。",
    "reason": "该文案强调玫瑰花寓意的爱情,突出其情感价值,以吸引想表达爱意的顾客。"
}
```

结构化输出:
{
    "description": "这束由绚丽玫瑰组成的花束,每一朵花瓣都承载着浓烈而纯粹的爱意,适合表达最真挚的情感。",
    "reason": "该文案强调玫瑰花寓意的爱情,突出其情感价值,以吸引想表达爱意的顾客。"
}