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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from typing import Optional
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
import google.generativeai as genai
|
| 6 |
+
import gradio as gr
|
| 7 |
+
|
| 8 |
+
GEMINI_API_KEY = "AIzaSyDJXIGTcvaTTwimpR2Gf1DMjVy01uEGWNI"
|
| 9 |
+
MODEL_NAME = "models/gemini-2.5-flash"
|
| 10 |
+
|
| 11 |
+
# Configure the API
|
| 12 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 13 |
+
|
| 14 |
+
class GeminiChatBot:
|
| 15 |
+
"""Main chatbot class with context management and multiple modes"""
|
| 16 |
+
|
| 17 |
+
def __init__(self, model_name: str = MODEL_NAME):
|
| 18 |
+
self.model = genai.GenerativeModel(model_name)
|
| 19 |
+
self.conversation_history = []
|
| 20 |
+
self.chat_session = None
|
| 21 |
+
self.system_prompt = ""
|
| 22 |
+
|
| 23 |
+
def set_system_prompt(self, mode: str):
|
| 24 |
+
"""Set system prompt based on chatbot mode"""
|
| 25 |
+
prompts = {
|
| 26 |
+
"general": """You are a helpful, accurate, and friendly AI assistant.
|
| 27 |
+
Provide clear, concise, and informative responses.
|
| 28 |
+
Always be honest about limitations and uncertainty.""",
|
| 29 |
+
|
| 30 |
+
"technical": """You are an expert technical support assistant.
|
| 31 |
+
Provide detailed technical solutions, code examples, and best practices.
|
| 32 |
+
When unsure, ask clarifying questions. Always suggest verification steps.""",
|
| 33 |
+
|
| 34 |
+
"creative": """You are a creative writing assistant with strong storytelling abilities.
|
| 35 |
+
Help users with creative writing, brainstorming, and narrative development.
|
| 36 |
+
Provide engaging and imaginative content.""",
|
| 37 |
+
|
| 38 |
+
"educational": """You are an educational tutor. Explain concepts clearly,
|
| 39 |
+
break down complex topics, and provide examples.
|
| 40 |
+
Encourage learning and ask clarifying questions.""",
|
| 41 |
+
|
| 42 |
+
"medical": """You are a medical information assistant.
|
| 43 |
+
Provide accurate health information and general guidance.
|
| 44 |
+
Always recommend consulting healthcare professionals for serious concerns.
|
| 45 |
+
Do NOT provide emergency medical advice."""
|
| 46 |
+
}
|
| 47 |
+
self.system_prompt = prompts.get(mode, prompts["general"])
|
| 48 |
+
|
| 49 |
+
def chat(self, user_message: str, mode: str = "general", temperature: float = 0.7) -> str:
|
| 50 |
+
"""Generate response using Gemini with context"""
|
| 51 |
+
try:
|
| 52 |
+
self.set_system_prompt(mode)
|
| 53 |
+
|
| 54 |
+
# Build messages with system context
|
| 55 |
+
messages = [
|
| 56 |
+
{"role": "user", "parts": [f"[SYSTEM: {self.system_prompt}]\n\n{user_message}"]}
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
# Add conversation history for context (last 5 exchanges)
|
| 60 |
+
if self.conversation_history:
|
| 61 |
+
history_context = "\n".join([
|
| 62 |
+
f"Previous: {msg}"
|
| 63 |
+
for msg in self.conversation_history[-5:]
|
| 64 |
+
])
|
| 65 |
+
full_message = f"[Conversation Context]\n{history_context}\n\n[New Message]\n{user_message}"
|
| 66 |
+
else:
|
| 67 |
+
full_message = user_message
|
| 68 |
+
|
| 69 |
+
# Generate response
|
| 70 |
+
response = self.model.generate_content(
|
| 71 |
+
full_message,
|
| 72 |
+
generation_config=genai.types.GenerationConfig(
|
| 73 |
+
temperature=temperature,
|
| 74 |
+
top_p=0.95,
|
| 75 |
+
top_k=40
|
| 76 |
+
)
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
bot_response = response.text
|
| 80 |
+
|
| 81 |
+
# Store in history
|
| 82 |
+
self.conversation_history.append(f"User: {user_message[:100]}...")
|
| 83 |
+
self.conversation_history.append(f"Bot: {bot_response[:100]}...")
|
| 84 |
+
|
| 85 |
+
return bot_response
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
return f"Error: {str(e)}\n\nMake sure your API key is valid. Get it from: https://aistudio.google.com/app/apikey"
|
| 89 |
+
|
| 90 |
+
# Initialize chatbot
|
| 91 |
+
chatbot = GeminiChatBot()
|
| 92 |
+
|
| 93 |
+
# Gradio Interface Functions
|
| 94 |
+
def respond(message: str, chat_history: list, mode: str, temperature: float):
|
| 95 |
+
"""Respond to user message and return updated chat history"""
|
| 96 |
+
response = chatbot.chat(message, mode=mode, temperature=temperature)
|
| 97 |
+
chat_history.append({"role": "user", "content": message})
|
| 98 |
+
chat_history.append({"role": "assistant", "content": response})
|
| 99 |
+
return "", chat_history
|
| 100 |
+
|
| 101 |
+
def clear_history():
|
| 102 |
+
"""Clear conversation history"""
|
| 103 |
+
chatbot.conversation_history = []
|
| 104 |
+
return [], ""
|
| 105 |
+
|
| 106 |
+
def export_chat(chat_history: list) -> str:
|
| 107 |
+
"""Export chat as JSON"""
|
| 108 |
+
if not chat_history:
|
| 109 |
+
return "No chat history to export"
|
| 110 |
+
|
| 111 |
+
export_data = {
|
| 112 |
+
"timestamp": datetime.now().isoformat(),
|
| 113 |
+
"conversation": chat_history
|
| 114 |
+
}
|
| 115 |
+
return json.dumps(export_data, indent=2)
|
| 116 |
+
|
| 117 |
+
# Create Gradio Interface
|
| 118 |
+
with gr.Blocks(title="Gemini ChatBot", theme=gr.themes.Soft()) as demo:
|
| 119 |
+
gr.Markdown("""
|
| 120 |
+
# 🤖 Nexus Intelligent ChatBot
|
| 121 |
+
|
| 122 |
+
A generalized, accurate chatbot powered by Google's Gemini AI.
|
| 123 |
+
Select your mode and start chatting!
|
| 124 |
+
""")
|
| 125 |
+
|
| 126 |
+
with gr.Row():
|
| 127 |
+
with gr.Column(scale=3):
|
| 128 |
+
chatbot_ui = gr.Chatbot(
|
| 129 |
+
label="Chat History",
|
| 130 |
+
height=500,
|
| 131 |
+
show_label=True
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
with gr.Column(scale=1):
|
| 135 |
+
gr.Markdown("### ⚙️ Settings")
|
| 136 |
+
|
| 137 |
+
mode = gr.Radio(
|
| 138 |
+
choices=["general", "technical", "creative", "educational", "medical"],
|
| 139 |
+
value="general",
|
| 140 |
+
label="Chat Mode",
|
| 141 |
+
info="Select conversation style"
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
temperature = gr.Slider(
|
| 145 |
+
minimum=0,
|
| 146 |
+
maximum=2,
|
| 147 |
+
value=0.7,
|
| 148 |
+
step=0.1,
|
| 149 |
+
label="Temperature",
|
| 150 |
+
info="Higher = more creative, Lower = more focused"
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
with gr.Row():
|
| 154 |
+
msg_input = gr.Textbox(
|
| 155 |
+
placeholder="Type your message here...",
|
| 156 |
+
label="Your Message",
|
| 157 |
+
lines=2
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
with gr.Row():
|
| 161 |
+
send_btn = gr.Button("Send", variant="primary", scale=2)
|
| 162 |
+
clear_btn = gr.Button("Clear Chat", scale=1)
|
| 163 |
+
export_btn = gr.Button("Export Chat", scale=1)
|
| 164 |
+
|
| 165 |
+
export_output = gr.Textbox(
|
| 166 |
+
label="Exported Chat (JSON)",
|
| 167 |
+
interactive=False,
|
| 168 |
+
visible=False
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
# Event handlers
|
| 172 |
+
send_btn.click(
|
| 173 |
+
respond,
|
| 174 |
+
inputs=[msg_input, chatbot_ui, mode, temperature],
|
| 175 |
+
outputs=[msg_input, chatbot_ui]
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
msg_input.submit(
|
| 179 |
+
respond,
|
| 180 |
+
inputs=[msg_input, chatbot_ui, mode, temperature],
|
| 181 |
+
outputs=[msg_input, chatbot_ui]
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
clear_btn.click(
|
| 185 |
+
clear_history,
|
| 186 |
+
outputs=[chatbot_ui, msg_input]
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
def toggle_export_visibility():
|
| 190 |
+
return gr.update(visible=True)
|
| 191 |
+
|
| 192 |
+
def get_and_show_export(chat_history):
|
| 193 |
+
return export_chat(chat_history), gr.update(visible=True)
|
| 194 |
+
|
| 195 |
+
export_btn.click(
|
| 196 |
+
get_and_show_export,
|
| 197 |
+
inputs=[chatbot_ui],
|
| 198 |
+
outputs=[export_output, export_output]
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
gr.Markdown("""
|
| 202 |
+
### 📝 Chat Modes:
|
| 203 |
+
- **General**: Friendly assistant for everyday questions
|
| 204 |
+
- **Technical**: Expert technical support and code help
|
| 205 |
+
- **Creative**: Storytelling and creative writing
|
| 206 |
+
- **Educational**: Learning and concept explanation
|
| 207 |
+
- **Medical**: Health information (consult professionals for serious concerns)
|
| 208 |
+
|
| 209 |
+
### 🔑 Setup:
|
| 210 |
+
1. Get your API key from [Google AI Studio](https://aistudio.google.com/app/apikey)
|
| 211 |
+
2. Set `GEMINI_API_KEY` in `.env` file or environment variables
|
| 212 |
+
3. Run the app and start chatting!
|
| 213 |
+
""")
|
| 214 |
+
|
| 215 |
+
if __name__ == "__main__":
|
| 216 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==4.36.0
|
| 2 |
+
google-generativeai==0.3.0
|
| 3 |
+
requests==2.31.0
|