DrekFretson commited on
Commit
3fa8fb7
·
verified ·
1 Parent(s): cab2b39

Delete test.ipynb

Browse files
Files changed (1) hide show
  1. test.ipynb +0 -471
test.ipynb DELETED
@@ -1,471 +0,0 @@
1
- Question data
2
- # Load metadata.jsonl
3
- import json
4
- # Load the metadata.jsonl file
5
- with open('metadata.jsonl', 'r') as jsonl_file:
6
- json_list = list(jsonl_file)
7
-
8
- json_QA = []
9
- for json_str in json_list:
10
- json_data = json.loads(json_str)
11
- json_QA.append(json_data)
12
- # randomly select 3 samples
13
- # {"task_id": "c61d22de-5f6c-4958-a7f6-5e9707bd3466", "Question": "A paper about AI regulation that was originally submitted to arXiv.org in June 2022 shows a figure with three axes, where each axis has a label word at both ends. Which of these words is used to describe a type of society in a Physics and Society article submitted to arXiv.org on August 11, 2016?", "Level": 2, "Final answer": "egalitarian", "file_name": "", "Annotator Metadata": {"Steps": "1. Go to arxiv.org and navigate to the Advanced Search page.\n2. Enter \"AI regulation\" in the search box and select \"All fields\" from the dropdown.\n3. Enter 2022-06-01 and 2022-07-01 into the date inputs, select \"Submission date (original)\", and submit the search.\n4. Go through the search results to find the article that has a figure with three axes and labels on each end of the axes, titled \"Fairness in Agreement With European Values: An Interdisciplinary Perspective on AI Regulation\".\n5. Note the six words used as labels: deontological, egalitarian, localized, standardized, utilitarian, and consequential.\n6. Go back to arxiv.org\n7. Find \"Physics and Society\" and go to the page for the \"Physics and Society\" category.\n8. Note that the tag for this category is \"physics.soc-ph\".\n9. Go to the Advanced Search page.\n10. Enter \"physics.soc-ph\" in the search box and select \"All fields\" from the dropdown.\n11. Enter 2016-08-11 and 2016-08-12 into the date inputs, select \"Submission date (original)\", and submit the search.\n12. Search for instances of the six words in the results to find the paper titled \"Phase transition from egalitarian to hierarchical societies driven by competition between cognitive and social constraints\", indicating that \"egalitarian\" is the correct answer.", "Number of steps": "12", "How long did this take?": "8 minutes", "Tools": "1. Web browser\n2. Image recognition tools (to identify and parse a figure with three axes)", "Number of tools": "2"}}
14
-
15
- import random
16
- # random.seed(42)
17
- random_samples = random.sample(json_QA, 1)
18
- for sample in random_samples:
19
- print("=" * 50)
20
- print(f"Task ID: {sample['task_id']}")
21
- print(f"Question: {sample['Question']}")
22
- print(f"Level: {sample['Level']}")
23
- print(f"Final Answer: {sample['Final answer']}")
24
- print(f"Annotator Metadata: ")
25
- print(f" ├── Steps: ")
26
- for step in sample['Annotator Metadata']['Steps'].split('\n'):
27
- print(f" │ ├── {step}")
28
- print(f" ├── Number of steps: {sample['Annotator Metadata']['Number of steps']}")
29
- print(f" ├── How long did this take?: {sample['Annotator Metadata']['How long did this take?']}")
30
- print(f" ├── Tools:")
31
- for tool in sample['Annotator Metadata']['Tools'].split('\n'):
32
- print(f" │ ├── {tool}")
33
- print(f" └── Number of tools: {sample['Annotator Metadata']['Number of tools']}")
34
- print("=" * 50)
35
- ==================================================
36
- Task ID: ed58682d-bc52-4baa-9eb0-4eb81e1edacc
37
- Question: What is the last word before the second chorus of the King of Pop's fifth single from his sixth studio album?
38
- Level: 2
39
- Final Answer: stare
40
- Annotator Metadata:
41
- ├── Steps:
42
- │ ├── 1. Google searched "King of Pop".
43
- │ ├── 2. Clicked on Michael Jackson's Wikipedia.
44
- │ ├── 3. Scrolled down to "Discography".
45
- │ ├── 4. Clicked on the sixth album, "Thriller".
46
- │ ├── 5. Looked under "Singles from Thriller".
47
- │ ├── 6. Clicked on the fifth single, "Human Nature".
48
- │ ├── 7. Google searched "Human Nature Michael Jackson Lyrics".
49
- │ ├── 8. Looked at the opening result with full lyrics sourced by Musixmatch.
50
- │ ├── 9. Looked for repeating lyrics to determine the chorus.
51
- │ ├── 10. Determined the chorus begins with "If they say" and ends with "Does he do me that way?"
52
- │ ├── 11. Found the second instance of the chorus within the lyrics.
53
- │ ├── 12. Noted the last word before the second chorus - "stare".
54
- ├── Number of steps: 12
55
- ├── How long did this take?: 20 minutes
56
- ├── Tools:
57
- │ ├── Web Browser
58
- └── Number of tools: 1
59
- ==================================================
60
- ### build a vector database based on the metadata.jsonl
61
- # https://python.langchain.com/docs/integrations/vectorstores/supabase/
62
- import os
63
- from dotenv import load_dotenv
64
- from langchain_huggingface import HuggingFaceEmbeddings
65
- from langchain_community.vectorstores import SupabaseVectorStore
66
- from supabase.client import Client, create_client
67
-
68
-
69
- load_dotenv()
70
- embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # dim=768
71
-
72
- supabase_url = os.environ.get("SUPABASE_URL")
73
- supabase_key = os.environ.get("SUPABASE_SERVICE_KEY")
74
- supabase: Client = create_client(supabase_url, supabase_key)
75
- # wrap the metadata.jsonl's questions and answers into a list of document
76
- from langchain.schema import Document
77
- docs = []
78
- for sample in json_QA:
79
- content = f"Question : {sample['Question']}\n\nFinal answer : {sample['Final answer']}"
80
- doc = {
81
- "content" : content,
82
- "metadata" : { # meatadata的格式必须时source键,否则会报错
83
- "source" : sample['task_id']
84
- },
85
- "embedding" : embeddings.embed_query(content),
86
- }
87
- docs.append(doc)
88
-
89
- # upload the documents to the vector database
90
- try:
91
- response = (
92
- supabase.table("documents")
93
- .insert(docs)
94
- .execute()
95
- )
96
- except Exception as exception:
97
- print("Error inserting data into Supabase:", exception)
98
-
99
- # ALTERNATIVE : Save the documents (a list of dict) into a csv file, and manually upload it to Supabase
100
- # import pandas as pd
101
- # df = pd.DataFrame(docs)
102
- # df.to_csv('supabase_docs.csv', index=False)
103
- # add items to vector database
104
- vector_store = SupabaseVectorStore(
105
- client=supabase,
106
- embedding= embeddings,
107
- table_name="documents",
108
- query_name="match_documents_langchain",
109
- )
110
- retriever = vector_store.as_retriever()
111
- query = "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?"
112
- # matched_docs = vector_store.similarity_search(query, 2)
113
- docs = retriever.invoke(query)
114
- docs[0]
115
- huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...
116
- To disable this warning, you can either:
117
- - Avoid using `tokenizers` before the fork if possible
118
- - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)
119
- Document(metadata={'source': '840bfca7-4f7b-481a-8794-c560c340185d'}, page_content='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?\n\nFinal answer : 80GSFC21M0002')
120
- # list of the tools used in all the samples
121
- from collections import Counter, OrderedDict
122
-
123
- tools = []
124
- for sample in json_QA:
125
- for tool in sample['Annotator Metadata']['Tools'].split('\n'):
126
- tool = tool[2:].strip().lower()
127
- if tool.startswith("("):
128
- tool = tool[11:].strip()
129
- tools.append(tool)
130
- tools_counter = OrderedDict(Counter(tools))
131
- print("List of tools used in all samples:")
132
- print("Total number of tools used:", len(tools_counter))
133
- for tool, count in tools_counter.items():
134
- print(f" ├── {tool}: {count}")
135
- List of tools used in all samples:
136
- Total number of tools used: 83
137
- ├── web browser: 107
138
- ├── image recognition tools (to identify and parse a figure with three axes): 1
139
- ├── search engine: 101
140
- ├── calculator: 34
141
- ├── unlambda compiler (optional): 1
142
- ├── a web browser.: 2
143
- ├── a search engine.: 2
144
- ├── a calculator.: 1
145
- ├── microsoft excel: 5
146
- ├── google search: 1
147
- ├── ne: 9
148
- ├── pdf access: 7
149
- ├── file handling: 2
150
- ├── python: 3
151
- ├── image recognition tools: 12
152
- ├── jsonld file access: 1
153
- ├── video parsing: 1
154
- ├── python compiler: 1
155
- ├── video recognition tools: 3
156
- ├── pdf viewer: 7
157
- ├── microsoft excel / google sheets: 3
158
- ├── word document access: 1
159
- ├── tool to extract text from images: 1
160
- ├── a word reversal tool / script: 1
161
- ├── counter: 1
162
- ├── excel: 3
163
- ├── image recognition: 5
164
- ├── color recognition: 3
165
- ├── excel file access: 3
166
- ├── xml file access: 1
167
- ├── access to the internet archive, web.archive.org: 1
168
- ├── text processing/diff tool: 1
169
- ├── gif parsing tools: 1
170
- ├── a web browser: 7
171
- ├── a search engine: 7
172
- ├── a speech-to-text tool: 2
173
- ├── code/data analysis tools: 1
174
- ├── audio capability: 2
175
- ├── pdf reader: 1
176
- ├── markdown: 1
177
- ├── a calculator: 5
178
- ├── access to wikipedia: 3
179
- ├── image recognition/ocr: 3
180
- ├── google translate access: 1
181
- ├── ocr: 4
182
- ├── bass note data: 1
183
- ├── text editor: 1
184
- ├── xlsx file access: 1
185
- ├── powerpoint viewer: 1
186
- ├── csv file access: 1
187
- ├── calculator (or use excel): 1
188
- ├── computer algebra system: 1
189
- ├── video processing software: 1
190
- ├── audio processing software: 1
191
- ├── computer vision: 1
192
- ├── google maps: 1
193
- ├── access to excel files: 1
194
- ├── calculator (or ability to count): 1
195
- ├── a file interface: 3
196
- ├── a python ide: 1
197
- ├── spreadsheet editor: 1
198
- ├── tools required: 1
199
- ├── b browser: 1
200
- ├── image recognition and processing tools: 1
201
- ├── computer vision or ocr: 1
202
- ├── c++ compiler: 1
203
- ├── access to google maps: 1
204
- ├── youtube player: 1
205
- ├── natural language processor: 1
206
- ├── graph interaction tools: 1
207
- ├── bablyonian cuniform -> arabic legend: 1
208
- ├── access to youtube: 1
209
- ├── image search tools: 1
210
- ├── calculator or counting function: 1
211
- ├── a speech-to-text audio processing tool: 1
212
- ├── access to academic journal websites: 1
213
- ├── pdf reader/extracter: 1
214
- ├── rubik's cube model: 1
215
- ├── wikipedia: 1
216
- ├── video capability: 1
217
- ├── image processing tools: 1
218
- ├── age recognition software: 1
219
- ├── youtube: 1
220
- Graph
221
- system_prompt = """
222
- You are a helpful assistant tasked with answering questions using a set of tools.
223
- If the tool is not available, you can try to find the information online. You can also use your own knowledge to answer the question.
224
- You need to provide a step-by-step explanation of how you arrived at the answer.
225
- ==========================
226
- Here is a few examples showing you how to answer the question step by step.
227
- """
228
- for i, samples in enumerate(random_samples):
229
- system_prompt += f"\nQuestion {i+1}: {samples['Question']}\nSteps:\n{samples['Annotator Metadata']['Steps']}\nTools:\n{samples['Annotator Metadata']['Tools']}\nFinal Answer: {samples['Final answer']}\n"
230
- system_prompt += "\n==========================\n"
231
- system_prompt += "Now, please answer the following question step by step.\n"
232
-
233
- # save the system_prompt to a file
234
- with open('system_prompt.txt', 'w') as f:
235
- f.write(system_prompt)
236
- # load the system prompt from the file
237
- with open('system_prompt.txt', 'r') as f:
238
- system_prompt = f.read()
239
- print(system_prompt)
240
- You are a helpful assistant tasked with answering questions using a set of tools.
241
- If the tool is not available, you can try to find the information online. You can also use your own knowledge to answer the question.
242
- You need to provide a step-by-step explanation of how you arrived at the answer.
243
- ==========================
244
- Here is a few examples showing you how to answer the question step by step.
245
-
246
- Question 1: In terms of geographical distance between capital cities, which 2 countries are the furthest from each other within the ASEAN bloc according to wikipedia? Answer using a comma separated list, ordering the countries by alphabetical order.
247
- Steps:
248
- 1. Search the web for "ASEAN bloc".
249
- 2. Click the Wikipedia result for the ASEAN Free Trade Area.
250
- 3. Scroll down to find the list of member states.
251
- 4. Click into the Wikipedia pages for each member state, and note its capital.
252
- 5. Search the web for the distance between the first two capitals. The results give travel distance, not geographic distance, which might affect the answer.
253
- 6. Thinking it might be faster to judge the distance by looking at a map, search the web for "ASEAN bloc" and click into the images tab.
254
- 7. View a map of the member countries. Since they're clustered together in an arrangement that's not very linear, it's difficult to judge distances by eye.
255
- 8. Return to the Wikipedia page for each country. Click the GPS coordinates for each capital to get the coordinates in decimal notation.
256
- 9. Place all these coordinates into a spreadsheet.
257
- 10. Write formulas to calculate the distance between each capital.
258
- 11. Write formula to get the largest distance value in the spreadsheet.
259
- 12. Note which two capitals that value corresponds to: Jakarta and Naypyidaw.
260
- 13. Return to the Wikipedia pages to see which countries those respective capitals belong to: Indonesia, Myanmar.
261
- Tools:
262
- 1. Search engine
263
- 2. Web browser
264
- 3. Microsoft Excel / Google Sheets
265
- Final Answer: Indonesia, Myanmar
266
-
267
- Question 2: 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.
268
- Steps:
269
- Step 1: Evaluate the position of the pieces in the chess position
270
- Step 2: Report the best move available for black: "Rd5"
271
- Tools:
272
- 1. Image recognition tools
273
- Final Answer: Rd5
274
-
275
- ==========================
276
- Now, please answer the following question step by step.
277
-
278
- import dotenv
279
- from langgraph.graph import MessagesState, START, StateGraph
280
- from langgraph.prebuilt import tools_condition
281
- from langgraph.prebuilt import ToolNode
282
- from langchain_google_genai import ChatGoogleGenerativeAI
283
- from langchain_huggingface import HuggingFaceEmbeddings
284
- from langchain_community.tools.tavily_search import TavilySearchResults
285
- from langchain_community.document_loaders import WikipediaLoader
286
- from langchain_community.document_loaders import ArxivLoader
287
- from langchain_community.vectorstores import SupabaseVectorStore
288
- from langchain.tools.retriever import create_retriever_tool
289
- from langchain_core.messages import HumanMessage, SystemMessage
290
- from langchain_core.tools import tool
291
- from supabase.client import Client, create_client
292
-
293
- # Define the retriever from supabase
294
- load_dotenv()
295
- embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # dim=768
296
-
297
- supabase_url = os.environ.get("SUPABASE_URL")
298
- supabase_key = os.environ.get("SUPABASE_SERVICE_KEY")
299
- supabase: Client = create_client(supabase_url, supabase_key)
300
- vector_store = SupabaseVectorStore(
301
- client=supabase,
302
- embedding= embeddings,
303
- table_name="documents",
304
- query_name="match_documents_langchain",
305
- )
306
-
307
- question_retrieve_tool = create_retriever_tool(
308
- vector_store.as_retriever(),
309
- "Question Retriever",
310
- "Find similar questions in the vector database for the given question.",
311
- )
312
-
313
- @tool
314
- def multiply(a: int, b: int) -> int:
315
- """Multiply two numbers.
316
-
317
- Args:
318
- a: first int
319
- b: second int
320
- """
321
- return a * b
322
-
323
- @tool
324
- def add(a: int, b: int) -> int:
325
- """Add two numbers.
326
-
327
- Args:
328
- a: first int
329
- b: second int
330
- """
331
- return a + b
332
-
333
- @tool
334
- def subtract(a: int, b: int) -> int:
335
- """Subtract two numbers.
336
-
337
- Args:
338
- a: first int
339
- b: second int
340
- """
341
- return a - b
342
-
343
- @tool
344
- def divide(a: int, b: int) -> int:
345
- """Divide two numbers.
346
-
347
- Args:
348
- a: first int
349
- b: second int
350
- """
351
- if b == 0:
352
- raise ValueError("Cannot divide by zero.")
353
- return a / b
354
-
355
- @tool
356
- def modulus(a: int, b: int) -> int:
357
- """Get the modulus of two numbers.
358
-
359
- Args:
360
- a: first int
361
- b: second int
362
- """
363
- return a % b
364
-
365
- @tool
366
- def wiki_search(query: str) -> str:
367
- """Search Wikipedia for a query and return maximum 2 results.
368
-
369
- Args:
370
- query: The search query."""
371
- search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
372
- formatted_search_docs = "\n\n---\n\n".join(
373
- [
374
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
375
- for doc in search_docs
376
- ])
377
- return {"wiki_results": formatted_search_docs}
378
-
379
- @tool
380
- def web_search(query: str) -> str:
381
- """Search Tavily for a query and return maximum 3 results.
382
-
383
- Args:
384
- query: The search query."""
385
- search_docs = TavilySearchResults(max_results=3).invoke(query=query)
386
- formatted_search_docs = "\n\n---\n\n".join(
387
- [
388
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
389
- for doc in search_docs
390
- ])
391
- return {"web_results": formatted_search_docs}
392
-
393
- @tool
394
- def arvix_search(query: str) -> str:
395
- """Search Arxiv for a query and return maximum 3 result.
396
-
397
- Args:
398
- query: The search query."""
399
- search_docs = ArxivLoader(query=query, load_max_docs=3).load()
400
- formatted_search_docs = "\n\n---\n\n".join(
401
- [
402
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
403
- for doc in search_docs
404
- ])
405
- return {"arvix_results": formatted_search_docs}
406
-
407
- @tool
408
- def similar_question_search(question: str) -> str:
409
- """Search the vector database for similar questions and return the first results.
410
-
411
- Args:
412
- question: the question human provided."""
413
- matched_docs = vector_store.similarity_search(query, 3)
414
- formatted_search_docs = "\n\n---\n\n".join(
415
- [
416
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
417
- for doc in matched_docs
418
- ])
419
- return {"similar_questions": formatted_search_docs}
420
-
421
- tools = [
422
- multiply,
423
- add,
424
- subtract,
425
- divide,
426
- modulus,
427
- wiki_search,
428
- web_search,
429
- arvix_search,
430
- question_retrieve_tool
431
- ]
432
-
433
- llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash")
434
- llm_with_tools = llm.bind_tools(tools)
435
- # load the system prompt from the file
436
- with open('system_prompt.txt', 'r') as f:
437
- system_prompt = f.read()
438
-
439
-
440
- # System message
441
- sys_msg = SystemMessage(content=system_prompt)
442
-
443
- # Node
444
- def assistant(state: MessagesState):
445
- """Assistant node"""
446
- return {"messages": [llm_with_tools.invoke([sys_msg] + state["messages"])]}
447
-
448
- # Build graph
449
- builder = StateGraph(MessagesState)
450
- builder.add_node("assistant", assistant)
451
- builder.add_node("tools", ToolNode(tools))
452
- builder.add_edge(START, "assistant")
453
- builder.add_conditional_edges(
454
- "assistant",
455
- # If the latest message (result) from assistant is a tool call -> tools_condition routes to tools
456
- # If the latest message (result) from assistant is a not a tool call -> tools_condition routes to END
457
- tools_condition,
458
- )
459
- builder.add_edge("tools", "assistant")
460
-
461
- # Compile graph
462
- graph = builder.compile()
463
- from IPython.display import Image, display
464
-
465
- display(Image(graph.get_graph(xray=True).draw_mermaid_png()))
466
-
467
- question = ""
468
- messages = [HumanMessage(content=question)]
469
- messages = graph.invoke({"messages": messages})
470
- for m in messages['messages']:
471
- m.pretty_print()