Spaces:
Sleeping
Sleeping
| 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") | |
| client = genai.Client(api_key=API_KEY) | |
| MODEL_ID = "gemini-2.5-flash" # Ensure this matches a valid model version | |
| def google_search_query(question): | |
| try: | |
| # Define the Google Search Tool | |
| google_search_tool = Tool(google_search=GoogleSearch()) | |
| instructions = "You are a helpful research assistant. Use a professional tone. " \ | |
| "Always cite your findings and be concise." | |
| # THE FIX: system_instruction goes INSIDE GenerateContentConfig | |
| response = client.models.generate_content( | |
| model=MODEL_ID, | |
| contents=question, | |
| config=GenerateContentConfig( | |
| tools=[google_search_tool], | |
| system_instruction=instructions # Moved here | |
| ), | |
| ) | |
| ai_response = response.text | |
| # Safely extract search results | |
| search_results = "" | |
| if response.candidates[0].grounding_metadata and response.candidates[0].grounding_metadata.search_entry_point: | |
| 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="Professional Research Hub", | |
| description=( | |
| "Advanced AI assistant powered by Gemini 2.0 and Google Search. " | |
| "Ask complex questions and get grounded, real-time answers with verified citations." | |
| ), | |
| theme="soft" | |
| ) | |
| if __name__ == "__main__": | |
| app.launch() |