Aia1010 commited on
Commit
1e66596
·
verified ·
1 Parent(s): ba29fbe

Update webapp.py

Browse files
Files changed (1) hide show
  1. webapp.py +12 -42
webapp.py CHANGED
@@ -3,64 +3,42 @@ import gradio as gr
3
  from google import genai
4
  from google.genai.types import GenerateContentConfig, GoogleSearch, Tool
5
 
6
- # -----------------------------
7
- # 1) Initialize GenAI Client
8
- # -----------------------------
9
- API_KEY = os.getenv("GOOGLE_API_KEY") # Set in Hugging Face Secrets
10
  client = genai.Client(api_key=API_KEY)
11
 
12
- MODEL_ID = "models/gemini-2.5-flash" # Replace with your desired model ID
13
 
14
- # -----------------------------
15
- # 2) (Optional) System Instruction
16
- # -----------------------------
17
  SYSTEM_INSTRUCTION = """
18
  You are a helpful assistant.
19
  If web search is enabled, use it to improve factual accuracy.
20
  Keep answers clear and structured.
21
  """
22
 
23
- # -----------------------------
24
- # 3) Gemini Call (with optional web search)
25
- # -----------------------------
26
  def google_search_query(question: str, use_web_search: bool):
27
  try:
28
- # Base response (no web search)
 
 
 
 
 
29
  response = client.models.generate_content(
30
  model=MODEL_ID,
31
  contents=question,
32
- config=GenerateContentConfig(
33
- system_instruction=SYSTEM_INSTRUCTION
34
- ),
35
  )
 
36
  ai_response = response.text if hasattr(response, "text") else "No response."
37
 
38
  search_results = "Web search not used."
39
  if use_web_search:
40
- google_search_tool = Tool(google_search=GoogleSearch())
41
- response = client.models.generate_content(
42
- model=MODEL_ID,
43
- contents=question,
44
- config=GenerateContentConfig(
45
- system_instruction=SYSTEM_INSTRUCTION,
46
- tools=[google_search_tool],
47
- ),
48
- )
49
-
50
- # Prefer web-assisted answer text if present
51
- if hasattr(response, "text") and response.text:
52
- ai_response = response.text
53
-
54
- # Safely extract rendered search content (may not always exist)
55
  try:
56
  search_results = (
57
  response.candidates[0]
58
  .grounding_metadata
59
  .search_entry_point
60
  .rendered_content
61
- )
62
- if not search_results:
63
- search_results = "Web search enabled, but no rendered search content returned."
64
  except Exception:
65
  search_results = "Web search enabled, but search results could not be extracted."
66
 
@@ -69,9 +47,6 @@ def google_search_query(question: str, use_web_search: bool):
69
  except Exception as e:
70
  return f"Error: {str(e)}", ""
71
 
72
- # -----------------------------
73
- # 4) Gradio UI (Chatbot + Checkbox)
74
- # -----------------------------
75
  with gr.Blocks(theme=gr.themes.Glass(secondary_hue="violet")) as app:
76
  gr.Markdown("# Gemini + Google Search Custom UI")
77
 
@@ -95,7 +70,6 @@ with gr.Blocks(theme=gr.themes.Glass(secondary_hue="violet")) as app:
95
 
96
  ai_response, search_results = google_search_query(question, use_web_search)
97
 
98
- # Chatbot expects tuples: (user, assistant)
99
  if use_web_search:
100
  final_answer = f"{ai_response}\n\n---\n\n**Web Search Results:**\n{search_results}"
101
  else:
@@ -110,10 +84,6 @@ with gr.Blocks(theme=gr.themes.Glass(secondary_hue="violet")) as app:
110
  outputs=[chatbot]
111
  )
112
 
113
- clear_button.click(
114
- fn=lambda: [],
115
- inputs=None,
116
- outputs=[chatbot]
117
- )
118
 
119
  app.launch()
 
3
  from google import genai
4
  from google.genai.types import GenerateContentConfig, GoogleSearch, Tool
5
 
6
+ API_KEY = os.getenv("GOOGLE_API_KEY")
 
 
 
7
  client = genai.Client(api_key=API_KEY)
8
 
9
+ MODEL_ID = "models/gemini-2.5-flash"
10
 
 
 
 
11
  SYSTEM_INSTRUCTION = """
12
  You are a helpful assistant.
13
  If web search is enabled, use it to improve factual accuracy.
14
  Keep answers clear and structured.
15
  """
16
 
 
 
 
17
  def google_search_query(question: str, use_web_search: bool):
18
  try:
19
+ config_kwargs = {"system_instruction": SYSTEM_INSTRUCTION}
20
+
21
+ if use_web_search:
22
+ google_search_tool = Tool(google_search=GoogleSearch())
23
+ config_kwargs["tools"] = [google_search_tool]
24
+
25
  response = client.models.generate_content(
26
  model=MODEL_ID,
27
  contents=question,
28
+ config=GenerateContentConfig(**config_kwargs),
 
 
29
  )
30
+
31
  ai_response = response.text if hasattr(response, "text") else "No response."
32
 
33
  search_results = "Web search not used."
34
  if use_web_search:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  try:
36
  search_results = (
37
  response.candidates[0]
38
  .grounding_metadata
39
  .search_entry_point
40
  .rendered_content
41
+ ) or "Web search enabled, but no rendered search content returned."
 
 
42
  except Exception:
43
  search_results = "Web search enabled, but search results could not be extracted."
44
 
 
47
  except Exception as e:
48
  return f"Error: {str(e)}", ""
49
 
 
 
 
50
  with gr.Blocks(theme=gr.themes.Glass(secondary_hue="violet")) as app:
51
  gr.Markdown("# Gemini + Google Search Custom UI")
52
 
 
70
 
71
  ai_response, search_results = google_search_query(question, use_web_search)
72
 
 
73
  if use_web_search:
74
  final_answer = f"{ai_response}\n\n---\n\n**Web Search Results:**\n{search_results}"
75
  else:
 
84
  outputs=[chatbot]
85
  )
86
 
87
+ clear_button.click(fn=lambda: [], inputs=None, outputs=[chatbot])
 
 
 
 
88
 
89
  app.launch()