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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
def __init__(self):
|
9 |
+
self.client = None
|
10 |
+
self.model_options = ["compound-beta", "compound-beta-mini"]
|
11 |
+
|
12 |
+
def initialize_client(self, api_key):
|
13 |
+
"""Initialize Groq client with API key"""
|
14 |
+
try:
|
15 |
+
self.client = Groq(api_key=api_key)
|
16 |
+
return True, "β
API Key validated successfully!"
|
17 |
+
except Exception as e:
|
18 |
+
return False, f"β Error initializing client: {str(e)}"
|
19 |
+
|
20 |
+
def get_system_prompt(self):
|
21 |
+
"""Get the system prompt for consistent behavior"""
|
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 |
+
"""Query the compound model and return response with tool execution info"""
|
52 |
+
if not self.client:
|
53 |
+
return "β Please set a valid API key first.", None, None
|
54 |
+
|
55 |
+
try:
|
56 |
+
start_time = time.time()
|
57 |
+
|
58 |
+
system_prompt = self.get_system_prompt()
|
59 |
+
|
60 |
+
chat_completion = self.client.chat.completions.create(
|
61 |
+
messages=[
|
62 |
+
{
|
63 |
+
"role": "system",
|
64 |
+
"content": system_prompt
|
65 |
+
},
|
66 |
+
{
|
67 |
+
"role": "user",
|
68 |
+
"content": query,
|
69 |
+
}
|
70 |
+
],
|
71 |
+
model=model,
|
72 |
+
temperature=temperature,
|
73 |
+
max_tokens=1500
|
74 |
+
)
|
75 |
+
|
76 |
+
end_time = time.time()
|
77 |
+
response_time = round(end_time - start_time, 2)
|
78 |
+
|
79 |
+
response_content = chat_completion.choices[0].message.content
|
80 |
+
executed_tools = getattr(chat_completion.choices[0].message, 'executed_tools', None)
|
81 |
+
tool_info = self.format_tool_info(executed_tools)
|
82 |
+
|
83 |
+
return response_content, tool_info, response_time
|
84 |
+
|
85 |
+
except Exception as e:
|
86 |
+
return f"β Error querying model: {str(e)}", None, None
|
87 |
+
|
88 |
+
def format_tool_info(self, executed_tools):
|
89 |
+
"""Format executed tools information for display"""
|
90 |
+
if not executed_tools:
|
91 |
+
return "π Tools Used: None (Used existing knowledge)"
|
92 |
+
|
93 |
+
tool_info = "π Tools Used:\n"
|
94 |
+
for i, tool in enumerate(executed_tools, 1):
|
95 |
+
try:
|
96 |
+
if hasattr(tool, 'name'):
|
97 |
+
tool_name = tool.name
|
98 |
+
elif hasattr(tool, 'tool_name'):
|
99 |
+
tool_name = tool.tool_name
|
100 |
+
elif isinstance(tool, dict):
|
101 |
+
tool_name = tool.get('name', 'Unknown')
|
102 |
+
else:
|
103 |
+
tool_name = str(tool)
|
104 |
+
|
105 |
+
tool_info += f"{i}. {tool_name}\n"
|
106 |
+
|
107 |
+
if hasattr(tool, 'parameters'):
|
108 |
+
params = tool.parameters
|
109 |
+
if isinstance(params, dict):
|
110 |
+
for key, value in params.items():
|
111 |
+
tool_info += f" - {key}: {value}\n"
|
112 |
+
elif hasattr(tool, 'input'):
|
113 |
+
tool_info += f" - Input: {tool.input}\n"
|
114 |
+
|
115 |
+
except Exception as e:
|
116 |
+
tool_info += f"{i}. Tool {i} (Error parsing details)\n"
|
117 |
+
|
118 |
+
return tool_info
|
119 |
+
|
120 |
+
def create_interface():
|
121 |
+
fact_checker = RealTimeFactChecker()
|
122 |
+
|
123 |
+
def validate_api_key(api_key):
|
124 |
+
if not api_key or api_key.strip() == "":
|
125 |
+
return "β Please enter a valid API key", False
|
126 |
+
|
127 |
+
success, message = fact_checker.initialize_client(api_key.strip())
|
128 |
+
return message, success
|
129 |
+
|
130 |
+
def process_query(query, model, temperature, api_key):
|
131 |
+
if not api_key or api_key.strip() == "":
|
132 |
+
return "β Please set your API key first", "", ""
|
133 |
+
|
134 |
+
if not query or query.strip() == "":
|
135 |
+
return "β Please enter a query", "", ""
|
136 |
+
|
137 |
+
if not fact_checker.client:
|
138 |
+
success, message = fact_checker.initialize_client(api_key.strip())
|
139 |
+
if not success:
|
140 |
+
return message, "", ""
|
141 |
+
|
142 |
+
response, tool_info, response_time = fact_checker.query_compound_model(
|
143 |
+
query.strip(), model, temperature
|
144 |
+
)
|
145 |
+
|
146 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
147 |
+
formatted_response = f"**Query:** {query}\n\n**Response:**\n{response}\n\n---\n*Generated at {timestamp} in {response_time}s*"
|
148 |
+
|
149 |
+
return formatted_response, tool_info or "", f"Response time: {response_time}s"
|
150 |
+
|
151 |
+
with gr.Blocks(title="Real-time Fact Checker & News Agent") as demo:
|
152 |
+
gr.Markdown("# Real-time Fact Checker & News Agent")
|
153 |
+
gr.Markdown("Powered by Groq's Compound Models with Built-in Web Search")
|
154 |
+
|
155 |
+
with gr.Row():
|
156 |
+
with gr.Column():
|
157 |
+
api_key_input = gr.Textbox(
|
158 |
+
label="Groq API Key",
|
159 |
+
placeholder="Enter your Groq API key here...",
|
160 |
+
type="password",
|
161 |
+
info="Get your free API key from https://console.groq.com/"
|
162 |
+
)
|
163 |
+
api_status = gr.Textbox(
|
164 |
+
label="Status",
|
165 |
+
value="Please enter your API key",
|
166 |
+
interactive=False
|
167 |
+
)
|
168 |
+
validate_btn = gr.Button("Validate API Key")
|
169 |
+
|
170 |
+
query_input = gr.Textbox(
|
171 |
+
label="Query",
|
172 |
+
placeholder="e.g., What are the latest AI developments today?",
|
173 |
+
lines=4
|
174 |
+
)
|
175 |
+
|
176 |
+
with gr.Row():
|
177 |
+
model_choice = gr.Dropdown(
|
178 |
+
choices=fact_checker.model_options,
|
179 |
+
value="compound-beta",
|
180 |
+
label="Model",
|
181 |
+
info="compound-beta: More capable | compound-beta-mini: Faster"
|
182 |
+
)
|
183 |
+
temperature = gr.Slider(
|
184 |
+
minimum=0.0,
|
185 |
+
maximum=1.0,
|
186 |
+
value=0.7,
|
187 |
+
step=0.1,
|
188 |
+
label="Temperature",
|
189 |
+
info="Higher = more creative, Lower = more focused"
|
190 |
+
)
|
191 |
+
|
192 |
+
with gr.Row():
|
193 |
+
submit_btn = gr.Button("Get Real-time Information")
|
194 |
+
clear_btn = gr.Button("Clear")
|
195 |
+
|
196 |
+
with gr.Column():
|
197 |
+
response_output = gr.Markdown(
|
198 |
+
label="Response",
|
199 |
+
value="*Your response will appear here...*"
|
200 |
+
)
|
201 |
+
|
202 |
+
tool_info_output = gr.Markdown(
|
203 |
+
label="Tool Execution Info",
|
204 |
+
value="*Tool execution details will appear here...*"
|
205 |
+
)
|
206 |
+
|
207 |
+
performance_output = gr.Textbox(
|
208 |
+
label="Performance",
|
209 |
+
value="",
|
210 |
+
interactive=False
|
211 |
+
)
|
212 |
+
|
213 |
+
validate_btn.click(
|
214 |
+
fn=validate_api_key,
|
215 |
+
inputs=[api_key_input],
|
216 |
+
outputs=[api_status, gr.State()]
|
217 |
+
)
|
218 |
+
|
219 |
+
submit_btn.click(
|
220 |
+
fn=process_query,
|
221 |
+
inputs=[query_input, model_choice, temperature, api_key_input],
|
222 |
+
outputs=[response_output, tool_info_output, performance_output]
|
223 |
+
)
|
224 |
+
|
225 |
+
clear_btn.click(
|
226 |
+
fn=lambda: ("", "*Your response will appear here...*", "*Tool execution details will appear here...*", ""),
|
227 |
+
outputs=[query_input, response_output, tool_info_output, performance_output]
|
228 |
+
)
|
229 |
+
|
230 |
+
gr.Markdown("""
|
231 |
+
### Useful Links
|
232 |
+
- [Groq Console](https://console.groq.com/) - Get your free API key
|
233 |
+
- [Groq Documentation](https://console.groq.com/docs/quickstart) - Learn more about Groq models
|
234 |
+
- [Compound Models Info](https://console.groq.com/docs/models) - Details about compound models
|
235 |
+
|
236 |
+
### Tips
|
237 |
+
- The compound models automatically use web search when real-time information is needed
|
238 |
+
- Try different temperature settings: 0.1 for factual queries, 0.7-0.9 for creative questions
|
239 |
+
- compound-beta is more capable but slower, compound-beta-mini is faster but less capable
|
240 |
+
- Check the Tool Execution Info to see when web search was used
|
241 |
+
""")
|
242 |
+
|
243 |
+
return demo
|
244 |
+
|
245 |
+
if __name__ == "__main__":
|
246 |
+
demo = create_interface()
|
247 |
+
demo.launch(
|
248 |
+
share=True
|
249 |
+
)
|