跳到主要內容
Open In ColabOpen on GitHub

從 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()

舊版

詳細資訊
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

詳細資訊
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}}
API 參考文件:ChatOpenAI | MemorySaver | StateGraph
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()
================================ Human Message =================================

I'm Bob, how are you?
================================== Ai Message ==================================

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()
================================ Human Message =================================

What is my name?
================================== Ai Message ==================================

Ye be callin' yerself Bob, I reckon! A fine name for a swashbuckler like yerself!

後續步驟

請參閱本教學,以獲得關於使用 RunnableWithMessageHistory 構建的更完整的指南。

查看 LCEL 概念文件以獲取更多背景資訊。


此頁面是否有幫助?