Ihor Kozar commited on
Commit
e4167da
·
1 Parent(s): d7b3096

feat: add retriever & vectorstore

Browse files
Files changed (6) hide show
  1. .gitignore +5 -0
  2. agent.py +48 -132
  3. agent0.py +0 -157
  4. tools.py → agent_tools.py +5 -3
  5. requirements.txt +2 -1
  6. test.py +113 -0
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ /.env
2
+ /temp
3
+ /temp.csv
4
+ /temp.xlsx
5
+ /chroma_db/
agent.py CHANGED
@@ -1,14 +1,14 @@
1
  import time
2
  from typing import TypedDict, Annotated, Optional
3
- from dotenv import load_dotenv
4
- from langchain.agents import initialize_agent
5
- from langchain_openai import ChatOpenAI
6
  from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage
 
7
  from langgraph.graph import StateGraph, START
8
  from langgraph.graph.message import add_messages
9
  from langgraph.prebuilt import ToolNode, tools_condition
10
-
11
- from tools import *
 
 
12
 
13
  load_dotenv()
14
 
@@ -35,7 +35,11 @@ sys_msg = SystemMessage(
35
  )
36
 
37
  tools = [
38
- duckduck_websearch,
 
 
 
 
39
  web_search,
40
  arvix_search,
41
  wiki_search,
@@ -46,18 +50,12 @@ tools = [
46
  excel_read,
47
  csv_read,
48
  image_caption,
49
- multiply,
50
- add,
51
- subtract,
52
- divide,
53
- modulus,
54
  ]
55
 
56
  print("agent.py loaded")
57
 
58
 
59
  class AgentState(TypedDict):
60
- """Agent state for the graph."""
61
  input_file: Optional[str]
62
  messages: Annotated[list[AnyMessage], add_messages]
63
 
@@ -65,11 +63,27 @@ class AgentState(TypedDict):
65
  class CUSTOM_AGENT:
66
  def __init__(self):
67
  self.llm = ChatOpenAI(name="gpt-4o",
68
- api_key='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')
69
 
70
  self.tools = tools
71
  self.llm_with_tools = self.llm.bind_tools(self.tools)
 
 
 
 
72
  self.app = self._graph_compile()
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  def _graph_compile(self):
75
  builder = StateGraph(AgentState)
@@ -87,8 +101,21 @@ class CUSTOM_AGENT:
87
  return react_graph
88
 
89
  def _assistant(self, state: AgentState):
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  return {
91
- "messages": [self.llm_with_tools.invoke([sys_msg] + state["messages"])],
92
  "input_file": state["input_file"]
93
  }
94
 
@@ -96,9 +123,9 @@ class CUSTOM_AGENT:
96
  keyword = "FINAL ANSWER: "
97
  index = text.find(keyword)
98
  if index != -1:
99
- return text[index + len(keyword):]
100
  else:
101
- return ""
102
 
103
  def run(self, task: dict):
104
  task_id, question, file_name = task["task_id"], task["question"], task["file_name"]
@@ -108,15 +135,17 @@ class CUSTOM_AGENT:
108
  question_text = question
109
  else:
110
  question_text = f'{question} with TASK-ID: {task_id}'
111
- messages = [HumanMessage(content=question_text)]
 
 
112
 
113
  max_retries = 3
114
  base_sleep = 1
115
  for attempt in range(max_retries):
116
  try:
117
- response = self.app.invoke({"messages": messages, "input_file": None})
118
  final_ans = self.extract_after_final_answer(response['messages'][-1].content)
119
- time.sleep(60) # avoid rate limit
120
  return final_ans
121
  except Exception as e:
122
  sleep_time = base_sleep * (attempt + 1)
@@ -127,116 +156,3 @@ class CUSTOM_AGENT:
127
  continue
128
  return f"Error processing query after {max_retries} attempts: {str(e)}"
129
  return "This is a default answer."
130
-
131
-
132
- questions = [
133
- {
134
- "task_id": "8e867cd7-cff9-4e6c-867a-ff5ddc2550be",
135
- "question": "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.",
136
- "file_name": ""
137
- },
138
- {
139
- "task_id": "a1e91b78-d3d8-4675-bb8d-62741b4b68a6",
140
- "question": "In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?",
141
- "file_name": ""
142
- },
143
- {
144
- "task_id": "2d83110e-a098-4ebb-9987-066c06fa42d0",
145
- "question": ".rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI",
146
- "file_name": ""
147
- },
148
- {
149
- "task_id": "cca530fc-4052-43b2-b130-b30968d8aa44",
150
- "question": "Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.",
151
- "file_name": "cca530fc-4052-43b2-b130-b30968d8aa44.png"
152
- },
153
- {
154
- "task_id": "4fc2f1ae-8625-45b5-ab34-ad4433bc21f8",
155
- "question": "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?",
156
- "file_name": ""
157
- },
158
- {
159
- "task_id": "6f37996b-2ac7-44b0-8e68-6d28256631b4",
160
- "question": "Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.",
161
- "file_name": ""
162
- },
163
- {
164
- "task_id": "9d191bce-651d-4746-be2d-7ef8ecadb9c2",
165
- "question": "Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the question \"Isn't that hot?\"",
166
- "file_name": ""
167
- },
168
- {
169
- "task_id": "cabe07ed-9eca-40ea-8ead-410ef5e83f91",
170
- "question": "What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?",
171
- "Level": "1",
172
- "file_name": ""
173
- },
174
- {
175
- "task_id": "3cef3a44-215e-4aed-8e3b-b1e3f08063b7",
176
- "question": "I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:\n\nmilk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts\n\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.",
177
- "Level": "1",
178
- "file_name": ""
179
- },
180
- {
181
- "task_id": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3",
182
- "question": "Hi, I'm making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I'm not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for \"a pinch of salt\" or \"two cups of ripe strawberries\" the ingredients on the list would be \"salt\" and \"ripe strawberries\".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.",
183
- "file_name": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3"
184
- },
185
- {
186
- "task_id": "305ac316-eef6-4446-960a-92d80d542f82",
187
- "question": "Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.",
188
- "file_name": ""
189
- },
190
- {
191
- "task_id": "f918266a-b3e0-4914-865d-4faa564f1aef",
192
- "question": "What is the final numeric output from the attached Python code?",
193
- "file_name": "f918266a-b3e0-4914-865d-4faa564f1aef.py"
194
- },
195
- {
196
- "task_id": "3f57289b-8c60-48be-bd80-01f8099ca449",
197
- "question": "How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?",
198
- "file_name": ""
199
- },
200
- {
201
- "task_id": "1f975693-876d-457b-a649-393859e79bf3",
202
- "question": "Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",
203
- "file_name": "1f975693-876d-457b-a649-393859e79bf3.mp3"
204
- },
205
- {
206
- "task_id": "840bfca7-4f7b-481a-8794-c560c340185d",
207
- "question": "On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?",
208
- "file_name": ""
209
- },
210
- {
211
- "task_id": "bda648d7-d618-4883-88f4-3466eabd860e",
212
- "question": "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.",
213
- "file_name": ""
214
- },
215
- {
216
- "task_id": "cf106601-ab4f-4af9-b045-5295fe67b37d",
217
- "question": "What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.",
218
- "file_name": ""
219
- },
220
- {
221
- "task_id": "a0c07678-e491-4bbc-8f0b-07405144218f",
222
- "question": "Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.",
223
- "file_name": ""
224
- },
225
- {
226
- "task_id": "7bd855d8-463d-4ed5-93ca-5fe35145f733",
227
- "question": "The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.",
228
- "file_name": "7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx"
229
- },
230
- {
231
- "task_id": "5a0c1adf-205e-4841-a666-7c3ef95def9d",
232
- "question": "What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?",
233
- "file_name": ""
234
- }
235
- ]
236
- # Test
237
- if __name__ == "__main__":
238
- agent = CUSTOM_AGENT()
239
- q = questions[0]
240
- print("Question:", q["question"])
241
- answer = agent.run(q)
242
- print("Answer:", answer)
 
1
  import time
2
  from typing import TypedDict, Annotated, Optional
 
 
 
3
  from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage
4
+ from langchain_openai import ChatOpenAI
5
  from langgraph.graph import StateGraph, START
6
  from langgraph.graph.message import add_messages
7
  from langgraph.prebuilt import ToolNode, tools_condition
8
+ from langchain.vectorstores import Chroma
9
+ from langchain.embeddings.openai import OpenAIEmbeddings
10
+ from langchain.chains import RetrievalQA
11
+ from agent_tools import *
12
 
13
  load_dotenv()
14
 
 
35
  )
