mdicio commited on
Commit
2525daf
·
0 Parent(s):

Refreshing Git repository and reconnecting to remote

Browse files
Files changed (9) hide show
  1. .gitattributes +39 -0
  2. .gitignore +4 -0
  3. README.md +15 -0
  4. agent.py +207 -0
  5. app.py +201 -0
  6. app_template.py +196 -0
  7. metadata.jsonl +0 -0
  8. requirements.txt +19 -0
  9. setup_actions.ipynb +415 -0
.gitattributes ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ chroma_store/*.sqlite3 filter=lfs diff=lfs merge=lfs -text
37
+ chroma_store/*.bin filter=lfs diff=lfs merge=lfs -text
38
+ chroma_store/chroma.sqlite3 !text !filter !merge !diff
39
+ chroma_store/fd03f165-2d41-469b-9c52-3a598fb45f9a/*.bin !text !filter !merge !diff
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ .env
2
+ ragdata/
3
+ chroma_store
4
+ .python-version
README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Template Final Assignment
3
+ emoji: 🕵🏻‍♂️
4
+ colorFrom: indigo
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 5.25.2
8
+ app_file: app.py
9
+ pinned: false
10
+ hf_oauth: true
11
+ # optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
12
+ hf_oauth_expiration_minutes: 480
13
+ ---
14
+
15
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
agent.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from langgraph.graph import START, StateGraph, MessagesState
4
+ from langgraph.prebuilt import tools_condition
5
+ from langgraph.prebuilt import ToolNode
6
+ from langchain_google_genai import ChatGoogleGenerativeAI
7
+ from langchain_groq import ChatGroq
8
+ from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings
9
+ from langchain_community.tools.tavily_search import TavilySearchResults
10
+ from langchain_community.document_loaders import WikipediaLoader
11
+ from langchain_community.document_loaders import ArxivLoader
12
+ from langchain_community.vectorstores import SupabaseVectorStore
13
+ from langchain_core.messages import SystemMessage, HumanMessage
14
+ from langchain_core.tools import tool
15
+ from langchain.tools.retriever import create_retriever_tool
16
+ from langchain_community.vectorstores import Chroma
17
+ from langchain.embeddings import HuggingFaceEmbeddings
18
+ from langchain.tools.retriever import create_retriever_tool
19
+ import os
20
+ import json
21
+ from datasets import load_dataset
22
+ from langchain.embeddings import HuggingFaceEmbeddings
23
+ from langchain.vectorstores import Chroma
24
+ from langchain.schema import Document
25
+
26
+ load_dotenv()
27
+
28
+ @tool
29
+ def calculator(query: str) -> str:
30
+ """Perform basic arithmetic operations based on the provided query.
31
+
32
+ Args:
33
+ query: A mathematical query as a string, e.g., '2 + 2' or '5 * 6'."""
34
+
35
+ try:
36
+ # Evaluate the mathematical expression
37
+ result = eval(query)
38
+ return {"calculator_result": str(result)}
39
+ except Exception as e:
40
+ return {"error": f"Error evaluating the expression: {str(e)}"}
41
+
42
+
43
+ @tool
44
+ def wiki_search(query: str) -> str:
45
+ """Search Wikipedia for a query and return maximum 2 results.
46
+
47
+ Args:
48
+ query: The search query."""
49
+ search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
50
+ formatted_search_docs = "\n\n---\n\n".join(
51
+ [
52
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
53
+ for doc in search_docs
54
+ ])
55
+ return {"wiki_results": formatted_search_docs}
56
+
57
+ @tool
58
+ def web_search(query: str) -> str:
59
+ """Search Tavily for a query and return maximum 3 results.
60
+
61
+ Args:
62
+ query: The search query."""
63
+ search_docs = TavilySearchResults(max_results=3).invoke(query=query)
64
+ formatted_search_docs = "\n\n---\n\n".join(
65
+ [
66
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
67
+ for doc in search_docs
68
+ ])
69
+ return {"web_results": formatted_search_docs}
70
+
71
+ @tool
72
+ def arvix_search(query: str) -> str:
73
+ """Search Arxiv for a query and return maximum 3 result.
74
+
75
+ Args:
76
+ query: The search query."""
77
+ search_docs = ArxivLoader(query=query, load_max_docs=3).load()
78
+ formatted_search_docs = "\n\n---\n\n".join(
79
+ [
80
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
81
+ for doc in search_docs
82
+ ])
83
+ return {"arvix_results": formatted_search_docs}
84
+
85
+ system_prompt = """You are a helpful assistant tasked with answering questions using a set of tools.
86
+ Now, I will ask you a question. Report your thoughts, and finish your answer with the following template:
87
+ FINAL ANSWER: [YOUR FINAL ANSWER].
88
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
89
+ Your answer should only start with "FINAL ANSWER: ", then follows with the answer. """
90
+
91
+ # System message
92
+ sys_msg = SystemMessage(content=system_prompt)
93
+
94
+ # build a retriever
95
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # dim=768
96
+
97
+ # Load the GAIA validation dataset
98
+ dataset = load_dataset("gaia-benchmark/GAIA", name="2023_level1", split="validation")
99
+
100
+ # Prepare the embeddings model
101
+ embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
102
+
103
+ # Extract questions and their answers
104
+ documents = []
105
+ for entry in dataset:
106
+ question = entry["Question"]
107
+ answer = entry["Final answer"]
108
+
109
+ # Create a document with both the question and the answer as metadata
110
+ metadata = {
111
+ "task_id": entry["task_id"],
112
+ "steps": entry["Annotator Metadata"]["Steps"],
113
+ "tools": entry["Annotator Metadata"]["Tools"],
114
+ "answer": answer
115
+ }
116
+
117
+ # Add the question to the list of documents
118
+ documents.append(
119
+ Document(
120
+ page_content=question,
121
+ metadata=metadata
122
+ )
123
+ )
124
+
125
+ # Insert the documents into Chroma
126
+ vectorstore = Chroma.from_documents(
127
+ documents=documents,
128
+ embedding=embeddings,
129
+ collection_name="gaia_validation",
130
+ persist_directory="./chroma_store"
131
+ )
132
+
133
+ create_retriever_tool = create_retriever_tool(
134
+ retriever=vectorstore.as_retriever(),
135
+ name="Question Search",
136
+ description="A tool to retrieve similar questions from a vector store.",
137
+ )
138
+
139
+
140
+ tools = [
141
+ calculator,
142
+ wiki_search,
143
+ web_search,
144
+ arvix_search,
145
+ ]
146
+
147
+ # Build graph function
148
+ def build_graph(provider: str = "groq"):
149
+ """Build the graph"""
150
+ # Load environment variables from .env file
151
+ if provider == "google":
152
+ # Google Gemini
153
+ llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
154
+ elif provider == "groq":
155
+ # Groq https://console.groq.com/docs/models
156
+ llm = ChatGroq(model="qwen-qwq-32b", temperature=0) # optional : qwen-qwq-32b gemma2-9b-it
157
+ elif provider == "huggingface":
158
+ # TODO: Add huggingface endpoint
159
+ llm = ChatHuggingFace(
160
+ llm=HuggingFaceEndpoint(
161
+ url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
162
+ temperature=0,
163
+ ),
164
+ )
165
+ else:
166
+ raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
167
+ # Bind tools to LLM
168
+ llm_with_tools = llm.bind_tools(tools)
169
+
170
+ # Node
171
+ def assistant(state: MessagesState):
172
+ """Assistant node"""
173
+ return {"messages": [llm_with_tools.invoke(state["messages"])]}
174
+
175
+ def retriever(state: MessagesState):
176
+ """Retriever node"""
177
+ similar_question = vectorstore.similarity_search(state["messages"][0].content)
178
+ example_msg = HumanMessage(
179
+ content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}",
180
+ )
181
+ return {"messages": [sys_msg] + state["messages"] + [example_msg]}
182
+
183
+ builder = StateGraph(MessagesState)
184
+ builder.add_node("retriever", retriever)
185
+ builder.add_node("assistant", assistant)
186
+ builder.add_node("tools", ToolNode(tools))
187
+ builder.add_edge(START, "retriever")
188
+ builder.add_edge("retriever", "assistant")
189
+ builder.add_conditional_edges(
190
+ "assistant",
191
+ tools_condition,
192
+ )
193
+ builder.add_edge("tools", "assistant")
194
+
195
+ # Compile graph
196
+ return builder.compile()
197
+
198
+ # test
199
+ if __name__ == "__main__":
200
+ question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
201
+ # Build the graph
202
+ graph = build_graph(provider="groq")
203
+ # Run the graph
204
+ messages = [HumanMessage(content=question)]
205
+ messages = graph.invoke({"messages": messages})
206
+ for m in messages["messages"]:
207
+ m.pretty_print()
app.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import os
3
+ import gradio as gr
4
+ import requests
5
+ import pandas as pd
6
+ from langchain_core.messages import HumanMessage
7
+ from agent import build_graph
8
+
9
+
10
+ # (Keep Constants as is)
11
+ # --- Constants ---
12
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
+
14
+ # --- Basic Agent Definition ---
15
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
16
+ class BasicAgent:
17
+ def __init__(self):
18
+ self.graph = build_graph()
19
+ print("✅ Agent initialized.")
20
+
21
+ def __call__(self, question: str) -> str:
22
+ print(f"📨 Received question: {question[:60]}...")
23
+ messages = [HumanMessage(content=question)]
24
+ result = self.graph.invoke({"messages": messages})
25
+ return result["messages"][-1].content # Simplify if needed
26
+
27
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
28
+ """
29
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
30
+ and displays the results.
31
+ """
32
+ # --- Determine HF Space Runtime URL and Repo URL ---
33
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
34
+
35
+ if profile:
36
+ username= f"{profile.username}"
37
+ print(f"User logged in: {username}")
38
+ else:
39
+ print("User not logged in.")
40
+ return "Please Login to Hugging Face with the button.", None
41
+
42
+ api_url = DEFAULT_API_URL
43
+ questions_url = f"{api_url}/questions"
44
+ submit_url = f"{api_url}/submit"
45
+
46
+ # 1. Instantiate Agent ( modify this part to create your agent)
47
+ try:
48
+ agent = BasicAgent()
49
+ except Exception as e:
50
+ print(f"Error instantiating agent: {e}")
51
+ return f"Error initializing agent: {e}", None
52
+ # 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)
53
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
54
+ print(agent_code)
55
+
56
+ # 2. Fetch Questions
57
+ print(f"Fetching questions from: {questions_url}")
58
+ try:
59
+ response = requests.get(questions_url, timeout=15)
60
+ response.raise_for_status()
61
+ questions_data = response.json()
62
+ if not questions_data:
63
+ print("Fetched questions list is empty.")
64
+ return "Fetched questions list is empty or invalid format.", None
65
+ print(f"Fetched {len(questions_data)} questions.")
66
+ except requests.exceptions.RequestException as e:
67
+ print(f"Error fetching questions: {e}")
68
+ return f"Error fetching questions: {e}", None
69
+ except requests.exceptions.JSONDecodeError as e:
70
+ print(f"Error decoding JSON response from questions endpoint: {e}")
71
+ print(f"Response text: {response.text[:500]}")
72
+ return f"Error decoding server response for questions: {e}", None
73
+ except Exception as e:
74
+ print(f"An unexpected error occurred fetching questions: {e}")
75
+ return f"An unexpected error occurred fetching questions: {e}", None
76
+
77
+ # 3. Run your Agent
78
+ results_log = []
79
+ answers_payload = []
80
+ print(f"Running agent on {len(questions_data)} questions...")
81
+ for item in questions_data:
82
+ task_id = item.get("task_id")
83
+ question_text = item.get("question")
84
+ if not task_id or question_text is None:
85
+ print(f"Skipping item with missing task_id or question: {item}")
86
+ continue
87
+ try:
88
+ submitted_answer = agent(question_text)
89
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
90
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
91
+ except Exception as e:
92
+ print(f"Error running agent on task {task_id}: {e}")
93
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
94
+
95
+ if not answers_payload:
96
+ print("Agent did not produce any answers to submit.")
97
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
98
+
99
+ # 4. Prepare Submission
100
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
101
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
102
+ print(status_update)
103
+
104
+ # 5. Submit
105
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
106
+ try:
107
+ response = requests.post(submit_url, json=submission_data, timeout=60)
108
+ response.raise_for_status()
109
+ result_data = response.json()
110
+ final_status = (
111
+ f"Submission Successful!\n"
112
+ f"User: {result_data.get('username')}\n"
113
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
114
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
115
+ f"Message: {result_data.get('message', 'No message received.')}"
116
+ )
117
+ print("Submission successful.")
118
+ results_df = pd.DataFrame(results_log)
119
+ return final_status, results_df
120
+ except requests.exceptions.HTTPError as e:
121
+ error_detail = f"Server responded with status {e.response.status_code}."
122
+ try:
123
+ error_json = e.response.json()
124
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
125
+ except requests.exceptions.JSONDecodeError:
126
+ error_detail += f" Response: {e.response.text[:500]}"
127
+ status_message = f"Submission Failed: {error_detail}"
128
+ print(status_message)
129
+ results_df = pd.DataFrame(results_log)
130
+ return status_message, results_df
131
+ except requests.exceptions.Timeout:
132
+ status_message = "Submission Failed: The request timed out."
133
+ print(status_message)
134
+ results_df = pd.DataFrame(results_log)
135
+ return status_message, results_df
136
+ except requests.exceptions.RequestException as e:
137
+ status_message = f"Submission Failed: Network error - {e}"
138
+ print(status_message)
139
+ results_df = pd.DataFrame(results_log)
140
+ return status_message, results_df
141
+ except Exception as e:
142
+ status_message = f"An unexpected error occurred during submission: {e}"
143
+ print(status_message)
144
+ results_df = pd.DataFrame(results_log)
145
+ return status_message, results_df
146
+
147
+
148
+ # --- Build Gradio Interface using Blocks ---
149
+ with gr.Blocks() as demo:
150
+ gr.Markdown("# Basic Agent Evaluation Runner")
151
+ gr.Markdown(
152
+ """
153
+ **Instructions:**
154
+
155
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
156
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
157
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
158
+
159
+ ---
160
+ **Disclaimers:**
161
+ 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).
162
+ 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.
163
+ """
164
+ )
165
+
166
+ gr.LoginButton()
167
+
168
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
169
+
170
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
171
+ # Removed max_rows=10 from DataFrame constructor
172
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
173
+
174
+ run_button.click(
175
+ fn=run_and_submit_all,
176
+ outputs=[status_output, results_table]
177
+ )
178
+
179
+ if __name__ == "__main__":
180
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
181
+ # Check for SPACE_HOST and SPACE_ID at startup for information
182
+ space_host_startup = os.getenv("SPACE_HOST")
183
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
184
+
185
+ if space_host_startup:
186
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
187
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
188
+ else:
189
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
190
+
191
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
192
+ print(f"✅ SPACE_ID found: {space_id_startup}")
193
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
194
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
195
+ else:
196
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
197
+
198
+ print("-"*(60 + len(" App Starting ")) + "\n")
199
+
200
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
201
+ demo.launch(debug=True, share=False)
app_template.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+
7
+ # (Keep Constants as is)
8
+ # --- Constants ---
9
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
+
11
+ # --- Basic Agent Definition ---
12
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
+ class BasicAgent:
14
+ def __init__(self):
15
+ print("BasicAgent initialized.")
16
+ def __call__(self, question: str) -> str:
17
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
18
+ fixed_answer = "This is a default answer."
19
+ print(f"Agent returning fixed answer: {fixed_answer}")
20
+ return fixed_answer
21
+
22
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
23
+ """
24
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
25
+ and displays the results.
26
+ """
27
+ # --- Determine HF Space Runtime URL and Repo URL ---
28
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
+
30
+ if profile:
31
+ username= f"{profile.username}"
32
+ print(f"User logged in: {username}")
33
+ else:
34
+ print("User not logged in.")
35
+ return "Please Login to Hugging Face with the button.", None
36
+
37
+ api_url = DEFAULT_API_URL
38
+ questions_url = f"{api_url}/questions"
39
+ submit_url = f"{api_url}/submit"
40
+
41
+ # 1. Instantiate Agent ( modify this part to create your agent)
42
+ try:
43
+ agent = BasicAgent()
44
+ except Exception as e:
45
+ print(f"Error instantiating agent: {e}")
46
+ return f"Error initializing agent: {e}", None
47
+ # 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)
48
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
+ print(agent_code)
50
+
51
+ # 2. Fetch Questions
52
+ print(f"Fetching questions from: {questions_url}")
53
+ try:
54
+ response = requests.get(questions_url, timeout=15)
55
+ response.raise_for_status()
56
+ questions_data = response.json()
57
+ if not questions_data:
58
+ print("Fetched questions list is empty.")
59
+ return "Fetched questions list is empty or invalid format.", None
60
+ print(f"Fetched {len(questions_data)} questions.")
61
+ except requests.exceptions.RequestException as e:
62
+ print(f"Error fetching questions: {e}")
63
+ return f"Error fetching questions: {e}", None
64
+ except requests.exceptions.JSONDecodeError as e:
65
+ print(f"Error decoding JSON response from questions endpoint: {e}")
66
+ print(f"Response text: {response.text[:500]}")
67
+ return f"Error decoding server response for questions: {e}", None
68
+ except Exception as e:
69
+ print(f"An unexpected error occurred fetching questions: {e}")
70
+ return f"An unexpected error occurred fetching questions: {e}", None
71
+
72
+ # 3. Run your Agent
73
+ results_log = []
74
+ answers_payload = []
75
+ print(f"Running agent on {len(questions_data)} questions...")
76
+ for item in questions_data:
77
+ task_id = item.get("task_id")
78
+ question_text = item.get("question")
79
+ if not task_id or question_text is None:
80
+ print(f"Skipping item with missing task_id or question: {item}")
81
+ continue
82
+ try:
83
+ submitted_answer = agent(question_text)
84
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
+ except Exception as e:
87
+ print(f"Error running agent on task {task_id}: {e}")
88
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
+
90
+ if not answers_payload:
91
+ print("Agent did not produce any answers to submit.")
92
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
+
94
+ # 4. Prepare Submission
95
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
+ print(status_update)
98
+
99
+ # 5. Submit
100
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
+ try:
102
+ response = requests.post(submit_url, json=submission_data, timeout=60)
103
+ response.raise_for_status()
104
+ result_data = response.json()
105
+ final_status = (
106
+ f"Submission Successful!\n"
107
+ f"User: {result_data.get('username')}\n"
108
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
109
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
+ f"Message: {result_data.get('message', 'No message received.')}"
111
+ )
112
+ print("Submission successful.")
113
+ results_df = pd.DataFrame(results_log)
114
+ return final_status, results_df
115
+ except requests.exceptions.HTTPError as e:
116
+ error_detail = f"Server responded with status {e.response.status_code}."
117
+ try:
118
+ error_json = e.response.json()
119
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
+ except requests.exceptions.JSONDecodeError:
121
+ error_detail += f" Response: {e.response.text[:500]}"
122
+ status_message = f"Submission Failed: {error_detail}"
123
+ print(status_message)
124
+ results_df = pd.DataFrame(results_log)
125
+ return status_message, results_df
126
+ except requests.exceptions.Timeout:
127
+ status_message = "Submission Failed: The request timed out."
128
+ print(status_message)
129
+ results_df = pd.DataFrame(results_log)
130
+ return status_message, results_df
131
+ except requests.exceptions.RequestException as e:
132
+ status_message = f"Submission Failed: Network error - {e}"
133
+ print(status_message)
134
+ results_df = pd.DataFrame(results_log)
135
+ return status_message, results_df
136
+ except Exception as e:
137
+ status_message = f"An unexpected error occurred during submission: {e}"
138
+ print(status_message)
139
+ results_df = pd.DataFrame(results_log)
140
+ return status_message, results_df
141
+
142
+
143
+ # --- Build Gradio Interface using Blocks ---
144
+ with gr.Blocks() as demo:
145
+ gr.Markdown("# Basic Agent Evaluation Runner")
146
+ gr.Markdown(
147
+ """
148
+ **Instructions:**
149
+
150
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
+
154
+ ---
155
+ **Disclaimers:**
156
+ 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).
157
+ 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.
158
+ """
159
+ )
160
+
161
+ gr.LoginButton()
162
+
163
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
164
+
165
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
+ # Removed max_rows=10 from DataFrame constructor
167
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
+
169
+ run_button.click(
170
+ fn=run_and_submit_all,
171
+ outputs=[status_output, results_table]
172
+ )
173
+
174
+ if __name__ == "__main__":
175
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
176
+ # Check for SPACE_HOST and SPACE_ID at startup for information
177
+ space_host_startup = os.getenv("SPACE_HOST")
178
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
+
180
+ if space_host_startup:
181
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
182
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
183
+ else:
184
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
+
186
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
187
+ print(f"✅ SPACE_ID found: {space_id_startup}")
188
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
+ else:
191
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
+
193
+ print("-"*(60 + len(" App Starting ")) + "\n")
194
+
195
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
196
+ demo.launch(debug=True, share=False)
metadata.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ requests
3
+ langchain
4
+ langchain-community
5
+ langchain-core
6
+ langchain-google-genai
7
+ langchain-huggingface
8
+ langchain-groq
9
+ langchain-tavily
10
+ langchain-chroma
11
+ langgraph
12
+ huggingface_hub
13
+ chromadb
14
+ sentence-transformers
15
+ arxiv
16
+ pymupdf
17
+ wikipedia
18
+ pgvector
19
+ python-dotenv
setup_actions.ipynb ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "55b5db25",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "name": "stderr",
11
+ "output_type": "stream",
12
+ "text": [
13
+ "/home/boom/.pyenv/versions/rag/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
14
+ " from .autonotebook import tqdm as notebook_tqdm\n"
15
+ ]
16
+ }
17
+ ],
18
+ "source": [
19
+ "from dotenv import load_dotenv\n",
20
+ "import os\n",
21
+ "\n",
22
+ "load_dotenv()\n",
23
+ "token = os.getenv(\"HUGGINGFACE_TOKEN\")\n",
24
+ "\n",
25
+ "from huggingface_hub import login\n",
26
+ "\n",
27
+ "login(token=os.environ[\"HUGGINGFACE_TOKEN\"])"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "execution_count": 4,
33
+ "id": "e2f982e3",
34
+ "metadata": {},
35
+ "outputs": [
36
+ {
37
+ "name": "stdout",
38
+ "output_type": "stream",
39
+ "text": [
40
+ "Help on function load_dataset in module datasets.load:\n",
41
+ "\n",
42
+ "load_dataset(path: str, name: Optional[str] = None, data_dir: Optional[str] = None, data_files: Union[str, collections.abc.Sequence[str], collections.abc.Mapping[str, Union[str, collections.abc.Sequence[str]]], NoneType] = None, split: Union[str, datasets.splits.Split, NoneType] = None, cache_dir: Optional[str] = None, features: Optional[datasets.features.features.Features] = None, download_config: Optional[datasets.download.download_config.DownloadConfig] = None, download_mode: Union[datasets.download.download_manager.DownloadMode, str, NoneType] = None, verification_mode: Union[datasets.utils.info_utils.VerificationMode, str, NoneType] = None, keep_in_memory: Optional[bool] = None, save_infos: bool = False, revision: Union[str, datasets.utils.version.Version, NoneType] = None, token: Union[bool, str, NoneType] = None, streaming: bool = False, num_proc: Optional[int] = None, storage_options: Optional[dict] = None, trust_remote_code: Optional[bool] = None, **config_kwargs) -> Union[datasets.dataset_dict.DatasetDict, datasets.arrow_dataset.Dataset, datasets.dataset_dict.IterableDatasetDict, datasets.iterable_dataset.IterableDataset]\n",
43
+ " Load a dataset from the Hugging Face Hub, or a local dataset.\n",
44
+ " \n",
45
+ " You can find the list of datasets on the [Hub](https://huggingface.co/datasets) or with [`huggingface_hub.list_datasets`].\n",
46
+ " \n",
47
+ " A dataset is a directory that contains some data files in generic formats (JSON, CSV, Parquet, etc.) and possibly\n",
48
+ " in a generic structure (Webdataset, ImageFolder, AudioFolder, VideoFolder, etc.)\n",
49
+ " \n",
50
+ " This function does the following under the hood:\n",
51
+ " \n",
52
+ " 1. Load a dataset builder:\n",
53
+ " \n",
54
+ " * Find the most common data format in the dataset and pick its associated builder (JSON, CSV, Parquet, Webdataset, ImageFolder, AudioFolder, etc.)\n",
55
+ " * Find which file goes into which split (e.g. train/test) based on file and directory names or on the YAML configuration\n",
56
+ " * It is also possible to specify `data_files` manually, and which dataset builder to use (e.g. \"parquet\").\n",
57
+ " \n",
58
+ " 2. Run the dataset builder:\n",
59
+ " \n",
60
+ " In the general case:\n",
61
+ " \n",
62
+ " * Download the data files from the dataset if they are not already available locally or cached.\n",
63
+ " * Process and cache the dataset in typed Arrow tables for caching.\n",
64
+ " \n",
65
+ " Arrow table are arbitrarily long, typed tables which can store nested objects and be mapped to numpy/pandas/python generic types.\n",
66
+ " They can be directly accessed from disk, loaded in RAM or even streamed over the web.\n",
67
+ " \n",
68
+ " In the streaming case:\n",
69
+ " \n",
70
+ " * Don't download or cache anything. Instead, the dataset is lazily loaded and will be streamed on-the-fly when iterating on it.\n",
71
+ " \n",
72
+ " 3. Return a dataset built from the requested splits in `split` (default: all).\n",
73
+ " \n",
74
+ " It can also use a custom dataset builder if the dataset contains a dataset script, but this feature is mostly for backward compatibility.\n",
75
+ " In this case the dataset script file must be named after the dataset repository or directory and end with \".py\".\n",
76
+ " \n",
77
+ " Args:\n",
78
+ " \n",
79
+ " path (`str`):\n",
80
+ " Path or name of the dataset.\n",
81
+ " \n",
82
+ " - if `path` is a dataset repository on the HF hub (list all available datasets with [`huggingface_hub.list_datasets`])\n",
83
+ " -> load the dataset from supported files in the repository (csv, json, parquet, etc.)\n",
84
+ " e.g. `'username/dataset_name'`, a dataset repository on the HF hub containing the data files.\n",
85
+ " \n",
86
+ " - if `path` is a local directory\n",
87
+ " -> load the dataset from supported files in the directory (csv, json, parquet, etc.)\n",
88
+ " e.g. `'./path/to/directory/with/my/csv/data'`.\n",
89
+ " \n",
90
+ " - if `path` is the name of a dataset builder and `data_files` or `data_dir` is specified\n",
91
+ " (available builders are \"json\", \"csv\", \"parquet\", \"arrow\", \"text\", \"xml\", \"webdataset\", \"imagefolder\", \"audiofolder\", \"videofolder\")\n",
92
+ " -> load the dataset from the files in `data_files` or `data_dir`\n",
93
+ " e.g. `'parquet'`.\n",
94
+ " \n",
95
+ " It can also point to a local dataset script but this is not recommended.\n",
96
+ " name (`str`, *optional*):\n",
97
+ " Defining the name of the dataset configuration.\n",
98
+ " data_dir (`str`, *optional*):\n",
99
+ " Defining the `data_dir` of the dataset configuration. If specified for the generic builders (csv, text etc.) or the Hub datasets and `data_files` is `None`,\n",
100
+ " the behavior is equal to passing `os.path.join(data_dir, **)` as `data_files` to reference all the files in a directory.\n",
101
+ " data_files (`str` or `Sequence` or `Mapping`, *optional*):\n",
102
+ " Path(s) to source data file(s).\n",
103
+ " split (`Split` or `str`):\n",
104
+ " Which split of the data to load.\n",
105
+ " If `None`, will return a `dict` with all splits (typically `datasets.Split.TRAIN` and `datasets.Split.TEST`).\n",
106
+ " If given, will return a single Dataset.\n",
107
+ " Splits can be combined and specified like in tensorflow-datasets.\n",
108
+ " cache_dir (`str`, *optional*):\n",
109
+ " Directory to read/write data. Defaults to `\"~/.cache/huggingface/datasets\"`.\n",
110
+ " features (`Features`, *optional*):\n",
111
+ " Set the features type to use for this dataset.\n",
112
+ " download_config ([`DownloadConfig`], *optional*):\n",
113
+ " Specific download configuration parameters.\n",
114
+ " download_mode ([`DownloadMode`] or `str`, defaults to `REUSE_DATASET_IF_EXISTS`):\n",
115
+ " Download/generate mode.\n",
116
+ " verification_mode ([`VerificationMode`] or `str`, defaults to `BASIC_CHECKS`):\n",
117
+ " Verification mode determining the checks to run on the downloaded/processed dataset information (checksums/size/splits/...).\n",
118
+ " \n",
119
+ " <Added version=\"2.9.1\"/>\n",
120
+ " keep_in_memory (`bool`, defaults to `None`):\n",
121
+ " Whether to copy the dataset in-memory. If `None`, the dataset\n",
122
+ " will not be copied in-memory unless explicitly enabled by setting `datasets.config.IN_MEMORY_MAX_SIZE` to\n",
123
+ " nonzero. See more details in the [improve performance](../cache#improve-performance) section.\n",
124
+ " save_infos (`bool`, defaults to `False`):\n",
125
+ " Save the dataset information (checksums/size/splits/...).\n",
126
+ " revision ([`Version`] or `str`, *optional*):\n",
127
+ " Version of the dataset script to load.\n",
128
+ " As datasets have their own git repository on the Datasets Hub, the default version \"main\" corresponds to their \"main\" branch.\n",
129
+ " You can specify a different version than the default \"main\" by using a commit SHA or a git tag of the dataset repository.\n",
130
+ " token (`str` or `bool`, *optional*):\n",
131
+ " Optional string or boolean to use as Bearer token for remote files on the Datasets Hub.\n",
132
+ " If `True`, or not specified, will get token from `\"~/.huggingface\"`.\n",
133
+ " streaming (`bool`, defaults to `False`):\n",
134
+ " If set to `True`, don't download the data files. Instead, it streams the data progressively while\n",
135
+ " iterating on the dataset. An [`IterableDataset`] or [`IterableDatasetDict`] is returned instead in this case.\n",
136
+ " \n",
137
+ " Note that streaming works for datasets that use data formats that support being iterated over like txt, csv, jsonl for example.\n",
138
+ " Json files may be downloaded completely. Also streaming from remote zip or gzip files is supported but other compressed formats\n",
139
+ " like rar and xz are not yet supported. The tgz format doesn't allow streaming.\n",
140
+ " num_proc (`int`, *optional*, defaults to `None`):\n",
141
+ " Number of processes when downloading and generating the dataset locally.\n",
142
+ " Multiprocessing is disabled by default.\n",
143
+ " \n",
144
+ " <Added version=\"2.7.0\"/>\n",
145
+ " storage_options (`dict`, *optional*, defaults to `None`):\n",
146
+ " **Experimental**. Key/value pairs to be passed on to the dataset file-system backend, if any.\n",
147
+ " \n",
148
+ " <Added version=\"2.11.0\"/>\n",
149
+ " trust_remote_code (`bool`, *optional*, defaults to `None`):\n",
150
+ " Whether or not to allow for datasets defined on the Hub using a dataset script. This option\n",
151
+ " should only be set to `True` for repositories you trust and in which you have read the code, as it will\n",
152
+ " execute code present on the Hub on your local machine.\n",
153
+ " \n",
154
+ " <Added version=\"2.16.0\"/>\n",
155
+ " \n",
156
+ " <Changed version=\"2.20.0\">\n",
157
+ " \n",
158
+ " `trust_remote_code` defaults to `False` if not specified.\n",
159
+ " \n",
160
+ " </Changed>\n",
161
+ " \n",
162
+ " **config_kwargs (additional keyword arguments):\n",
163
+ " Keyword arguments to be passed to the `BuilderConfig`\n",
164
+ " and used in the [`DatasetBuilder`].\n",
165
+ " \n",
166
+ " Returns:\n",
167
+ " [`Dataset`] or [`DatasetDict`]:\n",
168
+ " - if `split` is not `None`: the dataset requested,\n",
169
+ " - if `split` is `None`, a [`~datasets.DatasetDict`] with each split.\n",
170
+ " \n",
171
+ " or [`IterableDataset`] or [`IterableDatasetDict`]: if `streaming=True`\n",
172
+ " \n",
173
+ " - if `split` is not `None`, the dataset is requested\n",
174
+ " - if `split` is `None`, a [`~datasets.streaming.IterableDatasetDict`] with each split.\n",
175
+ " \n",
176
+ " Example:\n",
177
+ " \n",
178
+ " Load a dataset from the Hugging Face Hub:\n",
179
+ " \n",
180
+ " ```py\n",
181
+ " >>> from datasets import load_dataset\n",
182
+ " >>> ds = load_dataset('cornell-movie-review-data/rotten_tomatoes', split='train')\n",
183
+ " \n",
184
+ " # Load a subset or dataset configuration (here 'sst2')\n",
185
+ " >>> from datasets import load_dataset\n",
186
+ " >>> ds = load_dataset('nyu-mll/glue', 'sst2', split='train')\n",
187
+ " \n",
188
+ " # Manual mapping of data files to splits\n",
189
+ " >>> data_files = {'train': 'train.csv', 'test': 'test.csv'}\n",
190
+ " >>> ds = load_dataset('namespace/your_dataset_name', data_files=data_files)\n",
191
+ " \n",
192
+ " # Manual selection of a directory to load\n",
193
+ " >>> ds = load_dataset('namespace/your_dataset_name', data_dir='folder_name')\n",
194
+ " ```\n",
195
+ " \n",
196
+ " Load a local dataset:\n",
197
+ " \n",
198
+ " ```py\n",
199
+ " # Load a CSV file\n",
200
+ " >>> from datasets import load_dataset\n",
201
+ " >>> ds = load_dataset('csv', data_files='path/to/local/my_dataset.csv')\n",
202
+ " \n",
203
+ " # Load a JSON file\n",
204
+ " >>> from datasets import load_dataset\n",
205
+ " >>> ds = load_dataset('json', data_files='path/to/local/my_dataset.json')\n",
206
+ " \n",
207
+ " # Load from a local loading script (not recommended)\n",
208
+ " >>> from datasets import load_dataset\n",
209
+ " >>> ds = load_dataset('path/to/local/loading_script/loading_script.py', split='train')\n",
210
+ " ```\n",
211
+ " \n",
212
+ " Load an [`~datasets.IterableDataset`]:\n",
213
+ " \n",
214
+ " ```py\n",
215
+ " >>> from datasets import load_dataset\n",
216
+ " >>> ds = load_dataset('cornell-movie-review-data/rotten_tomatoes', split='train', streaming=True)\n",
217
+ " ```\n",
218
+ " \n",
219
+ " Load an image dataset with the `ImageFolder` dataset builder:\n",
220
+ " \n",
221
+ " ```py\n",
222
+ " >>> from datasets import load_dataset\n",
223
+ " >>> ds = load_dataset('imagefolder', data_dir='/path/to/images', split='train')\n",
224
+ " ```\n",
225
+ "\n"
226
+ ]
227
+ }
228
+ ],
229
+ "source": [
230
+ "help(load_dataset)"
231
+ ]
232
+ },
233
+ {
234
+ "cell_type": "code",
235
+ "execution_count": 5,
236
+ "id": "79deee46",
237
+ "metadata": {},
238
+ "outputs": [
239
+ {
240
+ "name": "stdout",
241
+ "output_type": "stream",
242
+ "text": [
243
+ "2023 1\n"
244
+ ]
245
+ },
246
+ {
247
+ "name": "stderr",
248
+ "output_type": "stream",
249
+ "text": [
250
+ "Generating test split: 93 examples [00:00, 10442.25 examples/s]\n",
251
+ "Generating validation split: 53 examples [00:00, 7329.56 examples/s]\n"
252
+ ]
253
+ }
254
+ ],
255
+ "source": [
256
+ "from datasets import load_dataset\n",
257
+ "\n",
258
+ "dataset = load_dataset(\"gaia-benchmark/GAIA\", name=\"2023_level1\", split=\"validation\", trust_remote_code=True, cache_dir = \"ragdata\")"
259
+ ]
260
+ },
261
+ {
262
+ "cell_type": "code",
263
+ "execution_count": 8,
264
+ "id": "752d0bfa",
265
+ "metadata": {},
266
+ "outputs": [
267
+ {
268
+ "data": {
269
+ "text/plain": [
270
+ "['dataset_info.json', 'gaia-validation.arrow', 'gaia-test.arrow']"
271
+ ]
272
+ },
273
+ "execution_count": 8,
274
+ "metadata": {},
275
+ "output_type": "execute_result"
276
+ }
277
+ ],
278
+ "source": [
279
+ "os.listdir(r\"ragdata/gaia-benchmark___gaia/2023_level1/0.0.1/ec492fe4320ee795b1aed6bb46229c5f693226b0f1316347501c24b4baeee005\")"
280
+ ]
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "execution_count": 12,
285
+ "id": "521be8df",
286
+ "metadata": {},
287
+ "outputs": [
288
+ {
289
+ "name": "stderr",
290
+ "output_type": "stream",
291
+ "text": [
292
+ "/tmp/ipykernel_15347/1929323449.py:43: LangChainDeprecationWarning: Since Chroma 0.4.x the manual persistence method is no longer supported as docs are automatically persisted.\n",
293
+ " vectorstore.persist()\n"
294
+ ]
295
+ }
296
+ ],
297
+ "source": [
298
+ "from datasets import load_dataset\n",
299
+ "from langchain.embeddings import HuggingFaceEmbeddings\n",
300
+ "from langchain.vectorstores import Chroma\n",
301
+ "from langchain.schema import Document\n",
302
+ "\n",
303
+ "# Load the GAIA validation dataset\n",
304
+ "dataset = load_dataset(\"gaia-benchmark/GAIA\", name=\"2023_level1\", split=\"validation\")\n",
305
+ "\n",
306
+ "# Prepare the embeddings model\n",
307
+ "embeddings = HuggingFaceEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n",
308
+ "\n",
309
+ "# Extract questions and their answers\n",
310
+ "documents = []\n",
311
+ "for entry in dataset:\n",
312
+ " question = entry[\"Question\"]\n",
313
+ " answer = entry[\"Final answer\"]\n",
314
+ " \n",
315
+ " # Create a document with both the question and the answer as metadata\n",
316
+ " metadata = {\n",
317
+ " \"task_id\": entry[\"task_id\"],\n",
318
+ " \"steps\": entry[\"Annotator Metadata\"][\"Steps\"],\n",
319
+ " \"tools\": entry[\"Annotator Metadata\"][\"Tools\"],\n",
320
+ " \"answer\": answer\n",
321
+ " }\n",
322
+ " \n",
323
+ " # Add the question to the list of documents\n",
324
+ " documents.append(\n",
325
+ " Document(\n",
326
+ " page_content=question,\n",
327
+ " metadata=metadata\n",
328
+ " )\n",
329
+ " )\n",
330
+ "\n",
331
+ "# Insert the documents into Chroma\n",
332
+ "vectorstore = Chroma.from_documents(\n",
333
+ " documents=documents,\n",
334
+ " embedding=embeddings,\n",
335
+ " collection_name=\"gaia_validation\",\n",
336
+ " persist_directory=\"./chroma_store\"\n",
337
+ ")\n",
338
+ "\n",
339
+ "# Persist the data for future use\n",
340
+ "vectorstore.persist()"
341
+ ]
342
+ },
343
+ {
344
+ "cell_type": "code",
345
+ "execution_count": 13,
346
+ "id": "210ea883",
347
+ "metadata": {},
348
+ "outputs": [
349
+ {
350
+ "name": "stdout",
351
+ "output_type": "stream",
352
+ "text": [
353
+ "{'tools': ['1. A calculator', '3. Video recognition tools', '1. A web browser.', '2. google search', '2. Web browser', '1. web browser', '2. calculator', '2. A speech-to-text tool', '3. Calculator', '1. Wikipedia', '3. Audio capability', '3. Color recognition', '1. Markdown', '2. Video processing software', '1. search engine', 'No tools required', '2. Video parsing', '1. A word reversal tool / script', '1. Image recognition tools', '2. Image recognition', '2. Calculator', '2. search engine', '2. Search engine', '1. Access to Excel files', '1. Web browser', '1. Calculator', '1. Search engine', '1. Text Editor', '1. PowerPoint viewer', '3. PDF access', '1. image recognition/OCR', '2. A search engine.', '3. Audio processing software', '1. Excel', '3. PDF viewer', '3. A calculator.', \"1. Rubik's cube model\", '1. Word document access', 'None', '1. A file interface', '3. Access to academic journal websites', '2. Color recognition', '3. Calculator (or ability to count)', '1. Python', '2. A speech-to-text audio processing tool']}\n"
354
+ ]
355
+ }
356
+ ],
357
+ "source": [
358
+ "from datasets import load_dataset\n",
359
+ "\n",
360
+ "# Load the GAIA validation dataset\n",
361
+ "dataset = load_dataset(\"gaia-benchmark/GAIA\", name=\"2023_level1\", split=\"validation\")\n",
362
+ "\n",
363
+ "# Initialize a set to store unique tools\n",
364
+ "unique_tools = set()\n",
365
+ "\n",
366
+ "# Iterate over each entry in the dataset\n",
367
+ "for entry in dataset:\n",
368
+ " # Access the tools used (they are stored in the 'Tools' field of 'Annotator Metadata')\n",
369
+ " tools = entry[\"Annotator Metadata\"][\"Tools\"]\n",
370
+ " \n",
371
+ " # Split the tools into a list (since they are stored as a string, we split by line breaks)\n",
372
+ " tools_list = tools.split('\\n')\n",
373
+ " \n",
374
+ " # Add each tool to the set (set automatically ensures uniqueness)\n",
375
+ " for tool in tools_list:\n",
376
+ " unique_tools.add(tool.strip()) # Remove any extra spaces or newlines\n",
377
+ "\n",
378
+ "# Convert the set of unique tools to a dictionary under the key 'tools'\n",
379
+ "tools_dict = {'tools': list(unique_tools)}\n",
380
+ "\n",
381
+ "# Print the unique tools to get a sense of what was used\n",
382
+ "print(tools_dict)\n"
383
+ ]
384
+ },
385
+ {
386
+ "cell_type": "code",
387
+ "execution_count": null,
388
+ "id": "55b688cd",
389
+ "metadata": {},
390
+ "outputs": [],
391
+ "source": []
392
+ }
393
+ ],
394
+ "metadata": {
395
+ "kernelspec": {
396
+ "display_name": "rag",
397
+ "language": "python",
398
+ "name": "python3"
399
+ },
400
+ "language_info": {
401
+ "codemirror_mode": {
402
+ "name": "ipython",
403
+ "version": 3
404
+ },
405
+ "file_extension": ".py",
406
+ "mimetype": "text/x-python",
407
+ "name": "python",
408
+ "nbconvert_exporter": "python",
409
+ "pygments_lexer": "ipython3",
410
+ "version": "3.11.0"
411
+ }
412
+ },
413
+ "nbformat": 4,
414
+ "nbformat_minor": 5
415
+ }