shukdevdattaEX commited on
Commit
4560f26
Β·
verified Β·
1 Parent(s): c8acb80

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +246 -0
app.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from groq import Groq
4
+ from datetime import datetime
5
+ import time
6
+
7
+ class RealTimeFactChecker:
8
+
9
+ def __init__(self):
10
+ self.client = None
11
+ self.model_options=["compound", "compound-mini"]
12
+
13
+ def initialize_client(self, api_key):
14
+ try:
15
+ self.client=Groq(api_key=api_key)
16
+ return True, "βœ… API Key validated successfully!"
17
+
18
+ except Exception as e:
19
+ return False, f"❌ Error initializing client: {str(e)}"
20
+
21
+ def get_system_prompt(self):
22
+ 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.
23
+ CORE RESPONSIBILITIES:
24
+ 1. **Fact Verification**: Always verify claims with current, reliable sources
25
+ 2. **Real-time Information**: Use web search for any information that changes frequently (news, stocks, weather, current events)
26
+ 3. **Source Transparency**: When using web search, mention the sources or indicate that you've searched for current information
27
+ 4. **Accuracy First**: If information is uncertain or conflicting, acknowledge this clearly
28
+ RESPONSE GUIDELINES:
29
+ - **Structure**: Start with a clear, direct answer, then provide supporting details
30
+ - **Recency**: Always prioritize the most recent, reliable information
31
+ - **Clarity**: Use clear, professional language while remaining accessible
32
+ - **Completeness**: Provide comprehensive answers but stay focused on the query
33
+ - **Source Awareness**: When you've searched for information, briefly indicate this (e.g., "Based on current reports..." or "Recent data shows...")
34
+ WHEN TO SEARCH:
35
+ - Breaking news or current events
36
+ - Stock prices, market data, or financial information
37
+ - Weather conditions or forecasts
38
+ - Recent scientific discoveries or research
39
+ - Current political developments
40
+ - Real-time statistics or data
41
+ - Verification of recent claims or rumors
42
+ RESPONSE FORMAT:
43
+ - Lead with key facts
44
+ - Include relevant context
45
+ - Mention timeframe when relevant (e.g., "as of today", "this week")
46
+ - If multiple sources conflict, acknowledge this
47
+ - End with a clear summary for complex topics
48
+ Remember: Your goal is to be the most reliable, up-to-date source of information possible."""
49
+
50
+ def query_compound_model(self, query, model, temperature=0.7):
51
+
52
+ if not self.client:
53
+ return "❌ Please set a valid API key first.", None, None
54
+
55
+ try:
56
+
57
+ start_time=time.time()
58
+
59
+ system_prompt = self.get_system_prompt()
60
+
61
+ chat_completion = self.client.chat.completions.create(
62
+ messages=[
63
+ {
64
+ "role": "system",
65
+ "content": system_prompt
66
+ },
67
+ {
68
+ "role": "user",
69
+ "content": query,
70
+ },
71
+ ]
72
+ model=model,
73
+ temperature=temperature,
74
+ max_tokens=1500
75
+
76
+ )
77
+
78
+ end_time = time.time()
79
+
80
+ response_time= round(end_time-start_time, 2)
81
+
82
+ response_content = chat_completion.choices[0].message.content # response to the question
83
+ executed_tools = getattr(chat_completion.choices[0].message, 'executed_tools', None)
84
+ tool_info = self.format_tool_info(executed_tools)
85
+
86
+ return response_content, tool_info, response_time
87
+
88
+ except Exception as e:
89
+ return f"❌ Error querying model: {str(e)}", None, None
90
+
91
+
92
+ def format_tool_info(self, executed_tools):
93
+ """Format executed tools information for display"""
94
+
95
+ if not executed_tools:
96
+ return "πŸ” Tools Used: None (Used existing knowledge)"
97
+
98
+ tool_info = "πŸ” Tools Used:\n"
99
+
100
+ for i, tool in enumerate(executed_tools, 1):
101
+ try:
102
+ if hasattr(tool, 'name'):
103
+ tool_name = tool.name
104
+ elif hasattr(tool, 'tool_name'):
105
+ tool_name = tool.tool_name
106
+ elif isinstance(tool, dict):
107
+ tool_name = tool.get('name', 'Unknown')
108
+ else:
109
+ tool_name = str(tool)
110
+
111
+ tool_info += f"{i}. {tool_name}\n"
112
+
113
+ if hasattr(tool, 'parameters'):
114
+ params = tool.parameters
115
+ if isinstance(params, dict):
116
+ for key, value in params.items():
117
+ tool_info += f" - {key}: {value}\n"
118
+ elif hasattr(tool, 'input'):
119
+ tool_info += f" - Input: {tool.input}\n"
120
+
121
+ except Exception as e:
122
+ tool_info += f"{i}. Tool {i} (Error parsing details)\n"
123
+
124
+ return tool_info
125
+
126
+ #### UI Design
127
+
128
+ def create_interface():
129
+ fact_checker = RealTimeFactChecker()
130
+
131
+ def validate_api_key(api_key):
132
+ if not api_key or api_key.strip() == "":
133
+ return "❌ Please enter a valid API key", False
134
+
135
+ success, message = fact_checker.initialize_client(api_key.strip())
136
+ return message, success
137
+
138
+ def process_query(query, model, temperature, api_key):
139
+ if not api_key or api_key.strip() == "":
140
+ return "❌ Please set your API key first", "", ""
141
+
142
+ if not query or query.strip() == "":
143
+ return "❌ Please enter a query", "", ""
144
+
145
+ if not fact_checker.client:
146
+ success, message = fact_checker.initialize_client(api_key.strip())
147
+ if not success:
148
+ return message, "", ""
149
+
150
+ response, tool_info, response_time = fact_checker.query_compound_model(
151
+ query.strip(), model, temperature
152
+ )
153
+
154
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
155
+ formatted_response = f"**Query:** {query}\n\n**Response:**\n{response}\n\n---\n*Generated at {timestamp} in {response_time}s*" # 11/11/2025 Query Response Time: 20s
156
+
157
+ return formatted_response, tool_info or "", f"Response time: {response_time}s"
158
+
159
+ with gr.Blocks(title="Real-time Fact Checker & News Agent", theme=gr.themes.Ocean()) as demo:
160
+ gr.Markdown("# Real-time Fact Checker & News Agent")
161
+ gr.Markdown("Powered by Groq's Compound Models with Built-in Web Search")
162
+
163
+ with gr.Row():
164
+ with gr.Column():
165
+ api_key_input = gr.Textbox(
166
+ label="Groq API Key",
167
+ placeholder="Enter your Groq API key here...",
168
+ type="password",
169
+ info="Get your free API key from https://console.groq.com/"
170
+ )
171
+ api_status = gr.Textbox(
172
+ label="Status",
173
+ value="Please enter your API key",
174
+ interactive=False
175
+ )
176
+ validate_btn = gr.Button("Validate API Key")
177
+
178
+ query_input = gr.Textbox(
179
+ label="Query",
180
+ placeholder="e.g., What are the latest AI developments today?",
181
+ lines=4
182
+ )
183
+
184
+ with gr.Row():
185
+ model_choice = gr.Dropdown(
186
+ choices=fact_checker.model_options,
187
+ value="compound",
188
+ label="Model",
189
+ info="compound-: More capable | compound-mini: Faster"
190
+ )
191
+
192
+ temperature = gr.Slider(
193
+ minimum=0.0,
194
+ maximum=1.0,
195
+ value=0.7,
196
+ step=0.1,
197
+ label="Temperature",
198
+ info="Higher = more creative, Lower = more focused"
199
+ )
200
+
201
+ with gr.Row():
202
+ submit_btn = gr.Button("Get Real-time Information")
203
+ clear_btn = gr.Button("Clear")
204
+
205
+ with gr.Column():
206
+
207
+ response_output = gr.Markdown(
208
+ label="Response",
209
+ value="*Your response will appear here...*"
210
+ )
211
+
212
+ tool_info_output = gr.Markdown(
213
+ label="Tool Execution Info",
214
+ value="*Tool execution details will appear here...*"
215
+ )
216
+
217
+ performance_output = gr.Textbox(
218
+ label="Performance",
219
+ value="",
220
+ interactive=False
221
+ )
222
+
223
+ validate_btn.click(
224
+ fn=validate_api_key,
225
+ inputs=[api_key_input],
226
+ outputs=[api_status, gr.State()]
227
+ )
228
+
229
+ submit_btn.click(
230
+ fn=process_query,
231
+ inputs=[query_input, model_choice, temperature, api_key_input],
232
+ outputs=[response_output, tool_info_output, performance_output]
233
+ )
234
+
235
+ clear_btn.click(
236
+ fn=lambda: ("", "*Your response will appear here...*", "*Tool execution details will appear here...*", ""),
237
+ outputs=[query_input, response_output, tool_info_output, performance_output]
238
+ )
239
+
240
+
241
+ return demo
242
+
243
+ if __name__ == "__main__":
244
+ demo = create_interface()
245
+ demo.launch(
246
+ )