pmeyhoefer commited on
Commit
c58c21b
·
verified ·
1 Parent(s): ea28b54

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -50
app.py CHANGED
@@ -23,8 +23,8 @@ except ImportError as e:
23
  from huggingface_hub import HfApi
24
 
25
  # --- Suchtool Imports (wie zuvor) ---
26
- USE_TAVILY = False
27
- USE_DUCKDUCKGO = True
28
 
29
  if USE_TAVILY:
30
  try:
@@ -95,7 +95,13 @@ def search_web(query: str, max_results: int = 3) -> str:
95
  # (Code unverändert)
96
  print(f"Tool: search_web(query='{query}', max_results={max_results})")
97
  if not search_client:
98
- return "Search tool is not available/configured."
 
 
 
 
 
 
99
  try:
100
  if USE_TAVILY and isinstance(search_client, TavilyClient):
101
  response = search_client.search(query=query, search_depth="basic", max_results=max_results)
@@ -238,80 +244,72 @@ def initialize_agent():
238
  global search_client, agent_instance
239
  print("Initializing agent and clients...")
240
 
241
- # Initialisiere Search Client (wenn nicht bereits geschehen)
242
- if search_client is None:
243
  print("Initializing search client...")
244
  if USE_TAVILY:
245
  tavily_key = os.getenv("TAVILY_API_KEY")
246
  if tavily_key:
247
  try: search_client = TavilyClient(api_key=tavily_key); print("Using Tavily for search.")
248
- except NameError: print("WARNUNG: TavilyClient Klasse nicht gefunden."); search_client = None
249
  else:
250
  print("WARNUNG: TAVILY_API_KEY nicht gefunden.")
 
251
  if USE_DUCKDUCKGO: # Fallback nur wenn Tavily nicht initialisiert werden konnte
252
  try: search_client = DDGS(); print("Falling back to DuckDuckGo for search.")
253
- except NameError: print("WARNUNG: DuckDuckGo nicht verfügbar."); search_client = None
254
- else: search_client = None
255
  elif USE_DUCKDUCKGO:
256
  try: search_client = DDGS(); print("Using DuckDuckGo for search.")
257
- except NameError: print("WARNUNG: duckduckgo-search nicht installiert/verfügbar."); search_client = None
258
  else:
259
  print("Web search is disabled by configuration.")
260
- search_client = False # Setze auf False, um erneute Initialisierung zu verhindern
261
 
262
  # --- LLM Model (vereinfacht via HfApiModel) ---
263
- # HfApiModel sollte HUGGINGFACE_TOKEN und HF_MODEL_ID aus Umgebungsvariablen lesen.
264
- # Wir prüfen hier nur, ob das Token vorhanden ist, da HfApiModel es benötigt.
265
  hf_token_check = os.getenv("HUGGINGFACE_TOKEN")
266
  if not hf_token_check:
267
  raise ValueError("HUGGINGFACE_TOKEN Secret nicht im Hugging Face Space gefunden! HfApiModel benötigt dies.")
268
 
269
- # Optional: Explizit Model ID übergeben, falls Umgebungsvariable nicht reicht
270
  model_config = {}
271
- if HF_MODEL_ID:
272
- # Prüfe, ob HfApiModel 'model_id' als Argument akzeptiert (Annahme: ja)
273
- # Falls nicht, muss man sich auf die Umgebungsvariable verlassen.
274
- # Man könnte hier versuchen, das Modell explizit zu setzen:
275
- # model_config['model_id'] = HF_MODEL_ID
276
- # Wir versuchen es erstmal ohne explizite Übergabe:
277
- print(f"HfApiModel will attempt to use model specified by HF_MODEL_ID env var (or its default): {HF_MODEL_ID}")
278
- # Man kann auch Parameter direkt übergeben, falls unterstützt:
279
- # model_config['max_new_tokens'] = 1500
280
- # model_config['temperature'] = 0.1
281
-
282
- hf_model = HfApiModel(**model_config) # Initialisiere mit optionalen Configs
283
 
