File size: 12,252 Bytes
5d46812
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1937b1
5d46812
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1937b1
5d46812
 
 
 
 
c1937b1
5d46812
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1937b1
5d46812
 
 
 
 
 
c1937b1
 
5d46812
 
 
 
 
c1937b1
 
5d46812
 
 
 
 
 
 
c1937b1
 
5d46812
 
 
 
 
 
 
 
c1937b1
5d46812
 
 
 
 
 
 
c1937b1
5d46812
c1937b1
 
 
 
 
5d46812
 
 
 
 
 
 
 
 
 
 
 
 
 
c1937b1
 
 
 
 
5d46812
 
 
c1937b1
 
5d46812
 
 
 
 
 
c1937b1
5d46812
 
c1937b1
 
5d46812
 
 
 
 
c1937b1
5d46812
 
 
 
 
c1937b1
5d46812
 
c1937b1
5d46812
 
c1937b1
5d46812
 
 
c1937b1
 
 
 
5d46812
 
c1937b1
5d46812
 
 
 
c1937b1
 
 
5d46812
 
 
 
c1937b1
5d46812
 
 
 
 
c1937b1
5d46812
 
 
 
 
c1937b1
5d46812
 
c1937b1
 
 
5d46812
 
 
 
 
c1937b1
 
5d46812
 
 
c1937b1
5d46812
 
 
 
 
c1937b1
 
 
5d46812
 
c1937b1
 
5d46812
 
c1937b1
5d46812
c1937b1
 
5d46812
 
 
 
 
c1937b1
5d46812
c1937b1
5d46812
c1937b1
 
 
 
 
 
 
5d46812
c1937b1
5d46812
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1937b1
 
 
5d46812
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1937b1
 
5d46812
c1937b1
5d46812
c1937b1
5d46812
 
c1937b1
5d46812
c1937b1
5d46812
c1937b1
5d46812
 
 
 
 
 
 
 
 
c1937b1
 
 
 
 
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import os
import json
import datetime
from groq import Groq
import gradio as gr

# ============================================
# GROQ CLIENT
# ============================================

client = Groq(api_key=os.environ.get("GROQ_API_KEY"))

# ============================================
# CONVERSATION MEMORY STORE
# ============================================

conversation_store = {
    "histories": {},
    "total_messages": 0,
    "session_start": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
}

# ============================================
# AI PERSONALITIES
# ============================================

PERSONALITIES = {
    "πŸ€– Default Assistant": {
        "id": "default",
        "system": """You are a highly intelligent, helpful AI assistant like ChatGPT.
You are knowledgeable across all domains β€” science, tech, history, arts, coding, math, and more.
You give clear, well-structured, detailed answers.
You use markdown formatting with headers, bullet points, and code blocks when helpful.
You are friendly, direct, and never say you cannot help unless absolutely necessary.""",
        "welcome": "Hello! I'm your AI Assistant. Ask me anything β€” I'm here to help! πŸ€–"
    },

    "πŸ‘¨β€πŸ’» Code Expert": {
        "id": "coder",
        "system": """You are an elite software engineer and coding expert with 20 years of experience.
You are fluent in Python, JavaScript, Java, C++, SQL, React, Node.js, and all major frameworks.
When answering coding questions:
- Always provide complete, working code
- Add clear comments explaining each part
- Suggest best practices and optimizations
- Point out potential bugs or edge cases
- Format all code in proper markdown code blocks with language specified""",
        "welcome": "Hey! I'm your Code Expert. Share any coding problem β€” I'll help you solve it! πŸ‘¨β€πŸ’»"
    },

    "🧠 Deep Thinker": {
        "id": "thinker",
        "system": """You are a profound philosophical thinker and intellectual powerhouse.
You approach every question with depth, nuance, and multi-dimensional analysis.
You draw connections across philosophy, science, psychology, history, and culture.
You think like a combination of Socrates, Einstein, and Richard Feynman.
Always end with a thought-provoking follow-up question to deepen the conversation.""",
        "welcome": "Greetings, curious mind. Ask me anything worth thinking deeply about. 🧠"
    },

    "πŸŽ“ Study Tutor": {
        "id": "tutor",
        "system": """You are the world's best study tutor β€” patient, clear, and brilliant at explaining.
You can teach any subject from basics to advanced level.
- Start with the big picture, then zoom into details
- Use real-world analogies and examples
- Break complex topics into digestible steps
- Create summaries and quizzes when helpful""",
        "welcome": "Hi! I'm your personal Study Tutor. What would you like to learn today? πŸŽ“"
    },

    "✍️ Creative Writer": {
        "id": "writer",
        "system": """You are a masterful creative writer, storyteller, and wordsmith.
You excel at stories, poetry, copywriting, blog posts, essays, and all forms of writing.
Your writing is vivid, emotionally resonant, and always tailored to the tone requested.""",
        "welcome": "Hello, wordsmith! Tell me what you'd like me to write for you. ✍️"
    },

    "πŸ’Ό Business Advisor": {
        "id": "business",
        "system": """You are a seasoned business advisor and strategist with decades of experience.
You advise on strategy, marketing, finance, leadership, startups, and career growth.
You give bold, actionable, no-nonsense advice backed by real business frameworks.""",
        "welcome": "Hello! I'm your Business Advisor. What business challenge can I help you solve? πŸ’Ό"
    },

    "πŸ˜„ Fun & Humor": {
        "id": "humor",
        "system": """You are a witty, hilarious, and entertaining AI with a great sense of humor.
You love jokes, banter, riddles, and making any topic fun.
You have the humor of a stand-up comedian but still answer questions accurately β€” just with more fun!""",
        "welcome": "Heyyy! πŸ˜„ Ready to have some fun? Ask me anything β€” I'll make it entertaining!"
    },
}

