如何检查LangChain中的Runnables

43 阅读2分钟

如何检查LangChain中的Runnables

引言

在使用LangChain表达式语言(LCEL)创建可运行链(runnables)时,了解其内部步骤有助于优化程序并解决潜在问题。本指南旨在帮助您通过编程方式检查链的内部过程,从而更好地理解和调试您的LangChain运行。

主要内容

创建一个示例链

首先,我们需要创建一个示例链,用于检索数据。以下是必要的安装步骤和代码:

%pip install -qU langchain langchain-openai faiss-cpu tiktoken

然后,我们使用LangChain库创建一个简单的检索链:

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()方法:

chain.get_graph()

虽然这种表示不太直观,但可以使用print_ascii()方法以更易理解的方式展示图形:

chain.get_graph().print_ascii()

这将输出一个简单的ASCII图形,帮助您理解链中的数据流和处理过程。

获取提示信息

如果您只想查看链中使用的提示信息,可以使用get_prompts()方法:

chain.get_prompts()

这将返回一个包含提示模板的列表,帮助您理解链如何构建请求和响应。

代码示例

完整的代码示例如下:

# 使用API代理服务提高访问稳定性
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()
)

# 获取和打印图形
chain.get_graph().print_ascii()

# 获取提示信息
prompts = chain.get_prompts()

常见问题和解决方案

  1. 访问API时遇到网络问题:
    由于某些地区的网络限制,您可能需要使用API代理服务来提高访问稳定性。

  2. 调试链中出现的问题:
    通过检查图形输出和提示信息,您可以更容易地定位和解决链中的问题。

总结和进一步学习资源

通过本指南,您已经学习了如何检查和调试LangChain中的可运行链。有关链运行的更多信息,请参阅LangChain的其它指南和调试相关资源。

参考资料

结束语:如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---