36
 
37
  tools = [
38
+ multiply,
39
+ add,
40
+ subtract,
41
+ divide,
42
+ modulus,
43
  web_search,
44
  arvix_search,
45
  wiki_search,
 
50
  excel_read,
51
  csv_read,
52
  image_caption,
 
 
 
 
 
53
  ]
54
 
55
  print("agent.py loaded")
56
 
57
 
58
  class AgentState(TypedDict):
 
59
  input_file: Optional[str]
60
  messages: Annotated[list[AnyMessage], add_messages]
61
 
 
63
  class CUSTOM_AGENT:
64
  def __init__(self):
65
  self.llm = ChatOpenAI(name="gpt-4o",
66
+ api_key=os.getenv("OPENAI_API_KEY"))
67
 
68
  self.tools = tools
69
  self.llm_with_tools = self.llm.bind_tools(self.tools)
70
+ initial_state = {
71
+ "input_file": None,
72
+ "messages": [],
73
+ }
74
  self.app = self._graph_compile()
75
+ self.initial_state = initial_state
76
+ self.sys_msg = sys_msg
77
+ # --- Chroma vectorstore + retriever ---
78
+ embeddings = OpenAIEmbeddings(api_key=os.getenv("OPENAI_API_KEY"))
79
+ persist_directory = "chroma_db"
80
+ self.vectorstore = Chroma(persist_directory=persist_directory, embedding_function=embeddings)
81
+ self.retriever = self.vectorstore.as_retriever(search_kwargs={"k": 3})
82
+ self.qa_chain = RetrievalQA.from_chain_type(
83
+ llm=self.llm,
84
+ retriever=self.retriever,
85
+ return_source_documents=True
86
+ )
87
 
