Freddolin commited on
Commit
c3c803a
·
verified ·
1 Parent(s): 5617dda

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +33 -120
agent.py CHANGED
@@ -1,130 +1,43 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import pandas as pd
5
- from agent import GaiaAgent
6
-
7
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
8
-
9
- def run_and_submit_all(profile: gr.OAuthProfile | None):
10
- space_id = os.getenv("SPACE_ID")
11
-
12
- if profile:
13
- username = f"{profile.username}"
14
- print(f"User logged in: {username}")
15
- else:
16
- print("User not logged in.")
17
- return "Please Login to Hugging Face with the button.", None
18
-
19
- api_url = DEFAULT_API_URL
20
- questions_url = f"{api_url}/questions"
21
- submit_url = f"{api_url}/submit"
22
-
23
- try:
24
- agent = GaiaAgent()
25
- except Exception as e:
26
- return f"Error initializing agent: {e}", None
27
-
28
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
29
-
30
- try:
31
- response = requests.get(questions_url, timeout=15)
32
- response.raise_for_status()
33
- questions_data = response.json()
34
- except Exception as e:
35
- return f"Error fetching questions: {e}", None
36
-
37
- results_log = []
38
- answers_payload = []
39
-
40
- print("\n--- STARTING AGENT RUN ---")
41
- for item in questions_data:
42
- task_id = item.get("task_id")
43
- question_text = item.get("question")
44
- if not task_id or question_text is None:
45
- continue
46
- try:
47
- final_answer, trace = agent(question_text)
48
-
49
- print("\n--- QUESTION ---")
50
- print(f"Task ID: {task_id}")
51
- print(f"Question: {question_text}")
52
- print("\n--- REASONING TRACE ---")
53
- print(trace)
54
- print("\n--- FINAL ANSWER (SUBMITTED) ---")
55
- print(final_answer)
56
-
57
- answers_payload.append({
58
- "task_id": task_id,
59
- "submitted_answer": final_answer,
60
- "reasoning_trace": trace
61
- })
62
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": final_answer})
63
- except Exception as e:
64
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
65
-
66
- if not answers_payload:
67
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
68
-
69
- submission_data = {
70
- "username": username.strip(),
71
- "agent_code": agent_code,
72
- "answers": answers_payload
73
- }
74
-
75
- try:
76
- response = requests.post(submit_url, json=submission_data, timeout=60)
77
- response.raise_for_status()
78
- result_data = response.json()
79
- final_status = (
80
- f"Submission Successful!\n"
81
- f"User: {result_data.get('username')}\n"
82
- f"Overall Score: {result_data.get('score', 'N/A')}% "
83
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
84
- f"Message: {result_data.get('message', 'No message received.')}"
85
  )
86
- results_df = pd.DataFrame(results_log)
87
- return final_status, results_df
88
- except Exception as e:
89
- return f"Submission Failed: {e}", pd.DataFrame(results_log)
90
-
91
-
92
- with gr.Blocks() as demo:
93
- gr.Markdown("# GAIA Agent Submission Interface")
94
- gr.Markdown("""
95
- Logga in och kör agenten.\n
96
- Du behöver INTE en OpenAI API-nyckel längre. Agenten kör en lokal modell.
97
- """)
98
- gr.LoginButton()
99
-
100
- run_button = gr.Button("Run Evaluation & Submit All Answers")
101
- status_output = gr.Textbox(label="Submission Result")
102
- results_table = gr.DataFrame(label="Answers")
103
 
104
- run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
105
 
106
- if __name__ == "__main__":
107
- print("\n" + "-"*30 + " App Starting " + "-"*30)
108
- space_host_startup = os.getenv("SPACE_HOST")
109
- space_id_startup = os.getenv("SPACE_ID")
110
 
111
- if space_host_startup:
112
- print(f" SPACE_HOST found: {space_host_startup}")
113
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
114
- else:
115
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
116
 
117
- if space_id_startup:
118
- print(f" SPACE_ID found: {space_id_startup}")
119
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
120
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
121
- else:
122
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
123
 
124
- print("-"*(60 + len(" App Starting ")) + "\n")
 
 
 
125
 
126
- print("Launching Gradio Interface for Basic Agent Evaluation...")
127
- demo.launch(debug=True, share=False)
128
 
129
 
130
 
 
1
+ from transformers import pipeline
2
+ from tools.asr_tool import transcribe_audio
3
+ from tools.excel_tool import analyze_excel
4
+ from tools.search_tool import search_duckduckgo
5
+ import mimetypes
6
+
7
+
8
+ class GaiaAgent:
9
+ def __init__(self):
10
+ print("Loading model...")
11
+ self.model = pipeline(
12
+ "text2text-generation",
13
+ model="MBZUAI/LaMini-Flan-T5-783M",
14
+ tokenizer="MBZUAI/LaMini-Flan-T5-783M"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  )
16
+ print("Model loaded.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ def __call__(self, query):
19
+ trace = ""
20
+ final_answer = ""
21
 
22
+ # Försök identifiera om det är en filreferens
23
+ if isinstance(query, str) and (query.endswith(".mp3") or query.endswith(".wav")):
24
+ trace = "Detected audio file. Transcribing..."
25
+ final_answer = transcribe_audio(query)
26
 
27
+ elif isinstance(query, str) and (query.endswith(".xls") or query.endswith(".xlsx")):
28
+ trace = "Detected Excel file. Analyzing..."
29
+ final_answer = analyze_excel(query)
 
 
30
 
31
+ elif "http" in query:
32
+ trace = "Detected URL or web reference. Performing search..."
33
+ final_answer = search_duckduckgo(query)
 
 
 
34
 
35
+ else:
36
+ trace = "General question. Using local model..."
37
+ output = self.model(query, max_new_tokens=128)
38
+ final_answer = output[0]["generated_text"].strip()
39
 
40
+ return final_answer, trace
 
41
 
42
 
43