File size: 5,284 Bytes
0d56e0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Import os to handle environment variables
#
# To run this app
# 
# streamlit run <path to this file, for example, rag\streamlit_app_basic.py>
#
import os
import uuid
import datetime
from dotenv import load_dotenv
import streamlit as st
from openai import AzureOpenAI

load_dotenv()

# --- Session State Initialization ---
if "conversations" not in st.session_state:
    st.session_state.conversations = {}

if "current_conversation_id" not in st.session_state:
    conversation_id = str(uuid.uuid4())
    st.session_state.conversations[conversation_id] = {
        "created_at": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
        "messages": [
            {"role": "system", "content":
                """You are a helpful AI assistant which answers questions about cricket and sports in general.

                   Do not answer questions about other topics.

                   If you do not know the answer, say 'I do not know the answer to that question.'"""
            }
        ]
    }
    st.session_state.current_conversation_id = conversation_id

def get_current_conversation():
    return st.session_state.conversations[st.session_state.current_conversation_id]["messages"]

def generate_response(input_text):
    client = AzureOpenAI(
        azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
        api_key=os.getenv("AZURE_OPENAI_KEY"),
        api_version=os.getenv("AZURE_OPENAI_API_VERSION")
    )
    model_name = os.getenv("AZURE_OPENAI_MODEL_NAME")
    try:
        current_messages = get_current_conversation()
        current_messages.append({"role": "user", "content": input_text})
        with st.spinner("Generating Answer. Please wait..."):
            response = client.chat.completions.create(
                model=model_name,
                messages=current_messages
            )
        answer = response.choices[0].message.content.strip()
        current_messages.append({"role": "assistant", "content": answer})
        return answer
    except Exception as e:
        print(f"Error: {e}")
        st.error("An error occurred while processing your request. Please check your Azure configuration.")
        return None

def create_new_conversation():
    conversation_id = str(uuid.uuid4())
    st.session_state.conversations[conversation_id] = {
        "created_at": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
        "messages": [
            {"role": "system", "content":
                """You are a helpful AI assistant which answers questions about cricket and sports in general.

                   Do not answer questions about other topics.

                   If you do not know the answer, say 'I do not know the answer to that question.'"""
            }
        ]
    }
    st.session_state.current_conversation_id = conversation_id
    st.session_state.user_question = ""  # Clear the input box

# --- Sidebar: Show only session titles ---
st.sidebar.title("Conversation Sessions")
for conv_id, conv_data in st.session_state.conversations.items():
    # Use first user message as title, else fallback to timestamp
    title = "New Conversation"
    for msg in conv_data["messages"]:
        if msg["role"] == "user":
            title = msg["content"][:30] + "..." if len(msg["content"]) > 30 else msg["content"]
            break
    if st.sidebar.button(title, key=f"conv_{conv_id}"):
        st.session_state.current_conversation_id = conv_id

# --- Main Page Layout ---
col1, col2 = st.columns([8, 1], gap="small")
with col2:
    st.markdown(
        """

        <style>

        div.stButton > button {

            width: 100%;

            background-color: #2563eb;

            color: white;

            font-weight: bold;

            border-radius: 6px;

            padding: 0.5em 0.8em;

            font-size: 1.1em;

        }

        </style>

        """,
        unsafe_allow_html=True,
    )
    st.button("🆕 New Chat", key="new_chat_btn", help="Start a new conversation", use_container_width=True, on_click=create_new_conversation)

st.markdown("<h1 style='text-align: center; color: #2563eb;'>Darshit's Chatbot 🤖</h1>", unsafe_allow_html=True)
st.markdown("---")

# --- Display Current Conversation ---
chat_container = st.container()
with chat_container:
    for message in get_current_conversation():
        if message["role"] == "user":
            st.markdown(
                f"<div style='background-color:#e0e7ff; border-radius:8px; padding:8px; margin-bottom:4px;'><b>You:</b> {message['content']}</div>",
                unsafe_allow_html=True,
            )
        elif message["role"] == "assistant":
            st.markdown(
                f"<div style='background-color:#f1f5f9; border-radius:8px; padding:8px; margin-bottom:8px;'><b>Bot:</b> {message['content']}</div>",
                unsafe_allow_html=True,
            )

# --- User Input ---
st.markdown("---")
user_question = st.text_input(
    "Ask any question about cricket or sports (Press Enter to submit):",
    key="user_question",
    placeholder="Type your question here...",
)
if user_question:
    answer = generate_response(user_question)
    if answer:
        st.info(answer)