天天看點

LangChain 完整指南:使用大語言模型建構強大的應用程式

作者:AI自智體

山行 山行AI

LangChain 完整指南:使用大語言模型建構強大的應用程式

LangChain 完整指南:使用大語言模型建構強大的應用程式

LangChain 是一個強大的架構,可以簡化建構進階語言模型應用程式的過程。随着大模型的熱度不斷攀升,LangChain也獲得了越來越多的開發人員親睐。

嗨,你好!讓我向你介紹LangChain,這是一個非常棒的庫,它能讓開發者利用大型語言模型(LLMs)和其他計算資源來建構強大的應用。在這份指南中,我将快速概述LangChain的工作原理,并探讨一些很酷的使用案例,例如問答系統、聊天機器人和智能代理。我還會帶你走過一個快速啟動指南,幫助你開始使用。讓我們開始吧!

What is LangChain?

是一個強大的架構,旨在幫助開發人員使用語言模型建構端到端的應用程式。它提供了一套工具、元件和接口,可簡化建立由大型語言模型 (LLM) 和聊天模型提供支援的應用程式的過程。LangChain 可以輕松管理與語言模型的互動,将多個元件連結在一起,并內建額外的資源,例如 API 和資料庫。

LangChain有很多核心概念:

1. Components and Chains

在 LangChain 中,Component 是子產品化的建構塊,可以組合起來建立強大的應用程式。Chain 是組合在一起以完成特定任務的一系列 Components(或其他 Chain)。例如,一個 Chain 可能包括一個 Prompt 模闆、一個語言模型和一個輸出解析器,它們一起工作以處理使用者輸入、生成響應并處理輸出。

2. Prompt Templates and Values

Prompt Template 負責建立 PromptValue,這是最終傳遞給語言模型的内容。Prompt Template 有助于将使用者輸入和其他動态資訊轉換為适合語言模型的格式。PromptValues 是具有方法的類,這些方法可以轉換為每個模型類型期望的确切輸入類型(如文本或聊天消息)。

3. Example Selectors

當您想要在 Prompts 中動态包含示例時,Example Selectors 很有用。他們接受使用者輸入并傳回一個示例清單以在提示中使用,使其更強大和特定于上下文。

4. Output Parsers

Output Parsers 負責将語言模型響應建構為更有用的格式。它們實作了兩種主要方法:一種用于提供格式化指令,另一種用于将語言模型的響應解析為結構化格式。這使得在您的應用程式中處理輸出資料變得更加容易。

5. Indexes and Retrievers

Index 是一種組織文檔的方式,使語言模型更容易與它們互動。檢索器是用于擷取相關文檔并将它們與語言模型組合的接口。LangChain 提供了用于處理不同類型的索引和檢索器的工具和功能,例如矢量資料庫和文本拆分器。

6. Chat Message History

LangChain 主要通過聊天界面與語言模型進行互動。ChatMessageHistory 類負責記住所有以前的聊天互動資料,然後可以将這些互動資料傳遞回模型、彙總或以其他方式組合。這有助于維護上下文并提高模型對對話的了解。

7. Agents and Toolkits

Agent 是在 LangChain 中推動決策制定的實體。他們可以通路一套工具,并可以根據使用者輸入決定調用哪個工具。Tookits 是一組工具,當它們一起使用時,可以完成特定的任務。代理執行器負責使用适當的工具運作代理。

通過了解和利用這些核心概念,您可以利用 LangChain 的強大功能來建構适應性強、高效且能夠處理複雜用例的進階語言模型應用程式。

What is a LangChain Agent?

LangChain Agent 是架構中驅動決策制定的實體。它可以通路一組工具,并可以根據使用者的輸入決定調用哪個工具。代理幫助建構複雜的應用程式,這些應用程式需要自适應和特定于上下文的響應。當存在取決于使用者輸入和其他因素的未知互動鍊時,它們特别有用。

如何使用 LangChain?

要使用 LangChain,開發人員首先要導入必要的元件和工具,例如 LLMs, chat models, agents, chains, 記憶體功能。這些元件組合起來建立一個可以了解、處理和響應使用者輸入的應用程式。

LangChain 為特定用例提供了多種元件,例如個人助理、文檔問答、聊天機器人、查詢表格資料、與 API 互動、提取、評估和彙總。

What’s a LangChain model?

LangChain model 是一種抽象,表示架構中使用的不同類型的模型。LangChain 中的模型主要分為三類:

1.LLM(大型語言模型):這些模型将文本字元串作為輸入并傳回文本字元串作為輸出。它們是許多語言模型應用程式的支柱。2.聊天模型( Chat Model):聊天模型由語言模型支援,但具有更結構化的 API。他們将聊天消息清單作為輸入并傳回聊天消息。這使得管理對話曆史記錄和維護上下文變得容易。3.文本嵌入模型(Text Embedding Models):這些模型将文本作為輸入并傳回表示文本嵌入的浮點清單。這些嵌入可用于文檔檢索、聚類和相似性比較等任務。

開發人員可以為他們的用例選擇合适的 LangChain 模型,并利用提供的元件來建構他們的應用程式。

LangChain 的主要特點

LangChain 旨在為六個主要領域的開發人員提供支援:

