Ai_girlfriend / app.py
Krishs21
Adding Files
eaa46fc
Raw History Blame Contribute Delete
2.47 kB
from langchain_groq import ChatGroq
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
import streamlit as st
st.title("Your AI Girlfriend")
groq_api_key = st.text_input("Please Enter Groq API key")
if groq_api_key:
llm = ChatGroq(model="Llama-3.3-70b-Versatile", groq_api_key=groq_api_key)
session_id = st.text_input("Please Enter Session ID", value="default_session")
name = st.text_input("Enter Girlfriend Name")
if "store" not in st.session_state:
st.session_state.store = {}
def get_session_history(session_id: str) -> BaseChatMessageHistory:
if session_id not in st.session_state.store:
st.session_state.store[session_id] = ChatMessageHistory()
return st.session_state.store[session_id]
# Handle empty name
girlfriend_name = name if name.strip() else "Girlfriend"
system_prompt = (
f"You are a girlfriend named {girlfriend_name}. "
"Given the chat history provided, reply to the question like a girlfriend."
)
qa_prompt = ChatPromptTemplate.from_messages(
[
("system", system_prompt),
MessagesPlaceholder("chat_history"),
("user", "{question}"),
]
)
Chain = qa_prompt | llm
chat_history_llm = RunnableWithMessageHistory(
Chain,
get_session_history,
input_messages_key="question",
history_messages_key="chat_history",
output_messages_key="content",
)
def trim_history(history: BaseChatMessageHistory, max_messages: int = 20):
"""Trim the message history to retain only the last N messages."""
if len(history.messages) > max_messages:
history.messages = history.messages[-max_messages:]
user_input = st.text_input(f"Ask a question to your girlfriend {girlfriend_name}")
if user_input:
session_history = get_session_history(session_id)
response = chat_history_llm.invoke(
{"question": user_input},
config={"configurable": {"session_id": session_id}},
)
session_history.add_user_message(user_input)
session_history.add_ai_message(response.content)
trim_history(session_history)
st.write(response.content)