当前位置: 首页 > wzjs >正文

wordpress qq头像不显示谷歌优化的网络公司

wordpress qq头像不显示,谷歌优化的网络公司,技术支持保定网站建设 定兴,做dw和ps的网站教学文章目录 一 LangChain输出解析器概述1.1 什么是输出解析器?1.2 主要功能与工作原理1.3 常用解析器类型 二 主要输出解析器类型2.1 Pydantic/Json输出解析器2.2 结构化输出解析器2.3 列表解析器2.4 日期解析器2.5 Json输出解析器2.6 xml输出解析器 三 高级使用技巧3…

文章目录

  • 一 LangChain输出解析器概述
    • 1.1 什么是输出解析器?
    • 1.2 主要功能与工作原理
    • 1.3 常用解析器类型
  • 二 主要输出解析器类型
    • 2.1 Pydantic/Json输出解析器
    • 2.2 结构化输出解析器
    • 2.3 列表解析器
    • 2.4 日期解析器
    • 2.5 Json输出解析器
    • 2.6 xml输出解析器
  • 三 高级使用技巧
    • 3.1 自定义解析逻辑
    • 3.2 重试与错误处理
    • 3.3 多模式解析
  • 四 实际应用示例
    • 4.1 构建问答系统
    • 4.2 性能优化建议
  • 五 总结

一 LangChain输出解析器概述

  • LangChain输出解析器是LangChain框架中的核心组件,主要用于将大型语言模型(LLM)生成的非结构化文本转换为结构化数据格式。它允许开发者定义期望的输出结构,并通过提示工程指导LLM生成符合该格式的响应。输出解析器在验证和转换模型输出时发挥着关键作用,确保数据能够无缝集成到应用程序的工作流程中。

1.1 什么是输出解析器?

输出解析器是LangChain框架中的一类组件,专门负责两大功能:

  1. 指令格式化:指导LLM如何格式化其输出
  2. 结果解析:将LLM的文本响应转换为结构化格式
    与直接使用原始API调用相比,输出解析器提供了更可靠、更可预测的结果处理方式,极大简化了后续的数据处理流程。

1.2 主要功能与工作原理

  • 输出解析器通过两个核心机制实现功能:首先通过get_format_instructions方法生成格式化指令,明确告知LLM输出应遵循的结构;然后通过parse方法将LLM的原始响应解析为目标数据结构。这种双重机制既保证了输出的规范性,又提供了灵活的数据转换能力。典型的应用场景包括将文本转换为JSON对象、列表、枚举值或特定领域对象等结构化数据。

1.3 常用解析器类型

  • LangChain提供了丰富的内置解析器,包括ListParser(列表解析器)、DatetimeParser(日期时间解析器)、EnumParser(枚举解析器)和PydanticOutputParser(JSON解析器)等。其中PydanticOutputParser特别强大,它基于Pydantic模型定义数据结构,可以处理嵌套复杂的JSON格式,并自动生成对应的格式指令。此外还有StructuredOutputParser用于处理自定义类结构,Auto-FixingParser可自动修复格式错误。

二 主要输出解析器类型

LangChain提供了多种输出解析器,适用于不同场景:

2.1 Pydantic/Json输出解析器

    • Pydantic/Json解析器允许您定义严格的输出模式,确保LLM响应符合预期的数据结构,非常适合需要强类型验证的场景。
from langchain.output_parsers import PydanticOutputParser
from pydantic import Field, BaseModelclass UserProfile(BaseModel):name: str = Field(description="用户全名")age: int = Field(description="用户年龄")hobbies: list[str] = Field(description="用户爱好列表")parser = PydanticOutputParser(pydantic_object=UserProfile)
  • 完整案例:
import os
from langchain_core.output_parsers import PydanticOutputParser
# from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import Field, BaseModel# 配置 API 易环境
os.environ["OPENAI_API_KEY"] = "hk-xxx"
os.environ["OPENAI_API_BASE"] = "https://api.openai-hk.com/v1"model=ChatOpenAI(model="gpt-4",temperature=0)# 定义期望的数据结构
class Joke(BaseModel):setup:str =Field(description="设置笑话的问题")punchline:str =Field(description="解决笑话的答案")# 用于提示语言模型填充数据结构的查询意图
joke_query="告诉我一个笑话"
# 设置解析器+将指令注入提示模板
# parser=JsonOutputParser(pydantic_object=Joke)
parser=PydanticOutputParser(pydantic_object=Joke)
prompt=PromptTemplate(template="回答用户的查询。\n{format_instructions}\n{query}\n",input_variables=["query"],partial_variables={"format_instructions":parser.get_format_instructions()}
)
print(parser.get_format_instructions())
  • 输出结果:
