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:\n{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語言開發的圖論與複雜網絡模組化工具,内置了常用的圖與複雜網絡分析算法,可以友善的進行複雜網絡資料分析、仿真模組化等工作。