|
from langchain_community.chat_message_histories import StreamlitChatMessageHistory |
|
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder |
|
from langchain_core.runnables.history import RunnableWithMessageHistory |
|
from langchain_google_genai import GoogleGenerativeAIimport |
|
import os |
|
from dotenv import load_dotenv |
|
|
|
|
|
import streamlit as st |
|
|
|
|
|
load_dotenv() |
|
api_key=os.getenv("GOOGLE_API_KEY") |
|
|
|
|
|
|
|
|
|
|
|
st.set_page_config(page_title="StreamlitChatMessageHistory", page_icon="π") |
|
st.title("π StreamlitChatMessageHistory") |
|
|
|
""" |
|
A basic example of using StreamlitChatMessageHistory to help LLMChain remember messages in a conversation. |
|
The messages are stored in Session State across re-runs automatically. You can view the contents of Session State |
|
in the expander below. View the |
|
[source code for this app](https://github.com/langchain-ai/streamlit-agent/blob/main/streamlit_agent/basic_memory.py). |
|
""" |
|
|
|
|
|
msgs = StreamlitChatMessageHistory(key="langchain_messages") |
|
if len(msgs.messages) == 0: |
|
msgs.add_ai_message("How can I help you?") |
|
|
|
view_messages = st.expander("View the message contents in session state") |
|
|
|
|
|
|
|
|
|
|
|
prompt = ChatPromptTemplate.from_messages( |
|
[ |
|
("system", "You are an AI chatbot having a conversation with a human."), |
|
MessagesPlaceholder(variable_name="history"), |
|
("human", "{question}"), |
|
] |
|
) |
|
|
|
chain = prompt | GoogleGenerativeAI(model="models/gemini-2.0-flash-exp", google_api_key=api_key) |
|
|
|
|
|
|
|
chain_with_history = RunnableWithMessageHistory( |
|
chain, |
|
lambda session_id: msgs, |
|
input_messages_key="question", |
|
history_messages_key="history", |
|
) |
|
|
|
|
|
for msg in msgs.messages: |
|
st.chat_message(msg.type).write(msg.content) |
|
|
|
|
|
if prompt := st.chat_input(): |
|
st.chat_message("human").write(prompt) |
|
|
|
config = {"configurable": {"session_id": "any"}} |
|
response = chain_with_history.invoke({"question": prompt}, config) |
|
st.chat_message("ai").write(response.content) |
|
|
|
|
|
with view_messages: |
|
""" |
|
Message History initialized with: |
|
```python |
|
msgs = StreamlitChatMessageHistory(key="langchain_messages") |
|
``` |
|
|
|
Contents of `st.session_state.langchain_messages`: |
|
""" |
|
view_messages.json(st.session_state.langchain_messages) |