打造你自己的输出解析器:轻松实现自定义输出格式
在使用AI模型时,通常需要将其输出解析为特定格式。本文将介绍如何创建自定义输出解析器,以便根据需要对模型的输出进行结构化。我们将探讨两种实现方式,并提供代码示例。
引言
AI模型的输出往往不是我们最终需要的格式,这时自定义输出解析器便派上了用场。本文旨在指导你如何使用 LangChain Execution Library (LCEL) 创建自定义解析器,以便将AI模型的输出转换为所需格式。
主要内容
1. 使用 RunnableLambda 或 RunnableGenerator
推荐使用 runnable lambda 和 runnable generator 进行输出解析。我们将使用一个简单的解析器,将模型输出的字母大小写颠倒。例如,模型输出 "Meow",解析器将输出 "mEOW"。
from typing import Iterable
from langchain_anthropic.chat_models import ChatAnthropic
from langchain_core.messages import AIMessage, AIMessageChunk
model = ChatAnthropic(model_name="claude-2.1")
def parse(ai_message: AIMessage) -> str:
"""Parse the AI message."""
return ai_message.content.swapcase()
chain = model | parse
chain.invoke("hello") # 'hELLO!'
# 使用API代理服务提高访问稳定性
对于需要流式解析的情况,可以使用 RunnableGenerator 包装解析器。
from langchain_core.runnables import RunnableGenerator
def streaming_parse(chunks: Iterable[AIMessageChunk]) -> Iterable[str]:
for chunk in chunks:
yield chunk.content.swapcase()
streaming_parse = RunnableGenerator(streaming_parse)
chain = model | streaming_parse
for chunk in chain.stream("tell me about yourself in one sentence"):
print(chunk, end="|", flush=True)
2. 继承解析基类
另一种方法是继承 BaseOutputParser 或类似的基类。这种方法通常需要更多代码编写,不推荐一般使用。
from langchain_core.exceptions import OutputParserException
from langchain_core.output_parsers import BaseOutputParser
class BooleanOutputParser(BaseOutputParser[bool]):
"""Custom boolean parser."""
true_val: str = "YES"
false_val: str = "NO"
def parse(self, text: str) -> bool:
cleaned_text = text.strip().upper()
if cleaned_text not in (self.true_val.upper(), self.false_val.upper()):
raise OutputParserException(
f"BooleanOutputParser expected output value to either be "
f"{self.true_val} or {self.false_val} (case-insensitive). "
f"Received {cleaned_text}."
)
return cleaned_text == self.true_val.upper()
代码示例
以下是一个完整的代码示例,展示如何使用 RunnableLambda 实现自定义解析器。
from langchain_anthropic.chat_models import ChatAnthropic
from langchain_core.messages import AIMessage
model = ChatAnthropic(model_name="claude-2.1")
def parse(ai_message: AIMessage) -> str:
"""Invert case of the AI message."""
return ai_message.content.swapcase()
chain = model | parse
result = chain.invoke("Hello, World!")
print(result) # 输出: 'hELLO, wORLD!'
# 使用API代理服务提高访问稳定性
常见问题和解决方案
- 无效的输出格式:确保模型输出与解析器期望的输入格式一致。
- 流式处理:如果解析器需要处理实时数据,请使用
RunnableGenerator。
总结和进一步学习资源
自定义输出解析器可以极大地增强AI模型的实用性。本文介绍的两种方法各有优缺点,开发者可以根据具体需求选择合适的实现方式。更多关于LCEL和LangChain的信息可以参考以下资源:
参考资料
- LangChain API Reference
- LangChain Core Documentation
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---