做网站前端的软件,wordpress模板框架,郴州网站建设服务,苍梧网站建设Langchain 的 Structured output parser 当您想要返回多个字段时#xff0c;可以使用此输出解析器。虽然 Pydantic/JSON 解析器更强大#xff0c;但我们最初尝试了仅具有文本字段的数据结构。
示例代码#xff0c;
from langchain.output_parsers import StructuredOutput… Langchain 的 Structured output parser 当您想要返回多个字段时可以使用此输出解析器。虽然 Pydantic/JSON 解析器更强大但我们最初尝试了仅具有文本字段的数据结构。
示例代码
from langchain.output_parsers import StructuredOutputParser, ResponseSchema
from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI在这里我们定义了我们想要接收的响应模式。
示例代码
response_schemas [ResponseSchema(nameanswer, descriptionanswer to the users question),ResponseSchema(namesource, descriptionsource used to answer the users question, should be a website.)
]
output_parser StructuredOutputParser.from_response_schemas(response_schemas)现在我们得到一个字符串其中包含如何格式化响应的说明然后将其插入提示符中。
format_instructions output_parser.get_format_instructions()
prompt PromptTemplate(templateanswer the users question as best as possible.\n{format_instructions}\n{question},input_variables[question],partial_variables{format_instructions: format_instructions}
)我们现在可以使用它来格式化提示以发送到语言模型然后解析返回的结果。
model OpenAI(temperature0)_input prompt.format_prompt(questionwhats the capital of france?)
output model(_input.to_string())output_parser.parse(output)输出结果 {answer: Paris,source: https://www.worldatlas.com/articles/what-is-the-capital-of-france.html}这是在聊天模型中使用它的示例
chat_model ChatOpenAI(temperature0)prompt ChatPromptTemplate(messages[HumanMessagePromptTemplate.from_template(answer the users question as best as possible.\n{format_instructions}\n{question}) ],input_variables[question],partial_variables{format_instructions: format_instructions}
)_input prompt.format_prompt(questionwhats the capital of france?)
output chat_model(_input.to_messages())output_parser.parse(output.content)输出结果 {answer: Paris, source: https://en.wikipedia.org/wiki/Paris}完结