dennis111 commited on
Commit
db29fc7
·
1 Parent(s): 2b380d2
Files changed (6) hide show
  1. agent.py +101 -2
  2. app.py +19 -2
  3. app_playground.ipynb +0 -0
  4. playground_api.ipynb +139 -1
  5. questions.csv +43 -0
  6. requirements.txt +3 -1
agent.py CHANGED
@@ -4,6 +4,8 @@ import time
4
  from typing import Optional
5
 
6
  from langchain.chat_models import init_chat_model
 
 
7
  from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, AnyMessage
8
  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
9
  from langgraph.graph import add_messages, START, END, StateGraph
@@ -48,6 +50,62 @@ def get_graph(llm):
48
  # Tavily retriever
49
  tavily_retriever = TavilySearchAPIRetriever(k=3)
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  @tool
52
  def retrieve(query: str):
53
  """
@@ -63,6 +121,20 @@ def get_graph(llm):
63
 
64
  return serialized
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  @tool
67
  def online_search(query: str):
68
  """
@@ -78,9 +150,36 @@ def get_graph(llm):
78
 
79
  return serialized
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
-
83
- tools = [retrieve, online_search]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  tool_node = ToolNode(tools)
85
  llm_with_tools = llm.bind_tools(tools)
86
 
 
4
  from typing import Optional
5
 
6
  from langchain.chat_models import init_chat_model
7
+ from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
8
+ from langchain_community.tools import TavilySearchResults
9
  from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, AnyMessage
10
  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
11
  from langgraph.graph import add_messages, START, END, StateGraph
 
50
  # Tavily retriever
51
  tavily_retriever = TavilySearchAPIRetriever(k=3)
52
 
53
+ @tool
54
+ def multiply(a: int, b: int) -> int:
55
+ """Multiply two numbers.
56
+ Args:
57
+ a: first int
58
+ b: second int
59
+ """
60
+ print("\n-------------------- Tool (Multiplication) has been called --------------------\n")
61
+ return a * b
62
+
63
+ @tool
64
+ def add(a: int, b: int) -> int:
65
+ """Add two numbers.
66
+
67
+ Args:
68
+ a: first int
69
+ b: second int
70
+ """
71
+ print("\n-------------------- Tool (Addition) has been called --------------------\n")
72
+ return a + b
73
+
74
+ @tool
75
+ def subtract(a: int, b: int) -> int:
76
+ """Subtract two numbers.
77
+
78
+ Args:
79
+ a: first int
80
+ b: second int
81
+ """
82
+ print("\n-------------------- Tool (Subtraction) has been called --------------------\n")
83
+ return a - b
84
+
85
+ @tool
86
+ def divide(a: int, b: int) -> int:
87
+ """Divide two numbers.
88
+
89
+ Args:
90
+ a: first int
91
+ b: second int
92
+ """
93
+ print("\n-------------------- Tool (Division) has been called --------------------\n")
94
+ if b == 0:
95
+ raise ValueError("Cannot divide by zero.")
96
+ return a / b
97
+
98
+ @tool
99
+ def modulus(a: int, b: int) -> int:
100
+ """Get the modulus of two numbers.
101
+
102
+ Args:
103
+ a: first int
104
+ b: second int
105
+ """
106
+ print("\n-------------------- Tool (Modulus) has been called --------------------\n")
107
+ return a % b
108
+
109
  @tool
110
  def retrieve(query: str):
111
  """
 
121
 
122
  return serialized
123
 
124
+ @tool
125
+ def wiki_search(query: str) -> str:
126
+ """Search Wikipedia for a query and return maximum 2 results.
127
+
128
+ Args:
129
+ query: The search query."""
130
+ search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
131
+ formatted_search_docs = "\n\n---\n\n".join(
132
+ [
133
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
134
+ for doc in search_docs
135
+ ])
136
+ return {"wiki_results": formatted_search_docs}
137
+
138
  @tool
139
  def online_search(query: str):
140
  """
 
150
 
151
  return serialized
152
 
