分類目錄:《大模型從入門到應(yīng)用》總目錄
LangChain系列文章:
- 基礎(chǔ)知識(shí)
- 快速入門
- 安裝與環(huán)境配置
- 鏈(Chains)、代理(Agent:)和記憶(Memory)
- 快速開發(fā)聊天模型
- 模型(Models)
- 基礎(chǔ)知識(shí)
- 大型語言模型(LLMs)
- 基礎(chǔ)知識(shí)
- LLM的異步API、自定義LLM包裝器、虛假LLM和人類輸入LLM(Human Input LLM)
- 緩存LLM的調(diào)用結(jié)果
- 加載與保存LLM類、流式傳輸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í)
- 記憶的類型
- 會(huì)話緩存記憶、會(huì)話緩存窗口記憶和實(shí)體記憶
- 對話知識(shí)圖譜記憶、對話摘要記憶和會(huì)話摘要緩沖記憶
- 對話令牌緩沖存儲(chǔ)器和基于向量存儲(chǔ)的記憶
- 將記憶添加到LangChain組件中
- 自定義對話記憶與自定義記憶類
- 聊天消息記錄
- 記憶的存儲(chǔ)與應(yīng)用
- 索引(Indexes)
- 基礎(chǔ)知識(shí)
- 文檔加載器(Document Loaders)
- 文本分割器(Text Splitters)
- 向量存儲(chǔ)器(Vectorstores)
- 檢索器(Retrievers)
- 鏈(Chains)
- 基礎(chǔ)知識(shí)
- 通用功能
- 自定義Chain和Chain的異步API
- LLMChain和RouterChain
- SequentialChain和TransformationChain
- 鏈的保存(序列化)與加載(反序列化)
- 鏈與索引
- 文檔分析和基于文檔的聊天
- 問答的基礎(chǔ)知識(shí)
- 圖問答(Graph QA)和帶來源的問答(Q&A with Sources)
- 檢索式問答
- 文本摘要(Summarization)、HyDE和向量數(shù)據(jù)庫的文本生成
- 代理(Agents)
- 基礎(chǔ)知識(shí)
- 代理類型
- 自定義代理(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ò)誤、訪問中間步驟和限制最大迭代次數(shù)
- 為代理程序設(shè)置超時(shí)時(shí)間和限制最大迭代次數(shù)和為代理程序和其工具添加共享內(nèi)存
- 計(jì)劃與執(zhí)行
- 回調(diào)函數(shù)(Callbacks)
LLMChain
LLMChain是查詢LLM對象最流行的方式之一。它使用提供的輸入鍵值(如果有的話,還包括內(nèi)存鍵值)格式化提示模板,將格式化的字符串傳遞給LLM,并返回LLM的輸出。下面我們展示了LLMChain類的附加功能:
from langchain import PromptTemplate, OpenAI, LLMChain
prompt_template = "What is a good name for a company that makes {product}?"
llm = OpenAI(temperature=0)
llm_chain = LLMChain(
llm=llm,
prompt=PromptTemplate.from_template(prompt_template)
)
llm_chain("colorful socks")
輸出:
{'product': 'colorful socks', 'text': '\n\nSocktastic!'}
LLM鏈條的額外運(yùn)行方式
除了所有Chain對象共享的__call__
和run
方法之外,LLMChain還提供了幾種調(diào)用鏈條邏輯的方式:
-
apply
:允許我們對一組輸入運(yùn)行鏈:
input_list = [
{"product": "socks"},
{"product": "computer"},
{"product": "shoes"}
]
llm_chain.apply(input_list)
[{'text': '\n\nSocktastic!'},
{'text': '\n\nTechCore Solutions.'},
{'text': '\n\nFootwear Factory.'}]
-
generate
:與apply
類似,但返回一個(gè)LLMResult而不是字符串。LLMResult通常包含有用的生成信息,例如令牌使用情況和完成原因。
llm_chain.generate(input_list)
輸出:
LLMResult(generations=[[Generation(text='\n\nSocktastic!', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nTechCore Solutions.', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nFootwear Factory.', generation_info={'finish_reason': 'stop', 'logprobs': None})]], llm_output={'token_usage': {'prompt_tokens': 36, 'total_tokens': 55, 'completion_tokens': 19}, 'model_name': 'text-davinci-003'})
-
predict
:與run
方法類似,只是輸入鍵被指定為關(guān)鍵字參數(shù),而不是Python字典。
# Single input example
llm_chain.predict(product="colorful socks")
輸出:
'\n\nSocktastic!'
輸入:
# Multiple inputs example
template = """Tell me a {adjective} joke about {subject}."""
prompt = PromptTemplate(template=template, input_variables=["adjective", "subject"])
llm_chain = LLMChain(prompt=prompt, llm=OpenAI(temperature=0))
llm_chain.predict(adjective="sad", subject="ducks")
輸出:
'\n\nQ: What did the duck say when his friend died?\nA: Quack, quack, goodbye.'
解析輸出結(jié)果
默認(rèn)情況下,即使底層的prompt
對象具有輸出解析器,LLMChain也不會(huì)解析輸出結(jié)果。如果你想在LLM輸出上應(yīng)用輸出解析器,可以使用predict_and_parse
代替predict
,以及apply_and_parse
代替apply
。
僅使用predict
方法:
from langchain.output_parsers import CommaSeparatedListOutputParser
output_parser = CommaSeparatedListOutputParser()
template = """List all the colors in a rainbow"""
prompt = PromptTemplate(template=template, input_variables=[], output_parser=output_parser)
llm_chain = LLMChain(prompt=prompt, llm=llm)
llm_chain.predict()
輸出:
'\n\nRed, orange, yellow, green, blue, indigo, violet'
使用predict_and_parser
方法:
llm_chain.predict_and_parse()
輸出:
['Red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
從字符串模板初始化
我們還可以直接使用字符串模板構(gòu)建一個(gè)LLMChain。
template = """Tell me a {adjective} joke about {subject}."""
llm_chain = LLMChain.from_string(llm=llm, template=template)
llm_chain.predict(adjective="sad", subject="ducks")
輸出:
'\n\nQ: What did the duck say when his friend died?\nA: Quack, quack, goodbye.'
RouterChain
本節(jié)演示了如何使用RouterChain創(chuàng)建一個(gè)根據(jù)給定輸入動(dòng)態(tài)選擇下一個(gè)鏈條的鏈條。RouterChain通常由兩個(gè)組件組成:
- 路由鏈本身(負(fù)責(zé)選擇下一個(gè)要調(diào)用的鏈條)
- 目標(biāo)鏈條,即路由鏈可以路由到的鏈條
本節(jié)中,我們將重點(diǎn)介紹不同類型的路由鏈。我們將展示這些路由鏈在MultiPromptChain
中的應(yīng)用,創(chuàng)建一個(gè)問題回答鏈條,根據(jù)給定的問題選擇最相關(guān)的提示,然后使用該提示回答問題。
from langchain.chains.router import MultiPromptChain
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.chains.llm import LLMChain
from langchain.prompts import PromptTemplate
physics_template = """You are a very smart physics professor. \
You are great at answering questions about physics in a concise and easy to understand manner. \
When you don't know the answer to a question you admit that you don't know.
Here is a question:
{input}"""
math_template = """You are a very good mathematician. You are great at answering math questions. \
You are so good because you are able to break down hard problems into their component parts, \
answer the component parts, and then put them together to answer the broader question.
Here is a question:
{input}"""
prompt_infos = [
{
"name": "physics",
"description": "Good for answering questions about physics",
"prompt_template": physics_template
},
{
"name": "math",
"description": "Good for answering math questions",
"prompt_template": math_template
}
]
llm = OpenAI()
destination_chains = {}
for p_info in prompt_infos:
name = p_info["name"]
prompt_template = p_info["prompt_template"]
prompt = PromptTemplate(template=prompt_template, input_variables=["input"])
chain = LLMChain(llm=llm, prompt=prompt)
destination_chains[name] = chain
default_chain = ConversationChain(llm=llm, output_key="text")
LLMRouterChain
LLMRouterChain鏈條使用一個(gè)LLM來確定如何進(jìn)行路由。
from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser
from langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE
destinations = [f"{p['name']}: {p['description']}" for p in prompt_infos]
destinations_str = "\n".join(destinations)
router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(
destinations=destinations_str
)
router_prompt = PromptTemplate(
template=router_template,
input_variables=["input"],
output_parser=RouterOutputParser(),
)
router_chain = LLMRouterChain.from_llm(llm, router_prompt)
chain = MultiPromptChain(router_chain=router_chain, destination_chains=destination_chains, default_chain=default_chain, verbose=True)
print(chain.run("What is black body radiation?"))
日志輸出:
> Entering new MultiPromptChain chain...
physics: {'input': 'What is black body radiation?'}
> Finished chain.
輸出:
Black body radiation is the term used to describe the electromagnetic radiation emitted by a “black body”—an object that absorbs all radiation incident upon it. A black body is an idealized physical body that absorbs all incident electromagnetic radiation, regardless of frequency or angle of incidence. It does not reflect, emit or transmit energy. This type of radiation is the result of the thermal motion of the body's atoms and molecules, and it is emitted at all wavelengths. The spectrum of radiation emitted is described by Planck's law and is known as the black body spectrum.
輸入:
print(chain.run("What is the first prime number greater than 40 such that one plus the prime number is divisible by 3"))
輸出:
> Entering new MultiPromptChain chain...
math: {'input': 'What is the first prime number greater than 40 such that one plus the prime number is divisible by 3'}
> Finished chain.
輸出:文章來源:http://www.zghlxwxcb.cn/news/detail-663152.html
The answer is 43. One plus 43 is 44 which is divisible by 3.
輸入:
print(chain.run("What is the name of the type of cloud that rins"))
日志輸出:
> Entering new MultiPromptChain chain...
None: {'input': 'What is the name of the type of cloud that rains?'}
> Finished chain.
輸出:
The type of cloud that rains is called a cumulonimbus cloud. It is a tall and dense cloud that is often accompanied by thunder and lightning.
EmbeddingRouterChain
EmbeddingRouterChain使用嵌入和相似性來在目標(biāo)鏈條之間進(jìn)行路由。
from langchain.chains.router.embedding_router import EmbeddingRouterChain
from langchain.embeddings import CohereEmbeddings
from langchain.vectorstores import Chroma
names_and_descriptions = [
("physics", ["for questions about physics"]),
("math", ["for questions about math"]),
]
router_chain = EmbeddingRouterChain.from_names_and_descriptions(
names_and_descriptions, Chroma, CohereEmbeddings(), routing_keys=["input"]
)
chain = MultiPromptChain(router_chain=router_chain, destination_chains=destination_chains, default_chain=default_chain, verbose=True)
print(chain.run("What is black body radiation?"))
日志輸出:
> Entering new MultiPromptChain chain...
physics: {'input': 'What is black body radiation?'}
> Finished chain.
輸出:
Black body radiation is the emission of energy from an idealized physical body (known as a black body) that is in thermal equilibrium with its environment. It is emitted in a characteristic pattern of frequencies known as a black-body spectrum, which depends only on the temperature of the body. The study of black body radiation is an important part of astrophysics and atmospheric physics, as the thermal radiation emitted by stars and planets can often be approximated as black body radiation.
輸入:
print(chain.run("What is the first prime number greater than 40 such that one plus the prime number is divisible by 3"))
日志輸出:
> Entering new MultiPromptChain chain...
math: {'input': 'What is the first prime number greater than 40 such that one plus the prime number is divisible by 3'}
> Finished chain.
輸出:
Answer: The first prime number greater than 40 such that one plus the prime number is divisible by 3 is 43.
參考文獻(xiàn):
[1] LangChain官方網(wǎng)站:https://www.langchain.com/
[2] LangChain ????? 中文網(wǎng),跟著LangChain一起學(xué)LLM/GPT開發(fā):https://www.langchain.com.cn/
[3] LangChain中文網(wǎng) - LangChain 是一個(gè)用于開發(fā)由語言模型驅(qū)動(dòng)的應(yīng)用程序的框架:http://www.cnlangchain.com/文章來源地址http://www.zghlxwxcb.cn/news/detail-663152.html
到了這里,關(guān)于自然語言處理從入門到應(yīng)用——LangChain:鏈(Chains)-[通用功能:LLMChain、RouterChain和SequentialChain]的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!