88
  def _graph_compile(self):
89
  builder = StateGraph(AgentState)
 
101
  return react_graph
102
 
103
  def _assistant(self, state: AgentState):
104
+ last_human = next((m for m in reversed(state["messages"]) if isinstance(m, HumanMessage)), None)
105
+ messages = [self.sys_msg] + state["messages"]
106
+
107
+ if last_human:
108
+ question_text = last_human.content
109
+ # use invoke instead of run
110
+ retrieved_output = self.qa_chain.invoke({"query": question_text})
111
+ retrieved_docs = retrieved_output["result"] # беремо тільки текст
112
+ context_message = HumanMessage(content=f"Context from vectorstore: {retrieved_docs}")
113
+ messages.append(context_message)
114
+
115
+ response = self.llm_with_tools.invoke(messages)
116
+
117
  return {
118
+ "messages": state["messages"] + [response],
119
  "input_file": state["input_file"]
120
  }
121
 
 
123
  keyword = "FINAL ANSWER: "
124
  index = text.find(keyword)
125
  if index != -1:
126
+ return text[index + len(keyword):].strip()
127
  else:
128
+ return text.strip()
129
 
130
  def run(self, task: dict):
131
  task_id, question, file_name = task["task_id"], task["question"], task["file_name"]
 
135
  question_text = question
136
  else:
137
  question_text = f'{question} with TASK-ID: {task_id}'
138
+
139
+ state = self.initial_state.copy()
140
+ state["messages"] = [HumanMessage(content=question_text)]
141
 
142
  max_retries = 3
143
  base_sleep = 1
144
  for attempt in range(max_retries):
145
  try:
146
+ response = self.app.invoke(state)
147
  final_ans = self.extract_after_final_answer(response['messages'][-1].content)
148
+ time.sleep(10) # avoid rate limit
149
  return final_ans
150
  except Exception as e:
151
  sleep_time = base_sleep * (attempt + 1)
 
156
  continue
157
  return f"Error processing query after {max_retries} attempts: {str(e)}"
158
  return "This is a default answer."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
