Spaces:
Sleeping
Sleeping
File size: 26,403 Bytes
c17a276 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
{
"cells": [
{
"cell_type": "markdown",
"id": "da10738e",
"metadata": {},
"source": [
"# Line-by-Line Code Explanation: Real-time Fact Checker\n",
"\n",
"Let me walk you through every single line of this fascinating fact-checking application, explaining exactly what each piece does and why it's important.\n",
"\n",
"## The Foundation: Import Statements (Lines 1-5)\n",
"\n",
"```python\n",
"import os\n",
"```\n",
"This line brings in the operating system interface. Think of this as giving your program the ability to interact with your computer's file system and environment. Although it's imported here, it's not heavily used in this particular program, but it's often included as a precaution for future functionality.\n",
"\n",
"```python\n",
"import gradio as gr\n",
"```\n",
"This is the star of our user interface show. Gradio is like a magic wand that transforms your Python functions into beautiful web interfaces. Instead of writing hundreds of lines of HTML, CSS, and JavaScript, Gradio lets you create interactive web apps with just a few Python commands. The `as gr` part creates a shorter nickname so we don't have to type \"gradio\" every time.\n",
"\n",
"```python\n",
"from groq import Groq\n",
"```\n",
"This imports the main client class from the Groq library. Groq is a company that provides super-fast AI inference services. Think of this import as bringing in your connection tool to talk to Groq's powerful AI models. The capital \"Groq\" is the class we'll use to create our AI client.\n",
"\n",
"```python\n",
"from datetime import datetime\n",
"```\n",
"This gives us the power to work with dates and times. We'll use this to timestamp our responses so users know exactly when their fact-check was performed. It's like adding a digital clock to our application.\n",
"\n",
"```python\n",
"import time\n",
"```\n",
"This module helps us measure how long things take. We'll use it to track how fast our AI responds to queries, which is valuable information for users who want to know the performance of their fact-checking requests.\n",
"\n",
"## The Heart of Our Application: The RealTimeFactChecker Class (Lines 7-8)\n",
"\n",
"```python\n",
"class RealTimeFactChecker:\n",
" def __init__(self):\n",
"```\n",
"Here we're creating our main class, which is like a blueprint for our fact-checking tool. Think of a class as a template that defines what our fact checker can do and what information it needs to remember. The `__init__` method is special - it's called automatically whenever we create a new fact checker. It's like the setup instructions that run when you first turn on a new device.\n",
"\n",
"## Setting Up the Initial State (Lines 9-10)\n",
"\n",
"```python\n",
" self.client = None\n",
" self.model_options = [\"compound-beta\", \"compound-beta-mini\"]\n",
"```\n",
"The first line creates a placeholder for our AI client. We start with `None` because we can't create the actual connection until the user provides their API key. It's like having an empty phone book entry until you get someone's phone number.\n",
"\n",
"The second line creates a list of AI models we can choose from. Think of these as different versions of the AI brain - \"compound-beta\" is like the full-featured version that's more capable but takes a bit longer, while \"compound-beta-mini\" is like the express version that's faster but not quite as sophisticated.\n",
"\n",
"## The API Key Validator (Lines 12-19)\n",
"\n",
"```python\n",
" def initialize_client(self, api_key):\n",
" \"\"\"Initialize Groq client with API key\"\"\"\n",
"```\n",
"This method is like a security guard for our application. Its job is to take the API key that the user provides and try to establish a connection with Groq's servers. The triple-quoted text is called a docstring - it's a note to other programmers (and your future self) explaining what this function does.\n",
"\n",
"```python\n",
" try:\n",
" self.client = Groq(api_key=api_key)\n",
" return True, \"✅ API Key validated successfully!\"\n",
"```\n",
"The `try` block is like saying \"attempt this, but be ready if something goes wrong.\" Here we're trying to create a new Groq client using the provided API key. If it works, we store the client in `self.client` and return a success message with a green checkmark emoji. The `True` tells the calling code that everything went well.\n",
"\n",
"```python\n",
" except Exception as e:\n",
" return False, f\"❌ Error initializing client: {str(e)}\"\n",
"```\n",
"The `except` block is our safety net. If anything goes wrong (like an invalid API key), instead of crashing the entire program, we catch the error, return `False` to indicate failure, and provide a helpful error message with a red X emoji. The `f\"...\"` is called an f-string, which lets us insert the actual error message into our response.\n",
"\n",
"## The AI's Instructions: System Prompt (Lines 21-47)\n",
"\n",
"```python\n",
" def get_system_prompt(self):\n",
" \"\"\"Get the system prompt for consistent behavior\"\"\"\n",
" return \"\"\"You are a Real-time Fact Checker and News Agent...\n",
"```\n",
"This method returns a very important piece of text that acts like a job description for our AI. Every time we send a query to the AI, we include these instructions to ensure it behaves consistently as a fact-checker rather than just a general chatbot. Think of this as the difference between talking to a librarian who knows they should help you find accurate information versus talking to someone random on the street.\n",
"\n",
"The system prompt tells the AI to:\n",
"- Always verify information with current sources\n",
"- Use web search for rapidly changing information like news and stock prices \n",
"- Be transparent about when it searched for information\n",
"- Structure responses clearly with key facts first\n",
"- Acknowledge when information is uncertain or conflicting\n",
"\n",
"## The Core Intelligence: Query Processing (Lines 49-78)\n",
"\n",
"```python\n",
" def query_compound_model(self, query, model, temperature=0.7):\n",
" \"\"\"Query the compound model and return response with tool execution info\"\"\"\n",
"```\n",
"This is the brain of our operation - the method that actually talks to the AI. It takes a user's question, the model they want to use, and a temperature setting (which controls how creative vs. focused the AI should be).\n",
"\n",
"```python\n",
" if not self.client:\n",
" return \"❌ Please set a valid API key first.\", None, None\n",
"```\n",
"This is our first safety check. If no client exists (meaning no valid API key was provided), we return an error message and empty values for the other expected return items.\n",
"\n",
"```python\n",
" try:\n",
" start_time = time.time()\n",
"```\n",
"We record the exact time when we start processing the request. This is like starting a stopwatch to measure how long the AI takes to respond.\n",
"\n",
"```python\n",
" system_prompt = self.get_system_prompt()\n",
"```\n",
"We fetch our AI instructions that we defined earlier. Every query includes these instructions to maintain consistent behavior.\n",
"\n",
"```python\n",
" chat_completion = self.client.chat.completions.create(\n",
" messages=[\n",
" {\n",
" \"role\": \"system\",\n",
" \"content\": system_prompt\n",
" },\n",
" {\n",
" \"role\": \"user\",\n",
" \"content\": query,\n",
" }\n",
" ],\n",
" model=model,\n",
" temperature=temperature,\n",
" max_tokens=1500\n",
" )\n",
"```\n",
"This is where the magic happens! We're sending a conversation to the AI with two messages: first, our system instructions (telling the AI how to behave), and second, the user's actual question. The `model` parameter chooses which AI brain to use, `temperature` controls creativity (0.0 = very focused, 1.0 = very creative), and `max_tokens` limits how long the response can be (about 1500 words maximum).\n",
"\n",
"```python\n",
" end_time = time.time()\n",
" response_time = round(end_time - start_time, 2)\n",
"```\n",
"We stop our stopwatch and calculate how long the entire process took, rounded to two decimal places for clean display.\n",
"\n",
"```python\n",
" response_content = chat_completion.choices[0].message.content\n",
" executed_tools = getattr(chat_completion.choices[0].message, 'executed_tools', None)\n",
" tool_info = self.format_tool_info(executed_tools)\n",
"```\n",
"We extract three pieces of information from the AI's response: the actual text answer, information about any tools (like web search) that were used, and we format that tool information for display. The `getattr` function safely tries to get the tool information, defaulting to `None` if it doesn't exist.\n",
"\n",
"```python\n",
" return response_content, tool_info, response_time\n",
"```\n",
"We return all three pieces of information so the interface can display them to the user.\n",
"\n",
"```python\n",
" except Exception as e:\n",
" return f\"❌ Error querying model: {str(e)}\", None, None\n",
"```\n",
"Our safety net again - if anything goes wrong during the AI query, we return an error message instead of crashing.\n",
"\n",
"## Making Tool Information User-Friendly (Lines 80-107)\n",
"\n",
"```python\n",
" def format_tool_info(self, executed_tools):\n",
" \"\"\"Format executed tools information for display\"\"\"\n",
" if not executed_tools:\n",
" return \"🔍 Tools Used: None (Used existing knowledge)\"\n",
"```\n",
"This method takes the raw tool information from the AI and makes it readable for humans. If no tools were used, it clearly states that the AI used its existing knowledge.\n",
"\n",
"```python\n",
" tool_info = \"🔍 Tools Used:\\n\"\n",
" for i, tool in enumerate(executed_tools, 1):\n",
"```\n",
"We start building a formatted list of tools. The `enumerate` function gives us both the tool and a counter starting from 1, so we can number the tools nicely.\n",
"\n",
"```python\n",
" try:\n",
" if hasattr(tool, 'name'):\n",
" tool_name = tool.name\n",
" elif hasattr(tool, 'tool_name'):\n",
" tool_name = tool.tool_name\n",
" elif isinstance(tool, dict):\n",
" tool_name = tool.get('name', 'Unknown')\n",
" else:\n",
" tool_name = str(tool)\n",
"```\n",
"This section handles the fact that tool information might come in different formats. We try several different ways to extract the tool name, falling back to \"Unknown\" if we can't figure it out. It's like having multiple keys to try on a lock.\n",
"\n",
"```python\n",
" tool_info += f\"{i}. {tool_name}\\n\"\n",
"```\n",
"We add the numbered tool name to our display string.\n",
"\n",
"```python\n",
" if hasattr(tool, 'parameters'):\n",
" params = tool.parameters\n",
" if isinstance(params, dict):\n",
" for key, value in params.items():\n",
" tool_info += f\" - {key}: {value}\\n\"\n",
" elif hasattr(tool, 'input'):\n",
" tool_info += f\" - Input: {tool.input}\\n\"\n",
"```\n",
"We try to extract and display additional details about what parameters were passed to each tool. This gives users insight into exactly what the AI searched for.\n",
"\n",
"```python\n",
" except Exception as e:\n",
" tool_info += f\"{i}. Tool {i} (Error parsing details)\\n\"\n",
"```\n",
"If we can't parse a particular tool's information, we still show that a tool was used, just without the details.\n",
"\n",
"## Building the User Interface (Lines 109-111)\n",
"\n",
"```python\n",
"def create_interface():\n",
" fact_checker = RealTimeFactChecker()\n",
"```\n",
"This function creates the web interface that users will interact with. First, we create an instance of our fact checker class - like assembling our fact-checking machine.\n",
"\n",
"## Interface Helper Functions (Lines 113-119)\n",
"\n",
"```python\n",
" def validate_api_key(api_key):\n",
" if not api_key or api_key.strip() == \"\":\n",
" return \"❌ Please enter a valid API key\", False\n",
"```\n",
"This helper function checks if the user actually entered an API key. The `strip()` method removes any extra whitespace, so we catch cases where someone just entered spaces.\n",
"\n",
"```python\n",
" success, message = fact_checker.initialize_client(api_key.strip())\n",
" return message, success\n",
"```\n",
"We try to initialize our client with the cleaned-up API key and return whatever message our initialize_client method gave us.\n",
"\n",
"## The Main Query Processing Helper (Lines 121-141)\n",
"\n",
"```python\n",
" def process_query(query, model, temperature, api_key):\n",
"```\n",
"This function orchestrates the entire fact-checking process from the user interface.\n",
"\n",
"```python\n",
" if not api_key or api_key.strip() == \"\":\n",
" return \"❌ Please set your API key first\", \"\", \"\"\n",
" \n",
" if not query or query.strip() == \"\":\n",
" return \"❌ Please enter a query\", \"\", \"\"\n",
"```\n",
"We perform input validation, making sure both the API key and query are provided. We return empty strings for the other expected outputs if validation fails.\n",
"\n",
"```python\n",
" if not fact_checker.client:\n",
" success, message = fact_checker.initialize_client(api_key.strip())\n",
" if not success:\n",
" return message, \"\", \"\"\n",
"```\n",
"If the client isn't already initialized (maybe the user entered a query without validating their API key first), we try to initialize it now.\n",
"\n",
"```python\n",
" response, tool_info, response_time = fact_checker.query_compound_model(\n",
" query.strip(), model, temperature\n",
" )\n",
"```\n",
"We send the actual query to our AI, getting back the response, tool information, and timing data.\n",
"\n",
"```python\n",
" timestamp = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n",
" formatted_response = f\"**Query:** {query}\\n\\n**Response:**\\n{response}\\n\\n---\\n*Generated at {timestamp} in {response_time}s*\"\n",
"```\n",
"We create a timestamp showing exactly when this response was generated and format it nicely with the original query, the AI's response, and timing information. The `strftime` method formats the date and time in a readable way.\n",
"\n",
"```python\n",
" return formatted_response, tool_info or \"\", f\"Response time: {response_time}s\"\n",
"```\n",
"We return all the information formatted for display. The `tool_info or \"\"` means \"use tool_info if it exists, otherwise use an empty string.\"\n",
"\n",
"## Creating the Visual Interface (Lines 143-151)\n",
"\n",
"```python\n",
" with gr.Blocks(title=\"Real-time Fact Checker & News Agent\") as demo:\n",
" gr.Markdown(\"# Real-time Fact Checker & News Agent\")\n",
" gr.Markdown(\"Powered by Groq's Compound Models with Built-in Web Search\")\n",
"```\n",
"We create the main container for our web interface. `gr.Blocks` is like creating a blank webpage that we can add components to. The `with` statement ensures everything we define inside gets added to this interface. The Markdown components add the title and description at the top.\n",
"\n",
"## Layout Structure: Two-Column Design (Lines 153-155)\n",
"\n",
"```python\n",
" with gr.Row():\n",
" with gr.Column():\n",
"```\n",
"We create a row that contains two columns. This gives us a side-by-side layout where inputs go on the left and outputs go on the right. It's like dividing a page into two sections.\n",
"\n",
"## Input Section: API Key Management (Lines 156-168)\n",
"\n",
"```python\n",
" api_key_input = gr.Textbox(\n",
" label=\"Groq API Key\",\n",
" placeholder=\"Enter your Groq API key here...\",\n",
" type=\"password\",\n",
" info=\"Get your free API key from https://console.groq.com/\"\n",
" )\n",
"```\n",
"This creates a password field for the API key. The `type=\"password\"` means the text gets hidden as the user types (showing dots instead of the actual key). The `info` parameter shows helpful text below the field.\n",
"\n",
"```python\n",
" api_status = gr.Textbox(\n",
" label=\"Status\",\n",
" value=\"Please enter your API key\",\n",
" interactive=False\n",
" )\n",
"```\n",
"This creates a read-only text field that shows the status of the API key validation. `interactive=False` means users can't edit it directly.\n",
"\n",
"```python\n",
" validate_btn = gr.Button(\"Validate API Key\")\n",
"```\n",
"A simple button that users click to test their API key.\n",
"\n",
"## Query Input Section (Lines 170-175)\n",
"\n",
"```python\n",
" query_input = gr.Textbox(\n",
" label=\"Query\",\n",
" placeholder=\"e.g., What are the latest AI developments today?\",\n",
" lines=4\n",
" )\n",
"```\n",
"This creates a larger text area where users can type their questions. The `lines=4` makes it tall enough for longer questions, and the placeholder gives users an idea of what kind of questions work well.\n",
"\n",
"## Model and Temperature Controls (Lines 177-194)\n",
"\n",
"```python\n",
" with gr.Row():\n",
" model_choice = gr.Dropdown(\n",
" choices=fact_checker.model_options,\n",
" value=\"compound-beta\",\n",
" label=\"Model\",\n",
" info=\"compound-beta: More capable | compound-beta-mini: Faster\"\n",
" )\n",
"```\n",
"We create a dropdown menu inside a row so it sits side-by-side with the temperature slider. Users can choose between the two AI models, with helpful descriptions of the trade-offs.\n",
"\n",
"```python\n",
" temperature = gr.Slider(\n",
" minimum=0.0,\n",
" maximum=1.0,\n",
" value=0.7,\n",
" step=0.1,\n",
" label=\"Temperature\",\n",
" info=\"Higher = more creative, Lower = more focused\"\n",
" )\n",
"```\n",
"This creates a slider that lets users control how creative vs. focused they want the AI to be. It starts at 0.7 (a good middle ground) and moves in steps of 0.1.\n",
"\n",
"## Action Buttons (Lines 196-198)\n",
"\n",
"```python\n",
" with gr.Row():\n",
" submit_btn = gr.Button(\"Get Real-time Information\")\n",
" clear_btn = gr.Button(\"Clear\")\n",
"```\n",
"Two buttons side by side: one to submit queries and one to clear all fields.\n",
"\n",
"## Output Section: Right Column (Lines 200-218)\n",
"\n",
"```python\n",
" with gr.Column():\n",
" response_output = gr.Markdown(\n",
" label=\"Response\",\n",
" value=\"*Your response will appear here...*\"\n",
" )\n",
"```\n",
"We start the second column with a Markdown component that will show the AI's response. Markdown format allows for nice formatting like bold text and links.\n",
"\n",
"```python\n",
" tool_info_output = gr.Markdown(\n",
" label=\"Tool Execution Info\",\n",
" value=\"*Tool execution details will appear here...*\"\n",
" )\n",
"```\n",
"Another Markdown area specifically for showing what tools the AI used.\n",
"\n",
"```python\n",
" performance_output = gr.Textbox(\n",
" label=\"Performance\",\n",
" value=\"\",\n",
" interactive=False\n",
" )\n",
"```\n",
"A read-only field for showing response times and performance metrics.\n",
"\n",
"## Connecting Actions to Functions (Lines 220-236)\n",
"\n",
"```python\n",
" validate_btn.click(\n",
" fn=validate_api_key,\n",
" inputs=[api_key_input],\n",
" outputs=[api_status, gr.State()]\n",
" )\n",
"```\n",
"This tells Gradio: \"When someone clicks the validate button, run the validate_api_key function, give it the text from api_key_input, and put the result in api_status.\" The `gr.State()` is a placeholder for the boolean return value that we don't directly display.\n",
"\n",
"```python\n",
" submit_btn.click(\n",
" fn=process_query,\n",
" inputs=[query_input, model_choice, temperature, api_key_input],\n",
" outputs=[response_output, tool_info_output, performance_output]\n",
" )\n",
"```\n",
"This connects the submit button to our main processing function, passing in all the user's choices and displaying results in all three output areas.\n",
"\n",
"```python\n",
" clear_btn.click(\n",
" fn=lambda: (\"\", \"*Your response will appear here...*\", \"*Tool execution details will appear here...*\", \"\"),\n",
" outputs=[query_input, response_output, tool_info_output, performance_output]\n",
" )\n",
"```\n",
"The clear button uses a lambda (anonymous) function to reset all fields to their default states. It's like a reset button for the entire interface.\n",
"\n",
"## Documentation and Help Section (Lines 238-251)\n",
"\n",
"```python\n",
" gr.Markdown(\"\"\"\n",
" ### Useful Links\n",
" - [Groq Console](https://console.groq.com/) - Get your free API key\n",
" - [Groq Documentation](https://console.groq.com/docs/quickstart) - Learn more about Groq models\n",
" - [Compound Models Info](https://console.groq.com/docs/models) - Details about compound models\n",
" \n",
" ### Tips\n",
" - The compound models automatically use web search when real-time information is needed\n",
" - Try different temperature settings: 0.1 for factual queries, 0.7-0.9 for creative questions\n",
" - compound-beta is more capable but slower, compound-beta-mini is faster but less capable\n",
" - Check the Tool Execution Info to see when web search was used\n",
" \"\"\")\n",
"```\n",
"This adds helpful documentation directly in the interface, giving users links to get API keys and tips for using the tool effectively.\n",
"\n",
"## Finalizing the Interface (Lines 253-254)\n",
"\n",
"```python\n",
" return demo\n",
"```\n",
"We return the completed interface so it can be launched.\n",
"\n",
"## Application Launch (Lines 256-260)\n",
"\n",
"```python\n",
"if __name__ == \"__main__\":\n",
" demo = create_interface()\n",
" demo.launch(\n",
" share=True\n",
" )\n",
"```\n",
"This is Python's way of saying \"only run this code if this file is being run directly (not imported by another file).\" We create our interface and launch it with `share=True`, which creates a public URL that can be accessed from anywhere on the internet for a limited time.\n",
"\n",
"## The Big Picture\n",
"\n",
"This application is a beautiful example of how modern AI tools can be made accessible to everyone. Instead of requiring users to write code or understand APIs, it provides a simple web interface where anyone can fact-check information in real-time. The code is structured to handle errors gracefully, provide clear feedback to users, and maintain transparency about how the AI is finding its information.\n",
"\n",
"The genius of this design is that it combines the power of advanced AI models with the simplicity of a web form, making cutting-edge fact-checking technology available to anyone with an internet browser."
]
},
{
"cell_type": "markdown",
"id": "c099b9b3",
"metadata": {},
"source": []
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|