Rahatara commited on
Commit
35500cf
·
verified ·
1 Parent(s): 3f7f6ec

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -0
app.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from google import genai
4
+ from google.genai.types import GenerateContentConfig, GoogleSearch, Tool
5
+
6
+ # Initialize GenAI Client
7
+ API_KEY = os.getenv("GEMINI_API_KEY") # Ensure to set this in Hugging Face Secrets
8
+ client = genai.Client(api_key=API_KEY)
9
+ MODEL_ID = "gemini-2.0-flash-exp" # Replace with your desired model ID
10
+
11
+ def google_search_query(question):
12
+ try:
13
+ # Define the Google Search Tool
14
+ google_search_tool = Tool(google_search=GoogleSearch())
15
+
16
+ # Generate the response
17
+ response = client.models.generate_content(
18
+ model=MODEL_ID,
19
+ contents=question,
20
+ config=GenerateContentConfig(tools=[google_search_tool]),
21
+ )
22
+
23
+ # Extract AI response and search results
24
+ ai_response = response.text # AI response as plain text
25
+ search_results = response.candidates[0].grounding_metadata.search_entry_point.rendered_content
26
+
27
+ return ai_response, search_results
28
+ except Exception as e:
29
+ return f"Error: {str(e)}", ""
30
+
31
+ # Gradio Interface
32
+ app = gr.Interface(
33
+ fn=google_search_query,
34
+ inputs=gr.Textbox(lines=2, label="Ask a Question"),
35
+ outputs=[
36
+ gr.Textbox(label="AI Response"),
37
+ gr.HTML(label="Search Results"),
38
+ ],
39
+ title="Google Search with Gemini AI",
40
+ description="Ask a question, and the AI will use Google search tools to provide an answer along with contextual search results.",
41
+ )
42
+
43
+ if __name__ == "__main__":
44
+ app.launch(share=True)