agent0.py DELETED
@@ -1,157 +0,0 @@
1
- import os
2
-
3
- import fitz
4
- from dotenv import load_dotenv
5
- from langchain_community.tools import DuckDuckGoSearchRun
6
- from langgraph.graph import START, StateGraph, MessagesState
7
- from langgraph.prebuilt import tools_condition
8
- from langgraph.prebuilt import ToolNode
9
- from langchain_groq import ChatGroq
10
- from langchain_community.tools.tavily_search import TavilySearchResults
11
- from langchain_community.document_loaders import WikipediaLoader
12
- from langchain_community.document_loaders import ArxivLoader
13
- from langchain_core.messages import SystemMessage, HumanMessage
14
- from langchain_core.tools import tool
15
- from langchain.text_splitter import RecursiveCharacterTextSplitter
16
- from langchain_community.retrievers import BM25Retriever
17
-
18
- if not hasattr(fitz, "fitz"):
19
- fitz.fitz = fitz
20
-
21
- load_dotenv()
22
-
23
-
24
- @tool(description="Multiply two integers and return the result")
25
- def multiply(a: int, b: int) -> int:
26
- return a * b
27
-
28
- @tool(description="Add two integers and return the result")
29
- def add(a: int, b: int) -> int:
30
- return a + b
31
-
32
- @tool(description="Subtract the second integer from the first and return the result")
33
- def subtract(a: int, b: int) -> int:
34
- return a - b
35
-
36
- @tool(description="Divide the first integer by the second and return the result; raises an error if the second integer is zero")
37
- def divide(a: int, b: int) -> int:
38
- if b == 0:
39
- raise ValueError("Cannot divide by zero.")
40
- return a / b
41
-
42
- @tool(description="Return the remainder of dividing the first integer by the second")
43
- def modulus(a: int, b: int) -> int:
44
- return a % b
45
-
46
- @tool(description="Search Wikipedia for the given query and return formatted results")
47
- def wiki_search(query: str) -> str:
48
- search_docs = WikipediaLoader(query=query, load_max_docs=10).load()
49
- formatted_search_docs = "\n\n---\n\n".join(
50
- [
51
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
52
- for doc in search_docs
53
- ])
54
- return {"wiki_results": formatted_search_docs}
55
-
56
- @tool(description="Search the web using Tavily and return formatted results")
57
- def web_search(query: str) -> str:
58
- search_docs = TavilySearchResults(max_results=3).invoke(query=query)
59
- formatted_search_docs = "\n\n---\n\n".join(
60
- [
61
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
62
- for doc in search_docs
63
- ])
64
- return {"web_results": formatted_search_docs}
65
-
66
- @tool(description="Search Arxiv for academic papers matching the query and return the first 1000 characters of each result")
67
- def arvix_search(query: str) -> str:
68
- search_docs = ArxivLoader(query=query, load_max_docs=10).load()
69
- formatted_search_docs = "\n\n---\n\n".join(
70
- [
71
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
72
- for doc in search_docs
73
- ])
74
- return {"arvix_results": formatted_search_docs}
75
-
76
-
77
- duck_duck_go_search_tool = DuckDuckGoSearchRun()
78
-
79
- system_prompt = (
80
- "You are a helpful assistant tasked with answering questions using a set of tools. "
81
- "Now, I will ask you a question. Report your thoughts, and finish your answer with the following template: "
82
- "FINAL ANSWER: [YOUR FINAL ANSWER]. "
83
- "YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. "
84
- "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. "
85
- "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. "
86
- "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. "
87
- "Your answer should only start with \"FINAL ANSWER: \", then follows with the answer."
88
- )
89
-
90
- sys_msg = SystemMessage(content=system_prompt)
91
-
92
- tools = [
93
- multiply,
94
- add,
95
- subtract,
96
- divide,
97
- modulus,
98
- wiki_search,
99
- web_search,
100
- arvix_search,
101
- duck_duck_go_search_tool,
102
- ]
103
-
104
- print("agent.py loaded")
105
-
106
-
107
- # Build graph function
108
- def build_graph(provider: str = "groq"):
109
- if provider == "groq":
110
- llm = ChatGroq(model="qwen/qwen3-32b", temperature=0, api_key='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')
111
- else:
112
- raise ValueError("Invalid provider. Choose 'groq'.")
113
-
114
- llm_with_tools = llm.bind_tools(tools)
115
-
116
- # Create BM25 retriever (example with Wikipedia + Arxiv docs)
117
- default_query = "artificial intelligence"
118
- all_docs = WikipediaLoader(query=default_query, load_max_docs=20).load() + ArxivLoader(query=default_query, load_max_docs=20).load()
119
-
120
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
121
- docs_chunks = text_splitter.split_documents(all_docs)
122
- bm25_retriever = BM25Retriever.from_documents(docs_chunks)
123
-
124
- def assistant(state: MessagesState):
125
- return {"messages": [llm_with_tools.invoke(state["messages"])]}
126
-
127
- def retriever(state: MessagesState):
128
- query = state["messages"][0].content
129
- similar_docs = bm25_retriever.get_relevant_documents(query)
130
- example_msg = HumanMessage(
131
- content=f"Here I provide a similar document for reference: \n\n{similar_docs[0].page_content if similar_docs else ''}",
132
- )
133
- return {"messages": [sys_msg] + state["messages"] + [example_msg]}
134
-
135
- builder = StateGraph(MessagesState)
136
- builder.add_node("retriever", retriever)
137
- builder.add_node("assistant", assistant)
138
- builder.add_node("tools", ToolNode(tools))
139
- builder.add_edge(START, "retriever")
140
- builder.add_edge("retriever", "assistant")
141
- builder.add_conditional_edges("assistant", tools_condition)
142
- builder.add_edge("tools", "assistant")
143
-
144
- return builder.compile()
145
-
146
-
147
- # Test
148
- if __name__ == "__main__":
149
- question = (
150
- "In terms of geographical distance between capital cities, which 2 countries are "
151
- "the furthest from each other within the ASEAN bloc according to wikipedia? "
152
- "Answer using a comma separated list, ordering the countries by alphabetical order."
153
- )
154
- graph = build_graph(provider="groq")
155
- messages = [HumanMessage(content=question)]
156
- messages = graph.invoke({"messages": messages})
157
- print(messages["messages"][-1].content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools.py → agent_tools.py RENAMED
@@ -1,17 +1,19 @@
 
1
  import re
2
  from typing import List
 
3
  import pandas as pd
4
  import requests
 
5
  from google import genai
6
  from google.genai import types
7
  from langchain_community.document_loaders import WebBaseLoader, ImageCaptionLoader, WikipediaLoader, ArxivLoader
8
- from langchain_community.retrievers import WikipediaRetriever
9
  from langchain_community.tools import DuckDuckGoSearchResults, TavilySearchResults
10
  from langchain_core.tools import tool
11
  from langchain_text_splitters import CharacterTextSplitter
12
- from langchain_community.tools import YouTubeSearchTool
13
 
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
15
 
16
 
17
  @tool(description="Multiply two integers and return the result")
@@ -239,7 +241,7 @@ def image_caption(dir: str) -> str:
239
  str: An answer to the question based on the video's content.
240
  """)
241
  def youtube_search(youtube_url: str, question: str) -> str:
242
- client = genai.Client(api_key="AIzaSyCAVxNjPshcsT3VLWeSJtPu0Jhi24wO5bs")
243
  response = client.models.generate_content(
244
  model='models/gemini-2.5-flash',
245
  contents=types.Content(
 
1
+ import os
2
  import re
3
  from typing import List
4
+
5
  import pandas as pd
6
  import requests
7
+ from dotenv import load_dotenv
8
  from google import genai
9
  from google.genai import types
10
  from langchain_community.document_loaders import WebBaseLoader, ImageCaptionLoader, WikipediaLoader, ArxivLoader
 
11
  from langchain_community.tools import DuckDuckGoSearchResults, TavilySearchResults
12
  from langchain_core.tools import tool
13
  from langchain_text_splitters import CharacterTextSplitter
 
14
 
15
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
16
+ load_dotenv()
17
 
18
 
19
  @tool(description="Multiply two integers and return the result")
 
241
  str: An answer to the question based on the video's content.
242
  """)
