Rahatara commited on
Commit
683b7d8
·
verified ·
1 Parent(s): 868ac47

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -0
app.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("GOOGLE_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
+ # Parse and format search results to separate links
28
+ link_list = "\n".join([f"<a href='{entry.url}' target='_blank'>{entry.title}</a>" for entry in response.candidates[0].grounding_metadata.search_entry_point.entries])
29
+ return ai_response, link_list
30
+ except Exception as e:
31
+ return f"Error: {str(e)}", "No results found."
32
+
33
+ # Gradio Interface
34
+ app = gr.Interface(
35
+ fn=google_search_query,
36
+ inputs=gr.Textbox(lines=2, label="Ask a Question"),
37
+ outputs=[
38
+ gr.Textbox(label="AI Response"),
39
+ gr.HTML(label="Search Results"),
40
+ ],
41
+ title="Google Search with Gemini AI",
42
+ description="Ask a question, and the AI will use Google search tools to provide an answer along with contextual search results.",
43
+ theme="huggingface",
44
+ layout="vertical"
45
+ )
46
+
47
+ if __name__ == "__main__":
48
+ app.launch(share=True)