import gradio as gr import os from google import genai from google.genai.types import Tool, GenerateContentConfig, GoogleSearch, UrlContext # Initialize the Gemini client def initialize_client(api_key): """Initialize the Gemini client with API key""" try: client = genai.Client(api_key=api_key) return client, None except Exception as e: return None, str(e) def search_with_context(api_key, query, url=None, enable_google_search=True, enable_url_context=True): """ Perform search using Gemini with optional URL context and Google search Args: api_key: Google Gemini API key query: Search query or question url: Optional URL for context enable_google_search: Whether to enable Google search enable_url_context: Whether to enable URL context """ if not api_key: return "❌ Please provide a valid API key", "", "" if not query: return "❌ Please provide a search query", "", "" try: # Initialize client client, error = initialize_client(api_key) if error: return f"❌ Error initializing client: {error}", "", "" model_id = "gemini-2.5-flash" # Configure tools based on user selection tools = [] if enable_url_context: tools.append({"url_context": {}}) if enable_google_search: tools.append({"google_search": {}}) if not tools: return "❌ Please enable at least one tool (URL Context or Google Search)", "", "" # Modify query to include URL if provided final_query = query if url and enable_url_context: final_query = f"{query} : {url}" # Generate content response = client.models.generate_content( model=model_id, contents=final_query, config=GenerateContentConfig( tools=tools, ) ) # Extract response text response_text = "" for part in response.candidates[0].content.parts: if hasattr(part, 'text') and part.text: response_text += part.text + "\n" # Extract URL context metadata url_metadata = "" try: if hasattr(response.candidates[0], 'url_context_metadata') and response.candidates[0].url_context_metadata: url_metadata = "📋 **URL Context Metadata:**\n\n" for metadata in response.candidates[0].url_context_metadata: url_metadata += f"• **URL:** {metadata.url}\n" url_metadata += f"• **Title:** {metadata.title}\n" if hasattr(metadata, 'snippet'): url_metadata += f"• **Snippet:** {metadata.snippet}\n" url_metadata += "\n" except Exception as e: url_metadata = f"URL metadata extraction error: {str(e)}" # Extract search metadata (if available) search_metadata = "" try: if hasattr(response.candidates[0], 'grounding_metadata') and response.candidates[0].grounding_metadata: search_metadata = "🔍 **Search Metadata:**\n\n" # Add search metadata details here if available search_metadata += str(response.candidates[0].grounding_metadata) except Exception as e: search_metadata = f"Search metadata extraction error: {str(e)}" if not response_text.strip(): response_text = "No response generated. Please check your query and try again." return response_text.strip(), url_metadata, search_metadata except Exception as e: return f"❌ Error: {str(e)}", "", "" # Create the Gradio interface def create_gradio_interface(): """Create and configure the Gradio interface""" with gr.Blocks( title="🔍 Gemini URL Context & Search App", theme=gr.themes.Soft(), css=""" .main-container { max-width: 1200px; margin: 0 auto; } .response-box { min-height: 200px; } .metadata-box { min-height: 150px; } """ ) as app: gr.HTML("""
Search and analyze content using Google's Gemini AI with URL context and web search capabilities
🚀 Built with Gradio and Google Gemini API
💡 Tip: Use URL context for analyzing specific web pages, and Google search for broader queries