Web_Search / app.py
Yasmeen7's picture
Update app.py
b001522 verified
import os
import gradio as gr
from google import genai
from google.genai.types import GenerateContentConfig, GoogleSearch, Tool
# --- API Key setup ---
API_KEY = os.getenv("GOOGLE_API_KEY")
if not API_KEY:
raise ValueError(
"❌ Missing GOOGLE_API_KEY! "
"Please add it as a secret in Hugging Face Spaces (Settings → Secrets)."
)
# --- Initialize GenAI Client ---
client = genai.Client(api_key=API_KEY)
MODEL_ID = "gemini-2.0-flash"
# --- Friendly system instructions ---
SYSTEM_INSTRUCTION = """
You are a friendly and helpful AI assistant.
Answer questions in a warm and easy-to-understand way, like explaining to a friend.
Always include relevant information from Google Search if available, and never make up answers.
Keep your tone polite, encouraging, and approachable.
"""
# --- Google Search query function ---
def google_search_query(question):
try:
google_search_tool = Tool(google_search=GoogleSearch())
# Combine system instruction + user question
prompt = f"{SYSTEM_INSTRUCTION}\n\nUser question: {question}"
response = client.models.generate_content(
model=MODEL_ID,
contents=prompt,
config=GenerateContentConfig(
tools=[google_search_tool]
)
)
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 a Question"),
outputs=[
gr.Textbox(label="AI Response"),
gr.HTML(label="Search Results"),
],
title="🌟 Friendly Google Helper",
description="Hi there! Ask me anything, and I’ll find answers from Google and explain them in a friendly, easy-to-understand way.",
)
# --- Launch app ---
if __name__ == "__main__":
app.launch(server_name="0.0.0.0", server_port=7860, share=True)