1.LLM 和提示:LangChain 使管理提示、優化它們以及為所有 LLM 建立通用界面變得容易。此外,它還包括一些用于處理 LLM 的便捷實用程式。2.鍊(Chain):這些是對 LLM 或其他實用程式的調用序列。LangChain 為鍊提供标準接口,與各種工具內建,為流行應用提供端到端的鍊。3.資料增強生成:LangChain 使鍊能夠與外部資料源互動以收集生成步驟的資料。例如,它可以幫助總結長文本或使用特定資料源回答問題。4.Agents:Agents 讓 LLM 做出有關行動的決定,采取這些行動,檢查結果,并繼續前進直到工作完成。LangChain 提供了代理的标準接口,多種代理可供選擇,以及端到端的代理示例。5.記憶體:LangChain 有一個标準的記憶體接口,有助于維護鍊或代理調用之間的狀态。它還提供了一系列記憶體實作和使用記憶體的鍊或代理的示例。6.評估:很難用傳統名額評估生成模型。這就是為什麼 LangChain 提供提示和鍊來幫助開發者自己使用 LLM 評估他們的模型。

使用示例

LangChain 支援大量用例,例如:

•針對特定文檔的問答:根據給定的文檔回答問題,使用這些文檔中的資訊來建立答案。•聊天機器人:建構可以利用 LLM 的功能生成文本的聊天機器人。•Agents:開發可以決定行動、采取這些行動、觀察結果并繼續執行直到完成的代理。

快速入門指南:使用 LangChain 建構端到端語言模型應用程式

•安裝

首先,安裝 LangChain。隻需運作以下指令:

pip install langchain           

•環境設定

現在,由于 LangChain 經常需要與模型提供者、資料存儲、API 等內建,我們将設定我們的環境。在這個例子中,我們将使用 OpenAI 的 API,是以我們需要安裝他們的 SDK:

pip install openai           

接下來,讓我們在終端中設定環境變量:

export OPENAI_API_KEY = "..."           

或者,如果您更喜歡在 Jupyter notebook 或 Python 腳本中工作,您可以像這樣設定環境變量:

import os 
os .environ[ "OPENAI_API_KEY" ] = "..."           

•建構語言模型應用程式:LLM

安裝好 LangChain 并設定好環境後,我們就可以開始建構我們的語言模型應用程式了。LangChain 提供了一堆子產品,您可以使用它們來建立語言模型應用程式。您可以将這些子產品組合起來用于更複雜的應用程式,或者将它們單獨用于更簡單的應用程式。•建構語言模型應用程式:Chat Model

除了 LLM,您還可以使用聊天模型。這些是語言模型的變體,它們在底層使用語言模型但具有不同的界面。聊天模型使用聊天消息作為輸入和輸出,而不是“文本輸入、文本輸出”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 為多組消息生成完成。這将傳回一個帶有附加消息參數的 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}           

對于聊天模型,您還可以通過使用 MessagePromptTemplate 來使用模闆。您可以從一個或多個 MessagePromptTemplates 建立 ChatPromptTemplate。ChatPromptTemplate 的方法format_prompt傳回一個 PromptValue,您可以将其轉換為字元串或 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={})           

您也可以将 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?")           

在此示例中,代理将以互動的方式執行搜尋和計算以提供最終答案。

最後,讓我們探索将記憶體與使用聊天模型初始化的鍊和代理一起使用。這與 Memory for LLMs 的主要差別在于我們可以将以前的消息保留為它們自己唯一的記憶體對象,而不是将它們壓縮成一個字元串。

下面是使用 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來維護跨與 AI 的多次互動的對話上下文。

就是這樣!現在您已經對如何使用 LangChain 建構端到端的語言模型應用有了深入的了解。通過遵循這些示例,您可以使用 LLM、聊天模型、代理、鍊和記憶體功能開發強大的語言模型應用程式。

結論

總之,LangChain 是一個強大的架構,它通過提供子產品化和靈活的方法簡化了建構進階語言模型應用程式的過程。通過了解元件、鍊、提示模闆、輸出解析器、索引、檢索器、聊天消息曆史記錄和代理等核心概念,您可以建立适合您特定需求的自定義解決方案。LangChain 的适應性和易用性使其成為開發人員的寶貴工具,使他們能夠釋放語言模型的全部潛力,并在廣泛的用例中建立智能的、上下文感覺的應用程式。

原文連結[1]

附錄

目前github上有幾個比較火的與LangChain相關的項目,大家可以選用:

•langchain本尊:https://github.com/hwchase17/langchain•基于LangChain建構本地知識庫:GitHub - imClumsyPanda/langchain-ChatGLM: langchain-ChatGLM, local knowledge based ChatGLM with langchain | 基于本地知識庫的 ChatGLM 問答[2]•意如其名:https://github.com/imClumsyPanda/langchain-ChatGLM-webui

References

[1] 原文連結: https://link.zhihu.com/?target=https%3A//levelup.gitconnected.com/a-complete-guide-to-langchain-building-powerful-applications-with-large-language-models-53ad54a1e7eb

[2] GitHub - imClumsyPanda/langchain-ChatGLM: langchain-ChatGLM, local knowledge based ChatGLM with langchain | 基于本地知識庫的 ChatGLM 問答: https://github.com/imClumsyPanda/langchain-ChatGLM

繼續閱讀