samoye16 commited on
Commit
819c25e
·
verified ·
1 Parent(s): c6e5dee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -15
app.py CHANGED
@@ -3,30 +3,67 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
6
- from agents import create_agent_flow
7
- from langchain_core.messages import HumanMessage
 
8
 
9
  # (Keep Constants as is)
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
13
- # --- Basic Agent Definition ---
14
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
15
- class BasicAgent:
16
 
 
 
17
  def __init__(self):
18
- print("BasicAgent initialized.")
19
- self.agent = create_agent_flow()
20
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  def __call__(self, question: str) -> str:
22
- print(f"Agent received question (first 50 chars): {question[:50]}...")
23
-
24
- question = [HumanMessage(content=question)]
25
- question_ask = self.agent.invoke({"messages": question})
26
- response = question_ask['messages'][-1].content
27
- print(f"Agent returning fixed answer: {response}")
28
- return response[8:]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
 
 
30
  def run_and_submit_all( profile: gr.OAuthProfile | None):
31
  """
32
  Fetches all questions, runs the BasicAgent on them, submits all answers,
@@ -154,9 +191,11 @@ with gr.Blocks() as demo:
154
  gr.Markdown(
155
  """
156
  **Instructions:**
 
157
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
158
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
159
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
160
  ---
161
  **Disclaimers:**
162
  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).
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ import time
7
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, WikipediaSearchTool, PythonInterpreterTool, FinalAnswerTool, LiteLLMModel
8
+
9
 
10
  # (Keep Constants as is)
11
  # --- Constants ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
 
14
+
 
 
15
 
16
+ # Define the real agent
17
+ class BasicAgent:
18
  def __init__(self):
19
+ print("Improved BasicAgent initialized with Gemini and enhanced tools.")
20
+
21
+ # Load Gemini through LiteLLM
22
+ self.model = LiteLLMModel(
23
+ model_id="gemini/gemini-2.0-flash-lite",
24
+ api_key=os.getenv("GEMINI_API_TOKEN"),
25
+ )
26
+
27
+ # Setup CodeAgent with tools
28
+ self.agent = CodeAgent(
29
+ tools=[
30
+ DuckDuckGoSearchTool(),
31
+ WikipediaSearchTool(),
32
+ PythonInterpreterTool(),
33
+ FinalAnswerTool(),
34
+ ],
35
+ model=self.model,
36
+ max_steps=10,
37
+ add_base_tools=True,
38
+ additional_authorized_imports=["pandas", "*"]
39
+ )
40
+
41
  def __call__(self, question: str) -> str:
42
+ """Main callable for processing questions with rate limiting."""
43
+ print(f"Running agent for task: {question[:50]}...")
44
+
45
+ # Prompt with strict output formatting
46
+ system_instruction = (
47
+ "I will ask you a question. Report your thoughts step by step. "
48
+ "Finish your answer only with the final answer. In the final answer don't write explanations. "
49
+ "The answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. "
50
+ "Avoid units, abbreviations, or articles unless specified. "
51
+ "Pay attention to each sentence in the question and verify the answer against every part. "
52
+ "Try searching more sources if initial results are insufficient.\nQUESTION: "
53
+ )
54
+
55
+ prompt = system_instruction + question
56
+ try:
57
+ result = self.agent.run(prompt)
58
+ except Exception as e:
59
+ result = f"Error: {str(e)}"
60
+
61
+ # Rate limiting to avoid 429 errors or API limits
62
+ print("Waiting 5 seconds to respect rate limits...")
63
+ time.sleep(5)
64
 
65
+ return result
66
+
67
  def run_and_submit_all( profile: gr.OAuthProfile | None):
68
  """
69
  Fetches all questions, runs the BasicAgent on them, submits all answers,
 
191
  gr.Markdown(
192
  """
193
  **Instructions:**
194
+
195
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
196
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
197
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
198
+
199
  ---
200
  **Disclaimers:**
201
  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).