# ============================================
# CORE CHAT FUNCTION
# ============================================

def chat(message, history, personality_name, temperature, max_tokens, system_override):
    if not message.strip():
        return "", history

    personality = PERSONALITIES.get(personality_name, PERSONALITIES["πŸ€– Default Assistant"])
    pid = personality["id"]
    system_prompt = system_override.strip() if system_override.strip() else personality["system"]

    # Build messages
    messages = [{"role": "system", "content": system_prompt}]
    for item in history:
        if item["role"] == "user":
            messages.append({"role": "user", "content": item["content"]})
        elif item["role"] == "assistant":
            messages.append({"role": "assistant", "content": item["content"]})
    messages.append({"role": "user", "content": message})

    try:
        response = client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=messages,
            temperature=temperature,
            max_tokens=int(max_tokens),
        )
        reply = response.choices[0].message.content
        conversation_store["total_messages"] += 1

        if pid not in conversation_store["histories"]:
            conversation_store["histories"][pid] = []
        conversation_store["histories"][pid].append({"role": "user", "content": message})
        conversation_store["histories"][pid].append({"role": "assistant", "content": reply})

        history.append({"role": "user", "content": message})
        history.append({"role": "assistant", "content": reply})
        return "", history

    except Exception as e:
        history.append({"role": "user", "content": message})
        history.append({"role": "assistant", "content": f"⚠️ Error: {str(e)}"})
        return "", history


def clear_chat():
    return []


def get_welcome(personality_name):
    personality = PERSONALITIES.get(personality_name, PERSONALITIES["πŸ€– Default Assistant"])
    return [{"role": "assistant", "content": personality["welcome"]}]


def get_stats():
    total = conversation_store["total_messages"]
    session = conversation_store["session_start"]
    histories = conversation_store["histories"]
    stats = f"""πŸ“Š Session Statistics

πŸ• Session Started: {session}
πŸ’¬ Total Messages: {total}
πŸ€– Personalities Used: {len(histories)}

Conversations by Personality:
"""
    for pid, msgs in histories.items():
        stats += f"\nβ€’ {pid}: {len(msgs)//2} exchanges"
    return stats


def export_chat(history, personality_name):
    if not history:
        return "No conversation to export."
    export = f"# AI Chat Export\nPersonality: {personality_name}\nDate: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}\n{'='*50}\n\n"
    for item in history:
        role = "You" if item["role"] == "user" else "AI"
        export += f"**{role}:** {item['content']}\n\n---\n\n"
    return export


def summarize_chat(history, personality_name):
    if len(history) < 2:
        return "Not enough conversation to summarize."
    conversation_text = ""
    for item in history[-10:]:
        role = "User" if item["role"] == "user" else "AI"
        conversation_text += f"{role}: {item['content'][:300]}\n"
    try:
        response = client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "system", "content": "Summarize this conversation in 5 bullet points."},
                {"role": "user", "content": conversation_text}
            ],
            temperature=0.3,
            max_tokens=500,
        )
        return f"πŸ“‹ Conversation Summary:\n\n{response.choices[0].message.content}"
    except Exception as e:
        return f"Error: {str(e)}"