"""
The output should be formatted as a JSON instance that conforms to the JSON schema below.As an example, for the schema {"properties": {"foo": {"title": "Foo", "description": "a list of strings", "type": "array", "items": {"type": "string"}}}, "required": ["foo"]}
the object {"foo": ["bar", "baz"]} is a well-formatted instance of the schema. The object {"properties": {"foo": ["bar", "baz"]}} is not well-formatted.Here is the output schema:
{"properties": {"setup": {"description": "设置笑话的问题", "title": "Setup", "type": "string"}, "punchline": {"description": "解决笑话的答案", "title": "Punchline", "type": "string"}}, "required": ["setup", "punchline"]}
"""
chain=prompt|model|parser
response=chain.invoke({"query":joke_query})
print(response)
"""
{'setup': '为什么计算机不能得感冒?', 'punchline': '因为它们有防火墙!'}
"""

2.2 结构化输出解析器

  • 当需要灵活定义输出结构而不想引入Pydantic依赖时,结构化输出解析器是理想选择。
from langchain.output_parsers import StructuredOutputParser, ResponseSchemaresponse_schemas = [ResponseSchema(name="answer", description="问题的答案"),ResponseSchema(name="source", description="答案来源")
]parser = StructuredOutputParser.from_response_schemas(response_schemas)
  • 完整代码
import os
from langchain.output_parsers import StructuredOutputParser, ResponseSchema
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI# 配置 API 易环境
os.environ["OPENAI_API_KEY"] = "hk-xxx"
os.environ["OPENAI_API_BASE"] = "https://api.openai-hk.com/v1"model=ChatOpenAI(model="gpt-4",temperature=0)response_schemas = [ResponseSchema(name="answer", description="问题的答案"),ResponseSchema(name="source", description="答案来源")
]# 设置解析器+将指令注入提示模板
parser = StructuredOutputParser.from_response_schemas(response_schemas)prompt=PromptTemplate(template="回答用户的查询。\n{format_instructions}\n{query}\n",input_variables=["query"],partial_variables={"format_instructions":parser.get_format_instructions()}
)
print(parser.get_format_instructions())
"""
The output should be a markdown code snippet formatted in the following schema, including the leading and trailing "```json" and "```":{"answer": string  // 问题的答案"source": string  // 答案来源
}"""
chain=prompt|model|parser
# 用于提示语言模型填充数据结构的查询意图
joke_query="告诉我一个笑话"
response=chain.invoke({"query":joke_query})print(response)
"""
{'answer': '为什么数学书总是很忧伤?因为它有太多的问题!', 'source': '常见幽默笑话'}
"""

2.3 列表解析器

  • 简单高效地将逗号分隔的列表响应转换为Python列表,适用于简单的枚举场景。
from langchain.output_parsers import CommaSeparatedListOutputParserparser = CommaSeparatedListOutputParser()

2.4 日期解析器

  • 专门处理日期时间字符串,将其转换为Python datetime对象,省去了手动解析的麻烦。
from langchain.output_parsers import DatetimeOutputParserparser = DatetimeOutputParser()

2.5 Json输出解析器

  • JSON作为现代API和Web应用中最常用的数据交换格式,LangChain提供了专门的JSON输出解析器来简化处理流程。

