cesarleoni commited on
Commit
ddb8c97
·
verified ·
1 Parent(s): 696832a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -80
app.py CHANGED
@@ -2,59 +2,42 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
-
6
- # ---- LangChain & Tools (OpenAI‑only) ----
7
- from langchain.chat_models import ChatOpenAI
8
- from langchain.agents import initialize_agent, Tool
9
- from langchain.utilities import WikipediaAPIWrapper
10
- from langchain.tools.python.tool import PythonREPLTool
11
 
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
- # --- GaiaAgent using only OpenAI ---
16
  class GaiaAgent:
17
  def __init__(self, model_name: str = "gpt-4"):
18
- key = os.getenv("OPENAIAPI")
 
19
  if not key:
20
- raise ValueError("Set OPENAIAPI in your Space secrets!")
21
- self.llm = ChatOpenAI(
22
- model_name=model_name,
23
- temperature=0,
24
- openai_api_key=key,
25
- )
26
-
27
- # Python REPL tool for calculations & parsing
28
- python_tool = PythonREPLTool()
29
-
30
- # DuckDuckGo instant answers for basic web search
31
- def web_search(query: str) -> str:
32
- resp = requests.get(
33
- "https://api.duckduckgo.com/",
34
- params={"q": query, "format": "json", "t": "hf_agent"}
35
- )
36
- data = resp.json()
37
- return data.get("AbstractText") or "No instant answer available."
38
- search_tool = Tool(
39
- name="web_search",
40
- func=web_search,
41
- description="Query the web for up‑to‑date information."
42
- )
43
-
44
- # Build agent: zero‑shot React, capped at 4 steps
45
- self.agent = initialize_agent(
46
- tools=[wiki_tool, python_tool, search_tool],
47
- llm=self.llm,
48
- agent="zero-shot-react-description",
49
- verbose=False,
50
- max_iterations=4,
51
- )
52
 
53
  def __call__(self, question: str) -> str:
54
- return self.agent.run(question)
55
-
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  def run_and_submit_all(profile: gr.OAuthProfile | None):
 
 
 
 
58
  if not profile:
59
  return "Please log in to Hugging Face with the button.", None
60
 
@@ -62,84 +45,76 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
62
  space_id = os.getenv("SPACE_ID", "unknown-space")
63
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
64
 
65
- # Instantiate our new agent
66
  try:
67
  agent = GaiaAgent(model_name=os.getenv("OPENAI_MODEL", "gpt-4"))
68
  except Exception as e:
69
  return f"Error initializing GaiaAgent: {e}", None
70
 
71
- # Fetch questions
72
  try:
73
  resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
74
  resp.raise_for_status()
75
- questions_data = resp.json()
76
- if not questions_data:
77
- return "Fetched questions list is empty or invalid.", None
78
  except Exception as e:
79
  return f"Error fetching questions: {e}", None
80
 
81
- # Run agent on each question
82
- results_log = []
83
- answers_payload = []
84
- for item in questions_data:
85
  tid = item.get("task_id")
86
  q = item.get("question")
87
  if not tid or q is None:
88
  continue
89
  try:
90
  ans = agent(q)
91
- except Exception as e:
92
- ans = f"AGENT_ERROR: {e}"
93
- results_log.append({
94
- "Task ID": tid,
95
- "Question": q,
96
- "Submitted Answer": ans
97
- })
98
- answers_payload.append({
99
- "task_id": tid,
100
- "submitted_answer": ans
101
- })
102
 
103
- if not answers_payload:
104
- return "Agent produced no answers.", pd.DataFrame(results_log)
105
 
106
- # Submit
107
  submission = {
108
  "username": username,
109
  "agent_code": agent_code,
110
- "answers": answers_payload
111
  }
112
  try:
113
- resp = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=60)
114
- resp.raise_for_status()
115
- res = resp.json()
116
  status = (
117
  f"✅ Submission Successful!\n"
118
  f"User: {res.get('username')}\n"
119
- f"Score: {res.get('score', 'N/A')}% "
120
- f"({res.get('correct_count', '?')}/"
121
- f"{res.get('total_attempted', '?')} correct)\n"
122
  f"{res.get('message','')}"
123
  )
124
  except Exception as e:
125
  status = f"❌ Submission Failed: {e}"
126
 
127
- return status, pd.DataFrame(results_log)
128
-
129
 
130
- # --- Gradio App ---
131
  with gr.Blocks() as demo:
132
- gr.Markdown("# GAIA Level 1 Agent Evaluation")
133
  gr.Markdown(
134
  """
135
- 1. Make sure `OPENAI_API_KEY` is set in your Space secrets.
136
- 2. Log in with the HF button.
137
- 3. Click **Run Evaluation & Submit All Answers**.
138
  """
139
  )
140
  gr.LoginButton()
