分類(lèi)目錄:《大模型從入門(mén)到應(yīng)用》總目錄
LangChain系列文章:
- 基礎(chǔ)知識(shí)
- 快速入門(mén)
- 安裝與環(huán)境配置
- 鏈(Chains)、代理(Agent:)和記憶(Memory)
- 快速開(kāi)發(fā)聊天模型
- 模型(Models)
- 基礎(chǔ)知識(shí)
- 大型語(yǔ)言模型(LLMs)
- 基礎(chǔ)知識(shí)
- LLM的異步API、自定義LLM包裝器、虛假LLM和人類(lèi)輸入LLM(Human Input LLM)
- 緩存LLM的調(diào)用結(jié)果
- 加載與保存LLM類(lèi)、流式傳輸LLM與Chat Model響應(yīng)和跟蹤tokens使用情況
- 聊天模型(Chat Models)
- 基礎(chǔ)知識(shí)
- 使用少量示例和響應(yīng)流式傳輸
- 文本嵌入模型
- Aleph Alpha、Amazon Bedrock、Azure OpenAI、Cohere等
- Embaas、Fake Embeddings、Google Vertex AI PaLM等
- 提示(Prompts)
- 基礎(chǔ)知識(shí)
- 提示模板
- 基礎(chǔ)知識(shí)
- 連接到特征存儲(chǔ)
- 創(chuàng)建自定義提示模板和含有Few-Shot示例的提示模板
- 部分填充的提示模板和提示合成
- 序列化提示信息
- 示例選擇器(Example Selectors)
- 輸出解析器(Output Parsers)
- 記憶(Memory)
- 基礎(chǔ)知識(shí)
- 記憶的類(lèi)型
- 會(huì)話緩存記憶、會(huì)話緩存窗口記憶和實(shí)體記憶
- 對(duì)話知識(shí)圖譜記憶、對(duì)話摘要記憶和會(huì)話摘要緩沖記憶
- 對(duì)話令牌緩沖存儲(chǔ)器和基于向量存儲(chǔ)的記憶
- 將記憶添加到LangChain組件中
- 自定義對(duì)話記憶與自定義記憶類(lèi)
- 聊天消息記錄
- 記憶的存儲(chǔ)與應(yīng)用
- 索引(Indexes)
- 基礎(chǔ)知識(shí)
- 文檔加載器(Document Loaders)
- 文本分割器(Text Splitters)
- 向量存儲(chǔ)器(Vectorstores)
- 檢索器(Retrievers)
- 鏈(Chains)
- 基礎(chǔ)知識(shí)
- 通用功能
- 自定義Chain和Chain的異步API
- LLMChain和RouterChain
- SequentialChain和TransformationChain
- 鏈的保存(序列化)與加載(反序列化)
- 鏈與索引
- 文檔分析和基于文檔的聊天
- 問(wèn)答的基礎(chǔ)知識(shí)
- 圖問(wèn)答(Graph QA)和帶來(lái)源的問(wèn)答(Q&A with Sources)
- 檢索式問(wèn)答
- 文本摘要(Summarization)、HyDE和向量數(shù)據(jù)庫(kù)的文本生成
- 代理(Agents)
- 基礎(chǔ)知識(shí)
- 代理類(lèi)型
- 自定義代理(Custom Agent)
- 自定義MRKL代理
- 帶有ChatModel的LLM聊天自定義代理和自定義多操作代理(Custom MultiAction Agent)
- 工具
- 基礎(chǔ)知識(shí)
- 自定義工具(Custom Tools)
- 多輸入工具和工具輸入模式
- 人工確認(rèn)工具驗(yàn)證和Tools作為OpenAI函數(shù)
- 工具包(Toolkit)
- 代理執(zhí)行器(Agent Executor)
- 結(jié)合使用Agent和VectorStore
- 使用Agents的異步API和創(chuàng)建ChatGPT克隆
- 處理解析錯(cuò)誤、訪問(wèn)中間步驟和限制最大迭代次數(shù)
- 為代理程序設(shè)置超時(shí)時(shí)間和限制最大迭代次數(shù)和為代理程序和其工具添加共享內(nèi)存
- 計(jì)劃與執(zhí)行
- 回調(diào)函數(shù)(Callbacks)
在《自然語(yǔ)言處理從入門(mén)到應(yīng)用——LangChain:快速入門(mén)》系列文章中我們會(huì)用最簡(jiǎn)練的語(yǔ)言與示例帶領(lǐng)大家快速調(diào)試并上手LangChain,讀者讀完本系列的文章后,就會(huì)對(duì)LangChain有一個(gè)大致的了解并可以將LangChain運(yùn)用到自己開(kāi)發(fā)的程序中。但如果讀者想對(duì)LangChain的各個(gè)模塊進(jìn)行更深入的了解,可以繼續(xù)學(xué)習(xí)《自然語(yǔ)言處理從入門(mén)到應(yīng)用——LangChain》系列文章。本文主要是闡述了如何快速通過(guò)LangChain快速開(kāi)發(fā)一個(gè)聊天模型。
聊天模型是語(yǔ)言模型的一種變化形式,雖然聊天模型底層使用的是語(yǔ)言模型,但它們提供的接口有些不同:它們沒(méi)有提供一個(gè)“文本輸入、文本輸出”API,而是提供了一個(gè)接口,其中“聊天消息”是輸入和輸出。聊天模型API是相當(dāng)新的,所以LangChain仍然在找出正確的抽象。
從聊天模型獲取消息完成
我們可以通過(guò)向聊天模型傳遞一條或多條消息來(lái)完成聊天,而響應(yīng)也將是一條消息。LangChain中當(dāng)前支持的消息類(lèi)型是AIMessage
、HumanMessage
、SystemMessage
和ChatMessage
,其中ChatMessage
接受任意角色參數(shù)。大多數(shù)時(shí)候,我們只需要處理HumanMessage
、AIMessage
和SystemMessage
即可.
from langchain.chat_models import ChatOpenAI
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
)
chat = ChatOpenAI(temperature=0)
我們通過(guò)傳入單個(gè)消息來(lái)完成:
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傳遞多條消息:
messages = [
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="Translate this sentence from English to French. I love programming.")
]
chat(messages)
輸出:
AIMessage(content="J'aime programmer.", additional_kwargs={})
我們還可以更進(jìn)一步,使用generate
為多組消息生成完成,這將返回一個(gè)帶有附加message
參數(shù)的LLMResult
:
batch_messages = [
[
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="Translate this sentence from English to French. I love programming.")
],
[
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="Translate this sentence from English to French. I love artificial intelligence.")
],
]
result = chat.generate(batch_messages)
result
輸出:
LLMResult(generations=[[ChatGeneration(text="J'aime programmer.", generation_info=None, message=AIMessage(content="J'aime programmer.", additional_kwargs={}))], [ChatGeneration(text="J'aime l'intelligence artificielle.", generation_info=None, message=AIMessage(content="J'aime l'intelligence artificielle.", additional_kwargs={}))]], llm_output={'token_usage': {'prompt_tokens': 71, 'completion_tokens': 18, 'total_tokens': 89}})
我們還可以從這個(gè)LLMResult
中獲取字符token的使用情況token_usage
:
result.llm_output['token_usage']
輸出:
{'prompt_tokens': 71, 'completion_tokens': 18, 'total_tokens': 89}
聊天提示模板
與LLM類(lèi)似,我們可以通過(guò)使用MessagePromptTemplate
來(lái)使用模板??梢詮囊粋€(gè)或多個(gè) MessagePromptTemplate
生成ChatPromptTemplate
。我們可以使用ChatPromptTemplate
的format_tip
,這將返回一個(gè)PromptValue
,我們可以將其轉(zhuǎn)換為字符串或Message
對(duì)象,具體取決于我們是想將格式化的值用作llm
或聊天模型的輸入。為了方便起見(jiàn),我們?cè)谀0迳瞎_(kāi)了一個(gè)from_template
方法。如果我們使用這個(gè)模板,它看起來(lái)是這樣的:
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="French", text="I love programming.").to_messages())
輸出:
AIMessage(content="J'aime programmer.", additional_kwargs={})
帶聊天模型的鏈
我們之前討論的LLMChain
也可以用于聊天模型:
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="French", text="I love programming.")
輸出:
"J'aime programmer."
具有聊天模型的代理
代理也可以與聊天模型一起使用,我們可以使用AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION
作為代理類(lèi)型來(lái)初始化一個(gè)聊天模型:
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
# 首先,我們加載我們要用來(lái)控制代理的語(yǔ)言模型
chat = ChatOpenAI(temperature=0)
# 其次,我們加載一些要使用的工具。請(qǐng)注意,“l(fā)lm-math”工具使用LLM,所以我們需要傳遞它
llm = OpenAI(temperature=0)
tools = load_tools(["serpapi", "llm-math"], llm=llm)
# 最后,我們使用工具、語(yǔ)言模型和我們要使用的代理類(lèi)型來(lái)初始化代理
agent = initialize_agent(tools, chat, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
# 測(cè)試代理
agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?")
我們將會(huì)得到輸出:
> Entering new AgentExecutor chain...
Thought: I need to use a search engine to find Olivia Wilde's boyfriend and a calculator to raise his age to the 0.23 power.
Action:
{
"action": "Search",
"action_input": "Olivia Wilde boyfriend"
}
Observation: Sudeikis and Wilde's relationship ended in November 2020. Wilde was publicly served with court documents regarding child custody while she was presenting Don't Worry Darling at CinemaCon 2022. In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don't Worry Darling.
Thought:I need to use a search engine to find Harry Styles' current age.
Action:
{
"action": "Search",
"action_input": "Harry Styles age"
}
Observation: 29 years
Thought:Now I need to calculate 29 raised to the 0.23 power.
Action:
{
"action": "Calculator",
"action_input": "29^0.23"
}
Observation: Answer: 2.169459462491557
Thought:I now know the final answer.
Final Answer: 2.169459462491557
> Finished chain.
'2.169459462491557'
記憶: 向鏈和代理添加狀態(tài)
我們也可以對(duì)鏈?zhǔn)褂肕emory,對(duì)代理使用聊天模型進(jìn)行初始化。這與LLM的Memory之間的主要區(qū)別在于我們不需要將以前的所有消息壓縮成一個(gè)字符串,而是可以將它們保留為自己獨(dú)特的記憶對(duì)象。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-553219.html
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?"
參考文獻(xiàn):
[1] LangChain ????? 中文網(wǎng),跟著LangChain一起學(xué)LLM/GPT開(kāi)發(fā):https://www.langchain.com.cn/
[2] LangChain中文網(wǎng) - LangChain 是一個(gè)用于開(kāi)發(fā)由語(yǔ)言模型驅(qū)動(dòng)的應(yīng)用程序的框架:http://www.cnlangchain.com/文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-553219.html
到了這里,關(guān)于自然語(yǔ)言處理從入門(mén)到應(yīng)用——LangChain:快速入門(mén)-[快速開(kāi)發(fā)聊天模型]的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!