File size: 6,301 Bytes
2540499
f80362a
2540499
f80362a
2540499
 
 
f80362a
 
 
 
 
 
 
 
 
2540499
 
 
 
 
 
ae9f5b7
 
2540499
 
 
 
9a7d97d
f80362a
9a7d97d
2540499
f80362a
 
2540499
f80362a
026a6c2
f80362a
2540499
90a5ca6
 
 
 
 
 
f80362a
90a5ca6
 
 
 
 
 
 
 
 
f80362a
 
90a5ca6
 
f80362a
 
2540499
026a6c2
 
 
 
 
 
f80362a
a1378df
026a6c2
 
f80362a
2540499
026a6c2
 
f80362a
d34c3c1
 
 
 
 
 
 
 
 
 
 
 
026a6c2
 
 
f80362a
026a6c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f80362a
ba68027
026a6c2
 
 
 
f80362a
026a6c2
 
f80362a
 
026a6c2
 
 
 
 
 
 
 
 
dcd432a
f80362a
 
026a6c2
 
 
f80362a
026a6c2
 
 
f80362a
026a6c2
 
f80362a
 
026a6c2
 
 
 
f80362a
026a6c2
 
 
 
 
 
 
 
f80362a
026a6c2
 
f80362a
 
026a6c2
 
 
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# app.py
# v1.0 - modular 

# External
import streamlit as st
import sqlite3
from datetime import datetime

# Internal
from logging_config import logger
from database import init_db, add_message, load_messages, DB_NAME
from retriever import load_retriever, TOP_K
from prompt import build_prompt
from api_client import send_query_to_llm
from get_csv import get_db_contents_as_csv
from session import get_session_id

# -----------------------
# Configuration and Setup
# -----------------------

# Setup logging
logger.info(f"Logging setup initialized successfully at {datetime.now().isoformat()}.")

# -----------------------
# Streamlit UI
# -----------------------

try:
    init_db(DB_NAME)  # Ensure DB is ready
    logger.info("DB initialized successfully.")

    # Initialize session state
    session_id = get_session_id()

    # Load retriever
    retriever = load_retriever()
    logger.info("Retriever initialized successfully.")

    # -----------------------
    # Download Chat History as CSV button
    # -----------------------

    st.sidebar.header("Download Your Chat History")
    if st.sidebar.button("Download History as CSV"):
        csv = get_db_contents_as_csv(session_id)
        if csv:
            st.sidebar.download_button(
                label="Download as CSV",
                data=csv,
                file_name="chat_history.csv",
                mime="text/csv"
            )
        else:
            st.sidebar.warning("No chat history available for download.")
            logger.info("No chat history available for download.")
    logger.info("Download History as CSV button initialized successfully.")
    # -----------------------

    st.title("Prometheus v1.0 - Personalized Canadian History Tutor")
    logger.info("Streamlit title initialized successfully.")

    # Instructions
    with st.expander("📋 Instructions", expanded=True):
        st.write(
            """
            - Press **Enter** to submit your query.
            - Type **'quit'** to clear the conversation history.
            - Use the sidebar button to download conversation history as a CSV file.
            - Textbook sources retrieved available in the sidebar.
            """
        )
        logger.info("Instructions expanded successfully.")

    # Chat-like UI for conversation history
    st.subheader("💬 Conversation History")
    messages = load_messages(session_id)
    if not messages:
        # Add initial assistant message
        initial_message = {
            "role": "assistant",
            "content": (
                "Hello, I'm Prometheus, your AI-powered personal tutor. "
                "I'm here to guide you through your learning journey using a step-by-step approach and Socratic progression to help you think critically, master concepts, and achieve your academic goals."
            )
        }
        add_message("assistant", initial_message["content"], session_id)
        messages = load_messages(session_id)
        logger.info("Initial assistant message added to conversation history.")
    for m in messages:
        with st.chat_message(m['role']):
            st.markdown(m['content'])
    logger.info("Conversation history UI initialized successfully.")

    # Input area for user query
    if prompt := st.chat_input("Ask Prometheus... Type 'quit' to clear history."):
        # If user inputs 'quit', clear conversation history
        if prompt.strip().lower() == 'quit':
            try:
                conn = sqlite3.connect(DB_NAME)
                c = conn.cursor()
                c.execute("DELETE FROM conversations")
                conn.commit()
                logger.info("Conversation history cleared.")
                st.success("Conversation history cleared.")
            except sqlite3.Error as e:
                logger.error(f"Error clearing conversation history: {e}")
                st.error("Failed to clear conversation history.")
            finally:
                conn.close()
                logger.info("DB connection closed.")
        else:
            # Immediately display user message in the UI
            messages.append({"role": "user", "content": prompt.strip()})
            with st.chat_message("user"):
                st.markdown(prompt.strip())
                logger.info(f"User message displayed in UI")
            
            # Add user message to DB
            add_message("user", prompt.strip(), session_id)
            logger.info(f"User message added to DB")

            # Retrieve chunks
            if retriever:
                results = retriever.retrieve(prompt.strip(), k=TOP_K)
                logger.info(f"Retrieved {len(results)} chunks for query: '{prompt.strip()}'")
            else:
                results = []
                logger.warning("Retriever is not available.")

            # Load updated messages (including user query)
            messages = load_messages(session_id)
            logger.info("Updated messages loaded, including user query")

            # Build prompt
            llm_prompt = build_prompt(prompt.strip(), results, messages)
            logger.info("Prompt built for api client")

            # Call LLM
            assistant_response = send_query_to_llm(llm_prompt)
            logger.info("API client response received")

            # Add assistant response to DB
            add_message("assistant", assistant_response, session_id)
            logger.info("Assistant response added to DB")

            # Display assistant response
            with st.chat_message("assistant"):
                st.markdown(assistant_response)
                logger.info("Assistant response displayed in UI")

        # Display retrieved sources in the sidebar
        with st.sidebar:
            st.header("📖 Sources")
            if results:
                for i, res in enumerate(results):
                    st.markdown(f"- **Result {i+1}:** Page {res['page_num']}")
                    st.code(res['content'])
                    logger.info(f"Sources displayed in sidebar")
            else:
                st.warning("No relevant sources found.")
                logger.info("No relevant sources found.")

except Exception as e:
    logger.error(f"Failed to initialize DB: {e}")
    raise ValueError("Failed to initialize DB.")