import osfrom langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import Field, BaseModel# 配置 API 易环境
os.environ["OPENAI_API_KEY"] = "hk-xxx"
os.environ["OPENAI_API_BASE"] = "https://api.openai-hk.com/v1"model=ChatOpenAI(model="gpt-4",temperature=0)# 定义期望的数据结构
class Joke(BaseModel):setup:str =Field(description="设置笑话的问题")punchline:str =Field(description="解决笑话的答案")# 用于提示语言模型填充数据结构的查询意图
joke_query="告诉我一个笑话"
# 设置解析器+将指令注入提示模板
parser=JsonOutputParser(pydantic_object=Joke)
prompt=PromptTemplate(template="回答用户的查询。\n{format_instructions}\n{query}\n",input_variables=["query"],partial_variables={"format_instructions":parser.get_format_instructions()}
)
print(parser.get_format_instructions())
"""
The output should be formatted as a JSON instance that conforms to the JSON schema below.As an example, for the schema {"properties": {"foo": {"title": "Foo", "description": "a list of strings", "type": "array", "items": {"type": "string"}}}, "required": ["foo"]}
the object {"foo": ["bar", "baz"]} is a well-formatted instance of the schema. The object {"properties": {"foo": ["bar", "baz"]}} is not well-formatted.Here is the output schema:{"properties": {"setup": {"description": "设置笑话的问题", "title": "Setup", "type": "string"}, "punchline": {"description": "解决笑话的答案", "title": "Punchline", "type": "string"}}, "required": ["setup", "punchline"]}"""
chain=prompt|model|parser
response=chain.invoke({"query":joke_query})
for s in chain.stream({"query":joke_query}):print(s)"""
{}
{'setup': ''}
{'setup': '为'}
{'setup': '为什'}
{'setup': '为什么'}
{'setup': '为什么电'}
{'setup': '为什么电脑'}
{'setup': '为什么电脑很'}
{'setup': '为什么电脑很好'}
{'setup': '为什么电脑很好吃'}
{'setup': '为什么电脑很好吃?'}
{'setup': '为什么电脑很好吃?', 'punchline': ''}
{'setup': '为什么电脑很好吃?', 'punchline': '因'}
{'setup': '为什么电脑很好吃?', 'punchline': '因为'}
{'setup': '为什么电脑很好吃?', 'punchline': '因为它'}
{'setup': '为什么电脑很好吃?', 'punchline': '因为它们'}
{'setup': '为什么电脑很好吃?', 'punchline': '因为它们有'}
{'setup': '为什么电脑很好吃?', 'punchline': '因为它们有很'}
{'setup': '为什么电脑很好吃?', 'punchline': '因为它们有很多'}
{'setup': '为什么电脑很好吃?', 'punchline': '因为它们有很多字'}
{'setup': '为什么电脑很好吃?', 'punchline': '因为它们有很多字节'}
{'setup': '为什么电脑很好吃?', 'punchline': '因为它们有很多字节('}
{'setup': '为什么电脑很好吃?', 'punchline': '因为它们有很多字节(bytes'}
{'setup': '为什么电脑很好吃?', 'punchline': '因为它们有很多字节(bytes)'}
{'setup': '为什么电脑很好吃?', 'punchline': '因为它们有很多字节(bytes)!'}
"""

2.6 xml输出解析器

  • LangChain的XML输出解析器为这些场景提供了专业支持。

import osfrom langchain_core.output_parsers import  XMLOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI# 配置 API 易环境
os.environ["OPENAI_API_KEY"] = "hk-xxx"
os.environ["OPENAI_API_BASE"] = "https://api.openai-hk.com/v1"model=ChatOpenAI(model="gpt-4",temperature=0)# 用于提示语言模型填充数据结构的查询意图
actor_query="生成周星驰的简化电影作品列表,按照最新的时间降序"# 设置解析器+将指令注入提示模板
parser=XMLOutputParser(tags=["movies","actor","film","name","genre"])
prompt=PromptTemplate(template="回答用户的查询。\n{format_instructions}\n{query}\n",input_variables=["query"],partial_variables={"format_instructions":parser.get_format_instructions()}
)
print(parser.get_format_instructions())
  • 执行输出:
"""
The output should be formatted as a XML file.
1. Output should conform to the tags below.
2. If tags are not given, make them on your own.
3. Remember to always open and close all the tags.As an example, for the tags ["foo", "bar", "baz"]:
1. String "<foo><bar><baz></baz></bar>
</foo>" is a well-formatted instance of the schema.
2. String "<foo><bar></foo>" is a badly-formatted instance.
3. String "<foo><tag></tag>
</foo>" is a badly-formatted instance.Here are the output tags:['movies', 'actor', 'film', 'name', 'genre']
"""
chain=prompt|model
response=chain.invoke({"query":actor_query})
xml_output=parser.parse(response.content)
print(response.content)
"""
```xml
<movies><actor><name>周星驰</name><film><name>美人鱼</name><genre>喜剧</genre><year>2016</year></film><film><name>西游降魔篇</name><genre>喜剧</genre><year>2013</year></film><film><name>长江七号</name><genre>科幻</genre><year>2008</year></film><film><name>功夫</name><genre>动作</genre><year>2004</year></film><film><name>少林足球</name><genre>喜剧</genre><year>2001</year></film></actor>
</movies>这是一个简化的电影作品列表,列出了周星驰的一些电影,包括电影名称、类型和年份。这个列表是按照最新的时间降序排列的。
"""

三 高级使用技巧

3.1 自定义解析逻辑

  • 通过继承BaseOutputParser,可以创建完全自定义的解析逻辑,处理特殊响应格式。
