Mtchmann commited on
Commit
44a1c66
·
verified ·
1 Parent(s): fd0abde

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -95
app.py CHANGED
@@ -1,121 +1,171 @@
1
- import os
2
  import gradio as gr
3
  import requests
4
- from huggingface_hub import HfApi
5
- from agent import solve # Import the new OpenAI-based agent solver
 
 
 
 
 
 
 
 
 
 
6
 
7
  # --- Constants ---
8
- GAIA_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
-
10
- MAX_QUESTIONS = 5 # Limit the number of questions to process in a single run
11
 
12
- # --- Helper Function to Fetch Questions ---
13
- def get_all_questions():
14
- """Fetches all available questions from the GAIA API."""
15
- response = requests.get(f"{GAIA_API_URL}/api/questions")
16
- response.raise_for_status()
17
- return response.json()
18
 
19
- # --- Core Application Logic ---
20
- def run_and_submit_all(
21
- profile: gr.OAuthProfile | None):
22
  """
23
- Orchestrates the process of fetching GAIA tasks, running the agent, and submitting results.
24
-
25
- This function now handles:
26
- 1. User authentication via Hugging Face OAuth.
27
- 2. Securely receiving API keys from the UI.
28
- 3. Setting environment variables for the agent at runtime.
29
- 4. Calling the new OpenAI-based agent from `agent.py`.
30
- 5. Submitting results under the authenticated user's name.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  """
32
- # 1. Validate User Login
33
- if profile is None:
34
- yield "### ❌ Error: Please log in with your Hugging Face account first."
35
- return
 
36
 
37
- # 2. **FIX**: Define `username` from the OAuth profile
 
38
  try:
39
- api = HfApi()
40
- hf_user = api.whoami(token=profile.token)
41
- username = hf_user['name']
42
- yield f"### ✅ Authenticated as Hugging Face user: **{username}**"
 
 
43
  except Exception as e:
44
- yield f"### ❌ Error during Hugging Face authentication: {e}"
45
- return
 
 
46
 
 
 
 
 
 
 
47
 
48
- # 5. Fetch and Process Questions
 
49
  try:
50
- yield "### 📥 Fetching questions from GAIA..."
51
- questions = get_all_questions()
52
- tasks = questions.get("questions", [])
53
- if not tasks:
54
- yield "### समाप्त No questions available to process."
55
- return
56
-
57
- yield f"### 🚀 Found {len(tasks)} questions. Starting agent on the first {MAX_QUESTIONS} tasks..."
58
-
59
- for i, task in enumerate(tasks[:MAX_QUESTIONS]):
60
- task_id = task["task_id"]
61
- question = task["Question"]
62
- task_prompt = f"Task ID: {task_id}\nQuestion: {question}"
63
-
64
- yield f"\n\n---"
65
- yield f"### 🧠 **Task {i+1}/{MAX_QUESTIONS}** (ID: {task_id})"
66
- yield f"> **Question:** {question}"
67
- yield "> Running agent..."
68
-
69
- # **INTEGRATION**: Call the new `solve` function from `agent.py`
70
- answer = solve(task_prompt)
71
- yield f"> **Agent's Answer:** {answer}"
72
-
73
- # Submit the answer to the GAIA API
74
- try:
75
- yield f"> Submitting answer for user '{username}'..."
76
- submission_payload = {
77
- "task_id": task_id,
78
- "submitted_answer": answer,
79
- "username": username,
80
- }
81
- response = requests.post(f"{GAIA_API_URL}/api/submit", json=submission_payload)
82
- response.raise_for_status()
83
- yield f"### ✅ **Submission Successful!**"
84
- yield f"> Server response: `{response.json()}`"
85
-
86
- except requests.exceptions.RequestException as e:
87
- yield f"### ❌ **Submission Failed!**"
88
- yield f"> Error submitting answer for task {task_id}: {e}"
89
 
90
- except Exception as e:
91
- yield f"\n### ❌ An unexpected error occurred: {e}"
92
- import traceback
93
- yield f"```\n{traceback.format_exc()}\n```"
94
 
 
95
 
