背景
1、langchain当中的chain = prompt | llm | output_parser这个链能更长吗?
在 LangChain 中,链(chain)可以根据需要变得非常长,并且可以包含多种不同类型的组件。链的目的是将多个步骤串联起来,以便以特定的顺序执行,从而处理复杂的任务。除了 prompt、llm 和 output_parser 之外,你还可以添加更多的步骤,例如:
验证器(Validator): 用于验证 LLM 输出是否符合预期格式或条件。
缓存(Cache): 用于存储和重用之前的 LLM 输出,以提高效率。
重试逻辑(Retry Logic): 如果 LLM 调用失败,则可以自动重试。
后处理(Post-Processing): 对 LLM 输出进行额外的处理,如文本摘要、翻译或数据格式化。
条件逻辑(Conditional Logic): 根据输出决定下一步操作,例如,使用 if-else 逻辑来决定是否需要进一步处理。
数据存储(Data Storage): 将 LLM 的输出保存到数据库或其他存储系统中。
通知(Notification): 在处理完成后发送通知,例如发送电子邮件或短信。
from langchain_core import PromptTemplate, LLM, StrOutputParser
from langchain_core.validators import TextLengthValidator
from langchain_core.cache import SimpleCache
from langchain_core.post_processors import TextSummarizer
from langchain_core.notifiers import EmailNotifier
# 创建 Prompt
prompt_template = "Please answer the following question: {question}"
prompt = PromptTemplate.from_template(prompt_template)
# 初始化语言模型
llm = LLM(model="gpt-3.5-turbo", api_key="your-api-key")
# 创建 OutputParser
output_parser = StrOutputParser()
# 创建 Validator
validator = TextLengthValidator(min_length=10, max_length=1000)
# 创建 Cache
cache = SimpleCache()
# 创建 Post-Processor
post_processor = TextSummarizer()
# 创建 Notifier
notifier = EmailNotifier()
# 构建更长的 Chain
chain = (
prompt
| llm
| cache # 先检查缓存
| output_parser
| validator # 验证输出
| post_processor # 后处理
| notifier # 发送通知
)
# 调用 Chain
response = chain.invoke({
"question": "What is the capital of France?"})
print(response)
在这个例子中,链不仅包括了提示、模型调用和输出解析,还加入了缓存检查、输出验证、文本摘要和通知发送。这样的链可以非常灵活和强大,能够处理各种复杂的工作流。
记住,链中的每个组件都应该实现 Runnable 接口,并且具有 invoke 方法,这样才能确保它们可以被串联起来执行。
参考文档
https://aitutor.liduos.com/02-langchain/02-2-1.html
https://langchain-ai.github.io/langgraph/tutorials/sql-agent/