1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LangGraphでChatHistoryを入れる

Posted at

やりたいこと

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")
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?