结构化输出

有时候我们希望输出的内容不是文本,而是像 json 那样结构化的数据。

  1. from langchain.output_parsers import StructuredOutputParser, ResponseSchema
  2. from langchain.prompts import PromptTemplate
  3. from langchain.llms import OpenAI
  4. llm = OpenAI(model_name="text-davinci-003")
  5. # 告诉他我们生成的内容需要哪些字段,每个字段类型式啥
  6. response_schemas = [
  7. ResponseSchema(name="bad_string", description="This a poorly formatted user input string"),
  8. ResponseSchema(name="good_string", description="This is your response, a reformatted response")
  9. ]
  10. # 初始化解析器
  11. output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
  12. # 生成的格式提示符
  13. # {
  14. # "bad_string": string // This a poorly formatted user input string
  15. # "good_string": string // This is your response, a reformatted response
  16. #}
  17. format_instructions = output_parser.get_format_instructions()
  18. template = """
  19. You will be given a poorly formatted string from a user.
  20. Reformat it and make sure all the words are spelled correctly
  21. {format_instructions}
  22. % USER INPUT:
  23. {user_input}
  24. YOUR RESPONSE:
  25. """
  26. # 将我们的格式描述嵌入到 prompt 中去,告诉 llm 我们需要他输出什么样格式的内容
  27. prompt = PromptTemplate(
  28. input_variables=["user_input"],
  29. partial_variables={"format_instructions": format_instructions},
  30. template=template
  31. )
  32. promptValue = prompt.format(user_input="welcom to califonya!")
  33. llm_output = llm(promptValue)
  34. # 使用解析器进行解析生成的内容
  35. output_parser.parse(llm_output)

image-20230406000017276