import streamlit as st
from datetime import datetime
from hybrid_processor import HybridProcessor
import logging
# Configure Streamlit page settings
st.set_page_config(layout="wide")
# Set up logging for debugging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Initialize the HybridProcessor
try:
processor = HybridProcessor()
except Exception as e:
logger.error(f"Failed to initialize HybridProcessor: {str(e)}")
raise
# Function to compare approaches and return results
def compare_approaches(question, processor):
try:
vector_result = processor.vector_processor.query(question)
logger.info(f"Vector result: {vector_result}")
graph_result = processor.graph_processor.query(question)
logger.info(f"Graph result: {graph_result}")
hybrid_result = processor.query(question)
logger.info(f"Hybrid result: {hybrid_result}")
vector_chunks_str = '\n\n'.join(
[f'Chunk {i + 1}: {chunk}' for i, chunk in enumerate(hybrid_result['chunks']['vector'])])
graph_chunks_str = '\n\n'.join(
[f'Record {i + 1}: {chunk}' for i, chunk in enumerate(hybrid_result['chunks']['graph'])])
hybrid_chunks_formatted = f"Vector Chunks:\n{vector_chunks_str}\n\nGraph Records:\n{graph_chunks_str}"
return {
"vector_answer": vector_result["answer"],
"vector_chunks": "\n\n".join(
[f"Chunk {i + 1}: {chunk}" for i, chunk in enumerate(vector_result["chunks"])]),
"graph_answer": graph_result["answer"],
"graph_chunks": "\n\n".join([f"Record {i + 1}: {chunk}" for i, chunk in enumerate(graph_result["chunks"])]),
"hybrid_answer": hybrid_result["answer"],
"hybrid_chunks": hybrid_chunks_formatted
}
except Exception as e:
logger.error(f"Error in compare_approaches: {str(e)}")
st.error(f"Error processing query: {str(e)}")
return {
"vector_answer": "Error processing query.",
"vector_chunks": "",
"graph_answer": "Error processing query.",
"graph_chunks": "",
"hybrid_answer": "Error processing query.",
"hybrid_chunks": ""
}
# Custom CSS for a modern dark theme UI
# Custom CSS for a modern dark theme UI with reduced font sizes
st.markdown("""
""", unsafe_allow_html=True)
# Streamlit App Layout
st.markdown('
', unsafe_allow_html=True)
# Initialize session state
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "vector_chunks" not in st.session_state:
st.session_state.vector_chunks = "Vector DB results will appear here"
if "graph_chunks" not in st.session_state:
st.session_state.graph_chunks = "Graph DB results will appear here"
if "hybrid_chunks" not in st.session_state:
st.session_state.hybrid_chunks = "Hybrid results will appear here"
# Create two columns for the split layout
col1, col2 = st.columns(2)
# Left Column: Chat Interface
# Left Column: Chat Interface
with col1:
# Chat display area using st.chat_message
with st.container():
# Placeholder if chat history is empty
if not st.session_state.chat_history:
st.markdown(
'Start the conversation by asking a question!
',
unsafe_allow_html=True
)
# Render chat history using st.chat_message
for message in st.session_state.chat_history:
with st.chat_message(message["role"], avatar="user" if message["role"] == "user" else "assistant"):
st.markdown(message["content"])
logger.info(f"Rendering chat message: {message}")
# Input area with Send and Clear buttons
with st.container():
query = st.text_input(
label="Ask a question",
placeholder="Ask in the format: 'What is the relationship between [Entity1] and [Entity2]?' (e.g., 'What is the relationship between Alice and TechCorp?')",
label_visibility="collapsed"
)
btn_col1, btn_col2 = st.columns([1, 1])
with btn_col1:
send_button = st.button("Send", key="send")
with btn_col2:
clear_button = st.button("Clear Chat", key="clear", help="Reset the conversation", type="secondary")
# Right Column: Single plain box with source text and use case questions
with col2:
st.markdown("""
Questions to Try:
- What are the key achievements of TechCorp?
- Who works for TechCorp?
**** Below source document has already been loaded for testing****
TechCorp Annual Report Summary
April 27, 2025
TechCorp, a leading AI company headquartered in San Francisco, achieved significant milestones in 2024. Founded by Alice Johnson, TechCorp employs 500 people and specializes in machine learning solutions. Alice, the CEO, collaborated with Bob Smith, CTO of InnovateAI, on a joint project to develop a new AI model. This partnership strengthened TechCorp's presence in New York, where InnovateAI is based.
The company expanded its operations to London, appointing Claire Brown as the regional director. Claire previously worked with Alice at Quantum Dynamics, a Boston-based firm. TechCorp's revenue grew by 20%, driven by contracts with GlobalTech in Seattle and DataSolutions in Chicago.
Key Achievements:
- Launched AI platform "NeuraNet" in San Francisco.
- Partnered with InnovateAI in New York.
- Opened a new office in London led by Claire Brown.
""", unsafe_allow_html=True)
# Handle the Send button click
if send_button and query:
# Add user message to chat history
st.session_state.chat_history.append({"role": "user", "content": query})
logger.info(f"User query added to chat history: {query}")
# Get responses from the processor
response = compare_approaches(query, processor)
logger.info(f"Compare approaches response: {response}")
# Add assistant response to chat history (only the answers)
assistant_response = (
f"**Vector DB Answer**: {response['vector_answer']}\n\n"
f"**Graph DB Answer**: {response['graph_answer']}\n\n"
f"**Hybrid Answer**: {response['hybrid_answer']}"
)
logger.info(f"Assistant response: {assistant_response}")
st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})
logger.info(f"Chat history after update: {st.session_state.chat_history}")
# Update the result displays (only chunks/records)
st.session_state.vector_chunks = response["vector_chunks"]
st.session_state.graph_chunks = response["graph_chunks"]
st.session_state.hybrid_chunks = response["hybrid_chunks"]
# Rerender the page
st.rerun()
# Handle the Clear Chat button
if clear_button:
st.session_state.chat_history = []
st.session_state.vector_chunks = "Vector DB results will appear here"
st.session_state.graph_chunks = "Graph DB results will appear here"
st.session_state.hybrid_chunks = "Hybrid results will appear here"
st.rerun()
# Chunks display at the bottom in accordion style
with st.container():
st.markdown('', unsafe_allow_html=True)
st.markdown("### Chunks and Records", unsafe_allow_html=True)
with st.expander("Vector DB Chunks"):
st.markdown(st.session_state.vector_chunks)
with st.expander("Graph DB Records"):
st.markdown(st.session_state.graph_chunks)
with st.expander("Hybrid Chunks/Records"):
st.markdown(st.session_state.hybrid_chunks)
st.markdown('
', unsafe_allow_html=True)
# Footer
st.markdown("""
""", unsafe_allow_html=True)
if __name__ == "__main__":
logger.info(f"===== Application Startup at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} =====")