LangChain链的类型及示例

LangChain 中的链(Chains)类型及示例

LangChain 提供了多种类型的链(Chains),用于将多个组件组合起来完成复杂任务。以下是主要的链类型及示例:

1. LLMChain(基础链)

最基本的链类型,将提示模板、LLM和输出解析器组合在一起。

1
2
3
4
5
6
7
8
9
10
11
12
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI

prompt = PromptTemplate(
input_variables=["product"],
template="为{product}写一个创意广告文案:"
)
llm = OpenAI(temperature=0.9)
chain = LLMChain(llm=llm, prompt=prompt)

print(chain.run("环保水杯"))

2. SequentialChain(顺序链)

按顺序执行多个链,前一个链的输出作为下一个链的输入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from langchain.chains import SequentialChain, LLMChain

# 第一个链:生成广告文案
prompt1 = PromptTemplate(
input_variables=["product"],
template="为{product}写一个创意广告文案:"
)
chain1 = LLMChain(llm=llm, prompt=prompt1, output_key="ad_copy")

# 第二个链:评估广告效果
prompt2 = PromptTemplate(
input_variables=["ad_copy"],
template="评估以下广告的效果:\n{ad_copy}\n\n评估结果:"
)
chain2 = LLMChain(llm=llm, prompt=prompt2, output_key="review")

overall_chain = SequentialChain(
chains=[chain1, chain2],
input_variables=["product"],
output_variables=["ad_copy", "review"]
)

result = overall_chain({"product": "智能手表"})
print(result)

3. TransformChain(转换链)

对输入进行转换而不调用LLM。

1
2
3
4
5
6
7
8
9
10
11
12
13
from langchain.chains import TransformChain

def transform_func(inputs: dict) -> dict:
text = inputs["text"]
return {"output_text": text.upper()}

transform_chain = TransformChain(
input_variables=["text"],
output_variables=["output_text"],
transform=transform_func
)

transform_chain.run({"text": "hello world"})

4. RouterChain(路由链)

根据输入决定使用哪个子链。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from langchain.chains.router import MultiPromptChain
from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser

physics_template = """你是一位物理专家。回答物理问题:
问题: {input}"""
math_template = """你是一位数学专家。回答数学问题:
问题: {input}"""

prompt_infos = [
{
"name": "physics",
"description": "适合回答物理问题",
"prompt_template": physics_template
},
{
"name": "math",
"description": "适合回答数学问题",
"prompt_template": math_template
}
]

router_chain = MultiPromptChain.from_prompts(
llm,
prompt_infos,
verbose=True
)

print(router_chain.run("什么是相对论?"))
print(router_chain.run("2+2等于几?"))

5. APIChain(API链)

与外部API交互的链。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from langchain.chains import APIChain
from langchain.llms import OpenAI

api_docs = """
API文档:
BASE URL: https://api.example.com

端点:
GET /weather?location={location}

参数:
- location: 城市名称

响应:
{
"temp": 温度,
"condition": 天气状况
}
"""

chain = APIChain.from_llm_and_api_docs(llm, api_docs, verbose=True)
chain.run("上海现在的天气如何?")

6. SQLDatabaseChain(数据库链)

与SQL数据库交互的链。

1
2
3
4
5
6
7
from langchain import SQLDatabase, SQLDatabaseChain

db = SQLDatabase.from_uri("sqlite:///chinook.db")
llm = OpenAI(temperature=0)

db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True)
db_chain.run("有多少位顾客?")

7. RetrievalQAChain(检索问答链)

结合检索器和LLM的问答链。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from langchain.chains import RetrievalQA
from langchain.document_loaders import TextLoader
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import FAISS

loader = TextLoader("state_of_the_union.txt")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)

embeddings = OpenAIEmbeddings()
docsearch = FAISS.from_documents(texts, embeddings)

qa = RetrievalQA.from_chain_type(
llm=OpenAI(),
chain_type="stuff",
retriever=docsearch.as_retriever()
)

query = "总统提到了什么重要政策?"
qa.run(query)

8. ConversationChain(对话链)

维护对话上下文的链。

1
2
3
4
5
6
7
8
9
10
11
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory

conversation = ConversationChain(
llm=OpenAI(),
memory=ConversationBufferMemory(),
verbose=True
)

conversation.predict(input="你好!")
conversation.predict(input="我很好,谢谢!你呢?")

9. MapReduceChain(映射归约链)

处理长文档的链,先映射处理各部分,再归约总结。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from langchain.chains import MapReduceChain

map_prompt = PromptTemplate(
input_variables=["page"],
template="总结以下文本:\n{page}"
)
reduce_prompt = PromptTemplate(
input_variables=["summaries"],
template="结合以下总结写出最终总结:\n{summaries}"
)

chain = MapReduceChain.from_params(
llm=llm,
map_prompt=map_prompt,
reduce_prompt=reduce_prompt
)

with open("long_document.txt") as f:
long_text = f.read()

result = chain.run({"input_text": long_text})

这些链可以单独使用,也可以组合起来构建更复杂的应用。LangChain还允许创建自定义链以满足特定需求。