Update app.py
Browse files
app.py
CHANGED
@@ -1,178 +1,202 @@
|
|
1 |
-
"""
|
2 |
-
Простой агент для Agent Challenge с использованием Gradio и Mixtral
|
3 |
-
"""
|
4 |
-
|
5 |
import os
|
6 |
-
import re
|
7 |
-
import math
|
8 |
-
import json
|
9 |
import gradio as gr
|
10 |
-
|
|
|
|
|
|
|
|
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
-
# или передан через Secrets в Hugging Face Spaces
|
15 |
-
HF_TOKEN = os.environ.get("HF_TOKEN")
|
16 |
|
17 |
-
#
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
-
|
30 |
-
|
|
|
|
|
|
|
31 |
try:
|
32 |
-
|
33 |
-
allowed_names = {k: v for k, v in math.__dict__.items() if not k.startswith("__")}
|
34 |
-
allowed_names["abs"] = abs
|
35 |
-
allowed_names["round"] = round
|
36 |
-
allowed_names["max"] = max
|
37 |
-
allowed_names["min"] = min
|
38 |
-
|
39 |
-
# Удаление потенциально опасных символов
|
40 |
-
safe_expression = re.sub(r"[^0-9\.\+\-\*\/\(\)\s]|\b(import|exec|eval|open|lambda|\_\_)\b", "", expression)
|
41 |
-
|
42 |
-
if safe_expression != expression:
|
43 |
-
return "Ошибка: Обнаружены недопустимые символы в выражении."
|
44 |
-
|
45 |
-
result = eval(safe_expression, {"__builtins__": {}}, allowed_names)
|
46 |
-
return f"Результат: {result}"
|
47 |
except Exception as e:
|
48 |
-
|
|
|
49 |
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
if "погода" in query.lower():
|
54 |
-
return "В городе, который вы ищете, сегодня солнечно, +25C."
|
55 |
-
elif "hugging face" in query.lower():
|
56 |
-
return "Hugging Face - это платформа и сообщество для работы с моделями машинного обучения."
|
57 |
-
elif "python" in query.lower():
|
58 |
-
return "Python - высокоуровневый язык программирования общего назначения, созданный Гвидо ван Россумом."
|
59 |
-
else:
|
60 |
-
return f"По вашему запросу '{query}' найдена общая информация."
|
61 |
|
62 |
-
#
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
-
|
69 |
-
tools
|
70 |
-
|
71 |
-
|
72 |
-
"function": {
|
73 |
-
"name": "calculator",
|
74 |
-
"description": "Выполняет математические вычисления",
|
75 |
-
"parameters": {
|
76 |
-
"type": "object",
|
77 |
-
"properties": {
|
78 |
-
"expression": {
|
79 |
-
"type": "string",
|
80 |
-
"description": "Математическое выражение для вычисления"
|
81 |
-
}
|
82 |
-
},
|
83 |
-
"required": ["expression"]
|
84 |
-
}
|
85 |
-
}
|
86 |
-
},
|
87 |
-
{
|
88 |
-
"type": "function",
|
89 |
-
"function": {
|
90 |
-
"name": "web_search",
|
91 |
-
"description": "Ищет информацию в интернете",
|
92 |
-
"parameters": {
|
93 |
-
"type": "object",
|
94 |
-
"properties": {
|
95 |
-
"query": {
|
96 |
-
"type": "string",
|
97 |
-
"description": "Поисковый запрос"
|
98 |
-
}
|
99 |
-
},
|
100 |
-
"required": ["query"]
|
101 |
-
}
|
102 |
-
}
|
103 |
-
}
|
104 |
-
]
|
105 |
|
106 |
-
|
107 |
-
messages = [{"role": "user", "content": query}]
|
108 |
|
109 |
-
|
110 |
-
max_iterations = 5
|
111 |
|
112 |
-
|
113 |
-
|
114 |
-
response = client.chat_completion(
|
115 |
-
messages=messages,
|
116 |
-
tools=tools,
|
117 |
-
tool_choice="auto",
|
118 |
-
temperature=0.1,
|
119 |
-
max_tokens=1024
|
120 |
-
)
|
121 |
-
|
122 |
-
# Получение ответа модели
|
123 |
-
assistant_message = response["choices"][0]["message"]
|
124 |
-
messages.append(assistant_message)
|
125 |
-
|
126 |
-
# Проверка на наличие вызовов инструментов
|
127 |
-
if "tool_calls" in assistant_message and assistant_message["tool_calls"]:
|
128 |
-
for tool_call in assistant_message["tool_calls"]:
|
129 |
-
# Получение имени и аргументов инструмента
|
130 |
-
function_name = tool_call["function"]["name"]
|
131 |
-
function_args = json.loads(tool_call["function"]["arguments"])
|
132 |
-
|
133 |
-
# Вызов соответствующего инструмента
|
134 |
-
if function_name == "calculator":
|
135 |
-
result = calculator(function_args["expression"])
|
136 |
-
elif function_name == "web_search":
|
137 |
-
result = web_search(function_args["query"])
|
138 |
-
else:
|
139 |
-
result = f"Инструмент {function_name} не найден."
|
140 |
-
|
141 |
-
# Добавление результата в сообщения
|
142 |
-
messages.append({
|
143 |
-
"role": "tool",
|
144 |
-
"tool_call_id": tool_call["id"],
|
145 |
-
"name": function_name,
|
146 |
-
"content": result
|
147 |
-
})
|
148 |
-
else:
|
149 |
-
# Если нет вызовов инструментов, возвращаем ответ
|
150 |
-
return assistant_message["content"]
|
151 |
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
# --- Создание Gradio интерфейса ---
|
156 |
-
def gradio_interface(query):
|
157 |
-
"""Обработчик для Gradio интерфейса."""
|
158 |
-
if not query.strip():
|
159 |
-
return "Пожалуйста, введите вопрос."
|
160 |
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
# Создание интерфейса
|
168 |
-
demo = gr.Interface(
|
169 |
-
fn=gradio_interface,
|
170 |
-
inputs=gr.Textbox(lines=2, placeholder="Введите ваш вопрос здесь..."),
|
171 |
-
outputs="text",
|
172 |
-
title="Agent Challenge - Финальный агент",
|
173 |
-
description="Этот агент может отвечать на вопросы, выполнять математические вычисления и искать информацию."
|
174 |
-
)
|
175 |
|
176 |
-
# Запуск интерфейса
|
177 |
if __name__ == "__main__":
|
178 |
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
|
|
|
|
|
|
2 |
import gradio as gr
|
3 |
+
import requests
|
4 |
+
import pandas as pd
|
5 |
+
import json
|
6 |
+
import re
|
7 |
+
from typing import List, Dict, Any, Optional
|
8 |
|
9 |
+
# --- Constants ---
|
10 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
|
11 |
|
12 |
+
# --- Simple GAIA Agent Definition ---
|
13 |
+
class SimpleGAIAAgent:
|
14 |
+
def __init__(self):
|
15 |
+
print("SimpleGAIAAgent initialized.")
|
16 |
+
|
17 |
+
def __call__(self, question: str) -> str:
|
18 |
+
"""Main method to process questions and generate answers"""
|
19 |
+
print(f"Agent received question: {question}")
|
20 |
+
|
21 |
+
# Basic question analysis
|
22 |
+
question_lower = question.lower()
|
23 |
+
|
24 |
+
# Handle calculation questions
|
25 |
+
if any(keyword in question_lower for keyword in ["calculate", "compute", "sum", "difference", "product", "divide"]):
|
26 |
+
# Extract numbers
|
27 |
+
numbers = re.findall(r'\d+', question)
|
28 |
+
if len(numbers) >= 2:
|
29 |
+
if "sum" in question_lower or "add" in question_lower or "plus" in question_lower:
|
30 |
+
result = sum(int(num) for num in numbers)
|
31 |
+
return f"The sum of the numbers is {result}"
|
32 |
+
elif "difference" in question_lower or "subtract" in question_lower or "minus" in question_lower:
|
33 |
+
result = int(numbers[0]) - int(numbers[1])
|
34 |
+
return f"The difference between {numbers[0]} and {numbers[1]} is {result}"
|
35 |
+
elif "product" in question_lower or "multiply" in question_lower:
|
36 |
+
result = int(numbers[0]) * int(numbers[1])
|
37 |
+
return f"The product of {numbers[0]} and {numbers[1]} is {result}"
|
38 |
+
elif "divide" in question_lower:
|
39 |
+
if int(numbers[1]) != 0:
|
40 |
+
result = int(numbers[0]) / int(numbers[1])
|
41 |
+
return f"The result of dividing {numbers[0]} by {numbers[1]} is {result}"
|
42 |
+
else:
|
43 |
+
return "Cannot divide by zero"
|
44 |
+
return "I'll calculate this for you: " + question
|
45 |
+
|
46 |
+
# Handle image analysis questions
|
47 |
+
elif any(keyword in question_lower for keyword in ["image", "picture", "photo", "graph", "chart"]):
|
48 |
+
return "Based on the image, I can see several key elements that help answer your question. The main subject appears to be [description] which indicates [answer]."
|
49 |
+
|
50 |
+
# Handle factual questions
|
51 |
+
elif any(keyword in question_lower for keyword in ["who", "what", "where", "when", "why", "how"]):
|
52 |
+
if "who" in question_lower:
|
53 |
+
return "The person involved is a notable figure in this field with significant contributions and achievements."
|
54 |
+
elif "when" in question_lower:
|
55 |
+
return "This occurred during a significant historical period, specifically in the early part of the relevant era."
|
56 |
+
elif "where" in question_lower:
|
57 |
+
return "The location is in a region known for its historical and cultural significance."
|
58 |
+
elif "what" in question_lower:
|
59 |
+
return "This refers to an important concept or entity that has several key characteristics and functions."
|
60 |
+
elif "why" in question_lower:
|
61 |
+
return "This happened due to a combination of factors including historical context, individual decisions, and broader societal trends."
|
62 |
+
elif "how" in question_lower:
|
63 |
+
return "The process involves several key steps that must be followed in sequence to achieve the desired outcome."
|
64 |
+
|
65 |
+
# General knowledge questions
|
66 |
+
else:
|
67 |
+
return "Based on my analysis, the answer to your question involves several important factors. First, we need to consider the context and specific details mentioned. Taking all available information into account, the most accurate response would be a comprehensive explanation that addresses all aspects of your query."
|
68 |
|
69 |
+
# FIXED FUNCTION: Added *args to handle extra arguments from Gradio
|
70 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None, *args):
|
71 |
+
"""
|
72 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers, and displays the results.
|
73 |
+
"""
|
74 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
75 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
76 |
+
if profile:
|
77 |
+
username= f"{profile.username}"
|
78 |
+
print(f"User logged in: {username}")
|
79 |
+
else:
|
80 |
+
print("User not logged in.")
|
81 |
+
return "Please Login to Hugging Face with the button.", None
|
82 |
|
83 |
+
api_url = DEFAULT_API_URL
|
84 |
+
questions_url = f"{api_url}/questions"
|
85 |
+
submit_url = f"{api_url}/submit"
|
86 |
+
|
87 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
88 |
try:
|
89 |
+
agent = SimpleGAIAAgent()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
except Exception as e:
|
91 |
+
print(f"Error instantiating agent: {e}")
|
92 |
+
return f"Error initializing agent: {e}", None
|
93 |
|
94 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
95 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
96 |
+
print(agent_code)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
+
# 2. Fetch Questions
|
99 |
+
print(f"Fetching questions from: {questions_url}")
|
100 |
+
try:
|
101 |
+
response = requests.get(questions_url, timeout=15)
|
102 |
+
response.raise_for_status()
|
103 |
+
questions_data = response.json()
|
104 |
+
if not questions_data:
|
105 |
+
print("Fetched questions list is empty.")
|
106 |
+
return "Fetched questions list is empty or invalid format.", None
|
107 |
+
print(f"Fetched {len(questions_data)} questions.")
|
108 |
+
except requests.exceptions.RequestException as e:
|
109 |
+
print(f"Error fetching questions: {e}")
|
110 |
+
return f"Error fetching questions: {e}", None
|
111 |
+
except requests.exceptions.JSONDecodeError as e:
|
112 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
113 |
+
print(f"Response text: {response.text[:500]}")
|
114 |
+
return f"Error decoding server response for questions: {e}", None
|
115 |
+
except Exception as e:
|
116 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
117 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
118 |
+
|
119 |
+
# 3. Run your Agent
|
120 |
+
results_log = []
|
121 |
+
answers_payload = []
|
122 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
123 |
+
for item in questions_data:
|
124 |
+
task_id = item.get("task_id")
|
125 |
+
question_text = item.get("question")
|
126 |
+
if not task_id or question_text is None:
|
127 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
128 |
+
continue
|
129 |
+
|
130 |
+
try:
|
131 |
+
submitted_answer = agent(question_text)
|
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 |
+
except Exception as e:
|
135 |
+
print(f"Error running agent on task {task_id}: {e}")
|
136 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
137 |
+
|
138 |
+
if not answers_payload:
|
139 |
+
print("Agent did not produce any answers to submit.")
|
140 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
141 |
+
|
142 |
+
# 4. Prepare Submission
|
143 |
+
submission_data = {
|
144 |
+
"username": username.strip(),
|
145 |
+
"agent_code": agent_code,
|
146 |
+
"answers": answers_payload
|
147 |
+
}
|
148 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
149 |
+
print(status_update)
|
150 |
+
|
151 |
+
# 5. Submit
|
152 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
153 |
+
try:
|
154 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
155 |
+
response.raise_for_status()
|
156 |
+
result_data = response.json()
|
157 |
+
final_status = (
|
158 |
+
f"Submission Successful!\n"
|
159 |
+
f"User: {result_data.get('username')}\n"
|
160 |
+
f"Overall Score: {result_data.get('overall_score', 'N/A')}\n"
|
161 |
+
f"Correct Answers: {result_data.get('correct_answers', 'N/A')}\n"
|
162 |
+
f"Total Questions: {result_data.get('total_questions', 'N/A')}\n"
|
163 |
+
)
|
164 |
+
print(final_status)
|
165 |
+
return final_status, pd.DataFrame(results_log)
|
166 |
+
except requests.exceptions.RequestException as e:
|
167 |
+
error_msg = f"Error submitting answers: {e}"
|
168 |
+
print(error_msg)
|
169 |
+
return error_msg, pd.DataFrame(results_log)
|
170 |
+
except Exception as e:
|
171 |
+
error_msg = f"An unexpected error occurred during submission: {e}"
|
172 |
+
print(error_msg)
|
173 |
+
return error_msg, pd.DataFrame(results_log)
|
174 |
+
|
175 |
+
# --- Gradio Interface ---
|
176 |
+
with gr.Blocks() as demo:
|
177 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
178 |
|
179 |
+
gr.Markdown("Instructions:")
|
180 |
+
gr.Markdown("1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...")
|
181 |
+
gr.Markdown("2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.")
|
182 |
+
gr.Markdown("3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
183 |
|
184 |
+
gr.Markdown("---")
|
|
|
185 |
|
186 |
+
gr.Markdown("Disclaimers: 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). This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.")
|
|
|
187 |
|
188 |
+
with gr.Row():
|
189 |
+
login_button = gr.LoginButton(value="Sign in with Hugging Face")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
190 |
|
191 |
+
with gr.Row():
|
192 |
+
submit_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
|
|
|
|
|
|
|
|
|
|
193 |
|
194 |
+
with gr.Row():
|
195 |
+
with gr.Column():
|
196 |
+
output_status = gr.Textbox(label="Run Status / Submission Result")
|
197 |
+
output_results = gr.Dataframe(label="Questions and Agent Answers")
|
198 |
+
|
199 |
+
submit_button.click(run_and_submit_all, inputs=[login_button], outputs=[output_status, output_results])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
200 |
|
|
|
201 |
if __name__ == "__main__":
|
202 |
demo.launch()
|