284
  # --- Agent Instanz ---
285
  available_tools = [search_web, download_task_file, read_file_content]
286
- active_tools = [t for t in available_tools if t is not None] # Filter out None tools (falls search nicht ging)
 
 
 
287
 
288
- # Verwende CodeAgent wie im Beispiel
289
  agent_instance = CodeAgent(
290
  tools=active_tools,
291
  model=hf_model
292
  )
293
  print(f"Smol CodeAgent initialized with {len(active_tools)} tools and HfApiModel.")
294
  if len(active_tools) < len(available_tools):
295
- print(f"Warning: Some tools might be inactive.")
296
 
297
 
298
- # --- Hauptfunktion run_and_submit_all (weitgehend unverändert) ---
299
- # Die Logik zum Holen der Fragen, Iterieren, Prompt erstellen, Agent aufrufen,
300
- # Antworten sammeln und Submitten bleibt gleich. Nur die Initialisierung oben ist anders.
301
- # --- Hauptfunktion run_and_submit_all (MIT DEBUG-PRINT) ---
302
- def run_and_submit_all( profile: gr.OAuthProfile | None, progress=gr.Progress(track_tqdm=True)):
303
  """
304
  Fetches all questions, runs the smolagents CodeAgent on them, submits all answers,
305
  and displays the results. Includes Gradio progress tracking.
306
  """
307
- # +++ DEBUGGING PRINT +++
 
 
308
  print(f"--- Entering run_and_submit_all ---")
309
- print(f"Received profile object: {profile}")
310
  if profile:
311
  print(f"Profile username: {getattr(profile, 'username', 'N/A')}")
312
- print(f"Profile details: {vars(profile) if profile else 'N/A'}") # Zeige alle Attribute des Profils
313
  else:
314
- print("Profile object is None.")
315
  # +++ END DEBUGGING PRINT +++
316
 
317
  space_id = os.getenv("SPACE_ID")
@@ -469,7 +467,7 @@ Let's begin the thinking process for Task {task_id}.
469
  return final_status, results_df
470
 
471
 
472
- # --- Gradio Interface (height Parameter entfernt) ---
473
  with gr.Blocks() as demo:
474
  gr.Markdown("# Smol CodeAgent Evaluation Runner (Hugging Face)") # Titel angepasst
