前面我们介绍了使用大模型的API,根据提示词来生成文本,今天我们看看如何使用Langchain的聊天模型来与不同的大模型进行交互。
聊天模型是LangChain的核心组件。它是一种语言模型,使用聊天消息作为输入并返回聊天消息作为输出(而不是使用纯文本)。LangChain 与许多模型提供商(OpenAI、Cohere、Hugging Face 等)集成,并公开了与所有这些模型交互的标准接口。LangChain 允许您在同步、异步、批处理和流模式下使用模型,并提供其他功能(例如缓存)等。
通过Langchain的聊天模型,我们可以非常容易的从一个模型切换到另外一个模型而无需更改代码。
聊天模型界面基于消息而不是原始文本。 LangChain目前支持的消息类型有AIMessage,HumanMessage,SystemMessage,FunctionMessage和ChatMessage—ChatMessage接受任意角色参数。 大多数时候,您只需处理 HumanMessage、AIMessage 和 SystemMessage
聊天模型应用了 Runnable 接口,这是 LangChain 表达式语言(LCEL)的基本构建块。这意味着它们支持 invoke、ainvoke、stream、astream、batch、abatch、astream_log 调用。
聊天模型接受 List[BaseMessage] 作为输入,或可以强制为消息的对象,包括 str (转换为 HumanMessage)和 PromptValue。
下面来看例子:
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
chat = ChatOpenAI(model="gpt-3.5-turbo-0125")
messages = [
SystemMessage(content="You're a helpful assistant"),
HumanMessage(content="Hello, how are you today?"),
]
result = chat.invoke(messages)
print(result.content)
输出结果:Hello! I’m just a virtual assistant, so I don’t have feelings, but I’m here and ready to help you. How can I assist you today?
如果要切换到其它聊天模型,只需要改动两行代码,以Claude为例:
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage, SystemMessage
chat = ChatAnthropic(model="claude-3-sonnet-20240229")
messages = [
SystemMessage(content="You're a helpful assistant"),
HumanMessage(content="Hello, how are you today?"),
]
result = chat.invoke(messages)
print(result.content)
输出结果:Hello! As an AI language model, I don’t have feelings or physical sensations, but I’m operating properly and ready to assist you with any questions or tasks you may have. How can I help you today?
如果需要流式输出,将最后两行替换如下代码即可:
for chunk in chat.stream(messages):
print(chunk.content, end="", flush=True)
从以上代码不难看出Langchain的聊天模型进一步封装了大模型,提供了一个统一的界面方便用户跟不同的大模型打交道。