import os import streamlit as st from google import genai from google.genai.types import Tool, GenerateContentConfig, GoogleSearch # Set page config st.set_page_config( page_title="Gemini Grounding Search", page_icon="🔍", layout="wide" ) # Custom CSS for styling st.markdown(""" """, unsafe_allow_html=True) # Title st.title("Gemini Grounding Search") # Initialize Gemini client if 'GEMINI_API_KEY' not in os.environ: api_key = st.text_input("Enter your Gemini API Key:", type="password") if api_key: os.environ['GEMINI_API_KEY'] = api_key # Search input search_query = st.text_input("Enter your search query:", "When is the next total solar eclipse in the United States?") if st.button("Search"): if 'GEMINI_API_KEY' not in os.environ: st.error("Please enter your Gemini API Key first!") else: try: client = genai.Client(api_key=os.environ['GEMINI_API_KEY']) model_id = "gemini-2.0-flash" google_search_tool = Tool( google_search = GoogleSearch() ) with st.spinner("Searching..."): response = client.models.generate_content( model=model_id, contents=search_query, config=GenerateContentConfig( tools=[google_search_tool], response_modalities=["TEXT"], ) ) # Display search results header st.header("Search Results") # Display the response text if response.candidates[0].content.parts: st.markdown('
' + response.candidates[0].content.parts[0].text.replace('\n', '
') + '
', unsafe_allow_html=True) # Display the grounding metadata if hasattr(response.candidates[0], 'grounding_metadata') and \ hasattr(response.candidates[0].grounding_metadata, 'search_entry_point') and \ hasattr(response.candidates[0].grounding_metadata.search_entry_point, 'rendered_content'): st.header("Related Searches") rendered_content = response.candidates[0].grounding_metadata.search_entry_point.rendered_content st.markdown(rendered_content, unsafe_allow_html=True) except Exception as e: st.error(f"An error occurred: {str(e)}")