from langchain.output_parsers import BaseOutputParserclass BooleanParser(BaseOutputParser[bool]):def parse(self, text: str) -> bool:cleaned = text.strip().lower()if cleaned in ("yes", "true", "1"):return Trueelif cleaned in ("no", "false", "0"):return Falseraise ValueError(f"无法解析为布尔值: {text}")@propertydef _type(self) -> str:return "boolean_parser"

3.2 重试与错误处理

  • 当初始解析失败时,重试解析器会自动尝试修正错误,显著提高系统鲁棒性。
from langchain.output_parsers import RetryWithErrorOutputParserretry_parser = RetryWithErrorOutputParser.from_llm(parser=parser,llm=chat_llm
)

3.3 多模式解析

  • 输出修正解析器可以检测并尝试自动修复格式错误的响应,特别适合生产环境中提高可靠性。
from langchain.output_parsers import OutputFixingParserfixing_parser = OutputFixingParser.from_llm(parser=parser, llm=chat_llm)

四 实际应用示例

4.1 构建问答系统

import osfrom langchain_core.output_parsers import JsonOutputParser
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from pydantic import BaseModel, Field# 配置 API 环境
os.environ["OPENAI_API_KEY"] = "hk-xxx"
os.environ["OPENAI_API_BASE"] = "https://api.openai-hk.com/v1"template = """根据上下文回答问题,并按照要求格式化输出。
上下文: {context}
问题: {question}
{format_instructions}"""prompt = ChatPromptTemplate.from_template(template)
model = ChatOpenAI(model="gpt-4")# 定义输出数据结构
class Answer(BaseModel):answer: str = Field(description="根据上下文回答问题")confidence: float = Field(description="回答的置信度")# 创建解析器
parser = JsonOutputParser(pydantic_model=Answer)chain = prompt | model | parserresult = chain.invoke({"context": "LangChain是一个LLM应用开发框架...","question": "LangChain是什么?","format_instructions": parser.get_format_instructions()
})print(result)

4.2 性能优化建议

  1. 清晰的指令:在提示中明确说明输出格式要求。
  2. 渐进式解析:复杂结构可分步解析。
  3. 错误回退:实现备用解析策略。
  4. 缓存机制:对相同输入缓存解析结果。
  5. 监控指标:跟踪解析成功率,及时发现模式问题。

五 总结

  • LangChain的输出解析器组件为LLM应用开发提供了关键的结构化数据处理能力。通过合理选择和使用各种解析器,开发者可以:
    • 确保数据的一致性和可靠性
    • 减少胶水代码和手动解析工作
    • 构建更健壮的生产级应用
    • 专注于业务逻辑而非数据清洗
http://www.dtcms.com/wzjs/46815.html

相关文章:

  • wordpress 链接数据库seo软件推广哪个好
  • wordpress 图册业民啊郑州seo线上推广技术
  • wordpress电影自动采集主题seo软件视频教程
  • 北京国都建设集团网站百度网站名称
  • 美女和帅哥做私人动作的漫画的网站关键词优化如何做
  • 品牌服装网站建设现状一般开车用什么导航最好
  • 有没有在线做动图的网站百度竞价托管外包代运营
  • 重庆网站制作企业百度广告电话号码
  • 做网站开封世界杯大数据
  • 做资源网站怎么不封北京网络营销推广培训哪家好
  • 学校网站源码php今日时政新闻
  • 国外在线网站建设平台西安seo网站排名
  • 网站整站个人建站
  • 手机做网站公司有哪些怎么在百度上设置自己的门店
  • 如何建设电影会员网站今日热点新闻头条国内
  • 人妖怎么做的手术视频网站网络运营师资格证
  • 如何建设公司网站知乎搜索引擎营销案例分析题
  • 电子商务网站开发项目设计报告阿里云搜索引擎网址
  • 西宁网站建设平台公司广州线下培训机构停课
  • 个人做慈善网站百度账户登录
  • 重庆市渝兴建设投资有限公司网站中视频自媒体平台注册
  • 外贸网址大全百度问答优化
  • 网站是用sql2012做的_在发布时可以改变为2008吗推广之家官网
  • 网站建设资质备案百度人工服务24小时热线电话
  • 专做医药中间体的网站百度关键词优化点击 教程
  • 泉做网站的公司廊坊百度快照优化哪家服务好
  • 亦庄建设局网站手机端怎么刷排名
  • 北京燕郊网站建设seo软件
  • 加强政府网站建设管理的重要性360推广登录
  • 浅谈顺丰的电子商务网站建设设计个人网站