LangChain输出解析器Output Parser用法
逗号分隔符的列表输出解析器(CommaSeparatedListOutputParser)
from langchain.output_parsers import CommaSeparatedListOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_community.llms import Tongyi
output_parser = CommaSeparatedListOutputParser()
format_instructions = output_parser.get_format_instructions()
prompt = PromptTemplate(
template = “请列除5个{subject}.\n{format_instructions}”,
input_variables = [“subject”],
partial_variables={“format_instructions”: format_instructions},
)
llm = Tongyi()
input = prompt.format(subject=”世界名曲”)
output = llm.invoke(input)
output_p = output_parser.parse(output)
print(output_p)
日期时间输出解析器
from langchain.output_parsers import DatetimeOutputParser
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
from langchain_community.llms import Tongyi
# 创建一个日期时间输出解析器
output_parser = DatetimeOutputParser()
template = “””
Answer the users question:
{question}
{format_instructions}
“””
prompt = PromptTemplate.from_template(template,partial_variables={“format_instructions”:output_parser.get_format_instructions()})
# 初始化大模型
llm = Tongyi()
# 创建一个LLMChain链
chain = LLMChain(prompt=prompt,llm =llm)
res = chain.invoke(“辛亥革命是哪一年?”)
# 最后还要调用parse方法对日期进行格式化输出
res_parser = output_parser.parse(res[“text”])
print(res_parser)
结构化输出解析器
from langchain.output_parsers import StructuredOutputParser, ResponseSchema
from langchain_community.llms import Tongyi
from langchain_core.prompts import PromptTemplate
from langchain.chains import LLMChain
response_schemas = [
ResponseSchema(name=”name”, description=”学生的姓名”),
ResponseSchema(name=”age”, description=”学生的年龄”)
]
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
format_instructions = output_parser.get_format_instructions()
prompt = PromptTemplate(
template=”回答下面问题,注意,请不要在回复中附带其他内容,只需要返回结构化的信息。\n{format_instructions}\n{question}”,
input_variables=[“question”],
partial_variables={“format_instructions”: format_instructions},
)
# 创建大模型
llm = Tongyi()
chain = LLMChain(prompt=prompt,llm =llm)
output = chain.invoke({“question”:”请给我一个非常大众的中国女孩的名字?”})
print(output_parser.parse(output[“text”]))
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
7. 本站有不少源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别!
66源码网 » LangChain输出解析器Output Parser用法