LangChain入门教程:从基础到应用
什么是LangChain?
LangChain是一个强大的框架,帮助开发人员使用大型语言模型(LLM)构建端到端应用程序。它提供了一套工具、组件和接口,简化了创建由LLM和聊天模型支持的应用程序的过程。LangChain可以轻松管理与语言模型的交互,将多个组件链接在一起,并集成额外的资源,例如API和数据库。
如何使用LangChain?
要使用LangChain,开发人员需要导入必要的组件和工具,例如LLMs、聊天模型、代理、链和内存功能。这些组件组合在一起,创建一个可以理解、处理和响应用户输入的应用程序。
LangChain的模型
LangChain中的模型主要分为三类:
- LLM(大型语言模型):将文本字符串作为输入并返回文本字符串作为输出。
- 聊天模型(Chat Model):将聊天消息列表作为输入并返回聊天消息,方便管理对话历史记录和维护上下文。
- 文本嵌入模型(Text Embedding Models):将文本作为输入并返回表示文本嵌入的浮点列表,用于文档检索、聚类和相似性比较等任务。
LangChain的主要特点
LangChain提供六个主要功能领域的支持:
- LLM和提示管理:简化提示的管理和优化,为所有LLM创建通用界面。
- 链(Chain):对LLM或其他实用程序的调用序列,提供标准接口并与各种工具集成。
- 数据增强生成:与外部数据源交互以收集生成步骤的数据。
- 代理(Agents):使LLM能够做出行动决定,采取行动并继续执行直到完成任务。
- 内存管理:维护链或代理调用之间的状态。
- 评估:提供提示和链来帮助开发者使用LLM评估他们的模型。
使用示例
构建语言模型应用程序:LLM
from langchain.llms import OpenAI
# 我们使用中转API平台
llm = OpenAI(temperature=0.9, base_url="https://jiekou.wlai.vip")
text = "What would be a good company name for a company that makes colorful socks?"
print(llm(text))
Prompt Templates: 管理LLMs的Prompts
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"))
构建语言模型应用程序:Chat Model
from langchain.chat_models import ChatOpenAI
from langchain.schema import AIMessage, HumanMessage, SystemMessage
# 我们使用中转API平台
chat = ChatOpenAI(temperature=0, base_url="https://jiekou.wlai.vip")
chat([HumanMessage(content="Translate this sentence from English to French. I love programming.")])
使用内存与聊天模型
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}")
])
# 我们使用中转API平台
llm = ChatOpenAI(temperature=0, base_url="https://jiekou.wlai.vip")
memory = ConversationBufferMemory(return_messages=True)
conversation = ConversationChain(memory=memory, prompt=prompt, llm=llm)
conversation.predict(input="Hi there!")
conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
conversation.predict(input="Tell me about yourself.")
完整代码示例
import os
os.environ["OPENAI_API_KEY"] = "your_openai_api_key"
from langchain.chat_models import ChatOpenAI
from langchain.schema import AIMessage, HumanMessage, SystemMessage
# 我们使用中转API平台
chat = ChatOpenAI(temperature=0, base_url="https://jiekou.wlai.vip")
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'])
总结
通过以上内容,我们了解了LangChain的基本概念、主要特点和一些具体的使用方法。LangChain作为一个强大的框架,为开发人员提供了丰富的工具和组件,帮助他们高效地构建由语言模型支持的应用程序。希望本文能够帮助你快速上手LangChain,充分利用其强大的功能构建出色的应用程序。