やりたいこと
LangGraphに過去のChat Historyもいれて解答生成したい
公式ドキュメント
こちらを読むと MessagesState
でやっているのですが、任意のGraphでも可能です。(よくよく考えてみると当たり前ですが‥)
Steps
step1: chat_history
をStateに追加
例.
class GraphState(TypedDict):
"""
Represents the state of our graph.
Attributes:
question: question
generation: LLM generation
documents: list of documents
chat_history: list of messages
"""
question: str
generation: str
documents: List[str]
chat_history: List[BaseMessage]
step2: Promptに MessagesPlaceholder("chat_history")
を入れる
Chainで過去のメッセージを使いたいところにMessagesPlaceholder("chat_history")
を入れる
from langchain_core.prompts import MessagesPlaceholder
# Generate
messages = (
[
("system", generate_prompt_template),
MessagesPlaceholder("chat_history"),
]
)
# messages = [("system", generate_prompt_template)] # chat_historyなしの場合
generate_prompt = ChatPromptTemplate.from_messages(messages=messages)
rag_chain = generate_prompt | chat | StrOutputParser()
step3: invoke時に chat_history
を渡す
inputs = {"question": "Resource Lockについて教えてください。", "chat_history": []}
res = app.invoke(inputs, stream_mode="values")