【动手学Langchain】初级篇3-创建第一个链

Posted by Orchid on February 19, 2025

在 LangChain 中,链(Chain) 是一个核心概念,用于将多个处理步骤或操作串联起来,形成一个复杂的工作流。链允许开发者将语言模型调用、工具使用、数据处理等步骤组合在一起,从而实现更强大的功能和自动化流程。

我们可以将提示词模板和大语言模型调用整合为一条链:

  • 老版本 LangChain ,使用 LLMChain 对模型进行封装(新版本已弃用):
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
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain import LLMChain

# 定义系统消息模板
system_template = "You are a professional translater. Please translate the following text from {input_language} to {output_language}"
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)

# 定义用户消息模板
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

# 将两个模板组合到消息聊天提示词模板中
chat_prompt = ChatPromptTemplate.from_messages(
    [
        system_message_prompt,
        human_message_prompt,
    ]
)

# 使用 LLMChain 组合大模型和聊天模板
chain = LLMChain(llm=tongyi_chat, prompt=chat_prompt)

# 运行链
chain.run(
    input_language="English",
    output_language="Chinese",
    text = "Hello World",
)
  • 最新版的 LangChain,使用 RunnableSequence 方法来替代旧的 LLMChain,即使用管道符 | 连接工作流:
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
30
31
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate

# 定义系统消息模板
system_template = "You are a professional translater. Please translate the following text from {input_language} to {output_language}"
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)

# 定义用户消息模板
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

# 将两个模板组合到消息聊天提示词模板中
chat_prompt = ChatPromptTemplate.from_messages(
    [
        system_message_prompt,
        human_message_prompt,
    ]
)

# 使用 RunnableSequence 组合大模型和聊天模板
chain = chat_prompt | tongyi_chat

# 调用 invoke 方法运行链
result = chain.invoke(
    {
        "input_language": "English",
        "output_language": "Chinese",
        "text": "Hello World",
    }
)

print(result.content)