Spaces:
Build error
Build error
File size: 4,746 Bytes
3132f43 |
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
import os
import datetime
import google.generativeai as genai
import streamlit as st
from dotenv import load_dotenv
from typing import Any, Dict, List
from db_ops import get_recent_conversations, init_db, store_conversation_summary, store_message
# Loading environment variables from .env file
load_dotenv()
# Configure Gemini API
gemini_api_key = os.getenv("GEMINI_API_KEY")
genai.configure(api_key=gemini_api_key)
# Intialize the gemini Model
model = genai.GenerativeModel("gemini-2.0-flash")
def chat_with_gemini(prompt:str, chat_history:List[Dict[str, str]]) -> str:
try:
# Format the message for Gemini
messages = []
for msg in chat_history:
if msg["role"] == "user":
messages.append({"role": "user", "parts": msg["content"]})
else:
messages.append({"role": "model", "parts": [msg["content"]]})
# Add current prompt
messages.append({"role": "user", "parts": [prompt]})
# Generate the response from Gemini
chat = model.start_chat(history=messages[:-1])
response = chat.send_message(prompt)
return response.text
except Exception as e:
return f"Error communicating with GEMINI API: {str(e)}"
def summarize_conversations(conversations:List[Dict[str, Any]])->str:
if not conversations:
return "No recent conversations to summarize."
# Format conversations for the model
conversation_texts = []
for idx, conv in enumerate(conversations, 1):
conv_text = f"Conversation {idx} ({conv['timestamp']}):\n"
for msg in conv["messages"]:
conv_text += f"{msg['role'].upper()}: {msg['content']}\n"
conversation_texts.append(conv_text)
prompt = f"""
Please provide a concise summary of the following recent conversations:
{"\n\n".join(conversation_texts)}
Focus on key topics discussed, questions asked, and information provided.
Highlight any recurring themes or import points.
"""
response = model.generate_content(prompt.strip())
return response.text
# Streamlit UI
def main():
st.set_page_config(page_title="Gemini-Chatbot", page_icon="๐ค")
st.title("๐ค Gemini AI Chatbot")
# Intialize the database
init_db()
# Intialize session state for chat history and session ID
if "session_id" not in st.session_state:
st.session_state.session_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
# Chat input area
with st.container():
user_input = st.chat_input("Type your message here...")
if user_input:
# Add user message to chat history
st.session_state.chat_history.append({"role": "user", "content": user_input})
store_message(st.session_state.session_id, "user", user_input)
# Get response from Gemini AI
with st.spinner("Thinking..."):
response = chat_with_gemini(user_input, st.session_state.chat_history)
# Add assistant message to chat history
st.session_state.chat_history.append({"role": "assistant", "content": response})
store_message(st.session_state.session_id, "assistant", response)
# Display the chat history
for message in st.session_state.chat_history:
with st.chat_message(message["role"]):
st.write(message["content"])
# Sidebar for recent conversations
with st.sidebar:
st.title("Conversation Recall")
if st.button("๐ธ Summarize Recent conversations"):
with st.spinner("Generating summary..."):
# Get recent conversations
recent_convs = get_recent_conversations(st.session_state.session_id, limit=5)
# Generate summary
summary = summarize_conversations(recent_convs)
# Store summary for recent conversations
if recent_convs:
store_conversation_summary(st.session_state.session_id, recent_convs[0]["id"], summary)
# Display summary
st.subheader("Summary of Recent Conversations")
st.write(summary)
# Clear chat button
if st.button("๐๏ธ Clear Chat"):
st.session_state.chat_history = []
st.session_state.session_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
st.success("Chat history cleared!")
st.rerun()
if __name__ == "__main__":
main() |