96
- # --- Gradio UI Definition ---
97
- with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
98
- gr.Markdown("# 🏆 GAIA Agent Runner")
99
  gr.Markdown(
100
- "This application runs an AI agent to solve tasks from the GAIA (General AI Assistants) benchmark. "
101
- "Log in with your Hugging Face account and provide your API keys to begin."
 
 
 
 
 
 
102
  )
103
 
104
- with gr.Row():
105
- login_button = gr.LoginButton(value="Login with Hugging Face 🤗")
106
- run_button = gr.Button("Run and Submit All Tasks", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
107
 
 
108
 
109
- gr.Markdown("---")
110
- gr.Markdown("### 📝 Live Output")
111
- output_textbox = gr.Markdown(value="> Waiting to start...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
- # Connect the "Run" button to the main logic function
114
- run_button.click(
115
- fn=run_and_submit_all,
116
- inputs=[question],
117
- outputs=[output_textbox],
118
  )
119
 
120
  if __name__ == "__main__":
121
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import requests
3
+ import os
4
+ import traceback
5
+
6
+ # --- Agent Integration ---
7
+ # We import the 'solve' function from our agent.py file.
8
+ # This keeps the agent's complex logic separate from the UI code.
9
+ try:
10
+ from agent import solve
11
+ except ImportError:
12
+ # Provide a dummy function if agent.py is missing, so the UI can still launch.
13
+ def solve(task: str) -> str:
14
+ return "Error: `agent.py` not found. Please ensure it is in the same directory."
15
 
16
  # --- Constants ---
17
+ GAIA_API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
18
 
19
+ # --- API Interaction Functions ---
 
 
 
 
 
20
 
21
+ def get_question():
 
 
22
  """
23
+ Fetches a single question from the GAIA API's /level1 endpoint.
24
+ Updates the UI with the question text and stores the task_id in a state variable.
25
+ """
26
+ try:
27
+ status_update = "Fetching question from GAIA API..."
28
+ print(status_update)
29
+ response = requests.get(f"{GAIA_API_BASE_URL}/level1")
30
+ response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
31
+ task_data = response.json()
32
+
33
+ question_id = task_data.get("task_id")
34
+ question = task_data.get("question")
35
+
36
+ if not question_id or not question:
37
+ error_msg = "API response did not contain 'task_id' or 'question'."
38
+ print(f"ERROR: {error_msg}")
39
+ return "", None, error_msg
40
+
41
+ success_msg = "Question fetched successfully."
42
+ print(f"Received Task (ID: {question_id})")
43
+ # Return values to update: question_box, question_id_state, status_box
44
+ return question, question_id, success_msg
45
+
46
+ except requests.exceptions.RequestException as e:
47
+ error_msg = f"Error fetching task: {e}"
48
+ print(f"ERROR: {error_msg}")
49
+ return "", None, error_msg
50
+
51
+
52
+ def run_agent(question_text: str):
53
  """
54
+ Takes the question text from the UI, runs the agent, and updates the UI
55
+ with the agent's answer.
56
+ """
57
+ if not question_text:
58
+ return "", "", "Cannot run agent: please get a question first."
59
 
60
+ status_update = "Invoking agent..."
61
+ print(status_update)
62
  try:
63
+ # The 'solve' function from agent.py is called here.
64
+ # It internally handles API key validation and its own execution logic.
65
+ answer = solve(question_text)
66
+ print(f"Agent generated answer: {answer}")
67
+ # Return values to update: answer_box, answer_state, status_box
68
+ return answer, answer, "Agent run complete."
69
  except Exception as e:
70
+ error_msg = f"An unexpected error occurred during agent execution: {e}"
71
+ print(f"ERROR: {error_msg}\n{traceback.format_exc()}")
72
+ return "", "", error_msg
73
+
74
 
75
+ def submit_answer(question_id: str, answer: str):
76
+ """
77
+ Submits the agent's answer for the current question_id to the GAIA API.
78
+ """
79
+ if not question_id or answer is None:
80
+ return "Cannot submit: missing Task ID or Answer. Please complete all previous steps."
81
 
82
+ status_update = f"Submitting answer for task {question_id}..."
83
+ print(status_update)
84
  try:
85
+ payload = {"task_id": question_id, "answer": answer}
86
+ response = requests.post(f"{GAIA_API_BASE_URL}/level1", json=payload)
87
+ response.raise_for_status()
88
+
89
+ result = response.json()
90
+ success_msg = f"✅ Submission Successful! Server response: {result}"
91
+ print(success_msg)
92
+ return success_msg
93
+
94
+ except requests.exceptions.RequestException as e:
95
+ error_detail = e.response.text if e.response else str(e)
96
+ error_msg = f"❌ Submission Failed: {error_detail}"
97
+ print(f"ERROR: {error_msg}")
98
+ return error_msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
 
 
 
 
100
 
101
+ # --- Gradio Interface Definition ---
102
 
103
+ with gr.Blocks() as demo:
104
+ gr.Markdown("# GAIA Level 1 Interactive Agent Runner")
 
105
  gr.Markdown(
106
+ """
107
+ **Instructions:**
108
+ 1. Ensure your `OPENAI_API_KEY` and `TAVILY_API_KEY` are set as environment variables in your Hugging Face Space secrets.
109
+ 2. Click **Get Question** to fetch a new task from the GAIA API.
110
+ 3. Click **Run Agent** to process the question. The agent's answer will appear below.
111
+ 4. Review the answer. You can edit it in the textbox if needed.
112
+ 5. Click **Submit Answer** to send your final answer to the scoring server.
113
+ """
114
  )
115
 
116
+ # State variables to hold data between interactions
117
+ question_id_state = gr.State(value=None)
118
+ answer_state = gr.State(value=None)
119
+
120
+ with gr.Column():
121
+ status_box = gr.Textbox(label="Status", interactive=False, lines=2)
122
+
123
+ with gr.Row():
124
+ get_question_btn = gr.Button("1. Get Question")
125
+ run_agent_btn = gr.Button("2. Run Agent")
126
+ submit_answer_btn = gr.Button("3. Submit Answer")
127
+
128
+ question_box = gr.Textbox(label="Question from GAIA", interactive=False, lines=4)
129
+ answer_box = gr.Textbox(label="Agent's Answer", interactive=True, lines=8)
130
 
131
+ # --- Button Click Handlers ---
132
 
133
+ # 1. Get Question Button
134
+ get_question_btn.click(
135
+ fn=get_question,
136
+ inputs=[],
137
+ outputs=[question_box, question_id_state, status_box]
138
+ )
139
+
140
+ # 2. Run Agent Button
141
+ run_agent_btn.click(
142
+ fn=run_agent,
143
+ inputs=[question_box],
144
+ outputs=[answer_box, answer_state, status_box]
145
+ )
146
+
147
+ # Allow user edits to the answer_box to update the answer_state
148
+ answer_box.change(
149
+ fn=lambda x: x,
150
+ inputs=[answer_box],
151
+ outputs=[answer_state]
152
+ )
153
 
154
+ # 3. Submit Answer Button
155
+ submit_answer_btn.click(
156
+ fn=submit_answer,
157
+ inputs=[question_id_state, answer_state],
158
+ outputs=[status_box]
159
  )
160
 
161
  if __name__ == "__main__":
162
+ # Startup check for required API keys
163
+ print("### 🚀 Starting GAIA Level 1 Gradio App ###")
164
+ if not os.environ.get("OPENAI_API_KEY") or not os.environ.get("TAVILY_API_KEY"):
165
+ print("\nWARNING: `OPENAI_API_KEY` and/or `TAVILY_API_KEY` are not set.")
166
+ print("The agent will fail if these are not configured in your environment (e.g., HF Space Secrets).\n")
167
+ else:
168
+ print("\n✅ `OPENAI_API_KEY` and `TAVILY_API_KEY` found.\n")
169
+
170
+ print("Launching Gradio Interface...")
171
+ demo.launch(debug=True, share=False)