141
  run_btn = gr.Button("Run Evaluation & Submit All Answers")
142
- status_out = gr.Textbox(label="Status / Submission Result", lines=5, interactive=False)
143
  results_tbl= gr.DataFrame(label="Questions and Agent Answers", wrap=True)
144
 
145
  run_btn.click(fn=run_and_submit_all, outputs=[status_out, results_tbl])
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
+ import openai
 
 
 
 
 
6
 
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
+ # --- Simple OpenAI‑based Agent ---
11
  class GaiaAgent:
12
  def __init__(self, model_name: str = "gpt-4"):
13
+ # Load your API key (no underscore)
14
+ key = os.getenv("OPENAIAPIKEY")
15
  if not key:
16
+ raise ValueError("Please set OPENAIAPIKEY in your Space secrets!")
17
+ openai.api_key = key
18
+ self.model = model_name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  def __call__(self, question: str) -> str:
21
+ """
22
+ Sends the question to OpenAI and returns the assistant's response.
23
+ """
24
+ prompt = [
25
+ {"role": "system", "content": "You are a helpful assistant answering GAIA Level 1 questions. Be concise and return just the final answer."},
26
+ {"role": "user", "content": question}
27
+ ]
28
+ resp = openai.ChatCompletion.create(
29
+ model=self.model,
30
+ messages=prompt,
31
+ temperature=0.0,
32
+ max_tokens=256,
33
+ )
34
+ return resp.choices[0].message.content.strip()
35
 
36
  def run_and_submit_all(profile: gr.OAuthProfile | None):
37
+ """
38
+ Fetches GAIA questions, runs GaiaAgent on each, submits answers,
39
+ and returns a status message + results DataFrame.
40
+ """
41
  if not profile:
42
  return "Please log in to Hugging Face with the button.", None
43
 
 
45
  space_id = os.getenv("SPACE_ID", "unknown-space")
46
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
47
 
48
+ # Instantiate our OpenAI agent
49
  try:
50
  agent = GaiaAgent(model_name=os.getenv("OPENAI_MODEL", "gpt-4"))
51
  except Exception as e:
52
  return f"Error initializing GaiaAgent: {e}", None
53
 
54
+ # 1) Fetch questions
55
  try:
56
  resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
57
  resp.raise_for_status()
58
+ questions = resp.json()
59
+ if not questions:
60
+ return "Server returned no questions.", None
61
  except Exception as e:
62
  return f"Error fetching questions: {e}", None
63
 
64
+ # 2) Run agent on each question
65
+ results = []
66
+ payload = []
67
+ for item in questions:
68
  tid = item.get("task_id")
69
  q = item.get("question")
70
  if not tid or q is None:
71
  continue
72
  try:
73
  ans = agent(q)
74
+ except Exception as ee:
75
+ ans = f"AGENT_ERROR: {ee}"
76
+ results.append({"Task ID": tid, "Question": q, "Submitted Answer": ans})
77
+ payload.append({"task_id": tid, "submitted_answer": ans})
 
 
 
 
 
 
 
78
 
79
+ if not payload:
80
+ return "Agent produced no answers.", pd.DataFrame(results)
81
 
82
+ # 3) Submit all answers
83
  submission = {
84
  "username": username,
85
  "agent_code": agent_code,
86
+ "answers": payload
87
  }
88
  try:
89
+ post = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=60)
90
+ post.raise_for_status()
91
+ res = post.json()
92
  status = (
93
  f"✅ Submission Successful!\n"
94
  f"User: {res.get('username')}\n"
95
+ f"Score: {res.get('score','N/A')}% "
96
+ f"({res.get('correct_count','?')}/"
97
+ f"{res.get('total_attempted','?')} correct)\n"
98
  f"{res.get('message','')}"
99
  )
100
  except Exception as e:
101
  status = f"❌ Submission Failed: {e}"
102
 
103
+ return status, pd.DataFrame(results)
 
104
 
105
+ # --- Gradio Interface ---
106
  with gr.Blocks() as demo:
107
+ gr.Markdown("# GAIA Level 1 Agent (OpenAI‑only)")
108
  gr.Markdown(
109
  """
110
+ 1. Add your OpenAI key (no underscore) as `OPENAIAPIKEY` in Space secrets.
111
+ 2. (Optional) Override model with `OPENAI_MODEL` (default: `gpt-4`).
112
+ 3. Log in with the button, then click **Run Evaluation & Submit All Answers**.
113
  """
114
  )
115
  gr.LoginButton()
116
  run_btn = gr.Button("Run Evaluation & Submit All Answers")
117
+ status_out = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
118
  results_tbl= gr.DataFrame(label="Questions and Agent Answers", wrap=True)
119
 
120
  run_btn.click(fn=run_and_submit_all, outputs=[status_out, results_tbl])