Langchain中链的基本调用方法| 豆包MarsCode AI刷题

241 阅读7分钟

在LangChain框架中,链(Chains)是构建复杂应用程序的基本单元。链可以理解为一系列处理步骤的组合,每个步骤都可能涉及语言模型、工具或数据源的操作。通过将这些基本组件以特定方式链接起来,我们可以创建出能够完成从简单到复杂任务的应用程序。下面,我将详细介绍LangChain中几种常见的链类型及其基本调用方法。

  1. 基本链 - LLMChain LLMChain是最基础也是最直接的一种链形式,它直接利用语言模型来生成响应。这种链适用于那些不需要额外工具支持的任务,如文本生成、摘要制作等。

主要功能:接受输入并返回基于大模型预测的结果。 使用场景:当任务可以通过单一的大规模语言模型解决时,比如生成创意内容、回答问题等。

  1. 复合链 - Sequential Chain 和 SimpleSequentialChain 当需要执行一系列相互依赖的任务时,可以使用Sequential Chain或其简化版本SimpleSequentialChain来按顺序执行多个子链。

主要功能:允许按照预定义的顺序执行多个链。 使用场景:适用于需要分阶段处理信息的情况,例如先进行文本分析再基于分析结果生成报告。

  1. 结构化输出链 - StructuredOutputChain 对于需要结构化输出的任务,比如提取特定格式的信息,可以使用StructuredOutputChain。这类链通常结合了特定的输出解析器,确保最终输出符合预期格式。

主要功能:根据给定的模式生成结构化的输出。 使用场景:当希望从非结构化文本中提取特定信息,并将其组织成易于进一步处理的形式时。

  1. 路由链 - RouterChain RouterChain用于根据输入选择不同的路径来执行任务。这对于需要根据不同条件应用不同逻辑的情景非常有用。

主要功能:依据某些标准动态决定接下来执行哪个链。 使用场景:面对多种类型的请求,每种类型需要不同的处理逻辑时。

通过上述介绍可以看出,LangChain提供了一套灵活且强大的机制来构建复杂的自然语言处理系统。无论是简单的文本生成还是复杂的多步骤推理过程,都能找到合适的链类型来满足需求。开发者可以根据具体应用场景选择适合的链类型,并通过合理的配置和组合实现高效的工作流程。此外,随着社区的发展和技术的进步,未来还会有更多创新性的链类型出现,为开发人员提供更多可能性。 使用 LangChain 模型进行链调用时,有一些基本方法和常用的模块。以下是一些基本模型的介绍

1.Chain 基类

Chain 是 LangChain 的核心类,它定义了调用链条的基本结构。通过继承 Chain,可以构建自己的链。

以下是如何创建一个自定义链的示例


class CustomChain(Chain):
    def __init__(self, some_param):
        super().__init__()
        self.some_param = some_param

    def _call(self, inputs):
        # 自定义逻辑
        return {"output": inputs["input"] + self.some_param}

    @property
    def input_keys(self):
        return ["input"]

    @property
    def output_keys(self):
        return ["output"]

custom_chain = CustomChain(some_param="!")
result = custom_chain.run({"input": "Hello"})  # 结果: {"output": "Hello!"}

run(input_data)

run() 方法适用于处理单个输入数据并返回链的输出,常用于单次调用。通过传入数据并运行链,返回处理结果。

from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

# 定义提示模板和语言模型
prompt = PromptTemplate(template="Translate '{text}' to French.", input_variables=["text"])
llm = OpenAI(model_name="text-davinci-003")

# 创建 LLMChain
chain = LLMChain(prompt=prompt, llm=llm)

# 使用 run() 进行单次调用
result = chain.run(text="Hello, how are you?")
print(result)  # 输出法语翻译,例如:"Bonjour, comment ça va ?"

apply(inputs)

apply() 方法适用于批量输入处理,将多个输入同时传递给链,返回多个结果。将输入数据批量传递给链处理,返回多个结果。

示例代码

inputs = [{"text": "Hello, how are you?"}, {"text": "What is your name?"}, {"text": "Goodbye!"}]

# 使用 apply() 批量处理
results = chain.apply(inputs)
for res in results:
    print(res)  # 输出每个输入的法语翻译

from_chain_type()

from_chain_type() 是 LangChain 提供的便捷方法,用于根据预设链类型创建实例。可以快速创建常见链类型的实例,如 LLMChain、SequentialChain。 示例代码

chain = LLMChain.from_chain_type(llm=llm, chain_type="simple", prompt=prompt)

# 调用 run() 进行测试
result = chain.run(text="Thank you very much!")
print(result)  # 输出法语翻译,例如:"Merci beaucoup !"

2. LLMChain

LLMChain 用于将输入内容与提示词模板合并,并传递给语言模型(如 OpenAI 的 GPT-3 或 GPT-4),生成预测结果。

