Qscar KIM commited on
Commit
ad4f10e
Β·
1 Parent(s): 913b19a

update codes

Browse files
Files changed (1) hide show
  1. app.py +36 -24
app.py CHANGED
@@ -4,54 +4,67 @@ import requests
4
  import inspect
5
  import pandas as pd
6
  import time
 
7
 
8
- # κ°•μ˜ λͺ©μ μ— λΆ€ν•©ν•˜λŠ” smolagents μ΅œμ‹  ν‘œμ€€ μ»΄ν¬λ„ŒνŠΈ μž„ν¬νŠΈ
9
- from smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool
10
 
11
- # --- Constants ---
12
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  # --- Basic Agent Definition ---
15
  # ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
16
  class BasicAgent:
17
  def __init__(self):
18
- # 슀페이슀 Secrets에 HF_TOKEN이 λ“±λ‘λ˜μ–΄ μžˆλ‹€λ©΄ λ°±μ—”λ“œμ—μ„œ μžλ™μœΌλ‘œ 읽어와 인증을 μˆ˜ν–‰ν•©λ‹ˆλ‹€.
19
- hf_token = os.getenv("HF_TOKEN")
20
- if not hf_token:
21
- print("⚠️ 크리티컬 κ²½κ³ : HF_TOKEN이 μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. 레이트 λ¦¬λ°‹μœΌλ‘œ 인해 μ „λΆ€ unknown μ²˜λ¦¬κ°€ 될 수 μžˆμŠ΅λ‹ˆλ‹€.")
22
-
23
- # model_idλ₯Ό λΉ„μ›Œλ‘λ©΄ smolagents ν”„λ ˆμž„μ›Œν¬κ°€ μ½”μŠ€ μ‹€μŠ΅μš©μœΌλ‘œ 보μž₯ν•˜λŠ” κ°€μž₯ μ•ˆμ •μ μΈ κΈ°λ³Έ λͺ¨λΈμ„ μžλ™μœΌλ‘œ λ§€ν•‘ν•©λ‹ˆλ‹€.
24
- self.model = InferenceClientModel(token=hf_token)
25
  self.search_tool = DuckDuckGoSearchTool()
26
-
27
- # κ°•μ˜ λ³Έμ—°μ˜ λͺ©μ μΈ ReAct(Thought -> Action) 루프λ₯Ό μˆ˜ν–‰ν•˜λŠ” μžμœ¨ν˜• μ½”λ“œ μ—μ΄μ „νŠΈ 쑰립
28
  self.agent = CodeAgent(
29
  tools=[self.search_tool],
30
  model=self.model,
31
  max_steps=5,
32
- add_base_tools=True # λ‚΄λΆ€ 파이썬 인터프리터 툴 μžλ™ ν™œμ„±ν™”
33
  )
34
- print("BasicAgent: smolagents κ·œκ²©μ„ μ€€μˆ˜ν•˜μ—¬ μžμœ¨ν˜• μ—μ΄μ „νŠΈ μ΄ˆκΈ°ν™”λ₯Ό μ™„λ£Œν–ˆμŠ΅λ‹ˆλ‹€.")
35
 
36
  def __call__(self, question: str) -> str:
37
- print(f"Agent received question (first 50 chars): {question[:50]}...")
38
-
39
  try:
40
  refined_prompt = (
41
  f"{question}\n\n"
42
  f"Solve this task step by step using your tools. "
43
  f"Provide the final short answer clearly at the very end."
44
  )
45
- # 자율 μΆ”λ‘  및 μ‹€ν–‰ 루프 가동
46
  result = self.agent.run(refined_prompt)
47
  if result is None:
48
  return "unknown"
49
-
50
  return str(result).strip()
51
-
52
  except Exception as e:
