File size: 2,713 Bytes
8c09efe 5c6d0a1 8c09efe 5c6d0a1 8c09efe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
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")
# Configure l'API de Gemini
#llm = GoogleGenerativeAI(model="models/text-bison-001", google_api_key=api_key)
#genai.configure(api_key=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).
"""
# Set up memory
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")
# Set up the LangChain, passing in Message History
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",
)
# Render current messages from StreamlitChatMessageHistory
for msg in msgs.messages:
st.chat_message(msg.type).write(msg.content)
# If user inputs a new prompt, generate and draw a new response
if prompt := st.chat_input():
st.chat_message("human").write(prompt)
# Note: new messages are saved to history automatically by Langchain during run
config = {"configurable": {"session_id": "any"}}
response = chain_with_history.invoke({"question": prompt}, config)
st.chat_message("ai").write(response.content)
# Draw the messages at the end, so newly generated ones show up immediately
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) |