sayed010 commited on
Commit
dfa0012
·
verified ·
1 Parent(s): 3732f9b

Create webapp.py

Browse files
Files changed (1) hide show
  1. webapp.py +61 -0
webapp.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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" # Replace with your desired model ID
10
+
11
+ def google_search_query(question, use_web_search):
12
+ try:
13
+ # Generate the AI response without web search initially
14
+ response = client.models.generate_content(
15
+ model=MODEL_ID,
16
+ contents=question,
17
+ )
18
+ ai_response = response.text # AI response as plain text
19
+
20
+ if use_web_search:
21
+ # If user selects web search, redefine the tool and generate response with web search
22
+ google_search_tool = Tool(google_search=GoogleSearch())
23
+ response = client.models.generate_content(
24
+ model=MODEL_ID,
25
+ contents=question,
26
+ config=GenerateContentConfig(tools=[google_search_tool]),
27
+ )
28
+ search_results = response.candidates[0].grounding_metadata.search_entry_point.rendered_content
29
+ else:
30
+ search_results = "Web search not used."
31
+
32
+ return ai_response, search_results
33
+ except Exception as e:
34
+ return f"Error: {str(e)}", ""
35
+
36
+ # Gradio Interface using Chatbot and conditional web search
37
+ with gr.Blocks(theme=gr.themes.Glass(secondary_hue = "violet")) as app:
38
+ gr.Markdown("# Gemini 2.0 Google Search Custom UI")
39
+ with gr.Row():
40
+ chatbot = gr.Chatbot(label="Chatbot Responses")
41
+ with gr.Row():
42
+ question_input = gr.Textbox(lines=2, label="Ask a Question")
43
+ web_search_checkbox = gr.Checkbox(label="Enhance with Web Search", value=False)
44
+ with gr.Row():
45
+ submit_button = gr.Button("Submit")
46
+
47
+ def update_chatbot(question, use_web_search, chat_log):
48
+ ai_response, search_results = google_search_query(question, use_web_search)
49
+ chat_log.append(("You", question))
50
+ chat_log.append(("AI", ai_response))
51
+ if use_web_search:
52
+ chat_log.append(("AI + Web Search", search_results))
53
+ return chat_log
54
+
55
+ submit_button.click(
56
+ fn=update_chatbot,
57
+ inputs=[question_input, web_search_checkbox, chatbot],
58
+ outputs=[chatbot]
59
+ )
60
+
61
+ app.launch()