czrrr commited on
Commit
1b12e7f
·
verified ·
1 Parent(s): c3829af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -23
app.py CHANGED
@@ -8,6 +8,7 @@ from zipfile import ZipFile
8
  import gradio as gr
9
  import pandas as pd
10
  import requests
 
11
  from smolagents import (
12
  CodeAgent,
13
  DuckDuckGoSearchTool,
@@ -22,9 +23,8 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
22
  RESULT_COLUMNS = ["Task ID", "Question", "Submitted Answer"]
23
  HTTP_TIMEOUT = 45
24
  MAX_EXTRACTED_CHARS = 35_000
25
- MODEL_ID = os.getenv(
26
- "GAIA_MODEL_ID", "huggingface/openai/gpt-oss-120b"
27
- )
28
 
29
 
30
  def clean_filename(value: str) -> str:
@@ -308,36 +308,107 @@ class AnalyzeGaiaImageTool(Tool):
308
  return f"Could not analyze the GAIA image: {exc}"
309
 
310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  class BasicAgent:
312
  def __init__(self):
313
  print("Inicializando o agente GAIA...")
314
 
315
  hf_token = os.getenv("HF_TOKEN")
316
- if not hf_token:
 
 
 
 
 
 
 
 
 
 
 
 
317
  raise RuntimeError(
318
- "O secret HF_TOKEN não está configurado no Hugging Face Space. "
319
- "Crie um token com permissão de inferência e adicione-o em "
320
- "Settings > Secrets."
321
  )
322
 
323
  self.model = LiteLLMModel(
324
- model_id=MODEL_ID,
325
- api_key=hf_token,
326
  temperature=0,
 
327
  )
328
  self.hf_token = hf_token
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  self.agent = CodeAgent(
330
- tools=[
331
- DuckDuckGoSearchTool(max_results=8, rate_limit=1.0),
332
- VisitWebpageTool(max_output_length=30_000),
333
- WikipediaSearchTool(
334
- user_agent="GAIA-Course-Agent/1.0 (educational project)",
335
- language="en",
336
- ),
337
- InspectGaiaAttachmentTool(),
338
- YouTubeTranscriptTool(),
339
- AnalyzeGaiaImageTool(),
340
- ],
341
  model=self.model,
342
  max_steps=10,
343
  planning_interval=4,
@@ -367,6 +438,10 @@ If the task asks what someone says in a YouTube video, call youtube_transcript
367
  with the exact video URL before searching the web.
368
  If the task depends on an attached image, call analyze_gaia_image with the
369
  task_id and complete question. Do not try to infer image contents from metadata.
 
 
 
 
370
  Prefer primary or official sources. When search snippets conflict, open the
371
  source and verify the relevant passage instead of guessing.
372
  Only call tools that are explicitly available. Never invent a function such as
@@ -404,9 +479,9 @@ If a number is requested, return only that number.
404
  or "Unauthorized" in error_text
405
  ):
406
  raise RuntimeError(
407
- "Falha de autenticação no modelo. Verifique se o secret "
408
- "HF_TOKEN contém um token válido com permissão para usar "
409
- "Inference Providers."
410
  ) from exc
411
  raise
412
  return self.format_exact_answer(question, str(result))
 
8
  import gradio as gr
9
  import pandas as pd
10
  import requests
11
+ from litellm import completion
12
  from smolagents import (
13
  CodeAgent,
14
  DuckDuckGoSearchTool,
 
23
  RESULT_COLUMNS = ["Task ID", "Question", "Submitted Answer"]
24
  HTTP_TIMEOUT = 45
25
  MAX_EXTRACTED_CHARS = 35_000
26
+ DEFAULT_HF_MODEL = "huggingface/openai/gpt-oss-120b"
27
+ DEFAULT_GEMINI_MODEL = "gemini/gemini-3.5-flash"
 
28
 
29
 
30
  def clean_filename(value: str) -> str:
 
308
  return f"Could not analyze the GAIA image: {exc}"
309
 
310
 
311
+ class ConsultGeminiTool(Tool):
312
+ name = "consult_gemini"
313
+ description = (
314
+ "Asks Gemini for an independent second opinion on a difficult question "
315
+ "or on evidence already collected. Use it to verify reasoning, resolve "
316
+ "conflicting sources, or check the exact requested answer format. Do "
317
+ "not use it as a substitute for inspecting official attachments."
318
+ )
319
+ inputs = {
320
+ "request": {
321
+ "type": "string",
322
+ "description": (
323
+ "The complete question plus any relevant evidence and the "
324
+ "specific point Gemini should verify."
325
+ ),
326
+ }
327
+ }
328
+ output_type = "string"
329
+
330
+ def forward(self, request: str) -> str:
331
+ api_key = os.getenv("GEMINI_API_KEY")
332
+ if not api_key:
333
+ return "Gemini consultation unavailable: GEMINI_API_KEY is missing."
334
+
335
+ model = os.getenv(
336
+ "GAIA_GEMINI_TOOL_MODEL", DEFAULT_GEMINI_MODEL
337
+ )
338
+ try:
339
+ response = completion(
340
+ model=model,
341
+ api_key=api_key,
342
+ messages=[
343
+ {
344
+ "role": "system",
345
+ "content": (
346
+ "You are a verification specialist assisting another "
347
+ "GAIA agent. Analyze the supplied question and evidence "
348
+ "critically. Identify uncertainty or contradictions, "
349
+ "then provide your recommended exact answer. Be concise "
350
+ "and never claim to have opened sources that were not "
351
+ "included in the request."
352
+ ),
353
+ },
354
+ {"role": "user", "content": str(request)},
355
+ ],
356
+ temperature=0,
357
+ max_tokens=900,
358
+ )
359
+ return str(response.choices[0].message.content).strip()
360
+ except Exception as exc:
361
+ return f"Gemini consultation failed: {exc}"
362
+
363
+
364
  class BasicAgent:
365
  def __init__(self):
366
  print("Inicializando o agente GAIA...")
367
 
368
  hf_token = os.getenv("HF_TOKEN")
369
+ gemini_api_key = os.getenv("GEMINI_API_KEY")
370
+ configured_model = os.getenv("GAIA_MODEL_ID")
371
+
372
+ model_id = configured_model or DEFAULT_HF_MODEL
373
+
374
+ if model_id.startswith("gemini/"):
375
+ model_api_key = gemini_api_key
376
+ required_secret = "GEMINI_API_KEY"
377
+ else:
378
+ model_api_key = hf_token
379
+ required_secret = "HF_TOKEN"
380
+
381
+ if not model_api_key:
382
  raise RuntimeError(
383
+ f"O secret {required_secret} não está configurado. "
384
+ "Adicione a chave em Settings > Variables and secrets > Secrets."
 
385
  )
386
 
387
  self.model = LiteLLMModel(
388
+ model_id=model_id,
389
+ api_key=model_api_key,
390
  temperature=0,
391
+ max_tokens=2_000,
392
  )
393
  self.hf_token = hf_token
394
+ self.model_id = model_id
395
+ print(f"Modelo principal selecionado: {model_id}")
396
+ agent_tools = [
397
+ DuckDuckGoSearchTool(max_results=8, rate_limit=1.0),
398
+ VisitWebpageTool(max_output_length=30_000),
399
+ WikipediaSearchTool(
400
+ user_agent="GAIA-Course-Agent/1.0 (educational project)",
401
+ language="en",
402
+ ),
403
+ InspectGaiaAttachmentTool(),
404
+ YouTubeTranscriptTool(),
405
+ AnalyzeGaiaImageTool(),
406
+ ]
407
+ if gemini_api_key:
408
+ agent_tools.append(ConsultGeminiTool())
409
+
410
  self.agent = CodeAgent(
411
+ tools=agent_tools,
 
 
 
 
 
 
 
 
 
 
412
  model=self.model,
413
  max_steps=10,
414
  planning_interval=4,
 
438
  with the exact video URL before searching the web.
439
  If the task depends on an attached image, call analyze_gaia_image with the
440
  task_id and complete question. Do not try to infer image contents from metadata.
441
+ When consult_gemini is available, use it selectively for a second opinion after
442
+ you have collected evidence, especially when sources conflict or your candidate
443
+ answer is uncertain. Give it the complete question and relevant evidence. Do
444
+ not blindly copy its response; compare it with the sources before deciding.
445
  Prefer primary or official sources. When search snippets conflict, open the
446
  source and verify the relevant passage instead of guessing.
447
  Only call tools that are explicitly available. Never invent a function such as
 
479
  or "Unauthorized" in error_text
480
  ):
481
  raise RuntimeError(
482
+ f"Falha de autenticação no modelo {self.model_id}. "
483
+ "Verifique a chave secreta correspondente ao provedor "
484
+ "(GEMINI_API_KEY para Gemini ou HF_TOKEN para Hugging Face)."
485
  ) from exc
486
  raise
487
  return self.format_exact_answer(question, str(result))