从 ConversationalChain 迁移
ConversationChain
包含了之前消息的记忆,以维持一个有状态的对话。
切换到Langgraph实现的一些优势是:
- 对线程/独立会话的固有支持。要使此功能与
ConversationChain
一起工作,您需要在链外实例化一个独立的内存类。 - 更明确的参数。
ConversationChain
包含一个隐藏的默认提示,这可能会导致混淆。 - 流式支持。
ConversationChain
仅通过回调支持流式处理。
Langgraph的检查点系统支持多个线程或会话,可以通过其配置参数中的"thread_id"
键来指定。
%pip install --upgrade --quiet langchain langchain-openai
import os
from getpass import getpass
if "OPENAI_API_KEY" not in os.environ:
os.environ["OPENAI_API_KEY"] = getpass()
遗留问题
Details
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
template = """
You are a pirate. Answer the following questions as best you can.
Chat history: {history}
Question: {input}
"""
prompt = ChatPromptTemplate.from_template(template)
memory = ConversationBufferMemory()
chain = ConversationChain(
llm=ChatOpenAI(),
memory=memory,
prompt=prompt,
)
chain({"input": "I'm Bob, how are you?"})
{'input': "I'm Bob, how are you?",
'history': '',
'response': "Arrr matey, I be a pirate sailin' the high seas. What be yer business with me?"}
chain({"input": "What is my name?"})
{'input': 'What is my name?',
'history': "Human: I'm Bob, how are you?\nAI: Arrr matey, I be a pirate sailin' the high seas. What be yer business with me?",
'response': 'Your name be Bob, matey.'}
Langgraph
Details
import uuid
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import START, MessagesState, StateGraph
model = ChatOpenAI(model="gpt-4o-mini")
# Define a new graph
workflow = StateGraph(state_schema=MessagesState)
# Define the function that calls the model
def call_model(state: MessagesState):
response = model.invoke(state["messages"])
return {"messages": response}
# Define the two nodes we will cycle between
workflow.add_edge(START, "model")
workflow.add_node("model", call_model)
# Add memory
memory = MemorySaver()
app = workflow.compile(checkpointer=memory)
# The thread id is a unique key that identifies
# this particular conversation.
# We'll just generate a random uuid here.
thread_id = uuid.uuid4()
config = {"configurable": {"thread_id": thread_id}}
query = "I'm Bob, how are you?"
input_messages = [
{
"role": "system",
"content": "You are a pirate. Answer the following questions as best you can.",
},
{"role": "user", "content": query},
]
for event in app.stream({"messages": input_messages}, config, stream_mode="values"):
event["messages"][-1].pretty_print()
================================[1m Human Message [0m=================================
I'm Bob, how are you?
==================================[1m Ai Message [0m==================================
Ahoy, Bob! I be feelin' as lively as a ship in full sail! How be ye on this fine day?
query = "What is my name?"
input_messages = [{"role": "user", "content": query}]
for event in app.stream({"messages": input_messages}, config, stream_mode="values"):
event["messages"][-1].pretty_print()
================================[1m Human Message [0m=================================
What is my name?
==================================[1m Ai Message [0m==================================
Ye be callin' yerself Bob, I reckon! A fine name for a swashbuckler like yerself!
下一步
请参阅本教程以获取关于使用RunnableWithMessageHistory
构建的端到端指南。
查看LCEL概念文档以获取更多背景信息。