153
+ @tool
154
+ def web_search(query: str) -> str:
155
+ """Search Tavily for a query and return maximum 3 results.
156
+
157
+ Args:
158
+ query: The search query."""
159
+ search_docs = TavilySearchResults(max_results=3).invoke(query=query)
160
+ formatted_search_docs = "\n\n---\n\n".join(
161
+ [
162
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
163
+ for doc in search_docs
164
+ ])
165
+ return {"web_results": formatted_search_docs}
166
 
167
+ @tool
168
+ def arvix_search(query: str) -> str:
169
+ """Search Arxiv for a query and return maximum 3 result.
170
+
171
+ Args:
172
+ query: The search query."""
173
+ print()
174
+ search_docs = ArxivLoader(query=query, load_max_docs=3).load()
175
+ formatted_search_docs = "\n\n---\n\n".join(
176
+ [
177
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
178
+ for doc in search_docs
179
+ ])
180
+ return {"arvix_results": formatted_search_docs}
181
+
182
+ tools = [wiki_search, web_search, arvix_search, multiply, add, subtract, divide, modulus]
183
  tool_node = ToolNode(tools)
184
  llm_with_tools = llm.bind_tools(tools)
185
 
app.py CHANGED
@@ -42,6 +42,23 @@ class BasicAgent:
42
  ]
43
  # Invoke the graph with the image
44
  response = self.graph.invoke({"messages": [HumanMessage(content=question_with_png),]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  else :
46
  # Invoke the graph with the question
47
  response = self.graph.invoke({"messages": [HumanMessage(content=question),]})
@@ -123,8 +140,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
123
 
124
  if content_type == "image/png":
125
  content = file.content
126
-
127
-
128
 
129
  if not task_id or question_text is None:
130
  print(f"Skipping item with missing task_id or question: {item}")
 
42
  ]
43
  # Invoke the graph with the image
44
  response = self.graph.invoke({"messages": [HumanMessage(content=question_with_png),]})
45
+ elif content_type == "text/x-python":
46
+ # Decode the content
47
+ content = content.decode("utf-8")
48
+ # Create message with the code
49
+ question_with_code = [{
50
+ "type": "text",
51
+ "text": question},
52
+ {
53
+ "type": "code",
54
+ "source_type": "text",
55
+ "data": content,
56
+ "mime_type": "text/x-python",
57
+
58
+ },
59
+ ]
60
+ # Invoke the graph with the code
61
+ response = self.graph.invoke({"messages": [HumanMessage(content=question_with_code),]})
62
  else :
63
  # Invoke the graph with the question
64
  response = self.graph.invoke({"messages": [HumanMessage(content=question),]})
 
140
 
141
  if content_type == "image/png":
142
  content = file.content
143
+ elif content_type == "text/x-python":
144
+ content = file.content.decode("utf-8")
145
 
146
  if not task_id or question_text is None:
147
  print(f"Skipping item with missing task_id or question: {item}")
app_playground.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
playground_api.ipynb CHANGED
@@ -665,13 +665,151 @@
665
  ],
666
  "execution_count": 11
667
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
668
  {
669
  "metadata": {},
670
  "cell_type": "code",
671
  "outputs": [],
672
  "execution_count": null,
673
  "source": "",
674
- "id": "6374fa56c240ea37"
675
  }
676
  ],
677
  "metadata": {
 
665
  ],
666
  "execution_count": 11
667
  },
