LangChain 的核心構建模塊 LLMChain
- LangChain 應用程序的核心構建模塊
- 語言模型 - LLMs
- 提示模板 - Prompt templates
- 輸出解析器 - Output Parsers
- LLMChain 組合
LangChain 應用程序的核心構建模塊
LangChain 應用程序的核心構建模塊 LLMChain 由三部分組成:
- 語言模型 - LLMs: 語言模型是這里的核心推理引擎。為了使用 LangChain,您需要了解不同類型的語言模型以及如何使用它們。
- 提示模板 - Prompt templates: 它為語言模型提供指令。它控制著語言模型的輸出,因此了解如何構建提示和不同的提示策略至關重要。
- 輸出解析器 - Output Parsers: 它們將 LLM 的原始響應翻譯成更易于使用的格式,從而方便下游使用輸出。
本部分我將單獨介紹這三個組件,然后介紹將所有組件結合在一起的 LLMChain:
語言模型 - LLMs
在 LangChain 中,存在兩種語言模型:
- LLMs: 將字符串作為輸入并返回字符串的語言模型;
LLMs 的輸入/輸出是簡單易懂的字符串。 - ChatModels: 聊天模型,將信息列表作為輸入并返回信息的語言模型;
ChatModels 的輸入是一個 ChatMessage 列表,輸出是一個 ChatMessage。ChatMessage 有兩個必備組件:- content(內容): 這是信息的內容。
- role(角色): 這是來自該 ChatMessage 的實體的角色。
LangChain 為這兩種語言模型提供了一個標準接口,該標準接口有兩個方法:
- predict: 接收一個字符串,返回一個字符串;明顯是 LLMs 的方法。
- predict_messages: 接收信息列表,返回信息;明顯是 ChatModels 的方法。
LangChain 提供了多個對象,可以輕松區分不同的角色:
- HumanMessage(人類信息): 來自人類/用戶的 ChatMessage。
- AIMessage(人工智能助手信息): 來自人工智能/助手的聊天信息。
- SystemMessage(系統信息): 系統消息來自系統的聊天信息。
- FunctionMessage(功能消息): 來自函數調用的聊天信息。
初始化 llm 與 chat_model
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAIllm = OpenAI(openai_api_key="xxx")
chat_model = ChatOpenAI(openai_api_key="xxx")
# 如果需要 API Key 可在博文下方留言
使用 predict 方法運行字符串輸入:
text = "What would be a good company name for a company that makes colorful socks?"print(llm.predict(text))
print(chat_model.predict(text))
使用 predict_message 方法運行信息列表輸入:
from langchain.schema import HumanMessagetext = "What would be a good company name for a company that makes colorful socks?"
messages = [HumanMessage(content=text)]print(llm.predict_messages(messages))
print(chat_model.predict_messages(messages))
提示模板 - Prompt templates
-
提示模板是什么?
在大語言模型中,開發人員通常不會直接將用戶輸入傳遞給語言模型,而是將用戶輸入添加到一個較大的文本段中,該文本段稱為 “提示模板”(Prompt Template)。
-
提示模板的目的?
這樣做的目的是為了為特定任務提供更多的上下文和指導,從而引導語言模型生成更有針對性的輸出。
這種方法有助于引導語言模型的生成,使其更加專注于特定任務,同時也可以控制生成的文本的風格和內容。通過提供上下文信息,提示模板可以在不同應用場景中引導語言模型的生成,以適應不同的用戶需求。
-
字符串提示模板案例:
from langchain.prompts import PromptTemplateprompt = PromptTemplate.from_template("What is a good name for a company that makes {product}?") prompt.format(product="colorful socks")
-
信息列表提示模板案例:
from langchain.prompts.chat import (ChatPromptTemplate,SystemMessagePromptTemplate,HumanMessagePromptTemplate, )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])chat_prompt.format_messages(input_language="English", output_language="French", text="I love programming.")
輸出解析器 - Output Parsers
-
輸出解析器的作用?
輸出解析器可將 LLM 的原始輸出轉換成下游可使用的格式。
-
輸出解析器的類型?
- 將 LLM 中的文本轉換為結構化信息(如 JSON);
- 將聊天信息轉換為字符串;
- 將調用返回的除信息外的額外信息(如 OpenAI 函數調用)轉換為字符串。
- 等;
-
案例:
下案例為編寫自己的輸出解析器 – 將逗號分隔的列表轉換為列表:
from langchain.schema import BaseOutputParserclass CommaSeparatedListOutputParser(BaseOutputParser):"""Parse the output of an LLM call to a comma-separated list."""def parse(self, text: str):"""Parse the output of an LLM call."""return text.strip().split(", ")CommaSeparatedListOutputParser().parse("hi, bye") # >> ['hi', 'bye']
LLMChain 組合
現在,我們將所有這些組合成一個鏈。
該鏈將接收輸入變量,將其傳遞給提示模板以創建提示,將提示傳遞給 LLM,然后將輸出傳遞給輸出解析器。
這是一種捆綁模塊化邏輯的便捷方法。請看測試案例:
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (ChatPromptTemplate,SystemMessagePromptTemplate,HumanMessagePromptTemplate,
)
from langchain.chains import LLMChain
from langchain.schema import BaseOutputParser# 輸出解析器部分
class CommaSeparatedListOutputParser(BaseOutputParser):"""Parse the output of an LLM call to a comma-separated list."""def parse(self, text: str):"""Parse the output of an LLM call."""return text.strip().split(", ")# 信息列表提示模板案例
template = """You are a helpful assistant who generates comma separated lists.
A user will pass in a category, and you should generate 5 objects in that category in a comma separated list.
ONLY return a comma separated list, and nothing more."""
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=ChatOpenAI(),prompt=chat_prompt,output_parser=CommaSeparatedListOutputParser()
)
chain.run("colors")
# >> ['red', 'blue', 'green', 'yellow', 'orange']
上一篇博文:【LangChain】P0 LangChain 是什么與準備工作
下一篇博文: