LangChain 是一個(gè)強(qiáng)大的框架,可以簡(jiǎn)化構(gòu)建高級(jí)語言模型應(yīng)用程序的過程。
What is LangChain?
LangChain是一個(gè)強(qiáng)大的框架,旨在幫助開發(fā)人員使用語言模型構(gòu)建端到端的應(yīng)用程序。它提供了一套工具、組件和接口,可簡(jiǎn)化創(chuàng)建由大型語言模型 (LLM) 和聊天模型提供支持的應(yīng)用程序的過程。LangChain 可以輕松管理與語言模型的交互,將多個(gè)組件鏈接在一起,并集成額外的資源,例如 API 和數(shù)據(jù)庫。
LangChain有很多核心概念:
1. Components and Chains
在 LangChain 中,Component 是模塊化的構(gòu)建塊,可以組合起來創(chuàng)建強(qiáng)大的應(yīng)用程序。Chain 是組合在一起以完成特定任務(wù)的一系列 Components(或其他 Chain)。例如,一個(gè) Chain 可能包括一個(gè) Prompt 模板、一個(gè)語言模型和一個(gè)輸出解析器,它們一起工作以處理用戶輸入、生成響應(yīng)并處理輸出。
2. Prompt Templates and Values
Prompt Template 負(fù)責(zé)創(chuàng)建 PromptValue,這是最終傳遞給語言模型的內(nèi)容。Prompt Template 有助于將用戶輸入和其他動(dòng)態(tài)信息轉(zhuǎn)換為適合語言模型的格式。PromptValues 是具有方法的類,這些方法可以轉(zhuǎn)換為每個(gè)模型類型期望的確切輸入類型(如文本或聊天消息)。
3. Example Selectors
當(dāng)您想要在 Prompts 中動(dòng)態(tài)包含示例時(shí),Example Selectors 很有用。他們接受用戶輸入并返回一個(gè)示例列表以在提示中使用,使其更強(qiáng)大和特定于上下文。
4. Output Parsers
Output Parsers 負(fù)責(zé)將語言模型響應(yīng)構(gòu)建為更有用的格式。它們實(shí)現(xiàn)了兩種主要方法:一種用于提供格式化指令,另一種用于將語言模型的響應(yīng)解析為結(jié)構(gòu)化格式。這使得在您的應(yīng)用程序中處理輸出數(shù)據(jù)變得更加容易。
5. Indexes and Retrievers
Index 是一種組織文檔的方式,使語言模型更容易與它們交互。檢索器是用于獲取相關(guān)文檔并將它們與語言模型組合的接口。LangChain 提供了用于處理不同類型的索引和檢索器的工具和功能,例如矢量數(shù)據(jù)庫和文本拆分器。
6. Chat Message History
LangChain 主要通過聊天界面與語言模型進(jìn)行交互。ChatMessageHistory 類負(fù)責(zé)記住所有以前的聊天交互數(shù)據(jù),然后可以將這些交互數(shù)據(jù)傳遞回模型、匯總或以其他方式組合。這有助于維護(hù)上下文并提高模型對(duì)對(duì)話的理解。
7. Agents and Toolkits
Agent 是在 LangChain 中推動(dòng)決策制定的實(shí)體。他們可以訪問一套工具,并可以根據(jù)用戶輸入決定調(diào)用哪個(gè)工具。Tookits 是一組工具,當(dāng)它們一起使用時(shí),可以完成特定的任務(wù)。代理執(zhí)行器負(fù)責(zé)使用適當(dāng)?shù)墓ぞ哌\(yùn)行代理。
通過理解和利用這些核心概念,您可以利用 LangChain 的強(qiáng)大功能來構(gòu)建適應(yīng)性強(qiáng)、高效且能夠處理復(fù)雜用例的高級(jí)語言模型應(yīng)用程序。
What is a LangChain Agent?
LangChain Agent 是框架中驅(qū)動(dòng)決策制定的實(shí)體。它可以訪問一組工具,并可以根據(jù)用戶的輸入決定調(diào)用哪個(gè)工具。代理幫助構(gòu)建復(fù)雜的應(yīng)用程序,這些應(yīng)用程序需要自適應(yīng)和特定于上下文的響應(yīng)。當(dāng)存在取決于用戶輸入和其他因素的未知交互鏈時(shí),它們特別有用。
如何使用 LangChain?
要使用 LangChain,開發(fā)人員首先要導(dǎo)入必要的組件和工具,例如 LLMs, chat models, agents, chains, 內(nèi)存功能。這些組件組合起來創(chuàng)建一個(gè)可以理解、處理和響應(yīng)用戶輸入的應(yīng)用程序。
LangChain 為特定用例提供了多種組件,例如個(gè)人助理、文檔問答、聊天機(jī)器人、查詢表格數(shù)據(jù)、與 API 交互、提取、評(píng)估和匯總。
What’s a LangChain model?
LangChain model 是一種抽象,表示框架中使用的不同類型的模型。LangChain 中的模型主要分為三類:
- LLM(大型語言模型):這些模型將文本字符串作為輸入并返回文本字符串作為輸出。它們是許多語言模型應(yīng)用程序的支柱。
- 聊天模型( Chat Model):聊天模型由語言模型支持,但具有更結(jié)構(gòu)化的 API。他們將聊天消息列表作為輸入并返回聊天消息。這使得管理對(duì)話歷史記錄和維護(hù)上下文變得容易。
- 文本嵌入模型(Text Embedding Models):這些模型將文本作為輸入并返回表示文本嵌入的浮點(diǎn)列表。這些嵌入可用于文檔檢索、聚類和相似性比較等任務(wù)。
開發(fā)人員可以為他們的用例選擇合適的 LangChain 模型,并利用提供的組件來構(gòu)建他們的應(yīng)用程序。
LangChain 的主要特點(diǎn)
LangChain 旨在為六個(gè)主要領(lǐng)域的開發(fā)人員提供支持:
- LLM 和提示:LangChain 使管理提示、優(yōu)化它們以及為所有 LLM 創(chuàng)建通用界面變得容易。此外,它還包括一些用于處理 LLM 的便捷實(shí)用程序。
- 鏈(Chain):這些是對(duì) LLM 或其他實(shí)用程序的調(diào)用序列。LangChain 為鏈提供標(biāo)準(zhǔn)接口,與各種工具集成,為流行應(yīng)用提供端到端的鏈。
- 數(shù)據(jù)增強(qiáng)生成:LangChain 使鏈能夠與外部數(shù)據(jù)源交互以收集生成步驟的數(shù)據(jù)。例如,它可以幫助總結(jié)長(zhǎng)文本或使用特定數(shù)據(jù)源回答問題。
- Agents:Agents 讓 LLM 做出有關(guān)行動(dòng)的決定,采取這些行動(dòng),檢查結(jié)果,并繼續(xù)前進(jìn)直到工作完成。LangChain 提供了代理的標(biāo)準(zhǔn)接口,多種代理可供選擇,以及端到端的代理示例。
- 內(nèi)存:LangChain 有一個(gè)標(biāo)準(zhǔn)的內(nèi)存接口,有助于維護(hù)鏈或代理調(diào)用之間的狀態(tài)。它還提供了一系列內(nèi)存實(shí)現(xiàn)和使用內(nèi)存的鏈或代理的示例。
- 評(píng)估:很難用傳統(tǒng)指標(biāo)評(píng)估生成模型。這就是為什么 LangChain 提供提示和鏈來幫助開發(fā)者自己使用 LLM 評(píng)估他們的模型。
使用示例
LangChain 支持大量用例,例如:
- 針對(duì)特定文檔的問答:根據(jù)給定的文檔回答問題,使用這些文檔中的信息來創(chuàng)建答案。
- 聊天機(jī)器人:構(gòu)建可以利用 LLM 的功能生成文本的聊天機(jī)器人。
- Agents:開發(fā)可以決定行動(dòng)、采取這些行動(dòng)、觀察結(jié)果并繼續(xù)執(zhí)行直到完成的代理。
快速入門指南:使用 LangChain 構(gòu)建端到端語言模型應(yīng)用程序
-
安裝
首先,安裝 LangChain。只需運(yùn)行以下命令:
pip install langchain
-
環(huán)境設(shè)置
現(xiàn)在,由于 LangChain 經(jīng)常需要與模型提供者、數(shù)據(jù)存儲(chǔ)、API 等集成,我們將設(shè)置我們的環(huán)境。在這個(gè)例子中,我們將使用 OpenAI 的 API,因此我們需要安裝他們的 SDK:
pip install openai
接下來,讓我們?cè)诮K端中設(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
安裝好 LangChain 并設(shè)置好環(huán)境后,我們就可以開始構(gòu)建我們的語言模型應(yīng)用程序了。LangChain 提供了一堆模塊,您可以使用它們來創(chuàng)建語言模型應(yīng)用程序。您可以將這些模塊組合起來用于更復(fù)雜的應(yīng)用程序,或者將它們單獨(dú)用于更簡(jiǎn)單的應(yīng)用程序。 -
構(gòu)建語言模型應(yīng)用程序:Chat Model
除了 LLM,您還可以使用聊天模型。這些是語言模型的變體,它們?cè)诘讓邮褂谜Z言模型但具有不同的界面。聊天模型使用聊天消息作為輸入和輸出,而不是“文本輸入、文本輸出”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.")])
# -> AIMessage(content="J'aime programmer.", additional_kwargs={})
或者傳遞多條消息給 OpenAI 的 gpt-3.5-turbo 和 gpt-4 models:
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.")
]
chat(messages)
# -> AIMessage(content="我喜歡編程。(Wǒ xǐhuān biānchéng.)", additional_kwargs={})
您還可以使用 generate 為多組消息生成完成。這將返回一個(gè)帶有附加消息參數(shù)的 LLMResult:
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)
result
# -> LLMResult(generations=[[ChatGeneration(text="我喜歡編程。(Wǒ xǐhuān biānchéng.)", generation_info=None, message=AIMessage(content="我喜歡編程。(Wǒ xǐhuān biānchéng.)", additional_kwargs={}))], [ChatGeneration(text="我喜愛人工智能。(Wǒ xǐ'ài rén gōng zhì néng.)", generation_info=None, message=AIMessage(content="我喜愛人工智能。(Wǒ xǐ'ài rén gōng zhì néng.)", additional_kwargs={}))]], llm_output={'token_usage': {'prompt_tokens': 71, 'completion_tokens': 18, 'total_tokens': 89}})
您還可以從 LLMResult 中提取 tokens 使用等信息:
result.llm_output['token_usage']
# -> {'prompt_tokens': 71, 'completion_tokens': 18, 'total_tokens': 89}
對(duì)于聊天模型,您還可以通過使用 MessagePromptTemplate 來使用模板。您可以從一個(gè)或多個(gè) MessagePromptTemplates 創(chuàng)建 ChatPromptTemplate。ChatPromptTemplate 的方法format_prompt
返回一個(gè) PromptValue,您可以將其轉(zhuǎn)換為字符串或 Message 對(duì)象,具體取決于您是否要使用格式化值作為 LLM 或聊天模型的輸入。
以下是一個(gè)例子:
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={})
您也可以將 LLMChain 與 Chat Model 一起使用:
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)
chain.run(input_language="English", output_language="Chinese", text="I love programming.")
# -> "我喜歡編程。(Wǒ xǐhuān biānchéng.)"
您還可以將代理與聊天模型一起使用。使用?AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION
?作為代理類型初始化?Agent
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI
from langchain.llms import OpenAI
# First, let's load the language model we're going to use to control the agent.
chat = ChatOpenAI(temperature=0)
# Next, let's load some tools to use. Note that the `llm-math` tool uses an LLM, so we need to pass that in.
llm = OpenAI(temperature=0)
tools = load_tools(["serpapi", "llm-math"], llm=llm)
# Finally, let's initialize an agent with the tools, the language model, and the type of agent we want to use.
agent = initialize_agent(tools, chat, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
# Now let's test it out!
agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?")
在此示例中,代理將以交互的方式執(zhí)行搜索和計(jì)算以提供最終答案。
最后,讓我們探索將內(nèi)存與使用聊天模型初始化的鏈和代理一起使用。這與 Memory for LLMs 的主要區(qū)別在于我們可以將以前的消息保留為它們自己唯一的內(nèi)存對(duì)象,而不是將它們壓縮成一個(gè)字符串。
下面是使用 a 的示例ConversationChain
:
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.")
# -> "Sure! I am an AI language model created by OpenAI. I was trained on a large dataset of text from the internet, which allows me to understand and generate human-like language. I can answer questions, provide information, and even have conversations like this one. Is there anything else you'd like to know about me?"
在此示例中,我們使用 aConversationChain
來維護(hù)跨與 AI 的多次交互的對(duì)話上下文。
就是這樣!現(xiàn)在您已經(jīng)對(duì)如何使用 LangChain 構(gòu)建端到端的語言模型應(yīng)用有了深入的了解。通過遵循這些示例,您可以使用 LLM、聊天模型、代理、鏈和內(nèi)存功能開發(fā)強(qiáng)大的語言模型應(yīng)用程序。
結(jié)論
總之,LangChain 是一個(gè)強(qiáng)大的框架,它通過提供模塊化和靈活的方法簡(jiǎn)化了構(gòu)建高級(jí)語言模型應(yīng)用程序的過程。通過了解組件、鏈、提示模板、輸出解析器、索引、檢索器、聊天消息歷史記錄和代理等核心概念,您可以創(chuàng)建適合您特定需求的自定義解決方案。LangChain 的適應(yīng)性和易用性使其成為開發(fā)人員的寶貴工具,使他們能夠釋放語言模型的全部潛力,并在廣泛的用例中創(chuàng)建智能的、上下文感知的應(yīng)用程序文章來源:http://www.zghlxwxcb.cn/news/detail-807206.html
一起學(xué)ai,關(guān)注我? 持續(xù)更新。文章來源地址http://www.zghlxwxcb.cn/news/detail-807206.html
到了這里,關(guān)于LangChain 完整指南:使用大語言模型構(gòu)建強(qiáng)大的應(yīng)用程序的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!