久久ER99热精品一区二区-久久精品99国产精品日本-久久精品免费一区二区三区-久久综合九色综合欧美狠狠

博客專欄

EEPW首頁 > 博客 > 獨家 | 開始使用LangChain:幫助你構建LLM驅動應用的新手教程(2)

獨家 | 開始使用LangChain:幫助你構建LLM驅動應用的新手教程(2)

發布人:數據派THU 時間:2023-07-16 來源:工程師 發布文章

提示: 管理LLM輸入


LLM有怪異的api。盡管用自然語言向LLM輸入提示應該感覺很直觀,但在從LLM獲得所需的輸出之前,需要對提示進行大量調整。這個過程稱為提示工程。一旦有了好的提示,您可能希望將其用作其他目的的模板。因此,LangChain為您提供了所謂的提示模板,可幫助您從多個組件構建提示。

from langchain import PromptTemplate
template = "What is a good name for a company that makes {product}?"
prompt = PromptTemplate(    input_variables=["product"],    template=template,)
prompt.format(product="colorful socks")


上面的提示可以看作是Zero-shot Learning(零射擊學習是一種設置,模型可以學習識別以前在訓練中沒有明確看到的事物),您希望LLM在足夠的相關數據上進行了訓練,以提供令人滿意的結果。改善LLM輸出的另一個技巧是在提示中添加一些示例,并使其成為一些問題設置。

from langchain import PromptTemplate, FewShotPromptTemplate
examples = [    {"word": "happy", "antonym": "sad"},    {"word": "tall", "antonym": "short"},]
example_template = """Word: {word}Antonym: {antonym}\n"""
example_prompt = PromptTemplate(    input_variables=["word", "antonym"],    template=example_template,)
few_shot_prompt = FewShotPromptTemplate(    examples=examples,    example_prompt=example_prompt,    prefix="Give the antonym of every input",    suffix="Word: {input}\nAntonym:",    input_variables=["input"],    example_separator="\n",)
few_shot_prompt.format(input="big")


上面的代碼將生成一個提示模板,并根據提供的示例和輸入組成以下提示:

Give the antonym of every input
Word: happyAntonym: sad


Word: tallAntonym: short

Word: bigAntonym:


Chain: 將LLMs與其他組件組合
在LangChain中Chain簡單地描述了將LLMs與其他組件組合以創建應用程序的過程。一些示例是: 將LLM與提示模板組合 (請參閱本節),通過將第一個LLM的輸出作為第二個LLM的輸入來順序組合多個LLM (請參閱本節),將LLM與外部數據組合,例如,對于問題回答 (請參閱索引),將LLM與長期記憶相結合,例如,對于上一節中的聊天記錄 (請參閱內存),我們創建了一個提示模板。當我們想將其與我們的LLM一起使用時,我們可以使用LLMChain,如下所示:

from langchain.chains import LLMChain
chain = LLMChain(llm = llm,                  prompt = prompt)
# Run the chain only specifying the input variable.chain.run("colorful socks")

如果我們想使用這個第一個LLM的輸出作為第二個LLM的輸入,我們可以使用一個SimpleSequentialChain:
from langchain.chains import LLMChain, SimpleSequentialChain
# Define the first chain as in the previous code example# ...
# Create a second chain with a prompt template and an LLMsecond_prompt = PromptTemplate(    input_variables=["company_name"],    template="Write a catchphrase for the following company: {company_name}",)
chain_two = LLMChain(llm=llm, prompt=second_prompt)
# Combine the first and the second chain 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")

圖片

結果示例


索引:訪問外部數據
LLM的一個限制是它們缺乏上下文信息 (例如,訪問某些特定文檔或電子郵件)。您可以通過允許LLMs訪問特定的外部數據來解決此問題。為此,您首先需要使用文檔加載器加載外部數據。LangChain為不同類型的文檔提供了各種加載程序,從pdf和電子郵件到網站和YouTube視頻。讓我們從YouTube視頻中加載一些外部數據。如果你想加載一個大的文本文檔并用文本拆分器拆分它,你可以參考官方文檔。