668
+ {
669
+ "metadata": {
670
+ "ExecuteTime": {
671
+ "end_time": "2025-04-29T15:09:54.403319Z",
672
+ "start_time": "2025-04-29T15:09:53.492844Z"
673
+ }
674
+ },
675
+ "cell_type": "code",
676
+ "source": [
677
+ "import pandas as pd\n",
678
+ "import json\n",
679
+ "# read the data from the json file\n",
680
+ "with open('data.json', 'r') as json_file:\n",
681
+ " data = json.load(json_file)\n",
682
+ "\n",
683
+ "df = pd.json_normalize(data)"
684
+ ],
685
+ "id": "6374fa56c240ea37",
686
+ "outputs": [],
687
+ "execution_count": 1
688
+ },
689
+ {
690
+ "metadata": {
691
+ "ExecuteTime": {
692
+ "end_time": "2025-04-29T15:12:51.673281Z",
693
+ "start_time": "2025-04-29T15:12:51.667626Z"
694
+ }
695
+ },
696
+ "cell_type": "code",
697
+ "source": "df.to_csv(r\"C:\\Users\\dennis.binzen\\PycharmProjects\\Final_Assignment\\questions.csv\", index=False)",
698
+ "id": "716173bb90f8835a",
699
+ "outputs": [],
700
+ "execution_count": 8
701
+ },
702
+ {
703
+ "metadata": {},
704
+ "cell_type": "code",
705
+ "outputs": [],
706
+ "execution_count": null,
707
+ "source": "",
708
+ "id": "c049f1c30bb8d62"
709
+ },
710
+ {
711
+ "metadata": {},
712
+ "cell_type": "code",
713
+ "outputs": [],
714
+ "execution_count": null,
715
+ "source": "",
716
+ "id": "f07e349d8b8c5ef0"
717
+ },
718
+ {
719
+ "metadata": {},
720
+ "cell_type": "markdown",
721
+ "source": " # Test File",
722
+ "id": "b15b5b960c6da99b"
723
+ },
724
+ {
725
+ "metadata": {
726
+ "ExecuteTime": {
727
+ "end_time": "2025-04-30T07:44:43.980549Z",
728
+ "start_time": "2025-04-30T07:44:31.398447Z"
729
+ }
730
+ },
731
+ "cell_type": "code",
732
+ "source": [
733
+ "import requests\n",
734
+ "url = \"https://agents-course-unit4-scoring.hf.space\"\n",
735
+ "task_id = \"f918266a-b3e0-4914-865d-4faa564f1aef\"\n",
736
+ "\n",
737
+ "qs = requests.get(f\"{url}/questions\").json()\n",
738
+ "\n",
739
+ "file = requests.get(f\"{url}/files/{task_id}\")"
740
+ ],
741
+ "id": "5b7ae8896d3dc148",
742
+ "outputs": [],
743
+ "execution_count": 10
744
+ },
745
+ {
746
+ "metadata": {
747
+ "ExecuteTime": {
748
+ "end_time": "2025-04-30T07:45:00.601163Z",
749
+ "start_time": "2025-04-30T07:45:00.595534Z"
750
+ }
751
+ },
752
+ "cell_type": "code",
753
+ "source": "file.headers.get(\"Content-Type\")",
754
+ "id": "be8292701e96d5de",
755
+ "outputs": [
756
+ {
757
+ "data": {
758
+ "text/plain": [
759
+ "'text/x-python; charset=utf-8'"
760
+ ]
761
+ },
762
+ "execution_count": 11,
763
+ "metadata": {},
764
+ "output_type": "execute_result"
765
+ }
766
+ ],
767
+ "execution_count": 11
768
+ },
769
+ {
770
+ "metadata": {
771
+ "ExecuteTime": {
772
+ "end_time": "2025-04-30T07:46:16.127266Z",
773
+ "start_time": "2025-04-30T07:46:16.123493Z"
774
+ }
775
+ },
776
+ "cell_type": "code",
777
+ "source": "content = file.content",
778
+ "id": "985e30b84a6f450",
779
+ "outputs": [],
780
+ "execution_count": 12
781
+ },
782
+ {
783
+ "metadata": {
784
+ "ExecuteTime": {
785
+ "end_time": "2025-04-30T07:46:44.072979Z",
786
+ "start_time": "2025-04-30T07:46:44.068393Z"
787
+ }
788
+ },
789
+ "cell_type": "code",
790
+ "source": "content.decode(\"utf-8\")",
791
+ "id": "f2031ab0bc44881c",
792
+ "outputs": [
793
+ {
794
+ "data": {
795
+ "text/plain": [
796
+ "'from random import randint\\nimport time\\n\\nclass UhOh(Exception):\\n pass\\n\\nclass Hmm:\\n def __init__(self):\\n self.value = randint(-100, 100)\\n\\n def Yeah(self):\\n if self.value == 0:\\n return True\\n else:\\n raise UhOh()\\n\\ndef Okay():\\n while True:\\n yield Hmm()\\n\\ndef keep_trying(go, first_try=True):\\n maybe = next(go)\\n try:\\n if maybe.Yeah():\\n return maybe.value\\n except UhOh:\\n if first_try:\\n print(\"Working...\")\\n print(\"Please wait patiently...\")\\n time.sleep(0.1)\\n return keep_trying(go, first_try=False)\\n\\nif __name__ == \"__main__\":\\n go = Okay()\\n print(f\"{keep_trying(go)}\")\\n'"
797
+ ]
798
+ },
799
+ "execution_count": 15,
800
+ "metadata": {},
801
+ "output_type": "execute_result"
802
+ }
803
+ ],
804
+ "execution_count": 15
805
+ },
806
  {
807
  "metadata": {},
808
  "cell_type": "code",
809
  "outputs": [],
810
  "execution_count": null,
811
  "source": "",
812
+ "id": "884714e1c0a073bf"
813
  }
814
  ],
815
  "metadata": {
questions.csv ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ task_id,question,Level,file_name
2
+ 8e867cd7-cff9-4e6c-867a-ff5ddc2550be,How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.,1,
3
+ a1e91b78-d3d8-4675-bb8d-62741b4b68a6,"In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?",1,
4
+ 2d83110e-a098-4ebb-9987-066c06fa42d0,".rewsna eht sa ""tfel"" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI",1,
5
+ cca530fc-4052-43b2-b130-b30968d8aa44,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.,1,cca530fc-4052-43b2-b130-b30968d8aa44.png
6
+ 4fc2f1ae-8625-45b5-ab34-ad4433bc21f8,Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?,1,
7
+ 6f37996b-2ac7-44b0-8e68-6d28256631b4,"Given this table defining * on the set S = {a, b, c, d, e}
8
+
9
+ |*|a|b|c|d|e|
10
+ |---|---|---|---|---|---|
11
+ |a|a|b|c|b|d|
12
+ |b|b|c|a|e|c|
13
+ |c|c|a|b|b|a|
14
+ |d|b|e|b|e|d|
15
+ |e|d|b|a|d|c|
16
+
17
+ provide 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.",1,
18
+ 9d191bce-651d-4746-be2d-7ef8ecadb9c2,"Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.
19
+
20
+ What does Teal'c say in response to the question ""Isn't that hot?""",1,
21
+ cabe07ed-9eca-40ea-8ead-410ef5e83f91,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?,1,
22
+ 3cef3a44-215e-4aed-8e3b-b1e3f08063b7,"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:
23
+
24
+ milk, 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
25
+
26
+ I 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.",1,
27
+ 99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3,"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.
28
+
29
+ In 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"".
30
+
31
+ Please format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.",1,99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3
32
+ 305ac316-eef6-4446-960a-92d80d542f82,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.,1,
33
+ f918266a-b3e0-4914-865d-4faa564f1aef,What is the final numeric output from the attached Python code?,1,f918266a-b3e0-4914-865d-4faa564f1aef.py
34
+ 3f57289b-8c60-48be-bd80-01f8099ca449,How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?,1,
35
+ 1f975693-876d-457b-a649-393859e79bf3,"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 :(
36
+
37
+ Could 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.",1,1f975693-876d-457b-a649-393859e79bf3.mp3
38
+ 840bfca7-4f7b-481a-8794-c560c340185d,"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?",1,
39
+ bda648d7-d618-4883-88f4-3466eabd860e,Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.,1,
40
+ cf106601-ab4f-4af9-b045-5295fe67b37d,"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.",1,
41
+ a0c07678-e491-4bbc-8f0b-07405144218f,"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.",1,
42
+ 7bd855d8-463d-4ed5-93ca-5fe35145f733,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.,1,7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx
43
+ 5a0c1adf-205e-4841-a666-7c3ef95def9d,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?,1,
requirements.txt CHANGED
@@ -13,4 +13,6 @@ wikipedia ~= 1.4.0
13
  langchain-google-genai ~=2.1.3
14
  tavily-python ~=0.7.0
15
  pandas ~=2.2.3
16
- matplotlib ~=3.10.1
 
 
 
13
  langchain-google-genai ~=2.1.3
14
  tavily-python ~=0.7.0
15
  pandas ~=2.2.3
16
+ matplotlib ~=3.10.1
17
+ arxiv ~=2.2.0
18
+ pymupdf ~=1.25.5