475
  gr.Markdown(f"""
@@ -486,19 +484,20 @@ with gr.Blocks() as demo:
486
  run_button = gr.Button("Run Evaluation & Submit All Answers")
487
 
488
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
489
- # KORREKTUR: 'height' Parameter entfernt
490
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
491
-
492
- def handle_run(request: gr.Request):
493
- profile = getattr(request, 'profile', None)
494
- # Stelle sicher, dass run_and_submit_all aufgerufen wird und nicht nur definiert
495
- return run_and_submit_all(profile, progress=gr.Progress(track_tqdm=True))
496
-
497
- run_button.click(fn=handle_run, inputs=[], outputs=[status_output, results_table], api_name="run_evaluation_smol_codeagent")
 
498
 
499
  # --- App Start (unverändert) ---
500
  if __name__ == "__main__":
501
- print("\n" + "-"*30 + " App Starting (Smol CodeAgent Version) " + "-"*30)
502
  # (Rest des Startblocks unverändert)
503
  space_host_startup = os.getenv("SPACE_HOST")
504
  space_id_startup = os.getenv("SPACE_ID")
@@ -511,8 +510,12 @@ if __name__ == "__main__":
511
  search_tool_status = 'Disabled';
512
  if USE_TAVILY: search_tool_status = 'Tavily'
513
  elif USE_DUCKDUCKGO: search_tool_status = 'DuckDuckGo'
 
 
 
 
514
  print(f" Search Tool: {search_tool_status}")
515
  print(f" PDF Reading: {'Enabled' if PDF_READER_AVAILABLE else 'Disabled (PyPDF2 missing)'}")
516
- print("-"*(60 + len(" App Starting (Smol CodeAgent Version) ")) + "\n")
517
  print("Launching Gradio Interface for Smol CodeAgent Evaluation...")
518
- demo.queue().launch(debug=False, share=False)
 
23
  from huggingface_hub import HfApi
24
 
25
  # --- Suchtool Imports (wie zuvor) ---
26
+ USE_TAVILY = False # Setze auf True, wenn du Tavily bevorzugst (benötigt TAVILY_API_KEY)
27
+ USE_DUCKDUCKGO = True # Setze auf True für DuckDuckGo (kein Key nötig)
28
 
29
  if USE_TAVILY:
30
  try:
 
95
  # (Code unverändert)
96
  print(f"Tool: search_web(query='{query}', max_results={max_results})")
97
  if not search_client:
98
+ # Extra Check, ob search_client explizit auf False gesetzt wurde (Initialisierung fehlgeschlagen)
99
+ if search_client is False:
100
+ return "Search tool is disabled by configuration or missing libraries."
101
+ else:
102
+ # Sollte nicht passieren, wenn initialize_agent korrekt läuft, aber zur Sicherheit
103
+ print("Warning: Search client not initialized before tool use.")
104
+ return "Search tool is not available/configured."
105
  try:
106
  if USE_TAVILY and isinstance(search_client, TavilyClient):
107
  response = search_client.search(query=query, search_depth="basic", max_results=max_results)
 
244
  global search_client, agent_instance
245
  print("Initializing agent and clients...")
246
 
247
+ # Initialisiere Search Client (wenn nicht bereits geschehen oder fehlgeschlagen)
248
+ if search_client is None: # Nur initialisieren, wenn noch nicht versucht
249
  print("Initializing search client...")
250
  if USE_TAVILY:
251
  tavily_key = os.getenv("TAVILY_API_KEY")
252
  if tavily_key:
253
  try: search_client = TavilyClient(api_key=tavily_key); print("Using Tavily for search.")
254
+ except NameError: print("WARNUNG: TavilyClient Klasse nicht gefunden."); search_client = False # Fehler markieren
255
  else:
256
  print("WARNUNG: TAVILY_API_KEY nicht gefunden.")
257
+ search_client = False # Fehler markieren
258
  if USE_DUCKDUCKGO: # Fallback nur wenn Tavily nicht initialisiert werden konnte
259
  try: search_client = DDGS(); print("Falling back to DuckDuckGo for search.")
260
+ except NameError: print("WARNUNG: DuckDuckGo nicht verfügbar."); search_client = False # Fehler markieren
 
261
  elif USE_DUCKDUCKGO:
262
  try: search_client = DDGS(); print("Using DuckDuckGo for search.")
263
+ except NameError: print("WARNUNG: duckduckgo-search nicht installiert/verfügbar."); search_client = False # Fehler markieren
264
  else:
265
  print("Web search is disabled by configuration.")
266
+ search_client = False # Explizit deaktiviert
267
 
268
  # --- LLM Model (vereinfacht via HfApiModel) ---
 
 
269
  hf_token_check = os.getenv("HUGGINGFACE_TOKEN")
270
  if not hf_token_check:
271
  raise ValueError("HUGGINGFACE_TOKEN Secret nicht im Hugging Face Space gefunden! HfApiModel benötigt dies.")
272
 
273
+ print(f"HfApiModel will attempt to use model specified by HF_MODEL_ID env var (or its default): {HF_MODEL_ID}")
274
  model_config = {}
275
+ # Optional: Parameter für HfApiModel setzen, falls nötig und unterstützt
276
+ # model_config['max_new_tokens'] = 1500
277
+ # model_config['temperature'] = 0.1
278
+
279
+ hf_model = HfApiModel(**model_config)
 
 
 
 
 
 
 
280
 
281
  # --- Agent Instanz ---
282
  available_tools = [search_web, download_task_file, read_file_content]
283
+ # Nur aktive Tools übergeben (wenn search_client nicht False ist)
284
+ active_tools = [t for t in available_tools if t is not None]
285
+ if search_client is False:
286
+ active_tools = [t for t in active_tools if t != search_web] # Entferne search_web, wenn Client fehlgeschlagen
287
 
 
288
  agent_instance = CodeAgent(
289
  tools=active_tools,
290
  model=hf_model
291
  )
292
  print(f"Smol CodeAgent initialized with {len(active_tools)} tools and HfApiModel.")
293
  if len(active_tools) < len(available_tools):
294
+ print(f"Warning: Some tools might be inactive due to configuration or missing libraries.")
295
 
296
 
297
+ # --- Hauptfunktion run_and_submit_all (Nimmt gr.Request) ---
298
+ def run_and_submit_all( request: gr.Request, progress=gr.Progress(track_tqdm=True)): # Geänderter Parameter
 
 
 
299
  """
300
  Fetches all questions, runs the smolagents CodeAgent on them, submits all answers,
301
  and displays the results. Includes Gradio progress tracking.
302
  """
303
+ # +++ Profil aus Request extrahieren +++
304
+ profile = getattr(request, 'profile', None)
305
+ # +++ DEBUGGING PRINT (wie zuvor) +++
306
  print(f"--- Entering run_and_submit_all ---")
307
+ print(f"Received profile object via request: {profile}")
308
  if profile:
309
  print(f"Profile username: {getattr(profile, 'username', 'N/A')}")
310
+ # print(f"Profile details: {vars(profile) if profile else 'N/A'}") # Details können viel loggen
311
  else:
312
+ print("Profile object via request is None.")
313
  # +++ END DEBUGGING PRINT +++
314
 
315
  space_id = os.getenv("SPACE_ID")
 
467
  return final_status, results_df
468
 
469
 
470
+ # --- Gradio Interface (Angepasster Button Click) ---
471
  with gr.Blocks() as demo:
472
  gr.Markdown("# Smol CodeAgent Evaluation Runner (Hugging Face)") # Titel angepasst
473
  gr.Markdown(f"""
 
484
  run_button = gr.Button("Run Evaluation & Submit All Answers")
485
 
486
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
487
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) # Ohne 'height'
488
+
489
+ # KORREKTUR: run_and_submit_all direkt aufrufen
490
+ # inputs=[] damit Gradio den request Parameter injiziert.
491
+ run_button.click(
492
+ fn=run_and_submit_all,
493
+ inputs=[], # Wichtig: Keine Inputs hier angeben
494
+ outputs=[status_output, results_table],
495
+ api_name="run_evaluation_smol_codeagent"
496
+ )
497
 