53
- # πŸ”΄ 먹톡 ν˜„μƒ 뢄석을 μœ„ν•΄ unknown λŒ€μ‹  μ‹€μ œ ν„°μ§„ μ—λŸ¬ 원인을 ν…Œμ΄λΈ”μ— λ…ΈμΆœμ‹œν‚΅λ‹ˆλ‹€.
54
- print(f"❌ μ—μ΄μ „νŠΈ μ‹€ν–‰ μ‹€νŒ¨ 둜그: {e}")
55
  return f"Error: {type(e).__name__}"
56
 
57
  def run_and_submit_all( profile: gr.OAuthProfile | None):
@@ -119,8 +132,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
119
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
120
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
121
 
122
- # 자율 μ—μ΄μ „νŠΈ 연쇄 호좜 μ‹œ ν—ˆκΉ…νŽ˜μ΄μŠ€ μ—”λ“œν¬μΈνŠΈκ°€ μ°¨λ‹¨ν•˜μ§€ μ•Šλ„λ‘ λŒ€κΈ° μ‹œκ°„μ„ 3초둜 μœ μ§€ν•©λ‹ˆλ‹€.
123
- time.sleep(3)
124
  except Exception as e:
125
  print(f"Error running agent on task {task_id}: {e}")
126
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
4
  import inspect
5
  import pandas as pd
6
  import time
7
+ import re
8
 
9
+ from smolagents import CodeAgent, InferenceClientModel, Tool
 
10
 
11
+ # --- Custom Tool Definition ---
12
+ class DuckDuckGoSearchTool(Tool):
13
+ name = "web_search"
14
+ description = "Searches the web for a given query and returns snippet results."
15
+ inputs = {"query": {"type": "string", "description": "The search query"}}
16
+ output_type = "string"
17
+
18
+ def forward(self, query: str) -> str:
19
+ try:
20
+ url = f"https://html.duckduckgo.com/html/?q={requests.utils.quote(query)}"
21
+ headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
22
+ response = requests.get(url, headers=headers, timeout=10)
23
+ if response.status_code != 200:
24
+ return f"Search failed with status code {response.status_code}"
25
+
26
+ html = response.text
27
+ snippets = re.findall(r'<a class="result__snippet"[^>]*>(.*?)</a>', html, re.DOTALL)
28
+ cleaned_snippets = []
29
+ for snip in snippets[:5]:
30
+ clean = re.sub(r'<[^>]+>', '', snip)
31
+ clean = clean.replace('\n', ' ').strip()
32
+ cleaned_snippets.append(clean)
33
+
34
+ if cleaned_snippets:
35
+ return "\n".join(f"- {s}" for s in cleaned_snippets)
36
+ return "No results found."
37
+ except Exception as e:
38
+ return f"Search error: {str(e)}"
39
 
40
  # --- Basic Agent Definition ---
41
  # ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
42
  class BasicAgent:
43
  def __init__(self):
44
+ self.model = InferenceClientModel(
45
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
46
+ token=os.getenv("HF_TOKEN")
47
+ )
 
 
 
48
  self.search_tool = DuckDuckGoSearchTool()
 
 
49
  self.agent = CodeAgent(
50
  tools=[self.search_tool],
51
  model=self.model,
52
  max_steps=5,
53
+ additional_authorized_imports=["pandas", "numpy", "json", "math", "re", "datetime"]
54
  )
 
55
 
56
  def __call__(self, question: str) -> str:
 
 
57
  try:
58
  refined_prompt = (
59
  f"{question}\n\n"
60
  f"Solve this task step by step using your tools. "
61
  f"Provide the final short answer clearly at the very end."
62
  )
 
63
  result = self.agent.run(refined_prompt)
64
  if result is None:
65
  return "unknown"
 
66
  return str(result).strip()
 
67
  except Exception as e:
 
 
68
  return f"Error: {type(e).__name__}"
69
 
70
  def run_and_submit_all( profile: gr.OAuthProfile | None):
 
132
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
133
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
134
 
135
+ time.sleep(2)
 
136
  except Exception as e:
137
  print(f"Error running agent on task {task_id}: {e}")
138
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})