# pip install youtube-transcript-api# pip install pytube
from langchain.document_loaders import YoutubeLoader
loader = YoutubeLoader.from_youtube_url("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
documents = loader.load()


現在,您已經準備好外部數據作為文檔,您可以使用矢量數據庫 (VectorStore) 中的文本嵌入模型 (請參閱模型) 對其進行索引。流行的矢量數據庫包括Pinecone,weavviate和Milvus。在本文中,我們使用的是Faiss,因為它不需要API密鑰。

# pip install faiss-cpufrom langchain.vectorstores import FAISS
# create the vectorestore to use as the indexdb = FAISS.from_documents(documents, embeddings)

您的文檔 (在本例中為視頻) 現在作為嵌入存儲在矢量存儲中。現在你可以用這個外部數據做各種各樣的事情。讓我們將其用于帶有信息尋回器的問答任務:

from langchain.chains import RetrievalQA
retriever = db.as_retriever()
qa = RetrievalQA.from_chain_type(    llm=llm,    chain_type="stuff",    retriever=retriever,    return_source_documents=True)
query = "What am I never going to do?"result = qa({"query": query})
print(result['result'])


圖片

結果示例


存儲器: 記住先前的對話
對于像聊天機器人這樣的應用程序來說,他們能夠記住以前的對話是至關重要的。但是默認情況下,LLMs沒有任何長期記憶,除非您輸入聊天記錄。


圖片有無記憶的聊天機器人的對比


LangChain通過提供處理聊天記錄的幾種不同選項來解決此問題:

  • 保留所有對話
  • 保留最新的k對話
  • 總結對話


在這個例子中,我們將使用ConversationChain作為這個應用程序會話內存。

from langchain import ConversationChain
conversation = ConversationChain(llm=llm, verbose=True)
conversation.predict(input="Alice has a parrot.")
conversation.predict(input="Bob has two cats.")
conversation.predict(input="How many pets do Alice and Bob have?")


這將生成上圖中的右手對話。如果沒有ConversationChain來保持對話記憶,對話將看起來像上圖中左側的對話。
代理: 訪問其他工具
盡管LLMs非常強大,但仍有一些局限性: 它們缺乏上下文信息 (例如,訪問訓練數據中未包含的特定知識),它們可能很快就會過時 (例如,GPT-4在2021年9月之前就接受了數據培訓),并且他們不擅長數學。
因為LLM可能會對自己無法完成的任務產生幻覺,所以我們需要讓他們訪問補充工具,例如搜索 (例如Google搜索),計算器 (例如Python REPL或Wolfram Alpha) 和查找 (例如,維基百科)。此外,我們需要代理根據LLM的輸出來決定使用哪些工具來完成任務。
請注意,某些LLM(例如google/flan-t5-xl) 不適用于以下示例,因為它們不遵循會話-反應-描述模板。對我來說,這是我在OpenAI上設置付費帳戶并切換到OpenAI API的原因。
下面是一個例子,代理人首先用維基百科查找奧巴馬的出生日期,然后用計算器計算他2022年的年齡。

# pip install wikipediafrom langchain.agents import load_toolsfrom langchain.agents import initialize_agentfrom langchain.agents import AgentType
tools = load_tools(["wikipedia", "llm-math"], llm=llm)agent = initialize_agent(tools,                         llm,                         agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,                         verbose=True)

agent.run("When was Barack Obama born? How old was he in 2022?")


圖片

結果圖片
總結
就在幾個月前,我們所有人 (或至少我們大多數人) 都對ChatGPT的功能印象深刻。現在,像LangChain這樣的新開發人員工具使我們能夠在幾個小時內在筆記本電腦上構建同樣令人印象深刻的原型--這是一些真正令人興奮的時刻!
LangChain是一個開源的Python庫,它使任何可以編寫代碼的人都可以構建以LLM為動力的應用程序。該軟件包為許多基礎模型提供了通用接口,可以進行提示管理,并在撰寫本文時通過代理充當其他組件 (如提示模板,其他LLM,外部數據和其他工具) 的中央接口。該庫提供了比本文中提到的更多的功能。以目前的發展速度,這篇文章也可能在一個月內過時。
在撰寫本文時,我注意到庫和文檔圍繞OpenAI的API展開。盡管許多示例與開源基礎模型google/flan-t5-xl一起使用,但我在兩者之間選擇了OpenAI API。盡管不是免費的,但在本文中嘗試OpenAI API只花了我大約1美元。


原文標題:Getting Started with LangChain: A Beginner’s Guide to Building LLM-Powered Applications原文鏈接:https://towardsdatascience.com/getting-started-with-langchain-a-beginners-guide-to-building-llm-powered-applications-95fc8898732c


*博客內容為網友個人發布,僅代表博主個人觀點,如有侵權請聯系工作人員刪除。



關鍵詞: AI

相關推薦

技術專區

關閉