示例代码

from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

# 创建提示模板
prompt = PromptTemplate(template="Translate '{text}' to French.", input_variables=["text"])

# 实例化语言模型
llm = OpenAI(model_name="text-davinci-003")

# 创建链
chain = LLMChain(prompt=prompt, llm=llm)

# 调用链并传入输入数据
result = chain.run(text="Hello, how are you?")
print(result)  # 输出:翻译后的法语文本

常用方法:

predict(kwargs)

根据输入内容,利用语言模型生成预测结果。predict() 方法接收关键字参数 kwargs,可以将需要的输入内容(如 text)传入链条。该方法返回一个单一预测结果,适合单一任务的调用。

代码示例

from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

# 创建提示模板和语言模型
prompt = PromptTemplate(template="Translate '{text}' to French.", input_variables=["text"])
llm = OpenAI(model_name="text-davinci-003")

# 创建 LLMChain 实例
chain = LLMChain(prompt=prompt, llm=llm)

# 使用 predict() 方法进行单次调用
result = chain.predict(text="Hello, how are you?")
print(result)  # 输出法语翻译,例如:"Bonjour, comment ça va ?"

predict_multiple(prompts)

predict_multiple() 方法用于批量处理多个输入,可以一次性对多个提示生成预测结果。predict_multiple() 方法接收一个列表 prompts,每个列表项是一个字典,包含相应的输入内容。该方法返回一组预测结果,适合批量输入的情况。

代码示例

prompts = [
    {"text": "Hello, how are you?"},
    {"text": "What is your name?"},
    {"text": "Goodbye!"}
]

# 使用 predict_multiple() 方法进行批量预测
results = chain.predict_multiple(prompts=prompts)
for res in results:
    print(res)  # 输出每个输入的法语翻译,例如:"Bonjour, comment ça va ?", "Quel est votre nom ?", "Au revoir !"

3. SequentialChain

SequentialChain 用于串行执行多个链的情况。一个链的输出可以作为下一个链的输入。 常用方法:

run(input_data)

将输入数据依次传递给多个链,返回最终的输出。

add_chain(chain, output_key)

将一个链添加到 SequentialChain 中并指定输出键。

4. SimpleSequentialChain

SimpleSequentialChain 是 SequentialChain 的简化版,适合处理顺序关系简单的多链调用情况。


chain1 = LLMChain(prompt=PromptTemplate(template="Translate '{text}' to French.", input_variables=["text"]), llm=llm)
chain2 = LLMChain(prompt=PromptTemplate(template="Explain '{text}' in English.", input_variables=["text"]), llm=llm)

# 创建简单顺序链
simple_chain = SimpleSequentialChain(chains=[chain1, chain2])

# 运行简单顺序链
result = simple_chain.run("Hello, how are you?")
print(result)  # 输出:最终的解释结果

5. RouterChain

RouterChain 可以根据输入条件选择不同的链来运行,适合根据特定条件动态选择链的情况。

常用方法: route(input_data):根据条件(例如输入的特定值)路由到对应链。 add_route(route, chain):定义路由条件并将链与其关联。

代码示例


# 假设定义了多个子链
french_chain = LLMChain(prompt=PromptTemplate(template="Translate '{text}' to French.", input_variables=["text"]), llm=llm)
spanish_chain = LLMChain(prompt=PromptTemplate(template="Translate '{text}' to Spanish.", input_variables=["text"]), llm=llm)

# 创建路由链
route_chain = RouterChain(router={"french": french_chain, "spanish": spanish_chain})

# 根据条件选择链
result = route_chain.route("Hello, how are you?", route="french")
print(result)  # 输出:法语翻译

6. ConversationChain

ConversationChain 用于上下文保持的对话应用,通过在链调用之间传递会话上下文实现对话的连贯性。

from langchain.chains import ConversationChain

# 创建内存对象
memory = ConversationBufferMemory()

# 创建对话链并传入内存
conversation = ConversationChain(llm=llm, memory=memory)

# 运行多轮对话
result1 = conversation.run("Hello!")
result2 = conversation.run("How are you?")
result3 = conversation.run("Tell me more about Paris.")
print(result1, result2, result3)  # 输出多轮对话的结果

7. Memory 模块

Memory 模块可以独立使用,也可与链配合,用于管理链条之间的上下文,方便实现多轮对话或上下文管理。


# 使用摘要型内存记录对话要点
memory = ConversationSummaryMemory()

# 将内存与对话链绑定
conversation = ConversationChain(llm=llm, memory=memory)

# 模拟对话
result1 = conversation.run("What's the capital of France?")
result2 = conversation.run("What famous landmarks are there?")
print(result1, result2)  # 会保留前文摘要

通过将这些调用方式组合使用可以构建强大且灵活的应用。