MainStreet123 commited on
Commit
f5ef7b3
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -11
app.py CHANGED
@@ -1,23 +1,121 @@
1
  import os
 
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  class BasicAgent:
 
 
14
  def __init__(self):
15
- print("BasicAgent initialized.")
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
@@ -146,11 +244,9 @@ with gr.Blocks() as demo:
146
  gr.Markdown(
147
  """
148
  **Instructions:**
149
-
150
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
-
154
  ---
155
  **Disclaimers:**
156
  Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
@@ -193,4 +289,5 @@ if __name__ == "__main__":
193
  print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
  print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
 
1
  import os
2
+ import sys
3
  import gradio as gr
4
  import requests
 
5
  import pandas as pd
6
 
7
+ # Allow importing smolagents from hf-smolagents venv when running from project root
8
+ _root = os.path.dirname(os.path.abspath(__file__))
9
+ _venv_lib = os.path.join(_root, "hf-smolagents", ".venv", "lib")
10
+ if os.path.isdir(_venv_lib):
11
+ for _name in os.listdir(_venv_lib):
12
+ if _name.startswith("python"):
13
+ _sp = os.path.join(_venv_lib, _name, "site-packages")
14
+ if os.path.isdir(_sp):
15
+ sys.path.insert(0, _sp)
16
+ break
17
+ else:
18
+ _sp = None
19
+ else:
20
+ _sp = None
21
+
22
+ from smolagents import CodeAgent, InferenceClientModel
23
+ from smolagents.default_tools import (
24
+ DuckDuckGoSearchTool,
25
+ FinalAnswerTool,
26
+ PythonInterpreterTool,
27
+ UserInputTool,
28
+ )
29
+
30
  # (Keep Constants as is)
31
  # --- Constants ---
32
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
33
 
34
+ # --- Multi-Agent System (smolagents) ---
35
+ def _create_model():
36
+ token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
37
+ return InferenceClientModel(
38
+ model_id="Qwen/Qwen2.5-Coder-7B-Instruct",
39
+ token=token,
40
+ )
41
+
42
+
43
+ def _create_code_agent(model):
44
+ """Code agent: Python interpreter + final answer. For math, calculations, data."""
45
+ return CodeAgent(
46
+ tools=[PythonInterpreterTool(), UserInputTool()],
47
+ model=model,
48
+ name="code_agent",
49
+ description="Use for math, calculations, data processing, or when the task can be solved by writing and running Python code. Call with a single clear task.",
50
+ max_steps=15,
51
+ )
52
+
53
+
54
+ def _create_web_agent(model):
55
+ """Web agent: DuckDuckGo search + final answer. For factual/search tasks."""
56
+ return CodeAgent(
57
+ tools=[DuckDuckGoSearchTool(), UserInputTool()],
58
+ model=model,
59
+ name="web_agent",
60
+ description="Use for factual questions, current events, or when you need to search the web. Give one search task per call; you can call me multiple times with different queries.",
61
+ max_steps=15,
62
+ )
63
+
64
+
65
+ def _create_evaluator_agent(model):
66
+ """Evaluator: picks best answer from multiple candidates, returns via final_answer."""
67
+ return CodeAgent(
68
+ tools=[FinalAnswerTool(), UserInputTool()],
69
+ model=model,
70
+ name="evaluator_agent",
71
+ description="Use to pick the single best answer from multiple candidate answers. Pass a task containing the original question and the list of candidate answers; return only the chosen best answer (concise, factual).",
72
+ max_steps=5,
73
+ )
74
+
75
+
76
+ def _create_manager_agent(model):
77
+ """Manager: decides code_agent vs web_agent; if web, runs multiple web queries then evaluator then final_answer."""
78
+ code_agent = _create_code_agent(model)
79
+ web_agent = _create_web_agent(model)
80
+ evaluator_agent = _create_evaluator_agent(model)
81
+ return CodeAgent(
82
+ tools=[UserInputTool()],
83
+ model=model,
84
+ managed_agents=[code_agent, web_agent, evaluator_agent],
85
+ name="manager",
86
+ description="Orchestrator: decide whether to use code_agent or web_agent. For web tasks, call web_agent multiple times with different search queries, then call evaluator_agent with the question and all answers to pick the best one, then call final_answer with that result.",
87
+ max_steps=25,
88
+ planning_interval=3,
89
+ )
90
+
91
+
92
  class BasicAgent:
93
+ """Wrapper: builds manager-led multi-agent system and returns final answer string per question."""
94
+
95
  def __init__(self):
96
+ print("Multi-agent system: initializing model and manager...")
97
+ self._model = _create_model()
98
+ self._manager = _create_manager_agent(self._model)
99
+ print("Multi-agent system initialized (manager + code_agent, web_agent, evaluator_agent).")
100
+
101
  def __call__(self, question: str) -> str:
102
+ print(f"Agent received question (first 80 chars): {question[:80]}...")
103
+ try:
104
+ result = self._manager.run(
105
+ question,
106
+ reset=True,
107
+ stream=False,
108
+ return_full_result=False,
109
+ )
110
+ if result is None:
111
+ out = "No answer produced."
112
+ else:
113
+ out = str(result).strip()
114
+ print(f"Agent returning answer (first 80 chars): {out[:80]}...")
115
+ return out
116
+ except Exception as e:
117
+ print(f"Agent error: {e}")
118
+ return f"AGENT ERROR: {e}"
119
 
120
  def run_and_submit_all( profile: gr.OAuthProfile | None):
121
  """
 
244
  gr.Markdown(
245
  """
246
  **Instructions:**
 
247
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
248
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
249
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
250
  ---
251
  **Disclaimers:**
252
  Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
 
289
  print("-"*(60 + len(" App Starting ")) + "\n")
290
 
291
  print("Launching Gradio Interface for Basic Agent Evaluation...")
292
+ demo.launch(debug=True, share=False)
293
+