Gemini_2_Web_Search / webapp.py
Aia1010's picture
Update webapp.py
1e66596 verified
import os
import gradio as gr
from google import genai
from google.genai.types import GenerateContentConfig, GoogleSearch, Tool
API_KEY = os.getenv("GOOGLE_API_KEY")
client = genai.Client(api_key=API_KEY)
MODEL_ID = "models/gemini-2.5-flash"
SYSTEM_INSTRUCTION = """
You are a helpful assistant.
If web search is enabled, use it to improve factual accuracy.
Keep answers clear and structured.
"""
def google_search_query(question: str, use_web_search: bool):
try:
config_kwargs = {"system_instruction": SYSTEM_INSTRUCTION}
if use_web_search:
google_search_tool = Tool(google_search=GoogleSearch())
config_kwargs["tools"] = [google_search_tool]
response = client.models.generate_content(
model=MODEL_ID,
contents=question,
config=GenerateContentConfig(**config_kwargs),
)
ai_response = response.text if hasattr(response, "text") else "No response."
search_results = "Web search not used."
if use_web_search:
try:
search_results = (
response.candidates[0]
.grounding_metadata
.search_entry_point
.rendered_content
) or "Web search enabled, but no rendered search content returned."
except Exception:
search_results = "Web search enabled, but search results could not be extracted."
return ai_response, search_results
except Exception as e:
return f"Error: {str(e)}", ""
with gr.Blocks(theme=gr.themes.Glass(secondary_hue="violet")) as app:
gr.Markdown("# Gemini + Google Search Custom UI")
chatbot = gr.Chatbot(label="Chatbot Responses", height=420)
with gr.Row():
question_input = gr.Textbox(lines=2, label="Ask a Question")
web_search_checkbox = gr.Checkbox(label="Enhance with Web Search", value=False)
with gr.Row():
submit_button = gr.Button("Submit")
clear_button = gr.Button("Clear")
def update_chatbot(question, use_web_search, chat_log):
if chat_log is None:
chat_log = []
question = (question or "").strip()
if not question:
return chat_log
ai_response, search_results = google_search_query(question, use_web_search)
if use_web_search:
final_answer = f"{ai_response}\n\n---\n\n**Web Search Results:**\n{search_results}"
else:
final_answer = ai_response
chat_log.append((question, final_answer))
return chat_log
submit_button.click(
fn=update_chatbot,
inputs=[question_input, web_search_checkbox, chatbot],
outputs=[chatbot]
)
clear_button.click(fn=lambda: [], inputs=None, outputs=[chatbot])
app.launch()