Athspi commited on
Commit
0617856
·
verified ·
1 Parent(s): cca6563

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +491 -38
app.py CHANGED
@@ -1,48 +1,501 @@
 
1
  import os
2
- import google.generativeai as genai
3
- from google.generativeai import types
4
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- def generate_text(user_input):
 
 
 
7
  try:
8
- # Initialize client with API key
9
- genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
10
-
11
- model = "gemini-2.5-pro-exp-03-25"
12
- contents = [
13
- types.Content(
14
- role="user",
15
- parts=[types.Part.from_text(user_input)],
16
- ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  ]
18
- config = types.GenerationConfig(
19
- temperature=2,
20
- response_mime_type="text/plain",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- # Generate response
24
- response = []
25
- for chunk in genai.generate_content_stream(
26
- model=model,
27
- contents=contents,
28
- generation_config=config,
29
- ):
30
- response.append(chunk.text)
31
-
32
- return ''.join(response)
33
-
34
  except Exception as e:
35
- return f"Error: {str(e)}"
36
-
37
- # Create Gradio interface
38
- iface = gr.Interface(
39
- fn=generate_text,
40
- inputs=gr.Textbox(lines=4, placeholder="Enter your prompt...", label="Input"),
41
- outputs=gr.Textbox(label="Output"),
42
- title="Gemini 2.5 Pro Demo",
43
- description="Generate text with Gemini 2.5 Pro (streaming enabled)",
44
- allow_flagging="never",
45
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  if __name__ == "__main__":
48
- iface.launch()
 
 
 
1
+ # -*- coding: utf-8 -*-
2
  import os
 
 
3
  import gradio as gr
4
+ # Import the main module and use an alias
5
+ import google.generativeai as genai
6
+ # Core types like Content/Part are accessed directly via 'genai'
7
+ # Other types like Tool, FunctionDeclaration are under genai.types
8
+
9
+ import requests
10
+ import markdownify
11
+ from urllib.robotparser import RobotFileParser
12
+ from urllib.parse import urlparse
13
+ import traceback
14
+ import json # Useful for debugging args
15
+
16
+ # --- Browser/Web Tool Functions ---
17
+
18
+ def can_crawl_url(url: str, user_agent: str = "PythonGoogleGenAIAgent/1.0") -> bool:
19
+ """Check robots.txt permissions for a URL"""
20
+ if not url:
21
+ print("No URL provided to can_crawl_url")
22
+ return False
23
+ try:
24
+ parsed_url = urlparse(url)
25
+ if not parsed_url.scheme or not parsed_url.netloc:
26
+ print(f"Invalid URL format for robots.txt check: {url}")
27
+ return False
28
+ robots_url = f"{parsed_url.scheme}://{parsed_url.netloc}/robots.txt"
29
+ print(f"Checking robots.txt at: {robots_url} for URL: {url}")
30
+ rp = RobotFileParser()
31
+ rp.set_url(robots_url)
32
+ rp.read()
33
+ can_fetch = rp.can_fetch(user_agent, url)
34
+ print(f"Can fetch {url} with agent '{user_agent}': {can_fetch}")
35
+ return can_fetch
36
+ except Exception as e:
37
+ print(f"Error checking robots.txt for {url}: {e}")
38
+ return False
39
+
40
+ def load_page(url: str) -> str:
41
+ """
42
+ Load webpage content as markdown. Designed to be used as a Gemini Function.
43
+ Args:
44
+ url: The URL of the webpage to load.
45
+ Returns:
46
+ Markdown content of the page or an error message.
47
+ """
48
+ print(f"Attempting to load page: {url}")
49
+ if not url:
50
+ return "Error: No URL provided."
51
+ if not url.startswith(('http://', 'https://')):
52
+ return f"Error: Invalid URL scheme. Please provide http or https URL. Got: {url}"
53
 
54
+ USER_AGENT = "PythonGoogleGenAIAgent/1.0 (Function Calling)"
55
+ if not can_crawl_url(url, user_agent=USER_AGENT):
56
+ print(f"URL {url} failed robots.txt check for agent {USER_AGENT}")
57
+ return f"Error: Access denied by robots.txt for URL {url}"
58
  try:
59
+ headers = {'User-Agent': USER_AGENT}
60
+ response = requests.get(url, timeout=15, headers=headers, allow_redirects=True)
61
+ response.raise_for_status()
62
+ content_type = response.headers.get('content-type', '').lower()
63
+ if 'html' not in content_type:
64
+ print(f"Non-HTML content type '{content_type}' at {url}. Returning summary.")
65
+ return f"Content at {url} is of type '{content_type}'. Size: {len(response.content)} bytes. Cannot convert to Markdown."
66
+
67
+ MAX_CONTENT_SIZE = 1_000_000
68
+ if len(response.content) > MAX_CONTENT_SIZE:
69
+ print(f"Content size {len(response.content)} exceeds limit {MAX_CONTENT_SIZE}. Truncating.")
70
+ try:
71
+ html_content = response.content[:MAX_CONTENT_SIZE].decode(response.apparent_encoding or 'utf-8', errors='ignore')
72
+ except Exception as decode_err:
73
+ print(f"Decoding error after truncation: {decode_err}. Falling back to utf-8 ignore.")
74
+ html_content = response.content[:MAX_CONTENT_SIZE].decode('utf-8', errors='ignore')
75
+ truncated_msg = "\n\n[Content truncated due to size limit]"
76
+ else:
77
+ html_content = response.text
78
+ truncated_msg = ""
79
+
80
+ markdown_content = markdownify.markdownify(html_content, heading_style="ATX", strip=['script', 'style'], escape_underscores=False)
81
+ markdown_content = '\n'.join([line.strip() for line in markdown_content.splitlines() if line.strip()])
82
+ print(f"Successfully loaded and converted {url} to markdown.")
83
+ return f"Content from {url}:\n\n" + markdown_content + truncated_msg
84
+
85
+ except requests.exceptions.Timeout:
86
+ print(f"Timeout error loading page: {url}")
87
+ return f"Error: Timeout while trying to load {url}"
88
+ except requests.exceptions.RequestException as e:
89
+ print(f"Request error loading page {url}: {str(e)}")
90
+ return f"Error loading page {url}: {str(e)}"
91
+ except Exception as e:
92
+ print(f"General error loading page {url}: {str(e)}")
93
+ traceback.print_exc()
94
+ return f"Error loading page {url}: An unexpected error occurred ({type(e).__name__})."
95
+
96
+
97
+ # --- Gemini Client Initialization and Configuration ---
98
+ try:
99
+ api_key = os.environ.get("GEMINI_API_KEY")
100
+ if not api_key:
101
+ raise ValueError("GEMINI_API_KEY environment variable not set.")
102
+ genai.configure(api_key=api_key)
103
+
104
+ MODEL_NAME = "gemini-2.5-pro-exp-03-25"
105
+ print(f"Attempting to use EXPERIMENTAL model: {MODEL_NAME}")
106
+
107
+ # Use genai.types for Tool, FunctionDeclaration etc.
108
+ browse_tool = genai.types.Tool(
109
+ function_declarations=[
110
+ genai.types.FunctionDeclaration(
111
+ name='load_page',
112
+ description='Fetches the content of a specific web page URL as Markdown text. Use this when the user asks for information from a specific URL they provide, or when you need to look up live information mentioned alongside a specific source URL.',
113
+ parameters={
114
+ 'type': 'object',
115
+ 'properties': {
116
+ 'url': {
117
+ 'type': 'string',
118
+ 'description': "The *full* URL of the webpage to load (must start with http:// or https://)."
119
+ }
120
+ },
121
+ 'required': ['url']
122
+ }
123
+ )
124
  ]
125
+ )
126
+ # Use genai.types.Tool, enable code execution with {}
127
+ code_execution_tool = genai.types.Tool(code_execution={})
128
+
129
+ tools = [browse_tool, code_execution_tool]
130
+
131
+ model = genai.GenerativeModel(
132
+ model_name=MODEL_NAME,
133
+ tools=tools,
134
+ # Use genai.types for HarmCategory and HarmBlockThreshold
135
+ safety_settings={
136
+ genai.types.HarmCategory.HARM_CATEGORY_HARASSMENT: genai.types.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
137
+ genai.types.HarmCategory.HARM_CATEGORY_HATE_SPEECH: genai.types.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
138
+ genai.types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: genai.types.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
139
+ genai.types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: genai.types.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
140
+ },
141
+ system_instruction="You are a helpful AI assistant called Gemini-Toolkit. You can browse specific web pages provided by the user via the 'load_page' tool. You can also execute Python code using the 'code_execution' tool to perform calculations, analyze data, or demonstrate programming concepts. Explain your reasoning and the steps you take. If asked to browse, confirm the URL you are accessing. If providing code, explain what it does.",
142
+ )
143
+ print(f"Gemini client initialized with model: {MODEL_NAME} and tools.")
144
+
145
+ except Exception as e:
146
+ print(f"CRITICAL ERROR: Error initializing Gemini client: {e}")
147
+ traceback.print_exc()
148
+ model = None
149
+ tools = []
150
+
151
+
152
+ # --- Gradio App Logic ---
153
+
154
+ def handle_function_call(function_call):
155
+ """Executes the function call requested by the model."""
156
+ function_name = function_call.name
157
+ args = function_call.args
158
+
159
+ print(f"Executing Function Call: {function_name} with args: {dict(args)}")
160
+
161
+ try:
162
+ if function_name == 'load_page':
163
+ url = args.get('url')
164
+ if url:
165
+ function_response_content = load_page(url=url)
166
+ MAX_RESPONSE_LEN = 50000
167
+ if len(function_response_content) > MAX_RESPONSE_LEN:
168
+ print(f"Tool Response truncated from {len(function_response_content)} to {MAX_RESPONSE_LEN} chars.")
169
+ function_response_content = function_response_content[:MAX_RESPONSE_LEN] + "\n\n[... Tool Response Truncated Due to Size Limit ...]"
170
+ else:
171
+ function_response_content = "Error: URL parameter was missing in the function call. Please ensure the 'url' argument is provided."
172
+ else:
173
+ print(f"Error: Received call for unknown function '{function_name}'")
174
+ function_response_content = f"Error: Unknown function '{function_name}' called by the model."
175
+
176
+ # *** CORRECTED: Use genai.Part and genai.types.FunctionResponse ***
177
+ function_response_part = genai.Part(
178
+ function_response=genai.types.FunctionResponse(
179
+ name=function_name,
180
+ response={'content': function_response_content}
181
+ )
182
  )
183
+ print(f"Function Response generated for {function_name}")
184
+ return function_response_part
185
+
186
+ except Exception as e:
187
+ print(f"Error during execution of function '{function_name}': {e}")
188
+ traceback.print_exc()
189
+ # *** CORRECTED: Use genai.Part and genai.types.FunctionResponse ***
190
+ return genai.Part(
191
+ function_response=genai.types.FunctionResponse(
192
+ name=function_name,
193
+ response={'error': f"Failed to execute function {function_name}: {str(e)}"}
194
+ )
195
+ )
196
+
197
+ def generate_response_with_tools(user_input, history_state):
198
+ """Handles user input, interacts with Gemini (incl. tools), and manages history."""
199
+ if not model:
200
+ return [[None, "Error: The AI model (Gemini) could not be initialized. Please check the logs or API key configuration."]], history_state or []
201
+
202
+ if not user_input.strip():
203
+ return [[None, "Please enter a valid query."]], history_state or []
204
+
205
+ # --- History Management ---
206
+ conversation_history = history_state if isinstance(history_state, list) else []
207
+ # *** CORRECTED: Use genai.Content and genai.Part ***
208
+ conversation_history.append(genai.Content(role="user", parts=[genai.Part.from_text(user_input)]))
209
+ print(f"\n--- Sending to Gemini (History length: {len(conversation_history)}) ---")
210
+
211
+ MAX_HISTORY_TURNS = 10
212
+ max_history_items = MAX_HISTORY_TURNS * 2 + (1 if conversation_history and conversation_history[0].role == "system" else 0)
213
+ if len(conversation_history) > max_history_items:
214
+ print(f"Trimming conversation history from {len(conversation_history)} items to ~{max_history_items}")
215
+ if conversation_history[0].role == "system":
216
+ conversation_history = [conversation_history[0]] + conversation_history[-(max_history_items-1):]
217
+ else:
218
+ conversation_history = conversation_history[-max_history_items:]
219
+
220
+ # --- Interaction Loop ---
221
+ MAX_TOOL_LOOPS = 5
222
+ loop_count = 0
223
+ current_history_for_api = list(conversation_history)
224
+ final_bot_message = ""
225
+
226
+ try:
227
+ while loop_count < MAX_TOOL_LOOPS:
228
+ loop_count += 1
229
+ print(f"Generation loop {loop_count}/{MAX_TOOL_LOOPS}...")
230
+
231
+ response = model.generate_content(
232
+ current_history_for_api,
233
+ request_options={"timeout": 120},
234
+ )
235
+
236
+ if not response.candidates:
237
+ print("Warning: No candidates received from Gemini.")
238
+ final_bot_message = "[No response generated by the model.]"
239
+ # *** CORRECTED: Use genai.Content and genai.Part ***
240
+ current_history_for_api.append(genai.Content(role="model", parts=[genai.Part.from_text(final_bot_message)]))
241
+ break
242
+
243
+ candidate = response.candidates[0]
244
+ # Use genai.types for Candidate fields
245
+ finish_reason = candidate.finish_reason
246
+
247
+ # Append model's response (Content object) to history
248
+ if candidate.content:
249
+ current_history_for_api.append(candidate.content) # content should already be a genai.Content object
250
+
251
+ # Check finish reason using genai.types.Candidate
252
+ if finish_reason not in (genai.types.Candidate.FinishReason.STOP, genai.types.Candidate.FinishReason.TOOL_CALL):
253
+ print(f"Warning: Generation stopped unexpectedly. Reason: {finish_reason.name}")
254
+ stop_reason_msg = f"[Model stopped generating. Reason: {finish_reason.name}]"
255
+ partial_text = ""
256
+ if candidate.content and candidate.content.parts:
257
+ partial_text = "".join([p.text for p in candidate.content.parts if hasattr(p, 'text') and p.text])
258
+ final_bot_message = (partial_text + "\n" if partial_text else "") + stop_reason_msg
259
+ break
260
+
261
+ # Use genai.types.Candidate for comparison
262
+ has_tool_call = finish_reason == genai.types.Candidate.FinishReason.TOOL_CALL
263
+
264
+ if has_tool_call:
265
+ print("Tool call requested by model.")
266
+ # Model response (genai.Content obj) is already appended above
267
+ if not candidate.content or not candidate.content.parts:
268
+ print("Error: TOOL_CALL indicated but candidate content/parts is missing.")
269
+ final_bot_message = "[Model indicated tool use but provided no details.]"
270
+ break
271
+
272
+ function_calls = [part.function_call for part in candidate.content.parts if hasattr(part, 'function_call') and part.function_call]
273
+
274
+ if not function_calls:
275
+ print("Warning: TOOL_CALL finish reason but no valid function_call part found.")
276
+ final_bot_message = "".join([p.text for p in candidate.content.parts if hasattr(p, 'text') and p.text])
277
+ if not final_bot_message:
278
+ final_bot_message = "[Model indicated tool use but provided no callable function or text.]"
279
+ break
280
+
281
+ tool_responses = []
282
+ for func_call in function_calls:
283
+ # handle_function_call now returns a genai.Part object
284
+ function_response_part = handle_function_call(func_call)
285
+ tool_responses.append(function_response_part)
286
+
287
+ if not tool_responses:
288
+ print("Warning: No valid tool responses generated despite TOOL_CALL.")
289
+ final_bot_message = "[Failed to process tool call request.]"
290
+ break
291
+
292
+ # Add tool responses to history using genai.Content
293
+ current_history_for_api.append(genai.Content(role="tool", parts=tool_responses)) # parts expects list of genai.Part
294
+ print("Added tool response(s) to history. Continuing loop...")
295
+ final_bot_message = ""
296
+ continue
297
+
298
+ else: # FinishReason == STOP
299
+ print("No tool call requested. Final response received.")
300
+ final_bot_message = ""
301
+ code_parts_display = []
302
+ # Extract text/code from the last model turn (genai.Content object) in history
303
+ if current_history_for_api and current_history_for_api[-1].role == "model":
304
+ last_model_content = current_history_for_api[-1]
305
+ if last_model_content.parts:
306
+ for part in last_model_content.parts: # part is already a genai.Part object
307
+ if hasattr(part, 'text') and part.text:
308
+ final_bot_message += part.text
309
+ if hasattr(part, 'executable_code') and part.executable_code:
310
+ lang = getattr(getattr(part.executable_code, 'language', None), 'name', 'python').lower()
311
+ code = getattr(part.executable_code, 'code', '')
312
+ code_parts_display.append(f"Suggested Code ({lang}):\n```{'python' if lang == 'unknown_language' else lang}\n{code}\n```")
313
+ elif hasattr(part, 'code_execution_result') and part.code_execution_result:
314
+ # outcome check uses genai.types
315
+ outcome_enum = getattr(genai.types, 'ExecutableCodeResponse', None)
316
+ outcome_ok_val = getattr(outcome_enum.Outcome, 'OK', None) if outcome_enum and hasattr(outcome_enum, 'Outcome') else 1
317
+ outcome_val = getattr(part.code_execution_result, 'outcome', None)
318
+ outcome_str = "Success" if outcome_val == outcome_ok_val else "Failure"
319
+ output = getattr(part.code_execution_result, 'output', '')
320
+ code_parts_display.append(f"Code Execution Result ({outcome_str}):\n```\n{output}\n```")
321
+
322
+ if code_parts_display:
323
+ final_bot_message += "\n\n" + "\n\n".join(code_parts_display)
324
+
325
+ if not final_bot_message.strip():
326
+ final_bot_message = "[Assistant completed its turn without generating text output.]"
327
+ # Add this as a text Part to the last model Content object if it was otherwise empty
328
+ if current_history_for_api[-1].role == "model" and not any(hasattr(p,'text') and p.text for p in current_history_for_api[-1].parts):
329
+ if not hasattr(current_history_for_api[-1], 'parts') or not current_history_for_api[-1].parts:
330
+ current_history_for_api[-1].parts = []
331
+ # *** CORRECTED: Use genai.Part ***
332
+ current_history_for_api[-1].parts.append(genai.Part.from_text(final_bot_message))
333
+ break
334
+
335
+ # End of while loop
336
+ if loop_count >= MAX_TOOL_LOOPS:
337
+ print(f"Warning: Reached maximum tool execution loops ({MAX_TOOL_LOOPS}).")
338
+ warning_msg = f"\n\n[Warning: Reached maximum tool execution loops ({MAX_TOOL_LOOPS}). The final response might be incomplete.]"
339
+ final_bot_message += warning_msg
340
+ # Append warning as a genai.Part to the last model message
341
+ if current_history_for_api and current_history_for_api[-1].role == "model":
342
+ if not hasattr(current_history_for_api[-1], 'parts') or not current_history_for_api[-1].parts:
343
+ current_history_for_api[-1].parts = []
344
+ # *** CORRECTED: Use genai.Part ***
345
+ current_history_for_api[-1].parts.append(genai.Part.from_text(warning_msg))
346
+
347
+ print("--- Response Generation Complete ---")
348
+
349
+ # --- Format final output for Gradio Chatbot ---
350
+ chatbot_display_list = []
351
+ user_msg_buffer = None
352
+ for content in current_history_for_api: # content is genai.Content object
353
+ if content.role == "system": continue
354
+
355
+ display_text = ""
356
+ if hasattr(content, 'parts') and content.parts:
357
+ for part in content.parts: # part is genai.Part object
358
+ # Extract text for display, format code etc.
359
+ if hasattr(part, 'text') and part.text:
360
+ display_text += part.text + "\n"
361
+ elif hasattr(part, 'executable_code') and part.executable_code:
362
+ lang = getattr(getattr(part.executable_code, 'language', None), 'name', 'python').lower()
363
+ code = getattr(part.executable_code, 'code', '')
364
+ display_text += f"\n```{'python' if lang == 'unknown_language' else lang}\n{code}\n```\n"
365
+ elif hasattr(part, 'code_execution_result') and part.code_execution_result:
366
+ # outcome check uses genai.types
367
+ outcome_enum = getattr(genai.types, 'ExecutableCodeResponse', None)
368
+ outcome_ok_val = getattr(outcome_enum.Outcome, 'OK', None) if outcome_enum and hasattr(outcome_enum, 'Outcome') else 1
369
+ outcome_val = getattr(part.code_execution_result, 'outcome', None)
370
+ outcome_str = "Success" if outcome_val == outcome_ok_val else "Failure"
371
+ output = getattr(part.code_execution_result, 'output', '')
372
+ display_text += f"\nCode Execution Result ({outcome_str}):\n```\n{output}\n```\n"
373
+
374
+ display_text = display_text.strip()
375
+
376
+ if not display_text and content.role not in ["tool"]: continue
377
+
378
+ if content.role == "user":
379
+ user_msg_buffer = display_text
380
+ elif content.role == "model":
381
+ if user_msg_buffer is not None:
382
+ chatbot_display_list.append([user_msg_buffer, display_text or "[Processing...]"])
383
+ user_msg_buffer = None
384
+ else:
385
+ chatbot_display_list.append([None, display_text])
386
+ # Ignore 'tool' role messages for chat display
387
+
388
+ if user_msg_buffer is not None:
389
+ chatbot_display_list.append([user_msg_buffer, None])
390
+
391
+ return chatbot_display_list, current_history_for_api
392
 
 
 
 
 
 
 
 
 
 
 
 
393
  except Exception as e:
394
+ print(f"ERROR during Gemini generation or tool processing: {str(e)}")
395
+ traceback.print_exc()
396
+ error_message = f"An error occurred: {str(e)}"
397
+ error_display_list = []
398
+ # Rebuild display from previous state (history_state)
399
+ if isinstance(history_state, list):
400
+ temp_user_msg = None
401
+ for content in history_state: # content is genai.Content
402
+ if content.role == "system": continue
403
+ text = ""
404
+ if hasattr(content, 'parts') and content.parts:
405
+ # parts contains genai.Part objects
406
+ text = "".join([p.text for p in content.parts if hasattr(p, 'text')])
407
+ if content.role == "user": temp_user_msg = text
408
+ elif content.role == "model" and temp_user_msg:
409
+ error_display_list.append([temp_user_msg, text])
410
+ temp_user_msg = None
411
+ elif content.role == "model": error_display_list.append([None, text])
412
+ if temp_user_msg: error_display_list.append([temp_user_msg, None])
413
+
414
+ error_display_list.append([None, error_message])
415
+
416
+ # Revert to history *before* this failed turn
417
+ previous_history = conversation_history[:-1] if isinstance(conversation_history, list) and conversation_history else []
418
+ return error_display_list, previous_history
419
+
420
+
421
+ # --- Gradio Interface ---
422
+
423
+ with gr.Blocks(title="Gemini AI Assistant w/ Tools", theme=gr.themes.Soft()) as demo:
424
+ gr.Markdown(f"# 🚀 Gemini AI Assistant ({MODEL_NAME})")
425
+ gr.Markdown("Ask questions, request info from specific URLs, or ask for code/calculations. Uses function calling and code execution.")
426
+
427
+ chatbot_display = gr.Chatbot(
428
+ label="Conversation",
429
+ bubble_full_width=False, # Keep param even if deprecated
430
+ height=600,
431
+ show_copy_button=True,
432
+ render_markdown=True,
433
+ )
434
+
435
+ with gr.Row():
436
+ msg_input = gr.Textbox(
437
+ label="Your Query",
438
+ placeholder="Ask anything...",
439
+ lines=3,
440
+ scale=4
441
+ )
442
+ with gr.Column(scale=1, min_width=150):
443
+ send_btn = gr.Button("➡️ Send", variant="primary")
444
+ clear_btn = gr.ClearButton(value="🗑️ Clear Chat")
445
+
446
+ # State stores list of genai.Content objects
447
+ chat_history_state = gr.State([])
448
+
449
+ def user_message_update(user_message, history_display_list):
450
+ """Appends user message to display list and clears input."""
451
+ if not user_message.strip():
452
+ return gr.update(value=""), history_display_list
453
+ return gr.update(value=""), history_display_list + [[user_message, None]]
454
+
455
+ def bot_response_update(history_display_list, history_state):
456
+ """Calls backend Gemini function and updates display/state."""
457
+ if not history_display_list or (len(history_display_list[-1]) > 1 and history_display_list[-1][1] is not None):
458
+ print("Bot update called without pending user message in display list.")
459
+ return history_display_list, history_state
460
+
461
+ user_message = history_display_list[-1][0]
462
+ print(f"User message being sent to backend: {user_message}")
463
+
464
+ updated_display_list, updated_history_state = generate_response_with_tools(user_message, history_state)
465
+
466
+ return updated_display_list, updated_history_state
467
+
468
+ # --- Event Listeners ---
469
+ msg_input.submit(
470
+ user_message_update,
471
+ [msg_input, chatbot_display],
472
+ [msg_input, chatbot_display],
473
+ queue=False,
474
+ ).then(
475
+ bot_response_update,
476
+ [chatbot_display, chat_history_state], # Pass display list and history state
477
+ [chatbot_display, chat_history_state] # Receive updated display list and state
478
+ )
479
+
480
+ send_btn.click(
481
+ user_message_update,
482
+ [msg_input, chatbot_display],
483
+ [msg_input, chatbot_display],
484
+ queue=False,
485
+ ).then(
486
+ bot_response_update,
487
+ [chatbot_display, chat_history_state],
488
+ [chatbot_display, chat_history_state]
489
+ )
490
+
491
+ # Custom clear function resets state
492
+ def clear_all():
493
+ return ["", None, []]
494
+
495
+ clear_btn.click(clear_all, [], [msg_input, chatbot_display, chat_history_state], queue=False)
496
+
497
 
498
  if __name__ == "__main__":
499
+ print("Starting Gradio App...")
500
+ demo.queue().launch(server_name="0.0.0.0", server_port=7860, show_error=True)
501
+ print("Gradio App Stopped.")