shukdevdatta123 commited on
Commit
d6f088e
·
verified ·
1 Parent(s): 5e92a92

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +363 -0
app.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
25
+ CORE RESPONSIBILITIES:
26
+ 1. **Fact Verification**: Always verify claims with current, reliable sources
27
+ 2. **Real-time Information**: Use web search for any information that changes frequently (news, stocks, weather, current events)
28
+ 3. **Source Transparency**: When using web search, mention the sources or indicate that you've searched for current information
29
+ 4. **Accuracy First**: If information is uncertain or conflicting, acknowledge this clearly
30
+
31
+ RESPONSE GUIDELINES:
32
+ - **Structure**: Start with a clear, direct answer, then provide supporting details
33
+ - **Recency**: Always prioritize the most recent, reliable information
34
+ - **Clarity**: Use clear, professional language while remaining accessible
35
+ - **Completeness**: Provide comprehensive answers but stay focused on the query
36
+ - **Source Awareness**: When you've searched for information, briefly indicate this (e.g., "Based on current reports..." or "Recent data shows...")
37
+
38
+ WHEN TO SEARCH:
39
+ - Breaking news or current events
40
+ - Stock prices, market data, or financial information
41
+ - Weather conditions or forecasts
42
+ - Recent scientific discoveries or research
43
+ - Current political developments
44
+ - Real-time statistics or data
45
+ - Verification of recent claims or rumors
46
+
47
+ RESPONSE FORMAT:
48
+ - Lead with key facts
49
+ - Include relevant context
50
+ - Mention timeframe when relevant (e.g., "as of today", "this week")
51
+ - If multiple sources conflict, acknowledge this
52
+ - End with a clear summary for complex topics
53
+
54
+ Remember: Your goal is to be the most reliable, up-to-date source of information possible."""
55
+
56
+ def query_compound_model(self, query, model, temperature=0.7):
57
+ """Query the compound model and return response with tool execution info"""
58
+ if not self.client:
59
+ return "❌ Please set a valid API key first.", None, None
60
+
61
+ try:
62
+ start_time = time.time()
63
+
64
+ chat_completion = self.client.chat.completions.create(
65
+ messages=[
66
+ {
67
+ "role": "system",
68
+ "content": self.get_system_prompt()
69
+ },
70
+ {
71
+ "role": "user",
72
+ "content": query,
73
+ }
74
+ ],
75
+ model=model,
76
+ temperature=temperature,
77
+ max_tokens=1000
78
+ )
79
+
80
+ end_time = time.time()
81
+ response_time = round(end_time - start_time, 2)
82
+
83
+ # Extract response
84
+ response_content = chat_completion.choices[0].message.content
85
+
86
+ # Check for executed tools
87
+ executed_tools = getattr(chat_completion.choices[0].message, 'executed_tools', None)
88
+
89
+ # Format tool execution info
90
+ tool_info = self.format_tool_info(executed_tools)
91
+
92
+ return response_content, tool_info, response_time
93
+
94
+ except Exception as e:
95
+ return f"❌ Error querying model: {str(e)}", None, None
96
+
97
+ def format_tool_info(self, executed_tools):
98
+ """Format executed tools information for display"""
99
+ if not executed_tools:
100
+ return "🔍 **Tools Used:** None (Used existing knowledge)"
101
+
102
+ tool_info = "🔍 **Tools Used:**\n"
103
+ for i, tool in enumerate(executed_tools, 1):
104
+ tool_name = tool.get('name', 'Unknown')
105
+ tool_info += f"{i}. **{tool_name}**\n"
106
+
107
+ # Add tool parameters if available
108
+ if 'parameters' in tool:
109
+ params = tool['parameters']
110
+ if isinstance(params, dict):
111
+ for key, value in params.items():
112
+ tool_info += f" - {key}: {value}\n"
113
+
114
+ return tool_info
115
+
116
+ def get_example_queries(self):
117
+ """Return categorized example queries"""
118
+ return {
119
+ "📰 Latest News": [
120
+ "What are the top 3 news stories today?",
121
+ "Latest developments in AI technology this week",
122
+ "Recent political events in the United States",
123
+ "Breaking news about climate change",
124
+ "What happened in the stock market today?"
125
+ ],
126
+ "💰 Financial Data": [
127
+ "Current price of Bitcoin",
128
+ "Tesla stock price today",
129
+ "How is the S&P 500 performing today?",
130
+ "Latest cryptocurrency market trends",
131
+ "What's the current inflation rate?"
132
+ ],
133
+ "🌤️ Weather Updates": [
134
+ "Current weather in New York City",
135
+ "Weather forecast for London this week",
136
+ "Is it going to rain in San Francisco today?",
137
+ "Temperature in Tokyo right now",
138
+ "Weather conditions in Sydney"
139
+ ],
140
+ "🔬 Science & Technology": [
141
+ "Latest breakthroughs in fusion energy",
142
+ "Recent discoveries in space exploration",
143
+ "New developments in quantum computing",
144
+ "Latest medical research findings",
145
+ "Recent advances in renewable energy"
146
+ ],
147
+ "🏆 Sports & Entertainment": [
148
+ "Latest football match results",
149
+ "Who won the recent tennis tournament?",
150
+ "Box office numbers for this weekend",
151
+ "Latest movie releases this month",
152
+ "Recent celebrity news"
153
+ ],
154
+ "🔍 Fact Checking": [
155
+ "Is it true that the Earth's population reached 8 billion?",
156
+ "Verify: Did company X announce layoffs recently?",
157
+ "Check if the recent earthquake in Turkey was magnitude 7+",
158
+ "Confirm the latest unemployment rate statistics",
159
+ "Verify recent claims about electric vehicle sales"
160
+ ]
161
+ }
162
+
163
+ def create_interface():
164
+ fact_checker = RealTimeFactChecker()
165
+
166
+ def validate_api_key(api_key):
167
+ if not api_key or api_key.strip() == "":
168
+ return "❌ Please enter a valid API key", False
169
+
170
+ success, message = fact_checker.initialize_client(api_key.strip())
171
+ return message, success
172
+
173
+ def process_query(query, model, temperature, api_key, system_prompt):
174
+ if not api_key or api_key.strip() == "":
175
+ return "❌ Please set your API key first", "", ""
176
+
177
+ if not query or query.strip() == "":
178
+ return "❌ Please enter a query", "", ""
179
+
180
+ # Initialize client if not already done
181
+ if not fact_checker.client:
182
+ success, message = fact_checker.initialize_client(api_key.strip())
183
+ if not success:
184
+ return message, "", ""
185
+
186
+ # Use custom system prompt if provided
187
+ if system_prompt and system_prompt.strip():
188
+ original_prompt = fact_checker.get_system_prompt
189
+ fact_checker.get_system_prompt = lambda: system_prompt.strip()
190
+
191
+ response, tool_info, response_time = fact_checker.query_compound_model(
192
+ query.strip(), model, temperature
193
+ )
194
+
195
+ # Restore original system prompt function
196
+ if system_prompt and system_prompt.strip():
197
+ fact_checker.get_system_prompt = original_prompt
198
+
199
+ # Format response with timestamp
200
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
201
+ formatted_response = f"**Query:** {query}\n\n**Response:**\n{response}\n\n---\n*Generated at {timestamp} in {response_time}s*"
202
+
203
+ return formatted_response, tool_info or "", f"⚡ Response time: {response_time}s"
204
+
205
+ def reset_system_prompt():
206
+ return fact_checker.get_system_prompt()
207
+
208
+ def load_example(example_text):
209
+ return example_text
210
+
211
+ # Create the Gradio interface
212
+ with gr.Blocks(title="Real-time Fact Checker & News Agent", theme=gr.themes.Soft()) as demo:
213
+ gr.Markdown("""
214
+ # 🔍 Real-time Fact Checker & News Agent
215
+
216
+ **Powered by Groq's Compound Models with Built-in Web Search**
217
+
218
+ This application provides real-time information by automatically searching the web when needed.
219
+ Enter your query below and get up-to-the-minute facts, news, and data!
220
+ """)
221
+
222
+ with gr.Row():
223
+ with gr.Column(scale=2):
224
+ # API Key section
225
+ with gr.Group():
226
+ gr.Markdown("### 🔑 API Configuration")
227
+ api_key_input = gr.Textbox(
228
+ label="Groq API Key",
229
+ placeholder="Enter your Groq API key here...",
230
+ type="password",
231
+ info="Get your free API key from https://console.groq.com/"
232
+ )
233
+ api_status = gr.Textbox(
234
+ label="Status",
235
+ value="⚠️ Please enter your API key",
236
+ interactive=False
237
+ )
238
+ validate_btn = gr.Button("Validate API Key", variant="secondary")
239
+
240
+ # Advanced options
241
+ with gr.Group():
242
+ gr.Markdown("### ⚙️ Advanced Options")
243
+ with gr.Accordion("System Prompt (Click to customize)", open=False):
244
+ system_prompt_input = gr.Textbox(
245
+ label="System Prompt",
246
+ value=fact_checker.get_system_prompt(),
247
+ lines=8,
248
+ info="Customize how the AI behaves and responds"
249
+ )
250
+ reset_prompt_btn = gr.Button("Reset to Default", variant="secondary", size="sm")
251
+
252
+ # Query section
253
+ with gr.Group():
254
+ gr.Markdown("### 💭 Your Query")
255
+ query_input = gr.Textbox(
256
+ label="Ask anything that requires real-time information",
257
+ placeholder="e.g., What are the latest AI developments today?",
258
+ lines=3
259
+ )
260
+
261
+ with gr.Row():
262
+ model_choice = gr.Dropdown(
263
+ choices=fact_checker.model_options,
264
+ value="compound-beta",
265
+ label="Model",
266
+ info="compound-beta: More capable | compound-beta-mini: Faster"
267
+ )
268
+ temperature = gr.Slider(
269
+ minimum=0.0,
270
+ maximum=1.0,
271
+ value=0.7,
272
+ step=0.1,
273
+ label="Temperature",
274
+ info="Higher = more creative, Lower = more focused"
275
+ )
276
+
277
+ submit_btn = gr.Button("🔍 Get Real-time Information", variant="primary", size="lg")
278
+ clear_btn = gr.Button("Clear", variant="secondary")
279
+
280
+ with gr.Column(scale=1):
281
+ # Example queries
282
+ with gr.Group():
283
+ gr.Markdown("### 📝 Example Queries")
284
+ gr.Markdown("Click any example to load it:")
285
+
286
+ examples = fact_checker.get_example_queries()
287
+ for category, queries in examples.items():
288
+ gr.Markdown(f"**{category}**")
289
+ for query in queries:
290
+ example_btn = gr.Button(query, variant="secondary", size="sm")
291
+ example_btn.click(
292
+ fn=load_example,
293
+ inputs=[gr.State(query)],
294
+ outputs=[query_input]
295
+ )
296
+
297
+ # Results section
298
+ gr.Markdown("### 📊 Results")
299
+
300
+ with gr.Row():
301
+ with gr.Column(scale=2):
302
+ response_output = gr.Markdown(
303
+ label="Response",
304
+ value="*Your response will appear here...*"
305
+ )
306
+
307
+ with gr.Column(scale=1):
308
+ tool_info_output = gr.Markdown(
309
+ label="Tool Execution Info",
310
+ value="*Tool execution details will appear here...*"
311
+ )
312
+
313
+ performance_output = gr.Textbox(
314
+ label="Performance",
315
+ value="",
316
+ interactive=False
317
+ )
318
+
319
+ # Event handlers
320
+ validate_btn.click(
321
+ fn=validate_api_key,
322
+ inputs=[api_key_input],
323
+ outputs=[api_status, gr.State()]
324
+ )
325
+
326
+ reset_prompt_btn.click(
327
+ fn=reset_system_prompt,
328
+ outputs=[system_prompt_input]
329
+ )
330
+
331
+ submit_btn.click(
332
+ fn=process_query,
333
+ inputs=[query_input, model_choice, temperature, api_key_input, system_prompt_input],
334
+ outputs=[response_output, tool_info_output, performance_output]
335
+ )
336
+
337
+ clear_btn.click(
338
+ fn=lambda: ("", "*Your response will appear here...*", "*Tool execution details will appear here...*", ""),
339
+ outputs=[query_input, response_output, tool_info_output, performance_output]
340
+ )
341
+
342
+ # Footer
343
+ gr.Markdown("""
344
+ ---
345
+ ### 🔗 Useful Links
346
+ - [Groq Console](https://console.groq.com/) - Get your free API key
347
+ - [Groq Documentation](https://console.groq.com/docs/quickstart) - Learn more about Groq models
348
+ - [Compound Models Info](https://console.groq.com/docs/models) - Details about compound models
349
+
350
+ ### 💡 Tips
351
+ - The compound models automatically use web search when real-time information is needed
352
+ - Try different temperature settings: 0.1 for factual queries, 0.7-0.9 for creative questions
353
+ - compound-beta is more capable but slower, compound-beta-mini is faster but less capable
354
+ """)
355
+
356
+ return demo
357
+
358
+ # Launch the application
359
+ if __name__ == "__main__":
360
+ demo = create_interface()
361
+ demo.launch(
362
+ share=True
363
+ )