498
  # --- App Start (unverändert) ---
499
  if __name__ == "__main__":
500
+ print("\n" + "-"*30 + " App Starting (Smol CodeAgent Version - Request Fix) " + "-"*30)
501
  # (Rest des Startblocks unverändert)
502
  space_host_startup = os.getenv("SPACE_HOST")
503
  space_id_startup = os.getenv("SPACE_ID")
 
510
  search_tool_status = 'Disabled';
511
  if USE_TAVILY: search_tool_status = 'Tavily'
512
  elif USE_DUCKDUCKGO: search_tool_status = 'DuckDuckGo'
513
+ # Check search client status based on initialization logic
514
+ if search_client is None and (USE_TAVILY or USE_DUCKDUCKGO): search_tool_status += " (Initialization Pending)"
515
+ elif search_client is False: search_tool_status += " (Failed to Initialize / Disabled)"
516
+
517
  print(f" Search Tool: {search_tool_status}")
518
  print(f" PDF Reading: {'Enabled' if PDF_READER_AVAILABLE else 'Disabled (PyPDF2 missing)'}")
519
+ print("-"*(60 + len(" App Starting (Smol CodeAgent Version - Request Fix) ")) + "\n")
520
  print("Launching Gradio Interface for Smol CodeAgent Evaluation...")
521
+ demo.queue().launch(debug=False, share=False) # queue() ist wichtig