shukdevdatta123 commited on
Commit
d3feebc
·
verified ·
1 Parent(s): 907fc48

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -589
app.py DELETED
@@ -1,589 +0,0 @@
1
- import os
2
- import json
3
- import time
4
- import gradio as gr
5
- from datetime import datetime
6
- from typing import List, Dict, Any, Optional, Union
7
- import threading
8
-
9
- # Import Groq
10
- from groq import Groq
11
-
12
- class CreativeAgenticAI:
13
- """
14
- Creative Agentic AI Chat Tool using Groq's compound models
15
- """
16
-
17
- def __init__(self, api_key: str, model: str = "compound-beta"):
18
- """
19
- Initialize the Creative Agentic AI system.
20
-
21
- Args:
22
- api_key: Groq API key
23
- model: Which Groq model to use ('compound-beta' or 'compound-beta-mini')
24
- """
25
- self.api_key = api_key
26
- if not self.api_key:
27
- raise ValueError("No API key provided")
28
-
29
- self.client = Groq(api_key=self.api_key)
30
- self.model = model
31
- self.conversation_history = []
32
-
33
- def chat(self, message: str,
34
- include_domains: List[str] = None,
35
- exclude_domains: List[str] = None,
36
- system_prompt: str = None,
37
- temperature: float = 0.7,
38
- max_tokens: int = 1024) -> Dict:
39
- """
40
- Send a message to the AI and get a response
41
-
42
- Args:
43
- message: User's message
44
- include_domains: List of domains to include for web search
45
- exclude_domains: List of domains to exclude from web search
46
- system_prompt: Custom system prompt
47
- temperature: Model temperature (0.0-2.0)
48
- max_tokens: Maximum tokens in response
49
-
50
- Returns:
51
- AI response with metadata
52
- """
53
- # Default system prompt if none provided
54
- if not system_prompt:
55
- system_prompt = """You are a creative and intelligent AI assistant with agentic capabilities.
56
- You can search the web, analyze information, and provide comprehensive responses.
57
- Be helpful, creative, and engaging while maintaining accuracy."""
58
-
59
- # Build messages
60
- messages = [{"role": "system", "content": system_prompt}]
61
-
62
- # Add conversation history (last 10 exchanges)
63
- messages.extend(self.conversation_history[-20:]) # Last 10 user-assistant pairs
64
-
65
- # Add current message
66
- messages.append({"role": "user", "content": message})
67
-
68
- # Set up API parameters
69
- params = {
70
- "messages": messages,
71
- "model": self.model,
72
- "temperature": temperature,
73
- "max_tokens": max_tokens
74
- }
75
-
76
- # Add domain filtering if specified
77
- if include_domains and include_domains[0].strip():
78
- params["include_domains"] = [domain.strip() for domain in include_domains if domain.strip()]
79
- if exclude_domains and exclude_domains[0].strip():
80
- params["exclude_domains"] = [domain.strip() for domain in exclude_domains if domain.strip()]
81
-
82
- try:
83
- # Make the API call
84
- response = self.client.chat.completions.create(**params)
85
- content = response.choices[0].message.content
86
-
87
- # Extract tool usage information
88
- tool_info = self._extract_tool_info(response)
89
-
90
- # Add to conversation history
91
- self.conversation_history.append({"role": "user", "content": message})
92
- self.conversation_history.append({"role": "assistant", "content": content})
93
-
94
- # Create response object
95
- response_data = {
96
- "content": content,
97
- "timestamp": datetime.now().isoformat(),
98
- "model": self.model,
99
- "tool_usage": tool_info,
100
- "parameters": {
101
- "temperature": temperature,
102
- "max_tokens": max_tokens,
103
- "include_domains": include_domains,
104
- "exclude_domains": exclude_domains
105
- }
106
- }
107
-
108
- return response_data
109
-
110
- except Exception as e:
111
- error_msg = f"Error: {str(e)}"
112
- self.conversation_history.append({"role": "user", "content": message})
113
- self.conversation_history.append({"role": "assistant", "content": error_msg})
114
-
115
- return {
116
- "content": error_msg,
117
- "timestamp": datetime.now().isoformat(),
118
- "model": self.model,
119
- "tool_usage": None,
120
- "error": str(e)
121
- }
122
-
123
- def _extract_tool_info(self, response) -> Dict:
124
- """Extract tool usage information in a JSON serializable format"""
125
- tool_info = None
126
- if hasattr(response.choices[0].message, 'executed_tools'):
127
- tools = response.choices[0].message.executed_tools
128
- if tools:
129
- tool_info = []
130
- for tool in tools:
131
- tool_dict = {
132
- "tool_type": getattr(tool, "type", "unknown"),
133
- "tool_name": getattr(tool, "name", "unknown"),
134
- }
135
- if hasattr(tool, "input"):
136
- tool_dict["input"] = str(tool.input)
137
- if hasattr(tool, "output"):
138
- tool_dict["output"] = str(tool.output)
139
- tool_info.append(tool_dict)
140
- return tool_info
141
-
142
- def clear_history(self):
143
- """Clear conversation history"""
144
- self.conversation_history = []
145
-
146
- def get_history_summary(self) -> str:
147
- """Get a summary of conversation history"""
148
- if not self.conversation_history:
149
- return "No conversation history"
150
-
151
- user_messages = [msg for msg in self.conversation_history if msg["role"] == "user"]
152
- assistant_messages = [msg for msg in self.conversation_history if msg["role"] == "assistant"]
153
-
154
- return f"Conversation: {len(user_messages)} user messages, {len(assistant_messages)} assistant responses"
155
-
156
- # Global variables
157
- ai_instance = None
158
- api_key_status = "Not Set"
159
-
160
- def validate_api_key(api_key: str, model: str) -> str:
161
- """Validate Groq API key and initialize AI instance"""
162
- global ai_instance, api_key_status
163
-
164
- if not api_key or len(api_key.strip()) < 10:
165
- api_key_status = "Invalid ❌"
166
- return "❌ Please enter a valid API key (should be longer than 10 characters)"
167
-
168
- try:
169
- # Test the API key
170
- client = Groq(api_key=api_key)
171
- # Try a simple request to validate
172
- test_response = client.chat.completions.create(
173
- messages=[{"role": "user", "content": "Hello"}],
174
- model=model,
175
- max_tokens=10
176
- )
177
-
178
- # Create AI instance
179
- ai_instance = CreativeAgenticAI(api_key=api_key, model=model)
180
- api_key_status = "Valid ✅"
181
-
182
- return f"✅ API Key Valid! Creative Agentic AI is ready.\n\n**Model:** {model}\n**Status:** Connected and ready for chat!"
183
-
184
- except Exception as e:
185
- api_key_status = "Invalid ❌"
186
- ai_instance = None
187
- return f"❌ Error validating API key: {str(e)}\n\nPlease check your API key and try again."
188
-
189
- def update_model(model: str) -> str:
190
- """Update the model selection"""
191
- global ai_instance
192
-
193
- if ai_instance:
194
- ai_instance.model = model
195
- return f"✅ Model updated to: **{model}**"
196
- else:
197
- return "⚠️ Please set your API key first"
198
-
199
- def chat_with_ai(message: str,
200
- include_domains: str,
201
- exclude_domains: str,
202
- system_prompt: str,
203
- temperature: float,
204
- max_tokens: int,
205
- history: List) -> tuple:
206
- """Main chat function"""
207
- global ai_instance
208
-
209
- if not ai_instance:
210
- error_msg = "⚠️ Please set your Groq API key first!"
211
- history.append([message, error_msg])
212
- return history, ""
213
-
214
- if not message.strip():
215
- return history, ""
216
-
217
- # Process domain lists
218
- include_list = [d.strip() for d in include_domains.split(",")] if include_domains.strip() else []
219
- exclude_list = [d.strip() for d in exclude_domains.split(",")] if exclude_domains.strip() else []
220
-
221
- try:
222
- # Get AI response
223
- response = ai_instance.chat(
224
- message=message,
225
- include_domains=include_list if include_list else None,
226
- exclude_domains=exclude_list if exclude_list else None,
227
- system_prompt=system_prompt if system_prompt.strip() else None,
228
- temperature=temperature,
229
- max_tokens=int(max_tokens)
230
- )
231
-
232
- # Format response
233
- ai_response = response["content"]
234
-
235
- # Add tool usage info if available
236
- if response.get("tool_usage"):
237
- ai_response += f"\n\n*🔧 Tools used: {len(response['tool_usage'])} tool(s)*"
238
-
239
- # Add to history
240
- history.append([message, ai_response])
241
-
242
- return history, ""
243
-
244
- except Exception as e:
245
- error_msg = f"❌ Error: {str(e)}"
246
- history.append([message, error_msg])
247
- return history, ""
248
-
249
- def clear_chat_history():
250
- """Clear the chat history"""
251
- global ai_instance
252
- if ai_instance:
253
- ai_instance.clear_history()
254
- return []
255
-
256
- def create_gradio_app():
257
- """Create the main Gradio application"""
258
-
259
- # Custom CSS for better styling
260
- css = """
261
- .container {
262
- max-width: 1200px;
263
- margin: 0 auto;
264
- }
265
- .header {
266
- text-align: center;
267
- background: linear-gradient(to right, #00ff94, #00b4db);
268
- color: white;
269
- padding: 20px;
270
- border-radius: 10px;
271
- margin-bottom: 20px;
272
- }
273
- .status-box {
274
- background-color: #f8f9fa;
275
- border: 1px solid #dee2e6;
276
- border-radius: 8px;
277
- padding: 15px;
278
- margin: 10px 0;
279
- }
280
- .example-box {
281
- background-color: #e8f4fd;
282
- border-left: 4px solid #007bff;
283
- padding: 15px;
284
- margin: 10px 0;
285
- border-radius: 0 8px 8px 0;
286
- }
287
- .domain-info {
288
- background-color: #fff3cd;
289
- border: 1px solid #ffeaa7;
290
- border-radius: 8px;
291
- padding: 15px;
292
- margin: 10px 0;
293
- }
294
- #neuroscope-accordion {
295
- background: linear-gradient(to right, #00ff94, #00b4db);
296
- border-radius: 8px;
297
- }
298
- """
299
-
300
- with gr.Blocks(css=css, title="🤖 Creative Agentic AI Chat", theme=gr.themes.Ocean()) as app:
301
-
302
- # Header
303
- gr.HTML("""
304
- <div class="header">
305
- <h1>🤖 NeuroScope-AI</h1>
306
- <p>Powered by Groq's Compound Models with Web Search & Agentic Capabilities</p>
307
- </div>
308
- """)
309
-
310
- # NeuroScope AI Section
311
- with gr.Group():
312
- with gr.Accordion("🤖 NeuroScope AI", open=False, elem_id="neuroscope-accordion"):
313
- gr.Markdown("""
314
- - 🧠 Intelligence (Neuro)
315
- - 🔍 Domain filtering (Scope)
316
- - 🤖 AI capabilities (AI)
317
- - ⚡ Precision (Scope implies focused, targeted results)
318
- """)
319
- with gr.Group():
320
- with gr.Accordion("📚 IMPORTANT !!!", open=False, elem_id="neuroscope-accordion"):
321
- gr.Markdown("""
322
- ### 🔍 **Web Search Behavior in NeuroScope AI**
323
-
324
- **No Domains Specified:**
325
-
326
- - AI operates with **unrestricted web search capabilities**.
327
- - Compound models autonomously search the **entire internet** for the most relevant and up-to-date information.
328
- - AI has complete freedom to use its **agentic tools** and browse **any website** it finds useful.
329
-
330
- **Include Domains Specified (e.g., `arxiv.org`, `*.edu`):**
331
-
332
- - AI is restricted to search **only the specified domains**.
333
- - Acts as a **strict whitelist**, making the AI **laser-focused** on your chosen sources.
334
- - Ensures information is sourced from **preferred or authoritative domains** (e.g., academic or research-focused).
335
-
336
- **Exclude Domains Specified (e.g., `wikipedia.org`, `reddit.com`):**
337
-
338
- - AI searches the entire web **except the listed domains**.
339
- - Useful for **filtering out unreliable or unwanted sources**.
340
- - Allows broad search with **targeted exclusions**.
341
-
342
- **Both Include and Exclude Domains Specified:**
343
-
344
- - **Only the include domains** are used for searching.
345
- - **Exclude list is ignored** because the include list already restricts search scope.
346
- - Guarantees AI pulls content **exclusively from whitelisted domains**, regardless of the excluded ones.
347
-
348
- ---
349
-
350
- ### 🎭 **Custom System Prompt Feature**
351
-
352
- Allows complete override of the AI’s **default personality and behavior**.
353
- You can redefine the AI to act as:
354
-
355
- - A **professional business consultant**
356
- - A **coding mentor**
357
- - A **creative writer**
358
- - A **specific character or persona**
359
- - Provides full control to **reshape the AI’s tone, expertise, and conversational style** with a single prompt.
360
- """)
361
-
362
- # API Key Section
363
- with gr.Row():
364
- api_key = gr.Textbox(
365
- label="🔑 Groq API Key",
366
- placeholder="Enter your Groq API key here...",
367
- type="password",
368
- info="Get your API key from: https://console.groq.com/"
369
- )
370
- model_selection = gr.Radio(
371
- choices=["compound-beta", "compound-beta-mini"],
372
- label="🧠 Model Selection",
373
- value="compound-beta",
374
- info="compound-beta: More powerful | compound-beta-mini: Faster"
375
- )
376
- connect_btn = gr.Button("🔗 Connect", variant="primary", size="lg")
377
-
378
- # Status display
379
- status_display = gr.Markdown("### 📊 Status: Not connected", elem_classes=["status-box"])
380
-
381
- # Connect button functionality
382
- connect_btn.click(
383
- fn=validate_api_key,
384
- inputs=[api_key, model_selection],
385
- outputs=[status_display]
386
- )
387
-
388
- model_selection.change(
389
- fn=update_model,
390
- inputs=[model_selection],
391
- outputs=[status_display]
392
- )
393
-
394
- # Main Chat Interface
395
- with gr.Tab("💬 Chat"):
396
- chatbot = gr.Chatbot(
397
- label="Creative AI Assistant",
398
- height=500,
399
- show_label=True,
400
- bubble_full_width=False,
401
- show_copy_button=True
402
- )
403
-
404
- with gr.Row():
405
- msg = gr.Textbox(
406
- label="Your Message",
407
- placeholder="Type your message here...",
408
- lines=3
409
- )
410
- with gr.Column():
411
- send_btn = gr.Button("📤 Send", variant="primary")
412
- clear_btn = gr.Button("🗑️ Clear", variant="secondary")
413
-
414
- # Advanced Settings
415
- with gr.Accordion("⚙️ Advanced Settings", open=False, elem_id="neuroscope-accordion"):
416
- with gr.Row():
417
- temperature = gr.Slider(
418
- minimum=0.0,
419
- maximum=2.0,
420
- value=0.7,
421
- step=0.1,
422
- label="🌡️ Temperature",
423
- info="Higher = more creative, Lower = more focused"
424
- )
425
- max_tokens = gr.Slider(
426
- minimum=100,
427
- maximum=4000,
428
- value=1024,
429
- step=100,
430
- label="📝 Max Tokens",
431
- info="Maximum length of response"
432
- )
433
-
434
- system_prompt = gr.Textbox(
435
- label="🎭 Custom System Prompt",
436
- placeholder="Override the default system prompt...",
437
- lines=2,
438
- info="Leave empty to use default creative assistant prompt"
439
- )
440
-
441
- # Domain Filtering Section
442
- with gr.Accordion("🌐 Domain Filtering (for Web Search)", open=False, elem_id="neuroscope-accordion"):
443
- gr.Markdown("""
444
- <div class="domain-info">
445
- <h4>🔍 Domain Filtering Guide</h4>
446
- <p>Control which websites the AI can search when answering your questions:</p>
447
- <ul>
448
- <li><strong>Include Domains:</strong> Only search these domains (comma-separated)</li>
449
- <li><strong>Exclude Domains:</strong> Never search these domains (comma-separated)</li>
450
- <li><strong>Examples:</strong> arxiv.org, *.edu, github.com, stackoverflow.com</li>
451
- <li><strong>Wildcards:</strong> Use *.edu for all educational domains</li>
452
- </ul>
453
- </div>
454
- """)
455
-
456
- with gr.Row():
457
- include_domains = gr.Textbox(
458
- label="✅ Include Domains (comma-separated)",
459
- placeholder="arxiv.org, *.edu, github.com, stackoverflow.com",
460
- info="Only search these domains"
461
- )
462
- exclude_domains = gr.Textbox(
463
- label="❌ Exclude Domains (comma-separated)",
464
- placeholder="wikipedia.org, reddit.com, twitter.com",
465
- info="Never search these domains"
466
- )
467
- with gr.Accordion("🔗 Common Domain Examples", open=False, elem_id="neuroscope-accordion"):
468
- gr.Markdown("""
469
- **Academic & Research:**
470
- - `arxiv.org`, `*.edu`, `scholar.google.com`, `researchgate.net`
471
-
472
- **Technology & Programming:**
473
- - `github.com`, `stackoverflow.com`, `docs.python.org`, `developer.mozilla.org`
474
-
475
- **News & Media:**
476
- - `reuters.com`, `bbc.com`, `npr.org`, `apnews.com`
477
-
478
- **Business & Finance:**
479
- - `bloomberg.com`, `wsj.com`, `nasdaq.com`, `sec.gov`
480
-
481
- **Science & Medicine:**
482
- - `nature.com`, `science.org`, `pubmed.ncbi.nlm.nih.gov`, `who.int`
483
- """)
484
-
485
- # How to Use Section
486
- with gr.Accordion("📖 How to Use This App", open=False, elem_id="neuroscope-accordion"):
487
- gr.Markdown("""
488
- ### 🚀 Getting Started
489
- 1. **Enter your Groq API Key** - Get one from [console.groq.com](https://console.groq.com/)
490
- 2. **Select a model** - Choose between compound-beta (powerful) or compound-beta-mini (fast)
491
- 3. **Click Connect** - Validate your key and connect to the AI
492
- 4. **Start chatting!** - Type your message and get intelligent responses
493
-
494
- ### 🎯 Key Features
495
- - **Agentic AI**: The AI can use tools and search the web autonomously
496
- - **Domain Filtering**: Control which websites the AI searches
497
- - **Creative Responses**: Optimized for engaging and helpful conversations
498
- - **Memory**: Maintains conversation context throughout the session
499
- - **Customizable**: Adjust temperature, tokens, and system prompts
500
-
501
- ### 💡 Tips for Best Results
502
- - Be specific in your questions for better responses
503
- - Use domain filtering for specialized research
504
- - Adjust temperature: higher for creativity, lower for precision
505
- - Try different system prompts for different conversation styles
506
- """)
507
-
508
- # Sample Examples Section
509
- with gr.Accordion("🎯 Sample Examples to Test", open=False, elem_id="neuroscope-accordion"):
510
- gr.Markdown("""
511
- <div class="example-box">
512
- <h4>🔬 Research & Analysis</h4>
513
- <ul>
514
- <li>"What are the latest breakthroughs in quantum computing?"</li>
515
- <li>"Compare different machine learning frameworks for beginners"</li>
516
- <li>"Analyze the current state of renewable energy technology"</li>
517
- </ul>
518
-
519
- <h4>💻 Programming & Tech</h4>
520
- <ul>
521
- <li>"Write a Python script to analyze CSV data and create visualizations"</li>
522
- <li>"Explain the differences between React and Vue.js with examples"</li>
523
- <li>"Help me debug this JavaScript code: [paste your code]"</li>
524
- </ul>
525
-
526
- <h4>🎨 Creative Tasks</h4>
527
- <ul>
528
- <li>"Write a short story about AI and humans working together"</li>
529
- <li>"Create a marketing plan for a sustainable fashion brand"</li>
530
- <li>"Generate ideas for a mobile app that helps with mental health"</li>
531
- </ul>
532
-
533
- <h4>📊 Business & Analysis</h4>
534
- <ul>
535
- <li>"What are the current trends in the cryptocurrency market?"</li>
536
- <li>"Analyze the pros and cons of remote work for startups"</li>
537
- <li>"Create a business plan outline for a food delivery service"</li>
538
- </ul>
539
-
540
- <h4>🌐 With Domain Filtering</h4>
541
- <ul>
542
- <li>Include "*.edu, arxiv.org": "Latest research on climate change solutions"</li>
543
- <li>Include "github.com, stackoverflow.com": "Best practices for API development"</li>
544
- <li>Exclude "wikipedia.org, reddit.com": "Professional analysis of market trends"</li>
545
- </ul>
546
- </div>
547
- """)
548
-
549
- # Event handlers
550
- send_btn.click(
551
- fn=chat_with_ai,
552
- inputs=[msg, include_domains, exclude_domains, system_prompt, temperature, max_tokens, chatbot],
553
- outputs=[chatbot, msg]
554
- )
555
-
556
- msg.submit(
557
- fn=chat_with_ai,
558
- inputs=[msg, include_domains, exclude_domains, system_prompt, temperature, max_tokens, chatbot],
559
- outputs=[chatbot, msg]
560
- )
561
-
562
- clear_btn.click(
563
- fn=clear_chat_history,
564
- outputs=[chatbot]
565
- )
566
-
567
- # Footer
568
- with gr.Accordion("🚀 About This Tool", open=True, elem_id="neuroscope-accordion"):
569
- gr.Markdown("""
570
- A Creative Agentic AI Chat Tool leverages Groq's powerful compound models to provide intelligent,
571
- context-aware responses with web search capabilities. Perfect for research, programming help,
572
- creative writing, and complex problem-solving.
573
-
574
- **Features:**
575
- - 🔍 Web search with domain filtering
576
- - 🧠 Advanced AI reasoning with tool usage
577
- - 💬 Conversational memory and context
578
- - ⚙️ Customizable parameters and prompts
579
- - 🎨 Creative and analytical capabilities
580
- """)
581
-
582
- return app
583
-
584
- # Main execution
585
- if __name__ == "__main__":
586
- app = create_gradio_app()
587
- app.launch(
588
- share=True
589
- )