Web_Search / app.py
yomnafarag95's picture
Update app.py
458d5d1 verified
import os
import gradio as gr
from google import genai
from google.genai.types import GenerateContentConfig, GoogleSearch, Tool
# Initialize GenAI Client
API_KEY = os.getenv("GOOGLE_API_KEY") # Make sure this is set in Hugging Face Secrets
client = genai.Client(api_key=API_KEY)
MODEL_ID = "gemini-2.0-flash" # Replace with your desired model ID
# System instruction: friendly and happy AI
SYSTEM_INSTRUCTION = """
You are a cheerful, friendly AI assistant. Always respond in a positive, helpful, and happy tone.
Provide clear answers and explanations, and make the user feel welcomed.
"""
def google_search_query(question):
try:
# Define the Google Search Tool
google_search_tool = Tool(google_search=GoogleSearch())
# Generate the response with system instruction
response = client.models.generate_content(
model=MODEL_ID,
contents=[SYSTEM_INSTRUCTION, question],
config=GenerateContentConfig(tools=[google_search_tool]),
)
# Extract AI response and search results
ai_response = response.text
search_results = response.candidates[0].grounding_metadata.search_entry_point.rendered_content
return ai_response, search_results
except Exception as e:
return f"Error: {str(e)}", ""
# Gradio Interface
app = gr.Interface(
fn=google_search_query,
inputs=gr.Textbox(lines=2, label="Ask me anything! 😊"),
outputs=[
gr.Textbox(label="AI Response"),
gr.HTML(label="Search Results"),
],
title="🌟 Friendly Google Search Assistant",
description="Ask any question and get a cheerful, friendly AI answer along with helpful Google search results.",
)
if __name__ == "__main__":
app.launch()