LangChain之Chain

LangChain中的Chain(链)指的是一个具有输入和输出的单独组件的模型。

LLMChain是最常见的链式模型之一。它由PromptTemplate、模型(LLM或ChatModel)和OutputParser(输出解析器,可选)组成。LLMChain可以接受多个输入变量,通过PromptTemplate将它们格式化为特定的Prompt。然后将其传递给LLM模型。最后,如果提供了OutputParser,则使用OutputParser将LLM的输出解析为用户期望的格式。

将LLM和Prompts结合在多步骤的工作流中,使用LLMChain 有许多链式搜索的应用程序可以查看哪些最适合您的用例。 下面的连接包含了很多使用chain的应用,https://python.langchain.com/en/latest/modules/chains/how_to_guides.html

简单链

## 导入基础库
from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.chains import SimpleSequentialChain
llm = OpenAI(temperature=1, openai_api_key=openai_api_key)
## 建立模板
template = '''你的任务是根据用户所提供的地区给出相应的菜肴
% USER LOCATION
{user_location}

你的回复:
'''
prompt_template = PromptTemplate(input_variables=["user_location"], template=template)
# 建立location的chain
location_chain = LLMChain(llm=llm, prompt=prompt_template)
## 接下来获取chain的返回结果输入到下一个chain中

mealtemplate = '''给你一个菜肴,请告诉我如何在家做那道菜,给出具体的步骤来、
% MEAL
{user_meal}

您的回复:
'''
prompt_template = PromptTemplate(input_variables=["user_meal"], template=mealtemplate)
location_chain = LLMChain(llm=llm, prompt=prompt_template)
# 建立meal的chain
meal_chain = LLMChain(llm=llm, prompt=prompt_template)
# 建立简单链
overall_chain = SimpleSequentialChain(chains=[location_chain, meal_chain], verbose=True)
review = overall_chain.run("湖北")

代码使用SimpleSequentialChain类创建一个表示任务链的对象。对象接受一个链列表和一个详细参数作为参数。verbose参数是一个布尔值,控制对象是否打印关于链执行的一些信息。如果verbose为True,对象将打印每个链的名称以及每个任务的输入和输出变量。如果verbose为False,对象将不输出任何内容。

总结链

很容易运行通过长期大量的文档,并得到一个摘要。检查这个视频的其他链类型除了 map-reduce

# 导入基础库
from langchain.chains.summarize import load_summarize_chain
from langchain.document_loaders import TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
# 导入文档
loader = TextLoader('data/PaulGrahamEssays/disc.txt')
documents = loader.load()

# 拆分文档内容
text_splitter = RecursiveCharacterTextSplitter(chunk_size=700, chunk_overlap=50)
texts = text_splitter.split_documents(documents)

# There is a lot of complexity hidden in this one line. I encourage you to check out the video above for more detail
chain = load_summarize_chain(llm, chain_type="map_reduce", verbose=True)
chain.run(texts)

定制链

LangChain 提供了很多现成的链接,但是有时候您可能想要为您的特定用例创建一个自定义链接。我们将创建一个自定义链,用于连接2个 LLMChains 的输出。 定制链的步骤 1. Chain 类的子类化,类的方法重写 2. 填写 input _ key 和 output _ key 属性 3. 添加显示如何执行链的 _ call 方法

from langchain.chains import LLMChain
from langchain.chains.base import Chain

from typing import Dict, List


class ConcatenateChain(Chain):
    chain_1: LLMChain
    chain_2: LLMChain

    @property
    def input_keys(self) -> List[str]:
        # 两个input_key的并集
        all_input_vars = set(self.chain_1.input_keys).union(set(self.chain_2.input_keys))
        return list(all_input_vars)

    @property
    def output_keys(self) -> List[str]:
        return ['concat_output']

    def _call(self, inputs: Dict[str, str]) -> Dict[str, str]:
        output_1 = self.chain_1.run(inputs)
        output_2 = self.chain_2.run(inputs)
        return {'concat_output': output_1 + output_2}
prompt_1 = PromptTemplate(
    input_variables=["product"],
    template="请给我生产 {product} 的公司的名称?",
)
chain_1 = LLMChain(llm=llm, prompt=prompt_1)

prompt_2 = PromptTemplate(
    input_variables=["product"],
    template="请给我生产制作{product}的公司的口号?",
)
chain_2 = LLMChain(llm=llm, prompt=prompt_2)
## 连接chain
concat_chain = ConcatenateChain(chain_1=chain_1, chain_2=chain_2)
concat_output = concat_chain.run("彩色的袜子")
print(f"Concatenated output:
{concat_output}")

Concatenated output: Rainbow Socks Co. "Step Into Colorful Comfort!"

集成Chain

LLM math,集成python,调用python来进行数学运算,返回相应的结果

# 调用LLMMath
from langchain import OpenAI, LLMMathChain

llm = OpenAI(temperature=0)
llm_math = LLMMathChain(llm=llm, verbose=True)

llm_math.run("What is 13 raised to the .3432 power?")

结果如下所示

> Entering new LLMMathChain chain...
What is 13 raised to the .3432 power?
import math
print(math.pow(13, .3432))
Answer: 2.4116004626599237

> Finished chain.

调用python很好的解决了chatgpt较弱的数理能力,上述过程也可以理解为chatgpt的插件模式 以下是一些常见的集成链及其功能。 LLM Math:结合Python解释器完成数据计算 SQLDatabaseChain:集合sqlite数据库完成查询 qa_with_sources:基于多个文档进行问答(底层用到Netwokx) LLMRequestChain:请求指定url查询结果,并用llm解释 PALChain:生成代码并运行得出结果 APIChain:根据api文档生成api请求

networkx是一个用Python语言开发的图论与复杂网络建模工具,内置了常用的图与复杂网络分析算法,可以方便的进行复杂网络数据分析、仿真建模等工作。

展开阅读全文

页面更新:2024-05-01

标签:链式   建模   菜肴   变量   模型   步骤   对象   名称   文档   网络

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top