Himel09 commited on
Commit
dde4107
·
verified ·
1 Parent(s): 639afe0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +239 -0
app.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from grok import Grok
3
+ import gradio as gr
4
+ from datetime import datetime
5
+ import time
6
+
7
+
8
+ class RTFC:
9
+ def __init__(self):
10
+ self.client = None
11
+ self.model_options = ["groq/compound", "groq/compound-mini"]
12
+
13
+ # Validate API Key
14
+ def server(self, api_key):
15
+ try:
16
+ self.client = Grok(api_key=api_key)
17
+ return True, "✅ API Key validated successfully"
18
+ except Exception as e:
19
+ return False, f"❌ Error: {str(e)}"
20
+
21
+ # System prompt (instructions for LLM)
22
+ def system_prompt(self):
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
+ # Query the Grok model
52
+ def query_compound_model(self, query, model, temperature=0.7):
53
+ if not self.client:
54
+ return "Please set a valid API Key", None, None
55
+
56
+ try:
57
+ start_time = time.time()
58
+ system_prompt = self.system_prompt()
59
+
60
+ response = self.client.chat.completions.create(
61
+ model=model,
62
+ messages=[
63
+ {"role": "system", "content": system_prompt},
64
+ {"role": "user", "content": query},
65
+ ],
66
+ temperature=temperature,
67
+ max_tokens=1000,
68
+ )
69
+
70
+ end_time = time.time()
71
+ response_time = round(end_time - start_time, 2)
72
+
73
+ final_response = response.choices[0].message.content
74
+ executed_tools = getattr(response.choices[0].message, "executed_tools", None)
75
+ tool_info = self.format_tool_info(executed_tools)
76
+
77
+ return final_response, tool_info, response_time
78
+
79
+ except Exception as e:
80
+ return f"Error: {str(e)}", None, None
81
+
82
+ # Tool info formatter
83
+ def format_tool_info(self, executed_tools):
84
+ if not executed_tools:
85
+ return "Tools Used: Existing Knowledge Only"
86
+
87
+ tool_info = "Tools Used:\n"
88
+ for i, tool in enumerate(executed_tools, 1):
89
+ try:
90
+ if hasattr(tool, "name"):
91
+ tool_name = tool.name
92
+ elif hasattr(tool, "tool_name"):
93
+ tool_name = tool.tool_name
94
+ elif isinstance(tool, dict):
95
+ tool_name = tool.get("name", "Unknown")
96
+ else:
97
+ tool_name = str(tool)
98
+
99
+ tool_info += f"{i}. {tool_name}\n"
100
+
101
+ if hasattr(tool, "parameters"):
102
+ params = tool.parameters
103
+ if isinstance(params, dict):
104
+ for key, value in params.items():
105
+ tool_info += f" - {key}: {value}\n"
106
+ elif hasattr(tool, "input"):
107
+ tool_info += f" - Input: {tool.input}\n"
108
+
109
+ except Exception:
110
+ tool_info += f"{i}. Tool {i} (Error parsing details)\n"
111
+
112
+ return tool_info
113
+
114
+
115
+ # ============== GRADIO INTERFACE ==============
116
+ def create_interface():
117
+ fact_checker = RTFC()
118
+
119
+ # Validate API key
120
+ def validate_api_key(api_key):
121
+ if not api_key or api_key.strip() == "":
122
+ return "Please enter a valid API key", False
123
+
124
+ success, message = fact_checker.server(api_key.strip())
125
+ return message, success
126
+
127
+ # Process query
128
+ def process_query(query, model, temperature, api_key):
129
+ if not api_key or api_key.strip() == "":
130
+ return "Please set your API key first", "", ""
131
+
132
+ if not query or query.strip() == "":
133
+ return "Please enter a query", "", ""
134
+
135
+ if not fact_checker.client:
136
+ success, message = fact_checker.server(api_key.strip())
137
+ if not success:
138
+ return message, "", ""
139
+
140
+ response, tool_info, response_time = fact_checker.query_compound_model(
141
+ query.strip(), model, temperature
142
+ )
143
+
144
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
145
+ formatted_response = (
146
+ f"**Query:** {query}\n\n**Response:**\n{response}\n\n---\n"
147
+ f"*Generated at {timestamp} in {response_time}s*"
148
+ )
149
+
150
+ return formatted_response, tool_info or "", f"Response time: {response_time}s"
151
+
152
+ # Gradio UI
153
+ with gr.Blocks(title="Real-Time Fact Checker", theme=gr.themes.Soft(primary_hue="blue")) as demo:
154
+ gr.Markdown("## 🧠 Real-time Fact Checker & News Agent")
155
+
156
+ with gr.Row():
157
+ with gr.Column(scale=1):
158
+ api_key_input = gr.Textbox(
159
+ label="Enter your GROK API Key",
160
+ placeholder="Enter your GROK API key here...",
161
+ type="password",
162
+ )
163
+
164
+ label_status = gr.Textbox(
165
+ label="Status",
166
+ value="Please enter your API key",
167
+ interactive=False,
168
+ )
169
+
170
+ validate_btn = gr.Button("Validate API Key")
171
+
172
+ query_input = gr.Textbox(
173
+ label="Query",
174
+ placeholder="e.g., What are the latest AI developments today?",
175
+ lines=4,
176
+ )
177
+
178
+ model_choice = gr.Dropdown(
179
+ choices=fact_checker.model_options,
180
+ value="groq/compound",
181
+ label="Model",
182
+ info="compound: More capable | compound-mini: Faster",
183
+ )
184
+
185
+ temperature = gr.Slider(
186
+ minimum=0.0,
187
+ maximum=1.0,
188
+ value=0.7,
189
+ step=0.1,
190
+ label="Temperature",
191
+ info="Higher = more creative, Lower = more focused",
192
+ )
193
+
194
+ with gr.Row():
195
+ submit_btn = gr.Button("🔎 Get Real-time Information")
196
+ clear_btn = gr.Button("🧹 Clear")
197
+
198
+ with gr.Column(scale=2):
199
+ response_output = gr.Markdown(
200
+ label="Response",
201
+ value="*Your response will appear here...*",
202
+ )
203
+
204
+ tool_info_output = gr.Markdown(
205
+ label="Tool Execution Info",
206
+ value="*Tool execution details will appear here...*",
207
+ )
208
+
209
+ performance_output = gr.Textbox(
210
+ label="Performance",
211
+ value="",
212
+ interactive=False,
213
+ )
214
+
215
+ # Button interactions
216
+ validate_btn.click(
217
+ fn=validate_api_key,
218
+ inputs=[api_key_input],
219
+ outputs=[label_status, gr.State()],
220
+ )
221
+
222
+ submit_btn.click(
223
+ fn=process_query,
224
+ inputs=[query_input, model_choice, temperature, api_key_input],
225
+ outputs=[response_output, tool_info_output, performance_output],
226
+ )
227
+
228
+ clear_btn.click(
229
+ fn=lambda: ("", "*Your response will appear here...*", "*Tool execution details will appear here...*", ""),
230
+ outputs=[query_input, response_output, tool_info_output, performance_output],
231
+ )
232
+
233
+ return demo
234
+
235
+
236
+ # ============== MAIN ENTRY POINT ==============
237
+ if __name__ == "__main__":
238
+ demo = create_interface()
239
+ demo.launch()