File size: 9,443 Bytes
9698c36
 
 
 
e25c0f9
9698c36
 
 
 
 
 
 
 
 
 
 
 
e25c0f9
9698c36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e25c0f9
 
9698c36
e25c0f9
9698c36
 
 
 
 
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import os
import uuid
import json
import time
import gradio as gr
import logging
from dotenv import load_dotenv
import google.generativeai as genai

from langgraph.graph import START, MessagesState, StateGraph
from langgraph.checkpoint.memory import MemorySaver
from langchain_core.messages import HumanMessage, AIMessage
from langchain_core.prompts.chat import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    MessagesPlaceholder,
    HumanMessagePromptTemplate,
)
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.messages import BaseMessage


# === Logging & .env ===
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
load_dotenv()

GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
if not GEMINI_API_KEY:
    raise ValueError("Missing GEMINI_API_KEY")
genai.configure(api_key=GEMINI_API_KEY)

HISTORY_FILE = "chat_history.json"

# === Persistent Storage ===
def load_all_sessions():
    if os.path.exists(HISTORY_FILE):
        with open(HISTORY_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return {}

def save_all_sessions(sessions):
    with open(HISTORY_FILE, "w", encoding="utf-8") as f:
        json.dump(sessions, f, indent=2)

# === Chatbot Class ===
class GeminiChatbot:
    def __init__(self):
        self.setup_model()

    def setup_model(self):
        system_template = """
        You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe.
        Your answers should be informative, engaging, and accurate. If a question doesn't make any sense, or isn't factually coherent, explain why instead of answering something not correct.
        If you don't know the answer to a question, please don't share false information.
        """

        self.prompt = ChatPromptTemplate.from_messages([
            SystemMessagePromptTemplate.from_template(system_template),
            MessagesPlaceholder(variable_name="chat_history"),
            HumanMessagePromptTemplate.from_template("{input}")
        ])

        self.model = ChatGoogleGenerativeAI(
            model="gemini-2.0-flash",
            temperature=0.7,
            top_p=0.95,
            google_api_key=GEMINI_API_KEY,
            convert_system_message_to_human=True
        )

        def call_model(state: MessagesState):
            chat_history = state["messages"][:-1]
            user_input = state["messages"][-1].content

            formatted_messages = self.prompt.format_messages(
                chat_history=chat_history,
                input=user_input
            )

            response = self.model.invoke(formatted_messages)
            return {"messages": response}

        workflow = StateGraph(state_schema=MessagesState)
        workflow.add_node("model", call_model)
        workflow.add_edge(START, "model")

        self.memory = MemorySaver()
        self.app = workflow.compile(checkpointer=self.memory)

    def get_response(self, user_message, history, thread_id):
        try:
            # Convert string history into LangChain message objects
            langchain_history = []
            for user, bot in history:
                langchain_history.append(HumanMessage(content=user))
                langchain_history.append(AIMessage(content=bot))

            # Add the new user message
            input_message = HumanMessage(content=user_message)
            full_history = langchain_history + [input_message]

            full_response = ""
            config = {"configurable": {"thread_id": thread_id}}

            # Invoke the model with full conversation
            response = self.app.invoke({"messages": full_history}, config)
            complete_response = response["messages"][-1].content

            for char in complete_response:
                full_response += char
                yield full_response
                time.sleep(0.01)

        except Exception as e:
            logger.error(f"LangGraph Error: {e}")
            yield f"⚠ Error: {type(e).__name__}{str(e)}"


# === Gradio UI ===
chatbot = GeminiChatbot()
sessions = load_all_sessions()


def launch_interface():
    with gr.Blocks(
            theme=gr.themes.Base(),
            css="""
        body {
            background-color: black;
        }
        .gr-block.gr-textbox textarea {
            background-color: #2f2f2f;
            color: white;
        }
        .gr-chatbot {
            background-color: #2f2f2f;
            color: white;
        }
        .gr-button, .gr-dropdown {
            margin: 5px auto;
            display: block;
            width: 50%;
        }
        .gr-markdown h2 {
            text-align: center;
            color: white;
        }
        """
    ) as demo:
        demo.title = "LangChain Powered ChatBot"
        gr.Markdown("## LangChain Powered ChatBot")

        current_thread_id = gr.State()
        session_names = gr.State()
        history = gr.State([])

        # Initialize with first session or create new
        if not sessions:
            new_id = str(uuid.uuid4())
            sessions[new_id] = []
            save_all_sessions(sessions)
            current_thread_id.value = new_id
            session_names.value = [f"NEW: {new_id}"]
        else:
            current_thread_id.value = next(iter(sessions.keys()))
            session_names.value = [f"PREVIOUS: {k}" for k in sessions.keys()]

        def get_dropdown_choices():
            """Get current dropdown choices including active sessions and new chat"""
            choices = []
            for session_id in sessions:
                if sessions[session_id]:  # Only show sessions with history
                    choices.append(f"PREVIOUS: {session_id}")
            choices.append(f"NEW: {current_thread_id.value}")
            return choices

        with gr.Column():
            new_chat_btn = gr.Button("New Chat", variant="primary")
            session_selector = gr.Dropdown(
                label="Chats",
                choices=get_dropdown_choices(),
                value=f"NEW: {current_thread_id.value}",
                interactive=True
            )

        chatbot_ui = gr.Chatbot(label="Conversation", height=320)

        with gr.Row():
            msg = gr.Textbox(placeholder="Ask a question...", container=False, scale=9)
            send = gr.Button("Send", variant="primary", scale=1)

        clear = gr.Button("Clear Current Chat")

        def start_new_chat():
            new_id = str(uuid.uuid4())
            sessions[new_id] = []
            save_all_sessions(sessions)

            # Format for dropdown
            display_name = f"NEW: {new_id}"
            updated_choices = [f"PREVIOUS: {k}" for k in sessions if sessions[k]] + [display_name]

            return (
                new_id,  # thread ID state
                [],  # history
                gr.update(choices=updated_choices, value=display_name),  # update dropdown
                display_name  # visible value
            )



        def switch_chat(selected_display_id):
            """Switch between different chat sessions"""
            if not selected_display_id:
                return current_thread_id.value, [], ""

            true_id = selected_display_id.split(": ", 1)[-1]
            chat_history = sessions.get(true_id, [])
            return true_id, chat_history, selected_display_id

        def respond(message, history, thread_id):
            """Generate response and update chat history"""
            if not message.strip():
                yield history
                return

            # Add user message to history
            history.append((message, ""))
            yield history

            # Stream response
            full_response = ""
            for chunk in chatbot.get_response(message, history[:-1], thread_id):
                full_response = chunk
                history[-1] = (message, full_response)
                yield history

            # Save updated session
            sessions[thread_id] = history
            save_all_sessions(sessions)

        def clear_current(thread_id):
            """Clear current chat history"""
            sessions[thread_id] = []
            save_all_sessions(sessions)
            return []

        new_chat_btn.click(
            start_new_chat,
            outputs=[current_thread_id, chatbot_ui, session_selector, session_selector]
        )

        session_selector.change(
            switch_chat,
            inputs=session_selector,
            outputs=[current_thread_id, chatbot_ui, session_selector]
        )

        send.click(
            respond,
            inputs=[msg, chatbot_ui, current_thread_id],
            outputs=[chatbot_ui]
        ).then(
            lambda: "", None, msg  # Clear input after sending
        )

        msg.submit(
            respond,
            inputs=[msg, chatbot_ui, current_thread_id],
            outputs=[chatbot_ui]
        ).then(
            lambda: "", None, msg  # Clear input after sending
        )

        clear.click(
            clear_current,
            inputs=[current_thread_id],
            outputs=[chatbot_ui]
        )

    return demo



# === Run App ===
if __name__ == "__main__":
    try:
        demo = launch_interface()
        demo.launch(share=True)
    except Exception as e:
        logger.critical(f"App failed: {e}")