shukdevdatta123 commited on
Commit
adb04b7
·
verified ·
1 Parent(s): acfe952

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -637
app.py DELETED
@@ -1,637 +0,0 @@
1
- import os
2
- import gradio as gr
3
- from groq import Groq
4
- import json
5
- from datetime import datetime
6
- import time
7
-
8
- class RealTimeFactChecker:
9
- def __init__(self):
10
- self.client = None
11
- self.model_options = ["compound-beta", "compound-beta-mini"]
12
-
13
- def initialize_client(self, api_key):
14
- """Initialize Groq client with API key"""
15
- try:
16
- self.client = Groq(api_key=api_key)
17
- return True, "✅ API Key validated successfully!"
18
- except Exception as e:
19
- return False, f"❌ Error initializing client: {str(e)}"
20
-
21
- def get_system_prompt(self):
22
- """Get the system prompt for consistent behavior"""
23
- return """You are a Real-time Fact Checker and News Agent. Your primary role is to provide accurate, up-to-date information by leveraging web search when needed.
24
- CORE RESPONSIBILITIES:
25
- 1. **Fact Verification**: Always verify claims with current, reliable sources
26
- 2. **Real-time Information**: Use web search for any information that changes frequently (news, stocks, weather, current events)
27
- 3. **Source Transparency**: When using web search, mention the sources or indicate that you've searched for current information
28
- 4. **Accuracy First**: If information is uncertain or conflicting, acknowledge this clearly
29
- RESPONSE GUIDELINES:
30
- - **Structure**: Start with a clear, direct answer, then provide supporting details
31
- - **Recency**: Always prioritize the most recent, reliable information
32
- - **Clarity**: Use clear, professional language while remaining accessible
33
- - **Completeness**: Provide comprehensive answers but stay focused on the query
34
- - **Source Awareness**: When you've searched for information, briefly indicate this (e.g., "Based on current reports..." or "Recent data shows...")
35
- WHEN TO SEARCH:
36
- - Breaking news or current events
37
- - Stock prices, market data, or financial information
38
- - Weather conditions or forecasts
39
- - Recent scientific discoveries or research
40
- - Current political developments
41
- - Real-time statistics or data
42
- - Verification of recent claims or rumors
43
- RESPONSE FORMAT:
44
- - Lead with key facts
45
- - Include relevant context
46
- - Mention timeframe when relevant (e.g., "as of today", "this week")
47
- - If multiple sources conflict, acknowledge this
48
- - End with a clear summary for complex topics
49
- Remember: Your goal is to be the most reliable, up-to-date source of information possible."""
50
-
51
- def query_compound_model(self, query, model, temperature=0.7, custom_system_prompt=None):
52
- """Query the compound model and return response with tool execution info"""
53
- if not self.client:
54
- return "❌ Please set a valid API key first.", None, None
55
-
56
- try:
57
- start_time = time.time()
58
-
59
- # Use custom system prompt if provided
60
- system_prompt = custom_system_prompt if custom_system_prompt else self.get_system_prompt()
61
-
62
- chat_completion = self.client.chat.completions.create(
63
- messages=[
64
- {
65
- "role": "system",
66
- "content": system_prompt
67
- },
68
- {
69
- "role": "user",
70
- "content": query,
71
- }
72
- ],
73
- model=model,
74
- temperature=temperature,
75
- max_tokens=1500
76
- )
77
-
78
- end_time = time.time()
79
- response_time = round(end_time - start_time, 2)
80
-
81
- # Extract response
82
- response_content = chat_completion.choices[0].message.content
83
-
84
- # Check for executed tools - Fixed the error here
85
- executed_tools = getattr(chat_completion.choices[0].message, 'executed_tools', None)
86
-
87
- # Format tool execution info
88
- tool_info = self.format_tool_info(executed_tools)
89
-
90
- return response_content, tool_info, response_time
91
-
92
- except Exception as e:
93
- return f"❌ Error querying model: {str(e)}", None, None
94
-
95
- def format_tool_info(self, executed_tools):
96
- """Format executed tools information for display - FIXED"""
97
- if not executed_tools:
98
- return "🔍 **Tools Used:** None (Used existing knowledge)"
99
-
100
- tool_info = "🔍 **Tools Used:**\n"
101
- for i, tool in enumerate(executed_tools, 1):
102
- try:
103
- # Handle different tool object types
104
- if hasattr(tool, 'name'):
105
- tool_name = tool.name
106
- elif hasattr(tool, 'tool_name'):
107
- tool_name = tool.tool_name
108
- elif isinstance(tool, dict):
109
- tool_name = tool.get('name', 'Unknown')
110
- else:
111
- tool_name = str(tool)
112
-
113
- tool_info += f"{i}. **{tool_name}**\n"
114
-
115
- # Add tool parameters if available
116
- if hasattr(tool, 'parameters'):
117
- params = tool.parameters
118
- if isinstance(params, dict):
119
- for key, value in params.items():
120
- tool_info += f" - {key}: {value}\n"
121
- elif hasattr(tool, 'input'):
122
- tool_info += f" - Input: {tool.input}\n"
123
-
124
- except Exception as e:
125
- tool_info += f"{i}. **Tool {i}** (Error parsing details)\n"
126
-
127
- return tool_info
128
-
129
- def get_example_queries(self):
130
- """Return categorized example queries"""
131
- return {
132
- "📰 Latest News": [
133
- "What are the top 3 news stories today?",
134
- "Latest developments in AI technology this week",
135
- "Recent political events in the United States",
136
- "Breaking news about climate change",
137
- "What happened in the stock market today?"
138
- ],
139
- "💰 Financial Data": [
140
- "Current price of Bitcoin",
141
- "Tesla stock price today",
142
- "How is the S&P 500 performing today?",
143
- "Latest cryptocurrency market trends",
144
- "What's the current inflation rate?"
145
- ],
146
- "🌤️ Weather Updates": [
147
- "Current weather in New York City",
148
- "Weather forecast for London this week",
149
- "Is it going to rain in San Francisco today?",
150
- "Temperature in Tokyo right now",
151
- "Weather conditions in Sydney"
152
- ],
153
- "🔬 Science & Technology": [
154
- "Latest breakthroughs in fusion energy",
155
- "Recent discoveries in space exploration",
156
- "New developments in quantum computing",
157
- "Latest medical research findings",
158
- "Recent advances in renewable energy"
159
- ],
160
- "🏆 Sports & Entertainment": [
161
- "Latest football match results",
162
- "Who won the recent tennis tournament?",
163
- "Box office numbers for this weekend",
164
- "Latest movie releases this month",
165
- "Recent celebrity news"
166
- ],
167
- "🔍 Fact Checking": [
168
- "Is it true that the Earth's population reached 8 billion?",
169
- "Verify: Did company X announce layoffs recently?",
170
- "Check if the recent earthquake in Turkey was magnitude 7+",
171
- "Confirm the latest unemployment rate statistics",
172
- "Verify recent claims about electric vehicle sales"
173
- ]
174
- }
175
-
176
- def get_custom_prompt_examples(self):
177
- """Return custom system prompt examples"""
178
- return {
179
- "🎯 Fact-Checker": "You are a fact-checker. Always verify claims with multiple sources and clearly indicate confidence levels in your assessments. Use phrases like 'highly confident', 'moderately confident', or 'requires verification' when presenting information.",
180
-
181
- "📊 News Analyst": "You are a news analyst. Focus on providing balanced, unbiased reporting with multiple perspectives on current events. Always present different viewpoints and avoid partisan language.",
182
-
183
- "💼 Financial Advisor": "You are a financial advisor. Provide accurate market data with context about trends and implications for investors. Always include disclaimers about market risks and the importance of professional financial advice.",
184
-
185
- "🔬 Research Assistant": "You are a research assistant specializing in scientific and technical information. Provide detailed, evidence-based responses with proper context about methodology and limitations of studies.",
186
-
187
- "🌍 Global News Correspondent": "You are a global news correspondent. Focus on international events and their interconnections. Provide cultural context and explain how events in one region might affect others.",
188
-
189
- "📈 Market Analyst": "You are a market analyst. Provide detailed financial analysis including technical indicators, market sentiment, and economic factors affecting price movements."
190
- }
191
-
192
- def create_interface():
193
- fact_checker = RealTimeFactChecker()
194
-
195
- # Custom CSS for beautiful styling
196
- custom_css = """
197
- <style>
198
- .gradio-container {
199
- max-width: 1400px !important;
200
- margin: 0 auto;
201
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
202
- min-height: 100vh;
203
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
204
- }
205
-
206
- .main-header {
207
- background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
208
- color: white;
209
- padding: 30px;
210
- border-radius: 20px;
211
- margin-bottom: 30px;
212
- text-align: center;
213
- box-shadow: 0 10px 30px rgba(0,0,0,0.3);
214
- }
215
-
216
- .main-header h1 {
217
- font-size: 2.5rem;
218
- margin: 0;
219
- text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
220
- }
221
-
222
- .main-header p {
223
- font-size: 1.2rem;
224
- margin: 10px 0 0 0;
225
- opacity: 0.9;
226
- }
227
-
228
- .feature-card {
229
- background: white;
230
- border-radius: 15px;
231
- padding: 25px;
232
- margin: 20px 0;
233
- box-shadow: 0 8px 25px rgba(0,0,0,0.1);
234
- border: 1px solid #e1e8ed;
235
- transition: transform 0.3s ease, box-shadow 0.3s ease;
236
- }
237
-
238
- .feature-card:hover {
239
- transform: translateY(-5px);
240
- box-shadow: 0 15px 40px rgba(0,0,0,0.2);
241
- }
242
-
243
- .example-grid {
244
- display: grid;
245
- grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
246
- gap: 15px;
247
- margin-top: 20px;
248
- }
249
-
250
- .example-category {
251
- background: #f8f9fa;
252
- border-radius: 10px;
253
- padding: 15px;
254
- border-left: 4px solid #667eea;
255
- }
256
-
257
- .example-category h4 {
258
- margin: 0 0 10px 0;
259
- color: #2d3748;
260
- font-weight: 600;
261
- }
262
-
263
- .status-success {
264
- background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
265
- color: white;
266
- padding: 10px 15px;
267
- border-radius: 8px;
268
- font-weight: 500;
269
- }
270
-
271
- .status-warning {
272
- background: linear-gradient(135deg, #ed8936 0%, #dd6b20 100%);
273
- color: white;
274
- padding: 10px 15px;
275
- border-radius: 8px;
276
- font-weight: 500;
277
- }
278
-
279
- .status-error {
280
- background: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
281
- color: white;
282
- padding: 10px 15px;
283
- border-radius: 8px;
284
- font-weight: 500;
285
- }
286
-
287
- .results-section {
288
- background: white;
289
- border-radius: 15px;
290
- padding: 30px;
291
- margin: 30px 0;
292
- box-shadow: 0 8px 25px rgba(0,0,0,0.1);
293
- }
294
-
295
- .tool-info {
296
- background: #f7fafc;
297
- border-left: 4px solid #4299e1;
298
- padding: 15px;
299
- border-radius: 8px;
300
- margin: 15px 0;
301
- }
302
-
303
- .performance-badge {
304
- background: linear-gradient(135deg, #38b2ac 0%, #319795 100%);
305
- color: white;
306
- padding: 8px 15px;
307
- border-radius: 20px;
308
- font-weight: 500;
309
- display: inline-block;
310
- margin: 10px 0;
311
- }
312
-
313
- .footer-section {
314
- background: #2d3748;
315
- color: white;
316
- padding: 30px;
317
- border-radius: 15px;
318
- margin-top: 30px;
319
- text-align: center;
320
- }
321
-
322
- .footer-section a {
323
- color: #63b3ed;
324
- text-decoration: none;
325
- font-weight: 500;
326
- }
327
-
328
- .footer-section a:hover {
329
- color: #90cdf4;
330
- text-decoration: underline;
331
- }
332
-
333
- .prompt-example {
334
- background: #ebf8ff;
335
- border: 1px solid #bee3f8;
336
- border-radius: 8px;
337
- padding: 12px;
338
- margin: 8px 0;
339
- cursor: pointer;
340
- transition: all 0.3s ease;
341
- }
342
-
343
- .prompt-example:hover {
344
- background: #bee3f8;
345
- transform: translateX(5px);
346
- }
347
-
348
- .prompt-example-title {
349
- font-weight: 600;
350
- color: #2b6cb0;
351
- margin-bottom: 5px;
352
- }
353
-
354
- .prompt-example-text {
355
- font-size: 0.9rem;
356
- color: #4a5568;
357
- line-height: 1.4;
358
- }
359
- </style>
360
- """
361
-
362
- def validate_api_key(api_key):
363
- if not api_key or api_key.strip() == "":
364
- return "❌ Please enter a valid API key", False
365
-
366
- success, message = fact_checker.initialize_client(api_key.strip())
367
- return message, success
368
-
369
- def process_query(query, model, temperature, api_key, system_prompt):
370
- if not api_key or api_key.strip() == "":
371
- return "❌ Please set your API key first", "", ""
372
-
373
- if not query or query.strip() == "":
374
- return "❌ Please enter a query", "", ""
375
-
376
- # Initialize client if not already done
377
- if not fact_checker.client:
378
- success, message = fact_checker.initialize_client(api_key.strip())
379
- if not success:
380
- return message, "", ""
381
-
382
- response, tool_info, response_time = fact_checker.query_compound_model(
383
- query.strip(), model, temperature, system_prompt.strip() if system_prompt else None
384
- )
385
-
386
- # Format response with timestamp
387
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
388
- formatted_response = f"**Query:** {query}\n\n**Response:**\n{response}\n\n---\n*Generated at {timestamp} in {response_time}s*"
389
-
390
- return formatted_response, tool_info or "", f"⚡ Response time: {response_time}s"
391
-
392
- def reset_system_prompt():
393
- return fact_checker.get_system_prompt()
394
-
395
- def load_example(example_text):
396
- return example_text
397
-
398
- def load_custom_prompt(prompt_text):
399
- return prompt_text
400
-
401
- # Create the Gradio interface
402
- with gr.Blocks(title="Real-time Fact Checker & News Agent", css=custom_css) as demo:
403
-
404
- # Header
405
- gr.HTML("""
406
- <div class="main-header">
407
- <h1>🔍 Real-time Fact Checker & News Agent</h1>
408
- <p>Powered by Groq's Compound Models with Built-in Web Search</p>
409
- </div>
410
- """)
411
-
412
- with gr.Row():
413
- with gr.Column(scale=2):
414
- # API Key section
415
- with gr.Group():
416
- gr.HTML('<div class="feature-card">API Key Section</div>')
417
- gr.Markdown("### 🔑 API Configuration")
418
- api_key_input = gr.Textbox(
419
- label="Groq API Key",
420
- placeholder="Enter your Groq API key here...",
421
- type="password",
422
- info="Get your free API key from https://console.groq.com/"
423
- )
424
- api_status = gr.Textbox(
425
- label="Status",
426
- value="⚠️ Please enter your API key",
427
- interactive=False
428
- )
429
- validate_btn = gr.Button("Validate API Key", variant="secondary")
430
- gr.HTML('</div>')
431
-
432
- # Advanced options
433
- with gr.Group():
434
- gr.HTML('<div class="feature-card">⚙️ Advanced Options</div>')
435
- gr.Markdown("### ⚙️ Advanced Options")
436
-
437
- # Custom System Prompt Examples
438
- with gr.Accordion("📝 System Prompt Examples (Click to view)", open=False):
439
- gr.Markdown("**Click any example to load it as your system prompt:**")
440
-
441
- custom_prompts = fact_checker.get_custom_prompt_examples()
442
- for title, prompt in custom_prompts.items():
443
- with gr.Row():
444
- gr.HTML(f"""
445
- <div class="prompt-example" onclick="document.getElementById('system_prompt_input').value = '{prompt}'">
446
- <div class="prompt-example-title">{title}</div>
447
- <div class="prompt-example-text">{prompt[:100]}...</div>
448
- </div>
449
- """)
450
-
451
- with gr.Accordion("🔧 System Prompt (Click to customize)", open=False):
452
- system_prompt_input = gr.Textbox(
453
- label="System Prompt",
454
- value=fact_checker.get_system_prompt(),
455
- lines=8,
456
- info="Customize how the AI behaves and responds",
457
- elem_id="system_prompt_input"
458
- )
459
- reset_prompt_btn = gr.Button("Reset to Default", variant="secondary", size="sm")
460
-
461
- # Add buttons for each custom prompt
462
- gr.Markdown("**Quick Load Custom Prompts:**")
463
- custom_prompts = fact_checker.get_custom_prompt_examples()
464
- for title, prompt in custom_prompts.items():
465
- prompt_btn = gr.Button(title, variant="secondary", size="sm")
466
- prompt_btn.click(
467
- fn=lambda p=prompt: p,
468
- outputs=[system_prompt_input]
469
- )
470
-
471
- gr.HTML('</div>')
472
-
473
- # Query section
474
- with gr.Group():
475
- gr.HTML('<div class="feature-card">Query section</div>')
476
- gr.Markdown("### 💭 Your Query")
477
- query_input = gr.Textbox(
478
- label="Ask anything that requires real-time information",
479
- placeholder="e.g., What are the latest AI developments today?",
480
- lines=4
481
- )
482
-
483
- with gr.Row():
484
- model_choice = gr.Dropdown(
485
- choices=fact_checker.model_options,
486
- value="compound-beta",
487
- label="Model",
488
- info="compound-beta: More capable | compound-beta-mini: Faster"
489
- )
490
- temperature = gr.Slider(
491
- minimum=0.0,
492
- maximum=1.0,
493
- value=0.7,
494
- step=0.1,
495
- label="Temperature",
496
- info="Higher = more creative, Lower = more focused"
497
- )
498
-
499
- submit_btn = gr.Button("🔍 Get Real-time Information", variant="primary", size="lg")
500
- clear_btn = gr.Button("Clear", variant="secondary")
501
- gr.HTML('</div>')
502
-
503
- with gr.Column(scale=1):
504
- # Example queries with tabs
505
- with gr.Group():
506
- gr.HTML('<div class="feature-card">Example queries with tabs</div>')
507
- gr.Markdown("### 📝 Example Queries")
508
- gr.Markdown("Click any example to load it:")
509
-
510
- examples = fact_checker.get_example_queries()
511
-
512
- with gr.Accordion("📰 Latest News", open=True):
513
- for query in examples["📰 Latest News"]:
514
- example_btn = gr.Button(query, variant="secondary", size="sm")
515
- example_btn.click(
516
- fn=lambda q=query: q,
517
- outputs=[query_input]
518
- )
519
-
520
- with gr.Accordion("💰 Financial Data", open=False):
521
- for query in examples["💰 Financial Data"]:
522
- example_btn = gr.Button(query, variant="secondary", size="sm")
523
- example_btn.click(
524
- fn=lambda q=query: q,
525
- outputs=[query_input]
526
- )
527
-
528
- with gr.Accordion("🌤️ Weather Updates", open=False):
529
- for query in examples["🌤️ Weather Updates"]:
530
- example_btn = gr.Button(query, variant="secondary", size="sm")
531
- example_btn.click(
532
- fn=lambda q=query: q,
533
- outputs=[query_input]
534
- )
535
-
536
- with gr.Accordion("🔬 Science & Technology", open=False):
537
- for query in examples["🔬 Science & Technology"]:
538
- example_btn = gr.Button(query, variant="secondary", size="sm")
539
- example_btn.click(
540
- fn=lambda q=query: q,
541
- outputs=[query_input]
542
- )
543
-
544
- with gr.Accordion("🏆 Sports & Entertainment", open=False):
545
- for query in examples["🏆 Sports & Entertainment"]:
546
- example_btn = gr.Button(query, variant="secondary", size="sm")
547
- example_btn.click(
548
- fn=lambda q=query: q,
549
- outputs=[query_input]
550
- )
551
-
552
- with gr.Accordion("🔍 Fact Checking", open=False):
553
- for query in examples["🔍 Fact Checking"]:
554
- example_btn = gr.Button(query, variant="secondary", size="sm")
555
- example_btn.click(
556
- fn=lambda q=query: q,
557
- outputs=[query_input]
558
- )
559
-
560
- gr.HTML('</div>')
561
-
562
- # Results section
563
- gr.HTML('<div class="results-section">')
564
- gr.Markdown("### 📊 Results")
565
-
566
- with gr.Row():
567
- with gr.Column(scale=2):
568
- response_output = gr.Markdown(
569
- label="Response",
570
- value="*Your response will appear here...*"
571
- )
572
-
573
- with gr.Column(scale=1):
574
- tool_info_output = gr.Markdown(
575
- label="Tool Execution Info",
576
- value="*Tool execution details will appear here...*"
577
- )
578
-
579
- performance_output = gr.Textbox(
580
- label="Performance",
581
- value="",
582
- interactive=False
583
- )
584
- gr.HTML('</div>')
585
-
586
- # Event handlers
587
- validate_btn.click(
588
- fn=validate_api_key,
589
- inputs=[api_key_input],
590
- outputs=[api_status, gr.State()]
591
- )
592
-
593
- reset_prompt_btn.click(
594
- fn=reset_system_prompt,
595
- outputs=[system_prompt_input]
596
- )
597
-
598
- submit_btn.click(
599
- fn=process_query,
600
- inputs=[query_input, model_choice, temperature, api_key_input, system_prompt_input],
601
- outputs=[response_output, tool_info_output, performance_output]
602
- )
603
-
604
- clear_btn.click(
605
- fn=lambda: ("", "*Your response will appear here...*", "*Tool execution details will appear here...*", ""),
606
- outputs=[query_input, response_output, tool_info_output, performance_output]
607
- )
608
-
609
- # Footer
610
- gr.HTML("""
611
- <div class="footer-section">
612
- <h3>🔗 Useful Links</h3>
613
- <p>
614
- <a href="https://console.groq.com/" target="_blank">Groq Console</a> - Get your free API key<br>
615
- <a href="https://console.groq.com/docs/quickstart" target="_blank">Groq Documentation</a> - Learn more about Groq models<br>
616
- <a href="https://console.groq.com/docs/models" target="_blank">Compound Models Info</a> - Details about compound models
617
- </p>
618
-
619
- <h3>💡 Tips</h3>
620
- <ul style="text-align: left; display: inline-block;">
621
- <li>The compound models automatically use web search when real-time information is needed</li>
622
- <li>Try different temperature settings: 0.1 for factual queries, 0.7-0.9 for creative questions</li>
623
- <li>compound-beta is more capable but slower, compound-beta-mini is faster but less capable</li>
624
- <li>Use custom system prompts to specialize the AI for different types of queries</li>
625
- <li>Check the Tool Execution Info to see when web search was used</li>
626
- </ul>
627
- </div>
628
- """)
629
-
630
- return demo
631
-
632
- # Launch the application
633
- if __name__ == "__main__":
634
- demo = create_interface()
635
- demo.launch(
636
- share=True
637
- )