DukeDDrake1999 commited on
Commit
a8dcb3e
·
verified ·
1 Parent(s): fceca04

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +15 -20
agent.py CHANGED
@@ -14,12 +14,12 @@ from google import genai
14
  from google.genai import types as genai_types
15
  from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIModel, Tool
16
 
17
-
18
  load_dotenv()
19
 
20
  DEFAULT_SCORING_API_URL = "https://agents-course-unit4-scoring.hf.space"
21
  DEFAULT_GEMINI_MODEL_ID = os.getenv("GEMINI_MODEL_ID", "gemini/gemini-2.5-flash")
22
  GEMINI_OPENAI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
 
23
  HTTP_SESSION = requests.Session()
24
  HTTP_SESSION.headers.update(
25
  {
@@ -27,8 +27,8 @@ HTTP_SESSION.headers.update(
27
  "Accept": "application/json, text/plain, */*",
28
  }
29
  )
30
- GAIA_OUTPUT_PROMPT = """
31
- You are an evaluation-grade GAIA benchmark AI assistant. Your execution must be perfectly precise and highly deterministic. Your sole purpose is to isolate and output the exact, minimal final answer.
32
 
33
  ### CORE DIRECTIVE
34
  You must NEVER output explanations, intermediate reasoning, conversational filler, or comments.
@@ -59,13 +59,10 @@ Format: [FINAL_ANSWER]
59
  ### EXAMPLES
60
  Q: What is 2 + 2?
61
  A: [4]
62
-
63
  Q: How many studio albums were published by Mercedes Sosa between 2000 and 2009 (inclusive)? Use 2022 English Wikipedia.
64
  A: [3]
65
-
66
  Q: Given the following group table on set S = {a, b, c, d, e}, identify any subset involved in counterexamples to commutativity.
67
  A: [b, e]
68
-
69
  Q: How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?
70
  A: [519]
71
  """.strip()
@@ -95,7 +92,6 @@ def _extract_text(response) -> str:
95
  text = getattr(response, "text", None)
96
  if text:
97
  return text.strip()
98
-
99
  parts: list[str] = []
100
  for candidate in getattr(response, "candidates", []) or []:
101
  content = getattr(candidate, "content", None)
@@ -110,7 +106,6 @@ def _call_gemini_text(prompt: str, system_instruction: str | None = None) -> str
110
  config = genai_types.GenerateContentConfig(temperature=0)
111
  if system_instruction:
112
  config.system_instruction = system_instruction
113
-
114
  response = _genai_client().models.generate_content(
115
  model=_normalize_model_id(),
116
  contents=prompt,
@@ -157,18 +152,15 @@ def _query_uploaded_file(file_bytes: bytes, file_name: str, mime_type: str, user
157
  suffix = Path(file_name or "attachment").suffix
158
  temp_path = None
159
  uploaded_file = None
160
-
161
  try:
162
  with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
163
  temp_file.write(file_bytes)
164
  temp_path = temp_file.name
165
-
166
  uploaded_file = client.files.upload(
167
  file=temp_path,
168
  config={"mime_type": mime_type},
169
  )
170
  _wait_until_active(client, uploaded_file)
171
-
172
  response = client.models.generate_content(
173
  model=_normalize_model_id(),
174
  contents=[uploaded_file, user_query],
@@ -270,7 +262,6 @@ class MathSolver(Tool):
270
  result = eval_node(parsed)
271
  except Exception as exc:
272
  return f"Math error: {exc}"
273
-
274
  if isinstance(result, float) and result.is_integer():
275
  return str(int(result))
276
  return str(result)
@@ -466,26 +457,31 @@ class FileAttachmentQueryTool(Tool):
466
  file_bytes, content_type = _download_task_file(task_id)
467
  suffix = Path(file_name or "").suffix.lower()
468
  mime_type = _mime_from_name(file_name, content_type)
469
-
470
  if suffix in {".txt", ".md", ".json", ".csv", ".py", ".html", ".xml", ".yaml", ".yml", ".log"}:
471
  file_text = _decode_text_bytes(file_bytes)
472
  return _textual_file_answer(file_text, user_query)
473
-
474
  if suffix in {".xlsx", ".xls"}:
475
  file_text = _excel_to_text(file_bytes)
476
  return _textual_file_answer(file_text, user_query)
477
-
478
  return _query_uploaded_file(file_bytes, file_name, mime_type, user_query)
479
 
480
 
481
  class BasicAgent:
482
  def __init__(self):
 
483
  _get_gemini_api_key()
 
 
 
 
 
 
 
 
484
  self.agent = CodeAgent(
485
  model=OpenAIModel(
486
- model_id=_normalize_model_id(),
487
- api_base=GEMINI_OPENAI_BASE_URL,
488
- api_key=_get_gemini_api_key(),
489
  temperature=0,
490
  ),
491
  tools=[
@@ -522,7 +518,6 @@ class BasicAgent:
522
  f"- file_name: {file_name}\n"
523
  "Use run_query_with_file if the question requires the attachment."
524
  )
525
-
526
  result = self.agent.run("\n".join(prompt_parts).strip())
527
  return _normalize_final_answer(str(result))
528
 
@@ -532,4 +527,4 @@ if __name__ == "__main__":
532
  "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? "
533
  "You can use the latest 2022 version of english wikipedia."
534
  )
535
- print(BasicAgent()(sample_question))
 
14
  from google.genai import types as genai_types
15
  from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIModel, Tool
16
 
 
17
  load_dotenv()
18
 
19
  DEFAULT_SCORING_API_URL = "https://agents-course-unit4-scoring.hf.space"
20
  DEFAULT_GEMINI_MODEL_ID = os.getenv("GEMINI_MODEL_ID", "gemini/gemini-2.5-flash")
21
  GEMINI_OPENAI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
22
+
23
  HTTP_SESSION = requests.Session()
24
  HTTP_SESSION.headers.update(
25
  {
 
27
  "Accept": "application/json, text/plain, */*",
28
  }
29
  )
30
+
31
+ GAIA_OUTPUT_PROMPT = """You are an evaluation-grade GAIA benchmark AI assistant. Your execution must be perfectly precise and highly deterministic. Your sole purpose is to isolate and output the exact, minimal final answer.
32
 
33
  ### CORE DIRECTIVE
34
  You must NEVER output explanations, intermediate reasoning, conversational filler, or comments.
 
59
  ### EXAMPLES
60
  Q: What is 2 + 2?
61
  A: [4]
 
62
  Q: How many studio albums were published by Mercedes Sosa between 2000 and 2009 (inclusive)? Use 2022 English Wikipedia.
63
  A: [3]
 
64
  Q: Given the following group table on set S = {a, b, c, d, e}, identify any subset involved in counterexamples to commutativity.
65
  A: [b, e]
 
66
  Q: How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?
67
  A: [519]
68
  """.strip()
 
92
  text = getattr(response, "text", None)
93
  if text:
94
  return text.strip()
 
95
  parts: list[str] = []
96
  for candidate in getattr(response, "candidates", []) or []:
97
  content = getattr(candidate, "content", None)
 
106
  config = genai_types.GenerateContentConfig(temperature=0)
107
  if system_instruction:
108
  config.system_instruction = system_instruction
 
109
  response = _genai_client().models.generate_content(
110
  model=_normalize_model_id(),
111
  contents=prompt,
 
152
  suffix = Path(file_name or "attachment").suffix
153
  temp_path = None
154
  uploaded_file = None
 
155
  try:
156
  with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
157
  temp_file.write(file_bytes)
158
  temp_path = temp_file.name
 
159
  uploaded_file = client.files.upload(
160
  file=temp_path,
161
  config={"mime_type": mime_type},
162
  )
163
  _wait_until_active(client, uploaded_file)
 
164
  response = client.models.generate_content(
165
  model=_normalize_model_id(),
166
  contents=[uploaded_file, user_query],
 
262
  result = eval_node(parsed)
263
  except Exception as exc:
264
  return f"Math error: {exc}"
 
265
  if isinstance(result, float) and result.is_integer():
266
  return str(int(result))
267
  return str(result)
 
457
  file_bytes, content_type = _download_task_file(task_id)
458
  suffix = Path(file_name or "").suffix.lower()
459
  mime_type = _mime_from_name(file_name, content_type)
 
460
  if suffix in {".txt", ".md", ".json", ".csv", ".py", ".html", ".xml", ".yaml", ".yml", ".log"}:
461
  file_text = _decode_text_bytes(file_bytes)
462
  return _textual_file_answer(file_text, user_query)
 
463
  if suffix in {".xlsx", ".xls"}:
464
  file_text = _excel_to_text(file_bytes)
465
  return _textual_file_answer(file_text, user_query)
 
466
  return _query_uploaded_file(file_bytes, file_name, mime_type, user_query)
467
 
468
 
469
  class BasicAgent:
470
  def __init__(self):
471
+ # We keep this here to ensure Gemini Tools don't throw an error later
472
  _get_gemini_api_key()
473
+
474
+ # Get the OpenAI API key for the main loop
475
+ openai_api_key = os.getenv("OPENAI_API_KEY")
476
+ if not openai_api_key:
477
+ raise RuntimeError(
478
+ "Missing OpenAI API key. Set OPENAI_API_KEY in your Hugging Face Space secrets."
479
+ )
480
+
481
  self.agent = CodeAgent(
482
  model=OpenAIModel(
483
+ model_id="gpt-4o-mini",
484
+ api_key=openai_api_key,
 
485
  temperature=0,
486
  ),
487
  tools=[
 
518
  f"- file_name: {file_name}\n"
519
  "Use run_query_with_file if the question requires the attachment."
520
  )
 
521
  result = self.agent.run("\n".join(prompt_parts).strip())
522
  return _normalize_final_answer(str(result))
523
 
 
527
  "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? "
528
  "You can use the latest 2022 version of english wikipedia."
529
  )
530
+ print(BasicAgent()(sample_question))