# ============================================
# GRADIO UI β€” Gradio 6.0 compatible
# ============================================

with gr.Blocks(title="πŸ€– AI Chat Assistant") as demo:

    gr.Markdown("# πŸ€– AI Chat Assistant\n### Full ChatGPT-like experience powered by LLaMA 3.3")

    with gr.Row():

        # LEFT SIDEBAR
        with gr.Column(scale=1):

            gr.Markdown("### 🎭 Personality")
            personality = gr.Radio(
                choices=list(PERSONALITIES.keys()),
                value="πŸ€– Default Assistant",
                label="Choose AI Mode",
                interactive=True
            )

            gr.Markdown("### βš™οΈ Settings")
            temperature = gr.Slider(
                minimum=0.0, maximum=1.5, value=0.7, step=0.1,
                label="🌑️ Creativity",
                info="Low = focused | High = creative"
            )
            max_tokens = gr.Slider(
                minimum=256, maximum=4096, value=1024, step=256,
                label="πŸ“ Response Length"
            )

            gr.Markdown("### πŸ› οΈ Custom Instructions")
            system_override = gr.Textbox(
                placeholder="Override personality with custom instructions...",
                label="System Prompt (optional)",
                lines=3
            )

            gr.Markdown("### πŸ”§ Actions")
            clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary")
            summarize_btn = gr.Button("πŸ“‹ Summarize", variant="secondary")
            export_btn = gr.Button("πŸ’Ύ Export Chat", variant="secondary")
            stats_btn = gr.Button("πŸ“Š Stats", variant="secondary")

            output_box = gr.Textbox(
                label="πŸ“„ Output",
                lines=8,
                interactive=False
            )

        # RIGHT CHAT AREA
        with gr.Column(scale=3):

            chatbot = gr.Chatbot(
                label="Chat",
                height=500,
                show_label=False,
                render_markdown=True,
            )

            with gr.Row():
                msg_input = gr.Textbox(
                    placeholder="Message AI Assistant... (Press Enter to send)",
                    lines=2,
                    scale=5,
                    show_label=False,
                    autofocus=True,
                )
                send_btn = gr.Button("Send ➀", variant="primary", scale=1)

            gr.Markdown("**⚑ Quick Prompts:**")
            with gr.Row():
                q1 = gr.Button("Explain quantum computing", size="sm")
                q2 = gr.Button("Write Python REST API", size="sm")
                q3 = gr.Button("30-day ML study plan", size="sm")
                q4 = gr.Button("Tell me a joke πŸ˜„", size="sm")

    # ============================================
    # EVENT HANDLERS
    # ============================================

    send_btn.click(
        fn=chat,
        inputs=[msg_input, chatbot, personality, temperature, max_tokens, system_override],
        outputs=[msg_input, chatbot]
    )
    msg_input.submit(
        fn=chat,
        inputs=[msg_input, chatbot, personality, temperature, max_tokens, system_override],
        outputs=[msg_input, chatbot]
    )
    personality.change(fn=get_welcome, inputs=[personality], outputs=[chatbot])
    clear_btn.click(fn=clear_chat, outputs=[chatbot])
    summarize_btn.click(
        fn=summarize_chat,
        inputs=[chatbot, personality],
        outputs=[output_box]
    )
    export_btn.click(
        fn=export_chat,
        inputs=[chatbot, personality],
        outputs=[output_box]
    )
    stats_btn.click(fn=get_stats, outputs=[output_box])

    q1.click(fn=lambda: "Explain quantum computing in simple terms", outputs=[msg_input])
    q2.click(fn=lambda: "Write Python code to build a REST API with FastAPI", outputs=[msg_input])
    q3.click(fn=lambda: "Give me a 30-day study plan to learn Machine Learning", outputs=[msg_input])
    q4.click(fn=lambda: "Tell me the funniest joke you know", outputs=[msg_input])

    demo.load(fn=get_welcome, inputs=[personality], outputs=[chatbot])


demo.launch(
    server_name="0.0.0.0",
    server_port=7860,
    theme=gr.themes.Soft()
)