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

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +128 -44
agent.py CHANGED
@@ -1,46 +1,130 @@
1
- import mimetypes
2
- from transformers import pipeline
3
- from tools.asr_tool import transcribe_audio
4
- from tools.excel_tool import analyze_excel
5
- from tools.search_tool import search_duckduckgo
6
-
7
- class GaiaAgent:
8
- def __init__(self):
9
- print("Loading model...")
10
- self.llm = pipeline("text-generation", model="mistralai/Mistral-7B-Instruct-v0.2", max_new_tokens=512, device="cpu")
11
-
12
- def __call__(self, question: str, files: list = None):
13
- trace = []
14
- context = ""
15
-
16
- if files:
17
- for file in files:
18
- mime, _ = mimetypes.guess_type(file.name)
19
- if mime and mime.startswith("audio"):
20
- transcription = transcribe_audio(file.name)
21
- trace.append(f"Transcribed audio: {transcription}")
22
- context += f"\nTranscription: {transcription}"
23
- elif mime and ("spreadsheet" in mime or file.name.endswith(".xlsx")):
24
- result = analyze_excel(file.name)
25
- trace.append(f"Excel analysis: {result}")
26
- context += f"\nSpreadsheet data: {result}"
27
-
28
- if "http" in question or "Wikipedia" in question or "YouTube" in question or "search" in question.lower():
29
- trace.append("Performing DuckDuckGo search...")
30
- search_result = search_duckduckgo(question)
31
- trace.append(f"Summary from search: {search_result}")
32
- context += f"\nSearch Result: {search_result}"
33
-
34
- # Include the original question
35
- prompt = f"""
36
- Answer the question based on the context below.
37
- Context: {context}
38
- Question: {question}
39
- Answer:
40
- """
41
- response = self.llm(prompt)[0]['generated_text'].split("Answer:")[-1].strip()
42
- trace.append(response)
43
-
44
- return response, "\n".join(trace)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
 
 
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