243
  def youtube_search(youtube_url: str, question: str) -> str:
244
+ client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))
245
  response = client.models.generate_content(
246
  model='models/gemini-2.5-flash',
247
  contents=types.Content(
requirements.txt CHANGED
@@ -25,4 +25,5 @@ langchain_openrouter
25
  langchain_google_genai
26
  langchain_openai
27
  google-genai
28
- openpyxl
 
 
25
  langchain_google_genai
26
  langchain_openai
27
  google-genai
28
+ openpyxl
29
+ chromadb
test.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from agent import CUSTOM_AGENT
2
+
3
+ questions = [
4
+ {
5
+ "task_id": "8e867cd7-cff9-4e6c-867a-ff5ddc2550be",
6
+ "question": "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.",
7
+ "file_name": ""
8
+ },
9
+ {
10
+ "task_id": "a1e91b78-d3d8-4675-bb8d-62741b4b68a6",
11
+ "question": "In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?",
12
+ "file_name": ""
13
+ },
14
+ {
15
+ "task_id": "2d83110e-a098-4ebb-9987-066c06fa42d0",
16
+ "question": ".rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI",
17
+ "file_name": ""
18
+ },
19
+ {
20
+ "task_id": "cca530fc-4052-43b2-b130-b30968d8aa44",
21
+ "question": "Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.",
22
+ "file_name": "cca530fc-4052-43b2-b130-b30968d8aa44.png"
23
+ },
24
+ {
25
+ "task_id": "4fc2f1ae-8625-45b5-ab34-ad4433bc21f8",
26
+ "question": "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?",
27
+ "file_name": ""
28
+ },
29
+ {
30
+ "task_id": "6f37996b-2ac7-44b0-8e68-6d28256631b4",
31
+ "question": "Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.",
32
+ "file_name": ""
33
+ },
34
+ {
35
+ "task_id": "9d191bce-651d-4746-be2d-7ef8ecadb9c2",
36
+ "question": "Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the question \"Isn't that hot?\"",
37
+ "file_name": ""
38
+ },
39
+ {
40
+ "task_id": "cabe07ed-9eca-40ea-8ead-410ef5e83f91",
41
+ "question": "What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?",
42
+ "Level": "1",
43
+ "file_name": ""
44
+ },
45
+ {
46
+ "task_id": "3cef3a44-215e-4aed-8e3b-b1e3f08063b7",
47
+ "question": "I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:\n\nmilk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts\n\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.",
48
+ "Level": "1",
49
+ "file_name": ""
50
+ },
51
+ {
52
+ "task_id": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3",
53
+ "question": "Hi, I'm making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I'm not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for \"a pinch of salt\" or \"two cups of ripe strawberries\" the ingredients on the list would be \"salt\" and \"ripe strawberries\".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.",
54
+ "file_name": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3"
55
+ },
56
+ {
57
+ "task_id": "305ac316-eef6-4446-960a-92d80d542f82",
58
+ "question": "Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.",
59
+ "file_name": ""
60
+ },
61
+ {
62
+ "task_id": "f918266a-b3e0-4914-865d-4faa564f1aef",
63
+ "question": "What is the final numeric output from the attached Python code?",
64
+ "file_name": "f918266a-b3e0-4914-865d-4faa564f1aef.py"
65
+ },
66
+ {
67
+ "task_id": "3f57289b-8c60-48be-bd80-01f8099ca449",
68
+ "question": "How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?",
69
+ "file_name": ""
70
+ },
71
+ {
72
+ "task_id": "1f975693-876d-457b-a649-393859e79bf3",
73
+ "question": "Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",
74
+ "file_name": "1f975693-876d-457b-a649-393859e79bf3.mp3"
75
+ },
76
+ {
77
+ "task_id": "840bfca7-4f7b-481a-8794-c560c340185d",
78
+ "question": "On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?",
79
+ "file_name": ""
80
+ },
81
+ {
82
+ "task_id": "bda648d7-d618-4883-88f4-3466eabd860e",
83
+ "question": "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.",
84
+ "file_name": ""
85
+ },
86
+ {
87
+ "task_id": "cf106601-ab4f-4af9-b045-5295fe67b37d",
88
+ "question": "What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.",
89
+ "file_name": ""
90
+ },
91
+ {
92
+ "task_id": "a0c07678-e491-4bbc-8f0b-07405144218f",
93
+ "question": "Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.",
94
+ "file_name": ""
95
+ },
96
+ {
97
+ "task_id": "7bd855d8-463d-4ed5-93ca-5fe35145f733",
98
+ "question": "The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.",
99
+ "file_name": "7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx"
100
+ },
101
+ {
102
+ "task_id": "5a0c1adf-205e-4841-a666-7c3ef95def9d",
103
+ "question": "What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?",
104
+ "file_name": ""
105
+ }
106
+ ]
107
+ # Test
108
+ if __name__ == "__main__":
109
+ agent = CUSTOM_AGENT()
110
+ q = questions[0]
111
+ print("Question:", q["question"])
112
+ answer = agent.run(q)
113
+ print("Answer:", answer)