什么是LangChain
LangChain是一個強(qiáng)大的框架,旨在幫助開發(fā)人員使用語言模型構(gòu)建端到端的應(yīng)用程序。它提供了一套工具、組件和接口,可簡化創(chuàng)建由大型語言模型 (LLM) 和聊天模型提供支持的應(yīng)用程序的過程。LangChain 可以輕松管理與語言模型的交互,將多個組件鏈接在一起,并集成額外的資源,例如 API 和數(shù)據(jù)庫。
官方文檔:https://python.langchain.com/en/latest/
中文文檔:https://www.langchain.com.cn/
如何使用 LangChain?
要使用 LangChain,開發(fā)人員首先要導(dǎo)入必要的組件和工具,例如 LLMs, chat models, agents, chains, 內(nèi)存功能。這些組件組合起來創(chuàng)建一個可以理解、處理和響應(yīng)用戶輸入的應(yīng)用程序。
LangChain 為特定用例提供了多種組件,例如個人助理、文檔問答、聊天機(jī)器人、查詢表格數(shù)據(jù)、與 API 交互、提取、評估和匯總。
LangChain的模型
LangChain model 是一種抽象,表示框架中使用的不同類型的模型。LangChain 中的模型主要分為三類:
1.LLM(大型語言模型):這些模型將文本字符串作為輸入并返回文本字符串作為輸出。它們是許多語言模型應(yīng)用程序的支柱。
2.聊天模型( Chat Model):聊天模型由語言模型支持,但具有更結(jié)構(gòu)化的 API。他們將聊天消息列表作為輸入并返回聊天消息。這使得管理對話歷史記錄和維護(hù)上下文變得容易。
3.文本嵌入模型(Text Embedding Models):這些模型將文本作為輸入并返回表示文本嵌入的浮點列表。這些嵌入可用于文檔檢索、聚類和相似性比較等任務(wù)。
LangChain 的主要特點
LangChain 旨在為六個主要領(lǐng)域的開發(fā)人員提供支持:
1.LLM 和提示:LangChain 使管理提示、優(yōu)化它們以及為所有 LLM 創(chuàng)建通用界面變得容易。此外,它還包括一些用于處理 LLM 的便捷實用程序。
2.鏈(Chain):這些是對 LLM 或其他實用程序的調(diào)用序列。LangChain 為鏈提供標(biāo)準(zhǔn)接口,與各種工具集成,為流行應(yīng)用提供端到端的鏈。
3.數(shù)據(jù)增強(qiáng)生成:LangChain 使鏈能夠與外部數(shù)據(jù)源交互以收集生成步驟的數(shù)據(jù)。例如,它可以幫助總結(jié)長文本或使用特定數(shù)據(jù)源回答問題。
4.Agents:Agents 讓 LLM 做出有關(guān)行動的決定,采取這些行動,檢查結(jié)果,并繼續(xù)前進(jìn)直到工作完成。LangChain 提供了代理的標(biāo)準(zhǔn)接口,多種代理可供選擇,以及端到端的代理示例。
5.內(nèi)存:LangChain 有一個標(biāo)準(zhǔn)的內(nèi)存接口,有助于維護(hù)鏈或代理調(diào)用之間的狀態(tài)。它還提供了一系列內(nèi)存實現(xiàn)和使用內(nèi)存的鏈或代理的示例。
6.評估:很難用傳統(tǒng)指標(biāo)評估生成模型。這就是為什么 LangChain 提供提示和鏈來幫助開發(fā)者自己使用 LLM 評估他們的模型。
使用示例
LangChain 支持大量用例,例如:
針對特定文檔的問答:根據(jù)給定的文檔回答問題,使用這些文檔中的信息來創(chuàng)建答案。聊天機(jī)器人:構(gòu)建可以利用 LLM 的功能生成文本的聊天機(jī)器人。Agents:開發(fā)可以決定行動、采取這些行動、觀察結(jié)果并繼續(xù)執(zhí)行直到完成的代理。
快速入門指南:使用 LangChain 構(gòu)建端到端語言模型應(yīng)用程序
[OPENAI_API_KEY可以去官網(wǎng)生成(調(diào)用接口要錢,比較便宜)]
安裝
首先,安裝 LangChain。只需運行以下命令:
pip install langchain
環(huán)境設(shè)置
現(xiàn)在,由于 LangChain 經(jīng)常需要與模型提供者、數(shù)據(jù)存儲、API 等集成,我們將設(shè)置我們的環(huán)境。在這個例子中,我們將使用 OpenAI 的 API,因此我們需要安裝他們的 SDK:
pip install openai
接下來,讓我們在終端中設(shè)置環(huán)境變量:
export OPENAI_API_KEY = "..."
或者,如果您更喜歡在 Jupyter notebook 或 Python 腳本中工作,您可以像這樣設(shè)置環(huán)境變量:
import os
os .environ[ "OPENAI_API_KEY" ] = "..."
構(gòu)建語言模型應(yīng)用程序:LLM
# 導(dǎo)入LLM包裝器。
from langchain.llms import OpenAI
# 初始化包裝器,temperature越高結(jié)果越隨機(jī)
llm = OpenAI(temperature=0.9)
# 進(jìn)行調(diào)用
text = "What would be a good company name for a company that makes colorful socks?"
print(llm(text))
#生成結(jié)果,結(jié)果是隨機(jī)的 例如: Glee Socks. Rainbow Cozy SocksKaleidoscope Socks.
Prompt Templates: 管理LLMs的Prompts
一般來說我們不會直接把輸入給模型,而是將輸入和一些別的句子連在一起,形成prompts之后給模型。
例如之前根據(jù)產(chǎn)品取名的用例,在實際服務(wù)中我們可能只想輸入"socks",那么"What would be a good company name for a company that makes"就是我們的template。
from langchain.prompts import PromptTemplate
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
print(prompt.format(product="colorful socks"))
# 輸出結(jié)果 What is a good name for a company that makes colorful socks?
構(gòu)建語言模型應(yīng)用程序:Chat Model
還可以使用聊天模型。這些是語言模型的變體,它們在底層使用語言模型但具有不同的界面。聊天模型使用聊天消息作為輸入和輸出,而不是“文本輸入、文本輸出”API。聊天模型 API 的使用還比較新,所以大家都還在尋找最佳抽象使用方式。
要完成聊天,您需要將一條或多條消息傳遞給聊天模型。LangChain 目前支持 AIMessage、HumanMessage、SystemMessage 和 ChatMessage 類型。您將主要使用 HumanMessage、AIMessage 和 SystemMessage。
from langchain.chat_models import ChatOpenAI
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
)
chat = ChatOpenAI(temperature=0)
chat([HumanMessage(content="Translate this sentence from English to French. I love programming.")])
#輸出結(jié)果 AIMessage(content="J'aime programmer.", additional_kwargs={})
使用 generate 為多組消息生成完成。這將返回一個帶有附加消息參數(shù)的 LLMResult:
from langchain.chat_models import ChatOpenAI
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
)
batch_messages = [
[
SystemMessage(content="You are a helpful assistant that translates English to Chinese."),
HumanMessage(content="Translate this sentence from English to Chinese. I love programming.")
],
[
SystemMessage(content="You are a helpful assistant that translates English to Chinese."),
HumanMessage(content="Translate this sentence from English to Chinese. I love artificial intelligence.")
],
]
result = chat.generate(batch_messages)
print(result)
result.llm_output['token_usage']
對于聊天模型,您還可以通過使用 MessagePromptTemplate 來使用模板。您可以從一個或多個 MessagePromptTemplates 創(chuàng)建 ChatPromptTemplate。ChatPromptTemplate 的方法format_prompt返回一個 PromptValue,您可以將其轉(zhuǎn)換為字符串或 Message 對象,具體取決于您是否要使用格式化值作為 LLM 或聊天模型的輸入。
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
chat = ChatOpenAI(temperature=0)
template="You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
# get a chat completion from the formatted messages
chat(chat_prompt.format_prompt(input_language="English", output_language="Chinese", text="I love programming.").to_messages())
# -> AIMessage(content="我喜歡編程。(Wǒ xǐhuān biānchéng.)", additional_kwargs={})
探索將內(nèi)存與使用聊天模型初始化的鏈和代理一起使用。這與 Memory for LLMs 的主要區(qū)別在于我們可以將以前的消息保留為它們自己唯一的內(nèi)存對象,而不是將它們壓縮成一個字符串。
from langchain.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate
)
from langchain.chains import ConversationChain
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template("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."),
MessagesPlaceholder(variable_name="history"),
HumanMessagePromptTemplate.from_template("{input}")
])
llm = ChatOpenAI(temperature=0)
memory = ConversationBufferMemory(return_messages=True)
conversation = ConversationChain(memory=memory, prompt=prompt, llm=llm)
conversation.predict(input="Hi there!")
# -> 'Hello! How can I assist you today?'
conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
# -> "That sounds like fun! I'm happy to chat with you. Is there anything specific you'd like to talk about?"
conversation.predict(input="Tell me about yourself.")
完整代碼
import os
os .environ[ "OPENAI_API_KEY" ] = ""
from langchain.chat_models import ChatOpenAI
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
)
chat = ChatOpenAI(temperature=0)
batch_messages = [
[
SystemMessage(content="You are a helpful assistant that translates English to Chinese."),
HumanMessage(content="Translate this sentence from English to Chinese. I love programming.")
],
[
SystemMessage(content="You are a helpful assistant that translates English to Chinese."),
HumanMessage(content="Translate this sentence from English to Chinese. I love artificial intelligence.")
],
]
result = chat.generate(batch_messages)
print(result)
print(result.llm_output['token_usage'])
print("********************************************************************")
from langchain.chat_models import ChatOpenAI
from langchain.chat_models import ChatOpenAI
from langchain import LLMChain
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
chat = ChatOpenAI(temperature=0)
template="You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
chain = LLMChain(llm=chat, prompt=chat_prompt)
print(chain.run(input_language="English", output_language="Chinese", text="I love programming."))
print("********************************************************************")
from langchain.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate
)
from langchain.chains import ConversationChain
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template("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."),
MessagesPlaceholder(variable_name="history"),
HumanMessagePromptTemplate.from_template("{input}")
])
llm = ChatOpenAI(temperature=0)
memory = ConversationBufferMemory(return_messages=True)
conversation = ConversationChain(memory=memory, prompt=prompt, llm=llm)
conversation.predict(input="Hi there!")
# -> 'Hello! How can I assist you today?'
conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
# -> "That sounds like fun! I'm happy to chat with you. Is there anything specific you'd like to talk about?"
print(conversation.predict(input="Tell me about yourself."))
print("aaaaaaaa")
print(sum(range(0,101)))
# # 導(dǎo)入LLM包裝器。
from langchain.llms import OpenAI
# 初始化包裝器,temperature越高結(jié)果越隨機(jī)
import os
from langchain.prompts import PromptTemplate
import openai
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
#你申請的openai的api key
os .environ[ "OPENAI_API_KEY" ] = ""
llm = OpenAI(temperature=0.9)
# 進(jìn)行調(diào)用
text = "What would be a good company name for a company that makes colorful socks?"
print(llm(text))
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
print(prompt.format(product="colorful socks"))
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)
chain.run("colorful socks")
def completion(prompt):
completions = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.8,
)
message = completions.choices[0].text
return message
print(completion("中關(guān)村科金是一家怎樣的公司?"))
信息抽取
根據(jù)輸入的內(nèi)容抽取關(guān)鍵信息
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAIChat
from langchain.chains import LLMChain
import os
import openai
# #你申請的openai的api key
os.environ['OPENAI_API_KEY'] = ''
text="北京市(Beijing),簡稱“京”,古稱燕京、北平,是中華人民共和國首都、直轄市、國家中心城市、超大城市,國務(wù)院批復(fù)確定的中國政治中心、文化中心、國際交往中心、科技創(chuàng)新中心, \
中國歷史文化名城和古都之一。 截至2020年,北京市下轄16個區(qū),總面積16410.54平方千米。 2022年末,北京市常住人口2184.3萬人。 \
北京市地處中國北部、華北平原北部,東與天津市毗連,其余均與河北省相鄰,中心位于東經(jīng)116°20′、北緯39°56′,是世界著名古都和現(xiàn)代化國際城市, \
也是中國共產(chǎn)黨中央委員會、中華人民共和國中央人民政府和中華人民共和國全國人民代表大會常務(wù)委員會所在地。\
北京市地勢西北高、東南低。西部、北部和東北部三面環(huán)山,東南部是一片緩緩向渤海傾斜的平原。境內(nèi)流經(jīng)的主要河流有:永定河、潮白河、北運河、拒馬河等,\
北京市的氣候為暖溫帶半濕潤半干旱季風(fēng)氣候,夏季高溫多雨,冬季寒冷干燥,春、秋短促。北京被世界城市研究機(jī)構(gòu)GaWC評為世界一線城市, \
聯(lián)合國報告指出北京市人類發(fā)展指數(shù)居中國城市第二位。 [4] 北京市成功舉辦夏奧會與冬奧會,成為全世界第一個“雙奧之城”。 \
2022年,北京市實現(xiàn)地區(qū)生產(chǎn)總值41610.9億元,按不變價格計算,比上年增長0.7%。其中,第一產(chǎn)業(yè)增加值111.5億元,下降1.6%;第二產(chǎn)業(yè)增加值6605.1億元,下降11.4%;第三產(chǎn)業(yè)增加值34894.3億元,增長3.4%。"
#加載openai的llm
llm = OpenAIChat(model_name="gpt-3.5-turbo")
#創(chuàng)建模板
fact_extraction_prompt = PromptTemplate(
input_variables=["text_input"],
template="從下面的本文中提取關(guān)鍵事實。盡量使用文本中的統(tǒng)計數(shù)據(jù)來說明事實:\n\n {text_input}"
)
#定義chain
fact_extraction_chain = LLMChain(llm=llm, prompt=fact_extraction_prompt)
facts = fact_extraction_chain.run(text)
print(facts)
輸出結(jié)果:
文檔問答
import os
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.text_splitter import TokenTextSplitter
from langchain.llms import OpenAI
from langchain.chains import ChatVectorDBChain
from langchain.document_loaders import DirectoryLoader
import jieba as jb
import openai
files=['xxx.txt','xxx.txt']
import time
start_time = time.time()
for file in files:
#讀取data文件夾中的中文文檔
my_file=f"./data/{file}"
with open(my_file,"r",encoding='utf-8') as f:
data = f.read()
#對中文文檔進(jìn)行分詞處理
cut_data = " ".join([w for w in list(jb.cut(data))])
#分詞處理后的文檔保存到data文件夾中的cut子文件夾中
cut_file=f"./data/cut/cut_{file}"
with open(cut_file, 'w') as f:
f.write(cut_data)
f.close()
#加載文檔
loader = DirectoryLoader('./data/cut',glob='**/*.txt')
docs = loader.load()
#文檔切塊
text_splitter = TokenTextSplitter(chunk_size=1000, chunk_overlap=0)
doc_texts = text_splitter.split_documents(docs)
#調(diào)用openai Embeddings
a=os.environ["OPENAI_API_KEY"] = ""
embeddings = OpenAIEmbeddings(openai_api_key=a)
#向量化
vectordb = Chroma.from_documents(doc_texts, embeddings, persist_directory="./data/cut")
vectordb.persist()
#創(chuàng)建聊天機(jī)器人對象chain
chain = ChatVectorDBChain.from_llm(OpenAI(temperature=0, model_name="gpt-3.5-turbo"), vectordb, return_source_documents=True)
def get_answer(question):
chat_history = []
result = chain({"question": question, "chat_history": chat_history})
return result["answer"]
question = "xxxxxxxxxxx"
print(get_answer(question))
end_time = time.time() # 程序結(jié)束時間
run_time = end_time - start_time # 程序的運行時間,單位為秒
print(run_time)
如果問題及答案在文檔中會返回正確的結(jié)果,如果不在文本中,則會返回錯誤信息
可能出現(xiàn)的問題
UnicodeEncodeError: 'gbk' codec can't encode character '\u0643' in position 58: illegal multibyte sequence
如果是vscode編輯器可能是電腦設(shè)置的問題,解決方法win+i > 時間和語言 > 時間 日期 區(qū)域格式設(shè)置 >其他時間 日期 區(qū)域格式設(shè)置>區(qū)域更改日期,時間或數(shù)字格式> 管理>更改系統(tǒng)區(qū)域設(shè)置
Beta打鉤能解決這個問題,這個是針對txt文本(其他文檔沒試過),出現(xiàn)問題不一定是代碼的問題,這個打鉤可能會影響電腦其他應(yīng)用亂碼(大部分應(yīng)用不會)文章來源:http://www.zghlxwxcb.cn/news/detail-462600.html
搜索問答(待更新)
可能出現(xiàn)的問題:文章來源地址http://www.zghlxwxcb.cn/news/detail-462600.html
ImportError: cannot import name 'load_tools' from 'langchain.agents'
我用的是python3.7,然后將python版本升級到了3.9就解決了。
到了這里,關(guān)于LangChain入門指南的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!