分類(lèi)目錄:《大模型從入門(mén)到應(yīng)用》總目錄
LangChain系列文章:
- 基礎(chǔ)知識(shí)
- 快速入門(mén)
- 安裝與環(huán)境配置
- 鏈(Chains)、代理(Agent:)和記憶(Memory)
- 快速開(kāi)發(fā)聊天模型
- 模型(Models)
- 基礎(chǔ)知識(shí)
- 大型語(yǔ)言模型(LLMs)
- 基礎(chǔ)知識(shí)
- LLM的異步API、自定義LLM包裝器、虛假LLM和人類(lèi)輸入LLM(Human Input LLM)
- 緩存LLM的調(diào)用結(jié)果
- 加載與保存LLM類(lèi)、流式傳輸LLM與Chat Model響應(yīng)和跟蹤tokens使用情況
- 聊天模型(Chat Models)
- 基礎(chǔ)知識(shí)
- 使用少量示例和響應(yīng)流式傳輸
- 文本嵌入模型
- Aleph Alpha、Amazon Bedrock、Azure OpenAI、Cohere等
- Embaas、Fake Embeddings、Google Vertex AI PaLM等
- 提示(Prompts)
- 基礎(chǔ)知識(shí)
- 提示模板
- 基礎(chǔ)知識(shí)
- 連接到特征存儲(chǔ)
- 創(chuàng)建自定義提示模板和含有Few-Shot示例的提示模板
- 部分填充的提示模板和提示合成
- 序列化提示信息
- 示例選擇器(Example Selectors)
- 輸出解析器(Output Parsers)
- 記憶(Memory)
- 基礎(chǔ)知識(shí)
- 記憶的類(lèi)型
- 會(huì)話緩存記憶、會(huì)話緩存窗口記憶和實(shí)體記憶
- 對(duì)話知識(shí)圖譜記憶、對(duì)話摘要記憶和會(huì)話摘要緩沖記憶
- 對(duì)話令牌緩沖存儲(chǔ)器和基于向量存儲(chǔ)的記憶
- 將記憶添加到LangChain組件中
- 自定義對(duì)話記憶與自定義記憶類(lèi)
- 聊天消息記錄
- 記憶的存儲(chǔ)與應(yīng)用
- 索引(Indexes)
- 基礎(chǔ)知識(shí)
- 文檔加載器(Document Loaders)
- 文本分割器(Text Splitters)
- 向量存儲(chǔ)器(Vectorstores)
- 檢索器(Retrievers)
- 鏈(Chains)
- 基礎(chǔ)知識(shí)
- 通用功能
- 自定義Chain和Chain的異步API
- LLMChain和RouterChain
- SequentialChain和TransformationChain
- 鏈的保存(序列化)與加載(反序列化)
- 鏈與索引
- 文檔分析和基于文檔的聊天
- 問(wèn)答的基礎(chǔ)知識(shí)
- 圖問(wèn)答(Graph QA)和帶來(lái)源的問(wèn)答(Q&A with Sources)
- 檢索式問(wèn)答
- 文本摘要(Summarization)、HyDE和向量數(shù)據(jù)庫(kù)的文本生成
- 代理(Agents)
- 基礎(chǔ)知識(shí)
- 代理類(lèi)型
- 自定義代理(Custom Agent)
- 自定義MRKL代理
- 帶有ChatModel的LLM聊天自定義代理和自定義多操作代理(Custom MultiAction Agent)
- 工具
- 基礎(chǔ)知識(shí)
- 自定義工具(Custom Tools)
- 多輸入工具和工具輸入模式
- 人工確認(rèn)工具驗(yàn)證和Tools作為OpenAI函數(shù)
- 工具包(Toolkit)
- 代理執(zhí)行器(Agent Executor)
- 結(jié)合使用Agent和VectorStore
- 使用Agents的異步API和創(chuàng)建ChatGPT克隆
- 處理解析錯(cuò)誤、訪問(wèn)中間步驟和限制最大迭代次數(shù)
- 為代理程序設(shè)置超時(shí)時(shí)間和限制最大迭代次數(shù)和為代理程序和其工具添加共享內(nèi)存
- 計(jì)劃與執(zhí)行
- 回調(diào)函數(shù)(Callbacks)
在本文中,我們將學(xué)習(xí)如何在LangChain中創(chuàng)建簡(jiǎn)單的鏈?zhǔn)竭B接并添加組件以及運(yùn)行它。鏈?zhǔn)竭B接允許我們將多個(gè)組件組合在一起,創(chuàng)建一個(gè)統(tǒng)一的應(yīng)用程序。例如,我們可以創(chuàng)建一個(gè)鏈?zhǔn)竭B接,接收用戶輸入,使用PromptTemplate
對(duì)其進(jìn)行格式化,然后將格式化后的響應(yīng)傳遞給LLM。我們可以通過(guò)將多個(gè)鏈?zhǔn)竭B接組合在一起或?qū)㈡準(zhǔn)竭B接與其他組件組合來(lái)構(gòu)建更復(fù)雜的鏈?zhǔn)竭B接。
快速入門(mén):使用LLMChain
LLMChain是一個(gè)簡(jiǎn)單的鏈?zhǔn)竭B接,它接收一個(gè)prompt
模板,使用用戶輸入對(duì)其進(jìn)行格式化,并返回LLM的響應(yīng)。要使用LLMChain,首先創(chuàng)建一個(gè)prompt
模板。
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
現(xiàn)在,我們可以創(chuàng)建一個(gè)非常簡(jiǎn)單的鏈?zhǔn)竭B接,它將接收用戶輸入,使用它來(lái)格式化prompt
,并將其發(fā)送到LLM。
from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)
# 僅指定輸入變量運(yùn)行鏈?zhǔn)竭B接。
print(chain.run("colorful socks"))
輸出:
Colorful Toes Co.
如果有多個(gè)變量,我們可以使用字典一次輸入它們。
prompt = PromptTemplate(
input_variables=["company", "product"],
template="What is a good name for {company} that makes {product}?",
)
chain = LLMChain(llm=llm, prompt=prompt)
print(chain.run({
'company': "ABC Startup",
'product': "colorful socks"
}))
輸出:
Socktopia Colourful Creations.
我們也可以在LLMChain中使用聊天模型:
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
)
human_message_prompt = HumanMessagePromptTemplate(
prompt=PromptTemplate(
template="What is a good name for a company that makes {product}?",
input_variables=["product"],
)
)
chat_prompt_template = ChatPromptTemplate.from_messages([human_message_prompt])
chat = ChatOpenAI(temperature=0.9)
chain = LLMChain(llm=chat, prompt=chat_prompt_template)
print(chain.run("colorful socks"))
輸出:
Rainbow Socks Co.
調(diào)用鏈?zhǔn)竭B接的不同方式
所有繼承自Chain
的類(lèi)都提供了幾種運(yùn)行鏈?zhǔn)竭B接邏輯的方式。其中最直接的一種方式是使用 __call__
:
chat = ChatOpenAI(temperature=0)
prompt_template = "Tell me a {adjective} joke"
llm_chain = LLMChain(
llm=chat,
prompt=PromptTemplate.from_template(prompt_template)
)
llm_chain(inputs={"adjective":"corny"})
輸出:
{'adjective': 'corny',
'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}
默認(rèn)情況下,__call__
方法會(huì)返回輸入和輸出的鍵值對(duì)。我們可以通過(guò)將return_only_outputs
設(shè)置為True
來(lái)配置它僅返回輸出的鍵值對(duì)。
llm_chain("corny", return_only_outputs=True)
{'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}
如果Chain
只輸出一個(gè)輸出鍵(即其output_keys
中只有一個(gè)元素),則可以使用run
方法。需要注意的是,run
方法輸出一個(gè)字符串而不是字典。
# llm_chain only has one output key, so we can use run
llm_chain.output_keys
輸出:
['text']
輸入:
llm_chain.run({"adjective":"corny"})
輸出:
'Why did the tomato turn red? Because it saw the salad dressing!'
在只有一個(gè)輸入鍵的情況下,我們可以直接輸入字符串,無(wú)需指定輸入映射。
# These two are equivalent
llm_chain.run({"adjective":"corny"})
llm_chain.run("corny")
# These two are also equivalent
llm_chain("corny")
llm_chain({"adjective":"corny"})
輸出:
{'adjective': 'corny',
'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}
我們可以通過(guò)Chain
對(duì)象的run
方法將其作為Agent
中的Tool
進(jìn)行簡(jiǎn)單集成。
為鏈?zhǔn)竭B接添加記憶
Chain
支持將BaseMemory
對(duì)象作為其memory
參數(shù),從而使Chain
對(duì)象能夠在多次調(diào)用之間保留數(shù)據(jù)。換句話說(shuō),memory
參數(shù)使Chain
成為一個(gè)有狀態(tài)的對(duì)象。
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
conversation = ConversationChain(
llm=chat,
memory=ConversationBufferMemory()
)
conversation.run("Answer briefly. What are the first 3 colors of a rainbow?")
# -> The first three colors of a rainbow are red, orange, and yellow.
conversation.run("And the next 4?")
# -> The next four colors of a rainbow are green, blue, indigo, and violet.
輸出:
'The next four colors of a rainbow are green, blue, indigo, and violet.'
基本上,BaseMemory
定義了langchain
存儲(chǔ)記憶的接口。它允許通過(guò)load_memory_variables
方法讀取存儲(chǔ)的數(shù)據(jù),并通過(guò)save_context
方法存儲(chǔ)新數(shù)據(jù)。我們可以在《自然語(yǔ)言處理從入門(mén)到應(yīng)用——LangChain:記憶(Memory》系列文章了解更多信息。
調(diào)試鏈?zhǔn)竭B接
僅從輸出中調(diào)試Chain
對(duì)象可能會(huì)很困難,因?yàn)榇蠖鄶?shù)Chain
對(duì)象涉及相當(dāng)數(shù)量的輸入prompt
預(yù)處理和LLM輸出后處理。將verbose
設(shè)置為True
將在運(yùn)行時(shí)打印出Chain
對(duì)象的一些內(nèi)部狀態(tài)。
conversation = ConversationChain(
llm=chat,
memory=ConversationBufferMemory(),
verbose=True
)
conversation.run("What is ChatGPT?")
日志輸出:
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: What is ChatGPT?
AI:
> Finished chain.
輸出:
'ChatGPT is an AI language model developed by OpenAI. It is based on the GPT-3 architecture and is capable of generating human-like responses to text prompts. ChatGPT has been trained on a massive amount of text data and can understand and respond to a wide range of topics. It is often used for chatbots, virtual assistants, and other conversational AI applications.'
使用SequentialChain將鏈?zhǔn)竭B接組合起來(lái)
在調(diào)用語(yǔ)言模型之后的下一步是對(duì)語(yǔ)言模型進(jìn)行一系列的調(diào)用。我們可以使用順序鏈?zhǔn)竭B接來(lái)實(shí)現(xiàn)這一點(diǎn),順序鏈?zhǔn)竭B接按照預(yù)定義的順序執(zhí)行其鏈接。具體而言,我們將使用SimpleSequentialChain
。這是最簡(jiǎn)單的順序鏈?zhǔn)竭B接類(lèi)型,其中每個(gè)步驟都具有單個(gè)輸入/輸出,一個(gè)步驟的輸出是下一個(gè)步驟的輸入。在本文中,我們的順序鏈?zhǔn)竭B接將首先為產(chǎn)品創(chuàng)建一個(gè)公司名稱(chēng),我們將重用之前初始化的LLMChain
來(lái)創(chuàng)建這個(gè)公司名稱(chēng)。然后再為產(chǎn)品創(chuàng)建一個(gè)口號(hào)。我們將初始化一個(gè)新的LLMChain
來(lái)創(chuàng)建這個(gè)口號(hào):
second_prompt = PromptTemplate(
input_variables=["company_name"],
template="Write a catchphrase for the following company: {company_name}",
)
chain_two = LLMChain(llm=llm, prompt=second_prompt)
現(xiàn)在我們可以將這兩個(gè)LLMChain結(jié)合起來(lái),這樣我們就可以一步創(chuàng)建一個(gè)公司名稱(chēng)和一個(gè)標(biāo)語(yǔ)。
from langchain.chains import SimpleSequentialChain
overall_chain = SimpleSequentialChain(chains=[chain, chain_two], verbose=True)
# Run the chain specifying only the input variable for the first chain.
catchphrase = overall_chain.run("colorful socks")
print(catchphrase)
日志輸出:
> Entering new SimpleSequentialChain chain...
Rainbow Socks Co.
"Put a little rainbow in your step!"
> Finished chain.
輸出:
"Put a little rainbow in your step!"
使用Chain類(lèi)創(chuàng)建自定義鏈?zhǔn)竭B接
LangChain提供了許多現(xiàn)成的鏈?zhǔn)竭B接,但有時(shí)我們可能希望為特定的用例創(chuàng)建自定義鏈?zhǔn)竭B接。在這個(gè)例子中,我們將創(chuàng)建一個(gè)自定義鏈?zhǔn)竭B接,它將兩個(gè)LLMChain的輸出連接起來(lái)。
要?jiǎng)?chuàng)建一個(gè)自定義鏈?zhǔn)竭B接:
- 創(chuàng)建一個(gè)
Chain
類(lèi)的子類(lèi) - 填寫(xiě)
input_keys
和output_keys
屬性 - 添加
_call
方法,展示如何執(zhí)行鏈?zhǔn)竭B接
下面的示例演示了這些步驟:
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]:
# Union of the input keys of the two chains.
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}
現(xiàn)在,我們可以嘗試運(yùn)行我們調(diào)用的鏈:
prompt_1 = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
chain_1 = LLMChain(llm=llm, prompt=prompt_1)
prompt_2 = PromptTemplate(
input_variables=["product"],
template="What is a good slogan for a company that makes {product}?",
)
chain_2 = LLMChain(llm=llm, prompt=prompt_2)
concat_chain = ConcatenateChain(chain_1=chain_1, chain_2=chain_2)
concat_output = concat_chain.run("colorful socks")
print(f"Concatenated output:\n{concat_output}")
輸出:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-664276.html
Concatenated output:
Funky Footwear Company
"Brighten Up Your Day with Our Colorful Socks!"
參考文獻(xiàn):
[1] LangChain官方網(wǎng)站:https://www.langchain.com/
[2] LangChain ????? 中文網(wǎng),跟著LangChain一起學(xué)LLM/GPT開(kāi)發(fā):https://www.langchain.com.cn/
[3] LangChain中文網(wǎng) - LangChain 是一個(gè)用于開(kāi)發(fā)由語(yǔ)言模型驅(qū)動(dòng)的應(yīng)用程序的框架:http://www.cnlangchain.com/文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-664276.html
到了這里,關(guān)于自然語(yǔ)言處理從入門(mén)到應(yīng)用——LangChain:鏈(Chains)-[基礎(chǔ)知識(shí)]的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!