Vladx commited on
Commit
1ca95c5
·
1 Parent(s): 6a82ce1
Files changed (12) hide show
  1. .gitattributes +0 -35
  2. .gitignore +130 -69
  3. README.md +90 -1
  4. agent.py +693 -115
  5. app.py +9 -7
  6. code_interpreter.py +281 -0
  7. explore_metadata.ipynb +332 -0
  8. image_processing.py +26 -0
  9. requirements.txt +3 -1
  10. supabase_docs.csv +0 -0
  11. system_prompt.txt +5 -17
  12. test.ipynb +0 -684
.gitattributes DELETED
@@ -1,35 +0,0 @@
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore CHANGED
@@ -2,6 +2,8 @@
2
  __pycache__/
3
  *.py[cod]
4
  *$py.class
 
 
5
  *.so
6
 
7
  # Distribution / packaging
@@ -18,19 +20,21 @@ parts/
18
  sdist/
19
  var/
20
  wheels/
 
21
  *.egg-info/
22
  .installed.cfg
23
  *.egg
 
24
 
25
- # Virtual environments
26
- venv/
27
- ENV/
28
- env/
29
- .env
30
- .venv
31
- env.bak/
32
- venv.bak/
33
- .python-version
34
 
35
  # Unit test / coverage reports
36
  htmlcov/
@@ -42,9 +46,34 @@ htmlcov/
42
  nosetests.xml
43
  coverage.xml
44
  *.cover
 
45
  .hypothesis/
46
  .pytest_cache/
47
- pytest-*.xml
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  # Jupyter Notebook
50
  .ipynb_checkpoints
@@ -53,64 +82,96 @@ pytest-*.xml
53
  profile_default/
54
  ipython_config.py
55
 
56
- # Logs
57
- *.log
58
- logs/
59
- log/
60
-
61
- # IDE specific files
62
- .idea/
63
- .vscode/
64
- *.swp
65
- *.swo
66
- *~
67
- .DS_Store
68
- .project
69
- .pydevproject
70
- .settings/
71
- .vs/
72
- *.sublime-project
73
- *.sublime-workspace
74
-
75
- # Database
76
- *.db
77
- *.rdb
78
- *.sqlite
79
- *.sqlite3
80
-
81
- # Environment variables
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  .env
83
- .env.local
84
- .env.development.local
85
- .env.test.local
86
- .env.production.local
87
-
88
- # macOS specific
89
- .DS_Store
90
- .AppleDouble
91
- .LSOverride
92
- Icon
93
- ._*
94
- .DocumentRevisions-V100
95
- .fseventsd
96
- .Spotlight-V100
97
- .TemporaryItems
98
- .Trashes
99
- .VolumeIcon.icns
100
- .com.apple.timemachine.donotpresent
101
-
102
- # AI/model files
103
- *.h5
104
- *.pb
105
- *.onnx
106
- *.tflite
107
- *.pt
108
- *.pth
109
- *.weights
110
-
111
- # Temporary files
112
- tmp/
113
- temp/
114
- .tmp
115
- *.tmp
 
 
 
 
 
 
 
 
 
 
116
 
 
 
 
2
  __pycache__/
3
  *.py[cod]
4
  *$py.class
5
+
6
+ # C extensions
7
  *.so
8
 
9
  # Distribution / packaging
 
20
  sdist/
21
  var/
22
  wheels/
23
+ share/python-wheels/
24
  *.egg-info/
25
  .installed.cfg
26
  *.egg
27
+ MANIFEST
28
 
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
 
39
  # Unit test / coverage reports
40
  htmlcov/
 
46
  nosetests.xml
47
  coverage.xml
48
  *.cover
49
+ *.py,cover
50
  .hypothesis/
51
  .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
 
78
  # Jupyter Notebook
79
  .ipynb_checkpoints
 
82
  profile_default/
83
  ipython_config.py
84
 
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
  .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Ruff stuff:
171
+ .ruff_cache/
172
+
173
+ # PyPI configuration file
174
+ .pypirc
175
 
176
+ ###
177
+ /image_outputs
README.md CHANGED
@@ -12,4 +12,93 @@ hf_oauth: true
12
  hf_oauth_expiration_minutes: 480
13
  ---
14
 
15
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  hf_oauth_expiration_minutes: 480
13
  ---
14
 
15
+ # **GAIA Agent**
16
+
17
+ ## **Introduction**
18
+
19
+ **GAIA Agent** is an automated system built to tackle and submit solutions for the GAIA benchmark, which tests the capabilities of general-purpose AI agents on diverse and challenging tasks. These tasks require a combination of reasoning, code execution, information retrieval, data interpretation, and multimodal understanding. Powered by advanced language models (such as HuggingFace, and Groq), the agent incorporates a versatile set of tools including browser tools, code interpreter tools, mathematical tools, document processing tools, image processing and generation tools. It is designed for seamless interaction with the benchmark, offering automatic evaluation, submission, and result display through a user-friendly Gradio interface.
20
+
21
+ ## **Tools Implementation**
22
+
23
+ ### **Browser tools**
24
+ - **Wikipedia Search:** Search Wikipedia for a query and return maximum 2 results.
25
+ - **Web Search:** Search the web for a query and return maximum 2 results.
26
+ - **Arxiv Search:** Search arXiv for a query and return maximum 2 results.
27
+
28
+ ### **Code interpreter tools**
29
+ - **Execute Multi-programming Language:** Execute code in multiple languages (Python, Bash, SQL, C, Java) and return results.
30
+
31
+ ### **Mathematical tools**
32
+ - **Multiplication Tools:** Multiplies 2 numbers
33
+ - **Addition:** Adds 2 numbers
34
+ - **Subtraction:** Subtracts 2 numbers
35
+ - **Division:** Divides 2 numbers
36
+ - **Modulus:** Get the modulus of 2 numbers
37
+ - **Power:** Get the power of 2 numbers
38
+ - **Square root:** Get the square root of a number
39
+
40
+ ### **Document processing tools**
41
+ - **Save and Read File:** Save content to a file and return the path
42
+ - **Download a File from URL:** Download a file from a URL and save it to a temporary location
43
+ - **Extract Text from Image:** Extract text from an image using OCR library pytesseract (if available)
44
+ - **Analyze CSV File:** Analyze a CSV file using pandas and answer a question about it
45
+ - **Analyze Excel File:** Analyze an Excel file using pandas and answer a question about it
46
+
47
+ ### **Image processing and generation tools**
48
+ - **Analyze Image:** Analyze basic properties of an image (size, mode, color analysis, thumbnail preview)
49
+ - **Transform Image:** Apply transformations: resize, rotate, crop, flip, brightness, contrast, blur, sharpen, grayscale
50
+ - **Draw on Image:** Draw shapes (rectangle, circle, line) or text onto an image
51
+ - **Generate Simple Image:** Generate a simple image (gradient, noise, pattern, chart)
52
+ - **Combine Images:** Combine multiple images (collage, stack, blend)
53
+
54
+
55
+ ## **Installation**
56
+ Clone the repository, change the current working directory to this repository's root folder:
57
+
58
+ ```
59
+ git clone https://github.com/fisherman611/gaia-agent.git
60
+ ```
61
+ ```
62
+ cd gaia-agent
63
+ ```
64
+
65
+ Install ```requirements.txt``` (replace `3.11` with your installed Python version):
66
+
67
+ ```
68
+ py -3.11 -m pip install -r requirements.txt
69
+ ```
70
+
71
+ ## **Environment Variables**
72
+ Store some API keys an variables in the `.env` file and load it in your code using `load_dotenv`
73
+
74
+ ```
75
+ SUPABASE_URL=...
76
+ SUPABASE_SERVICE_ROLE_KEY=...
77
+ SUPABASE_SERVICE_KEY=...
78
+ HUGGINGFACEHUB_API_TOKEN=...
79
+ GROQ_API_KEY=...
80
+ TAVILY_API_KEY=...
81
+ LANGSMITH_API_KEY=...
82
+
83
+ LANGSMITH_TRACING=true
84
+ LANGSMITH_PROJECT=ai_agent_course
85
+ LANGSMITH_ENDPOINT=https://api.smith.langchain.com
86
+ ```
87
+
88
+ ## **Demo**
89
+ To run the application using the command line, use the following command (replace `3.11` with your installed Python version):
90
+ ```
91
+ py -3.11 app.py
92
+ ```
93
+ Or run in the [Hugging Face Space](https://huggingface.co/spaces/fisherman611/gaia-agent)
94
+ ## **Resources**
95
+ - [GAIA Benchmark](https://huggingface.co/spaces/gaia-benchmark/leaderboard)
96
+ - [Hugging Face Agents Course](https://huggingface.co/agents-course)
97
+ - [Langgraph Agents](https://langchain-ai.github.io/langgraph/)
98
+
99
+
100
+ ## **Contributing**
101
+ Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request.
102
+
103
+ ## **License**
104
+ This project is licensed under the [MIT License](https://mit-license.org/).
agent.py CHANGED
@@ -1,15 +1,36 @@
1
- """LangGraph Agent"""
2
  import os
3
  from dotenv import load_dotenv
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  from langgraph.graph import START, StateGraph, MessagesState
5
- from langgraph.prebuilt import tools_condition
6
- from langgraph.prebuilt import ToolNode
7
- from langchain_google_genai import ChatGoogleGenerativeAI
8
- from langchain_groq import ChatGroq
9
- from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings
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_community.vectorstores import SupabaseVectorStore
14
  from langchain_core.messages import SystemMessage, HumanMessage
15
  from langchain_core.tools import tool
@@ -18,61 +39,13 @@ from supabase.client import Client, create_client
18
 
19
  load_dotenv()
20
 
21
- @tool
22
- def multiply(a: int, b: int) -> int:
23
- """Multiply two numbers.
24
- Args:
25
- a: first int
26
- b: second int
27
- """
28
- return a * b
29
 
30
- @tool
31
- def add(a: int, b: int) -> int:
32
- """Add two numbers.
33
-
34
- Args:
35
- a: first int
36
- b: second int
37
- """
38
- return a + b
39
-
40
- @tool
41
- def subtract(a: int, b: int) -> int:
42
- """Subtract two numbers.
43
-
44
- Args:
45
- a: first int
46
- b: second int
47
- """
48
- return a - b
49
-
50
- @tool
51
- def divide(a: int, b: int) -> int:
52
- """Divide two numbers.
53
-
54
- Args:
55
- a: first int
56
- b: second int
57
- """
58
- if b == 0:
59
- raise ValueError("Cannot divide by zero.")
60
- return a / b
61
-
62
- @tool
63
- def modulus(a: int, b: int) -> int:
64
- """Get the modulus of two numbers.
65
-
66
- Args:
67
- a: first int
68
- b: second int
69
- """
70
- return a % b
71
 
72
  @tool
73
  def wiki_search(query: str) -> str:
74
  """Search Wikipedia for a query and return maximum 2 results.
75
-
76
  Args:
77
  query: The search query."""
78
  search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
@@ -80,13 +53,15 @@ def wiki_search(query: str) -> str:
80
  [
81
  f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
82
  for doc in search_docs
83
- ])
 
84
  return {"wiki_results": formatted_search_docs}
85
 
 
86
  @tool
87
  def web_search(query: str) -> str:
88
  """Search Tavily for a query and return maximum 3 results.
89
-
90
  Args:
91
  query: The search query."""
92
  search_docs = TavilySearchResults(max_results=3).invoke(query=query)
@@ -94,13 +69,15 @@ def web_search(query: str) -> str:
94
  [
95
  f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
96
  for doc in search_docs
97
- ])
 
98
  return {"web_results": formatted_search_docs}
99
 
 
100
  @tool
101
- def arvix_search(query: str) -> str:
102
  """Search Arxiv for a query and return maximum 3 result.
103
-
104
  Args:
105
  query: The search query."""
106
  search_docs = ArxivLoader(query=query, load_max_docs=3).load()
@@ -108,28 +85,620 @@ def arvix_search(query: str) -> str:
108
  [
109
  f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
110
  for doc in search_docs
111
- ])
112
- return {"arvix_results": formatted_search_docs}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
  # load the system prompt from the file
117
  with open("system_prompt.txt", "r", encoding="utf-8") as f:
118
  system_prompt = f.read()
 
119
 
120
  # System message
121
  sys_msg = SystemMessage(content=system_prompt)
122
 
123
  # build a retriever
124
- embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # dim=768
 
 
125
  supabase: Client = create_client(
126
- os.environ.get("SUPABASE_URL"),
127
- os.environ.get("SUPABASE_SERVICE_KEY"))
128
  vector_store = SupabaseVectorStore(
129
  client=supabase,
130
- embedding= embeddings,
131
- table_name="documents",
132
- query_name="match_documents_langchain",
133
  )
134
  create_retriever_tool = create_retriever_tool(
135
  retriever=vector_store.as_retriever(),
@@ -138,38 +707,53 @@ create_retriever_tool = create_retriever_tool(
138
  )
139
 
140
 
141
-
142
  tools = [
 
 
 
143
  multiply,
144
  add,
145
  subtract,
146
  divide,
147
  modulus,
148
- wiki_search,
149
- web_search,
150
- arvix_search,
 
 
 
 
 
 
 
 
 
 
151
  ]
152
 
 
153
  # Build graph function
154
- def build_graph(provider: str = "google"):
155
  """Build the graph"""
156
  # Load environment variables from .env file
157
- if provider == "google":
158
- # Google Gemini
159
- llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
160
- elif provider == "groq":
161
  # Groq https://console.groq.com/docs/models
162
- llm = ChatGroq(model="qwen-qwq-32b", temperature=0) # optional : qwen-qwq-32b gemma2-9b-it
163
  elif provider == "huggingface":
164
  # TODO: Add huggingface endpoint
165
  llm = ChatHuggingFace(
166
  llm=HuggingFaceEndpoint(
167
- url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
 
 
 
 
168
  temperature=0,
169
  ),
 
170
  )
171
  else:
172
- raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
173
  # Bind tools to LLM
174
  llm_with_tools = llm.bind_tools(tools)
175
 
@@ -177,47 +761,41 @@ def build_graph(provider: str = "google"):
177
  def assistant(state: MessagesState):
178
  """Assistant node"""
179
  return {"messages": [llm_with_tools.invoke(state["messages"])]}
180
-
181
- # def retriever(state: MessagesState):
182
- # """Retriever node"""
183
- # similar_question = vector_store.similarity_search(state["messages"][0].content)
184
- #example_msg = HumanMessage(
185
- # content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}",
186
- # )
187
- # return {"messages": [sys_msg] + state["messages"] + [example_msg]}
188
-
189
- from langchain_core.messages import AIMessage
190
 
191
  def retriever(state: MessagesState):
192
- query = state["messages"][-1].content
193
- similar_doc = vector_store.similarity_search(query, k=1)[0]
194
 
195
- content = similar_doc.page_content
196
- if "Final answer :" in content:
197
- answer = content.split("Final answer :")[-1].strip()
 
 
198
  else:
199
- answer = content.strip()
200
-
201
- return {"messages": [AIMessage(content=answer)]}
202
-
203
- # builder = StateGraph(MessagesState)
204
- #builder.add_node("retriever", retriever)
205
- #builder.add_node("assistant", assistant)
206
- #builder.add_node("tools", ToolNode(tools))
207
- #builder.add_edge(START, "retriever")
208
- #builder.add_edge("retriever", "assistant")
209
- #builder.add_conditional_edges(
210
- # "assistant",
211
- # tools_condition,
212
- #)
213
- #builder.add_edge("tools", "assistant")
214
 
215
  builder = StateGraph(MessagesState)
216
  builder.add_node("retriever", retriever)
217
-
218
- # Retriever ist Start und Endpunkt
219
- builder.set_entry_point("retriever")
220
- builder.set_finish_point("retriever")
 
 
 
 
 
221
 
222
  # Compile graph
223
  return builder.compile()
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  from dotenv import load_dotenv
3
+ from typing import List, Dict, Any, Optional
4
+ import tempfile
5
+ import re
6
+ import json
7
+ import requests
8
+ from urllib.parse import urlparse
9
+ import pytesseract
10
+ from PIL import Image, ImageDraw, ImageFont, ImageEnhance, ImageFilter
11
+ import cmath
12
+ import pandas as pd
13
+ import uuid
14
+ import numpy as np
15
+ from code_interpreter import CodeInterpreter
16
+
17
+ interpreter_instance = CodeInterpreter()
18
+
19
+ from image_processing import *
20
+
21
+ """Langraph"""
22
  from langgraph.graph import START, StateGraph, MessagesState
 
 
 
 
 
23
  from langchain_community.tools.tavily_search import TavilySearchResults
24
  from langchain_community.document_loaders import WikipediaLoader
25
  from langchain_community.document_loaders import ArxivLoader
26
+ from langgraph.prebuilt import ToolNode, tools_condition
27
+ from langchain_google_genai import ChatGoogleGenerativeAI
28
+ from langchain_groq import ChatGroq
29
+ from langchain_huggingface import (
30
+ ChatHuggingFace,
31
+ HuggingFaceEndpoint,
32
+ HuggingFaceEmbeddings,
33
+ )
34
  from langchain_community.vectorstores import SupabaseVectorStore
35
  from langchain_core.messages import SystemMessage, HumanMessage
36
  from langchain_core.tools import tool
 
39
 
40
  load_dotenv()
41
 
42
+ ### =============== BROWSER TOOLS =============== ###
 
 
 
 
 
 
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  @tool
46
  def wiki_search(query: str) -> str:
47
  """Search Wikipedia for a query and return maximum 2 results.
48
+
49
  Args:
50
  query: The search query."""
51
  search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
 
53
  [
54
  f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
55
  for doc in search_docs
56
+ ]
57
+ )
58
  return {"wiki_results": formatted_search_docs}
59
 
60
+
61
  @tool
62
  def web_search(query: str) -> str:
63
  """Search Tavily for a query and return maximum 3 results.
64
+
65
  Args:
66
  query: The search query."""
67
  search_docs = TavilySearchResults(max_results=3).invoke(query=query)
 
69
  [
70
  f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
71
  for doc in search_docs
72
+ ]
73
+ )
74
  return {"web_results": formatted_search_docs}
75
 
76
+
77
  @tool
78
+ def arxiv_search(query: str) -> str:
79
  """Search Arxiv for a query and return maximum 3 result.
80
+
81
  Args:
82
  query: The search query."""
83
  search_docs = ArxivLoader(query=query, load_max_docs=3).load()
 
85
  [
86
  f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
87
  for doc in search_docs
88
+ ]
89
+ )
90
+ return {"arxiv_results": formatted_search_docs}
91
+
92
+
93
+ ### =============== CODE INTERPRETER TOOLS =============== ###
94
+
95
+
96
+ @tool
97
+ def execute_code_multilang(code: str, language: str = "python") -> str:
98
+ """Execute code in multiple languages (Python, Bash, SQL, C, Java) and return results.
99
+
100
+ Args:
101
+ code (str): The source code to execute.
102
+ language (str): The language of the code. Supported: "python", "bash", "sql", "c", "java".
103
+
104
+ Returns:
105
+ A string summarizing the execution results (stdout, stderr, errors, plots, dataframes if any).
106
+ """
107
+ supported_languages = ["python", "bash", "sql", "c", "java"]
108
+ language = language.lower()
109
+
110
+ if language not in supported_languages:
111
+ return f"❌ Unsupported language: {language}. Supported languages are: {', '.join(supported_languages)}"
112
+
113
+ result = interpreter_instance.execute_code(code, language=language)
114
+
115
+ response = []
116
+
117
+ if result["status"] == "success":
118
+ response.append(f"✅ Code executed successfully in **{language.upper()}**")
119
+
120
+ if result.get("stdout"):
121
+ response.append(
122
+ "\n**Standard Output:**\n```\n" + result["stdout"].strip() + "\n```"
123
+ )
124
+
125
+ if result.get("stderr"):
126
+ response.append(
127
+ "\n**Standard Error (if any):**\n```\n"
128
+ + result["stderr"].strip()
129
+ + "\n```"
130
+ )
131
+
132
+ if result.get("result") is not None:
133
+ response.append(
134
+ "\n**Execution Result:**\n```\n"
135
+ + str(result["result"]).strip()
136
+ + "\n```"
137
+ )
138
+
139
+ if result.get("dataframes"):
140
+ for df_info in result["dataframes"]:
141
+ response.append(
142
+ f"\n**DataFrame `{df_info['name']}` (Shape: {df_info['shape']})**"
143
+ )
144
+ df_preview = pd.DataFrame(df_info["head"])
145
+ response.append("First 5 rows:\n```\n" + str(df_preview) + "\n```")
146
+
147
+ if result.get("plots"):
148
+ response.append(
149
+ f"\n**Generated {len(result['plots'])} plot(s)** (Image data returned separately)"
150
+ )
151
+
152
+ else:
153
+ response.append(f"❌ Code execution failed in **{language.upper()}**")
154
+ if result.get("stderr"):
155
+ response.append(
156
+ "\n**Error Log:**\n```\n" + result["stderr"].strip() + "\n```"
157
+ )
158
+
159
+ return "\n".join(response)
160
+
161
+
162
+ ### =============== MATHEMATICAL TOOLS =============== ###
163
+
164
+
165
+ @tool
166
+ def multiply(a: float, b: float) -> float:
167
+ """
168
+ Multiplies two numbers.
169
+
170
+ Args:
171
+ a (float): the first number
172
+ b (float): the second number
173
+ """
174
+ return a * b
175
+
176
+
177
+ @tool
178
+ def add(a: float, b: float) -> float:
179
+ """
180
+ Adds two numbers.
181
+
182
+ Args:
183
+ a (float): the first number
184
+ b (float): the second number
185
+ """
186
+ return a + b
187
+
188
+
189
+ @tool
190
+ def subtract(a: float, b: float) -> int:
191
+ """
192
+ Subtracts two numbers.
193
+
194
+ Args:
195
+ a (float): the first number
196
+ b (float): the second number
197
+ """
198
+ return a - b
199
+
200
+
201
+ @tool
202
+ def divide(a: float, b: float) -> float:
203
+ """
204
+ Divides two numbers.
205
+
206
+ Args:
207
+ a (float): the first float number
208
+ b (float): the second float number
209
+ """
210
+ if b == 0:
211
+ raise ValueError("Cannot divided by zero.")
212
+ return a / b
213
+
214
+
215
+ @tool
216
+ def modulus(a: int, b: int) -> int:
217
+ """
218
+ Get the modulus of two numbers.
219
+
220
+ Args:
221
+ a (int): the first number
222
+ b (int): the second number
223
+ """
224
+ return a % b
225
+
226
+
227
+ @tool
228
+ def power(a: float, b: float) -> float:
229
+ """
230
+ Get the power of two numbers.
231
+
232
+ Args:
233
+ a (float): the first number
234
+ b (float): the second number
235
+ """
236
+ return a**b
237
+
238
+
239
+ @tool
240
+ def square_root(a: float) -> float | complex:
241
+ """
242
+ Get the square root of a number.
243
+
244
+ Args:
245
+ a (float): the number to get the square root of
246
+ """
247
+ if a >= 0:
248
+ return a**0.5
249
+ return cmath.sqrt(a)
250
+
251
+
252
+ ### =============== DOCUMENT PROCESSING TOOLS =============== ###
253
+
254
+
255
+ @tool
256
+ def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
257
+ """
258
+ Save content to a file and return the path.
259
+
260
+ Args:
261
+ content (str): the content to save to the file
262
+ filename (str, optional): the name of the file. If not provided, a random name file will be created.
263
+ """
264
+ temp_dir = tempfile.gettempdir()
265
+ if filename is None:
266
+ temp_file = tempfile.NamedTemporaryFile(delete=False, dir=temp_dir)
267
+ filepath = temp_file.name
268
+ else:
269
+ filepath = os.path.join(temp_dir, filename)
270
+
271
+ with open(filepath, "w") as f:
272
+ f.write(content)
273
+
274
+ return f"File saved to {filepath}. You can read this file to process its contents."
275
+
276
+
277
+ @tool
278
+ def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
279
+ """
280
+ Download a file from a URL and save it to a temporary location.
281
+
282
+ Args:
283
+ url (str): the URL of the file to download.
284
+ filename (str, optional): the name of the file. If not provided, a random name file will be created.
285
+ """
286
+ try:
287
+ # Parse URL to get filename if not provided
288
+ if not filename:
289
+ path = urlparse(url).path
290
+ filename = os.path.basename(path)
291
+ if not filename:
292
+ filename = f"downloaded_{uuid.uuid4().hex[:8]}"
293
+
294
+ # Create temporary file
295
+ temp_dir = tempfile.gettempdir()
296
+ filepath = os.path.join(temp_dir, filename)
297
+
298
+ # Download the file
299
+ response = requests.get(url, stream=True)
300
+ response.raise_for_status()
301
+
302
+ # Save the file
303
+ with open(filepath, "wb") as f:
304
+ for chunk in response.iter_content(chunk_size=8192):
305
+ f.write(chunk)
306
+
307
+ return f"File downloaded to {filepath}. You can read this file to process its contents."
308
+ except Exception as e:
309
+ return f"Error downloading file: {str(e)}"
310
+
311
+
312
+ @tool
313
+ def extract_text_from_image(image_path: str) -> str:
314
+ """
315
+ Extract text from an image using OCR library pytesseract (if available).
316
+
317
+ Args:
318
+ image_path (str): the path to the image file.
319
+ """
320
+ try:
321
+ # Open the image
322
+ image = Image.open(image_path)
323
+
324
+ # Extract text from the image
325
+ text = pytesseract.image_to_string(image)
326
+
327
+ return f"Extracted text from image:\n\n{text}"
328
+ except Exception as e:
329
+ return f"Error extracting text from image: {str(e)}"
330
+
331
+
332
+ @tool
333
+ def analyze_csv_file(file_path: str, query: str) -> str:
334
+ """
335
+ Analyze a CSV file using pandas and answer a question about it.
336
+
337
+ Args:
338
+ file_path (str): the path to the CSV file.
339
+ query (str): Question about the data
340
+ """
341
+ try:
342
+ # Read the CSV file
343
+ df = pd.read_csv(file_path)
344
+
345
+ # Run various analyses based on the query
346
+ result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
347
+ result += f"Columns: {', '.join(df.columns)}\n\n"
348
+
349
+ # Add summary statistics
350
+ result += "Summary statistics:\n"
351
+ result += str(df.describe())
352
+
353
+ return result
354
+
355
+ except Exception as e:
356
+ return f"Error analyzing CSV file: {str(e)}"
357
+
358
+
359
+ @tool
360
+ def analyze_excel_file(file_path: str, query: str) -> str:
361
+ """
362
+ Analyze an Excel file using pandas and answer a question about it.
363
+
364
+ Args:
365
+ file_path (str): the path to the Excel file.
366
+ query (str): Question about the data
367
+ """
368
+ try:
369
+ # Read the Excel file
370
+ df = pd.read_excel(file_path)
371
+
372
+ # Run various analyses based on the query
373
+ result = (
374
+ f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
375
+ )
376
+ result += f"Columns: {', '.join(df.columns)}\n\n"
377
+
378
+ # Add summary statistics
379
+ result += "Summary statistics:\n"
380
+ result += str(df.describe())
381
+
382
+ return result
383
+
384
+ except Exception as e:
385
+ return f"Error analyzing Excel file: {str(e)}"
386
+
387
+
388
+ ### ============== IMAGE PROCESSING AND GENERATION TOOLS =============== ###
389
+
390
+
391
+ @tool
392
+ def analyze_image(image_base64: str) -> Dict[str, Any]:
393
+ """
394
+ Analyze basic properties of an image (size, mode, color analysis, thumbnail preview).
395
+
396
+ Args:
397
+ image_base64 (str): Base64 encoded image string
398
+
399
+ Returns:
400
+ Dictionary with analysis result
401
+ """
402
+ try:
403
+ img = decode_image(image_base64)
404
+ width, height = img.size
405
+ mode = img.mode
406
+
407
+ if mode in ("RGB", "RGBA"):
408
+ arr = np.array(img)
409
+ avg_colors = arr.mean(axis=(0, 1))
410
+ dominant = ["Red", "Green", "Blue"][np.argmax(avg_colors[:3])]
411
+ brightness = avg_colors.mean()
412
+ color_analysis = {
413
+ "average_rgb": avg_colors.tolist(),
414
+ "brightness": brightness,
415
+ "dominant_color": dominant,
416
+ }
417
+ else:
418
+ color_analysis = {"note": f"No color analysis for mode {mode}"}
419
+
420
+ thumbnail = img.copy()
421
+ thumbnail.thumbnail((100, 100))
422
+ thumb_path = save_image(thumbnail, "thumbnails")
423
+ thumbnail_base64 = encode_image(thumb_path)
424
+
425
+ return {
426
+ "dimensions": (width, height),
427
+ "mode": mode,
428
+ "color_analysis": color_analysis,
429
+ "thumbnail": thumbnail_base64,
430
+ }
431
+ except Exception as e:
432
+ return {"error": str(e)}
433
 
434
 
435
+ @tool
436
+ def transform_image(
437
+ image_base64: str, operation: str, params: Optional[Dict[str, Any]] = None
438
+ ) -> Dict[str, Any]:
439
+ """
440
+ Apply transformations: resize, rotate, crop, flip, brightness, contrast, blur, sharpen, grayscale.
441
+
442
+ Args:
443
+ image_base64 (str): Base64 encoded input image
444
+ operation (str): Transformation operation
445
+ params (Dict[str, Any], optional): Parameters for the operation
446
+
447
+ Returns:
448
+ Dictionary with transformed image (base64)
449
+ """
450
+ try:
451
+ img = decode_image(image_base64)
452
+ params = params or {}
453
+
454
+ if operation == "resize":
455
+ img = img.resize(
456
+ (
457
+ params.get("width", img.width // 2),
458
+ params.get("height", img.height // 2),
459
+ )
460
+ )
461
+ elif operation == "rotate":
462
+ img = img.rotate(params.get("angle", 90), expand=True)
463
+ elif operation == "crop":
464
+ img = img.crop(
465
+ (
466
+ params.get("left", 0),
467
+ params.get("top", 0),
468
+ params.get("right", img.width),
469
+ params.get("bottom", img.height),
470
+ )
471
+ )
472
+ elif operation == "flip":
473
+ if params.get("direction", "horizontal") == "horizontal":
474
+ img = img.transpose(Image.FLIP_LEFT_RIGHT)
475
+ else:
476
+ img = img.transpose(Image.FLIP_TOP_BOTTOM)
477
+ elif operation == "adjust_brightness":
478
+ img = ImageEnhance.Brightness(img).enhance(params.get("factor", 1.5))
479
+ elif operation == "adjust_contrast":
480
+ img = ImageEnhance.Contrast(img).enhance(params.get("factor", 1.5))
481
+ elif operation == "blur":
482
+ img = img.filter(ImageFilter.GaussianBlur(params.get("radius", 2)))
483
+ elif operation == "sharpen":
484
+ img = img.filter(ImageFilter.SHARPEN)
485
+ elif operation == "grayscale":
486
+ img = img.convert("L")
487
+ else:
488
+ return {"error": f"Unknown operation: {operation}"}
489
+
490
+ result_path = save_image(img)
491
+ result_base64 = encode_image(result_path)
492
+ return {"transformed_image": result_base64}
493
+
494
+ except Exception as e:
495
+ return {"error": str(e)}
496
+
497
+
498
+ @tool
499
+ def draw_on_image(
500
+ image_base64: str, drawing_type: str, params: Dict[str, Any]
501
+ ) -> Dict[str, Any]:
502
+ """
503
+ Draw shapes (rectangle, circle, line) or text onto an image.
504
+
505
+ Args:
506
+ image_base64 (str): Base64 encoded input image
507
+ drawing_type (str): Drawing type
508
+ params (Dict[str, Any]): Drawing parameters
509
+
510
+ Returns:
511
+ Dictionary with result image (base64)
512
+ """
513
+ try:
514
+ img = decode_image(image_base64)
515
+ draw = ImageDraw.Draw(img)
516
+ color = params.get("color", "red")
517
+
518
+ if drawing_type == "rectangle":
519
+ draw.rectangle(
520
+ [params["left"], params["top"], params["right"], params["bottom"]],
521
+ outline=color,
522
+ width=params.get("width", 2),
523
+ )
524
+ elif drawing_type == "circle":
525
+ x, y, r = params["x"], params["y"], params["radius"]
526
+ draw.ellipse(
527
+ (x - r, y - r, x + r, y + r),
528
+ outline=color,
529
+ width=params.get("width", 2),
530
+ )
531
+ elif drawing_type == "line":
532
+ draw.line(
533
+ (
534
+ params["start_x"],
535
+ params["start_y"],
536
+ params["end_x"],
537
+ params["end_y"],
538
+ ),
539
+ fill=color,
540
+ width=params.get("width", 2),
541
+ )
542
+ elif drawing_type == "text":
543
+ font_size = params.get("font_size", 20)
544
+ try:
545
+ font = ImageFont.truetype("arial.ttf", font_size)
546
+ except IOError:
547
+ font = ImageFont.load_default()
548
+ draw.text(
549
+ (params["x"], params["y"]),
550
+ params.get("text", "Text"),
551
+ fill=color,
552
+ font=font,
553
+ )
554
+ else:
555
+ return {"error": f"Unknown drawing type: {drawing_type}"}
556
+
557
+ result_path = save_image(img)
558
+ result_base64 = encode_image(result_path)
559
+ return {"result_image": result_base64}
560
+
561
+ except Exception as e:
562
+ return {"error": str(e)}
563
+
564
+
565
+ @tool
566
+ def generate_simple_image(
567
+ image_type: str,
568
+ width: int = 500,
569
+ height: int = 500,
570
+ params: Optional[Dict[str, Any]] = None,
571
+ ) -> Dict[str, Any]:
572
+ """
573
+ Generate a simple image (gradient, noise, pattern, chart).
574
+
575
+ Args:
576
+ image_type (str): Type of image
577
+ width (int), height (int)
578
+ params (Dict[str, Any], optional): Specific parameters
579
+
580
+ Returns:
581
+ Dictionary with generated image (base64)
582
+ """
583
+ try:
584
+ params = params or {}
585
+
586
+ if image_type == "gradient":
587
+ direction = params.get("direction", "horizontal")
588
+ start_color = params.get("start_color", (255, 0, 0))
589
+ end_color = params.get("end_color", (0, 0, 255))
590
+
591
+ img = Image.new("RGB", (width, height))
592
+ draw = ImageDraw.Draw(img)
593
+
594
+ if direction == "horizontal":
595
+ for x in range(width):
596
+ r = int(
597
+ start_color[0] + (end_color[0] - start_color[0]) * x / width
598
+ )
599
+ g = int(
600
+ start_color[1] + (end_color[1] - start_color[1]) * x / width
601
+ )
602
+ b = int(
603
+ start_color[2] + (end_color[2] - start_color[2]) * x / width
604
+ )
605
+ draw.line([(x, 0), (x, height)], fill=(r, g, b))
606
+ else:
607
+ for y in range(height):
608
+ r = int(
609
+ start_color[0] + (end_color[0] - start_color[0]) * y / height
610
+ )
611
+ g = int(
612
+ start_color[1] + (end_color[1] - start_color[1]) * y / height
613
+ )
614
+ b = int(
615
+ start_color[2] + (end_color[2] - start_color[2]) * y / height
616
+ )
617
+ draw.line([(0, y), (width, y)], fill=(r, g, b))
618
+
619
+ elif image_type == "noise":
620
+ noise_array = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8)
621
+ img = Image.fromarray(noise_array, "RGB")
622
+
623
+ else:
624
+ return {"error": f"Unsupported image_type {image_type}"}
625
+
626
+ result_path = save_image(img)
627
+ result_base64 = encode_image(result_path)
628
+ return {"generated_image": result_base64}
629
+
630
+ except Exception as e:
631
+ return {"error": str(e)}
632
+
633
+
634
+ @tool
635
+ def combine_images(
636
+ images_base64: List[str], operation: str, params: Optional[Dict[str, Any]] = None
637
+ ) -> Dict[str, Any]:
638
+ """
639
+ Combine multiple images (collage, stack, blend).
640
+
641
+ Args:
642
+ images_base64 (List[str]): List of base64 images
643
+ operation (str): Combination type
644
+ params (Dict[str, Any], optional)
645
+
646
+ Returns:
647
+ Dictionary with combined image (base64)
648
+ """
649
+ try:
650
+ images = [decode_image(b64) for b64 in images_base64]
651
+ params = params or {}
652
+
653
+ if operation == "stack":
654
+ direction = params.get("direction", "horizontal")
655
+ if direction == "horizontal":
656
+ total_width = sum(img.width for img in images)
657
+ max_height = max(img.height for img in images)
658
+ new_img = Image.new("RGB", (total_width, max_height))
659
+ x = 0
660
+ for img in images:
661
+ new_img.paste(img, (x, 0))
662
+ x += img.width
663
+ else:
664
+ max_width = max(img.width for img in images)
665
+ total_height = sum(img.height for img in images)
666
+ new_img = Image.new("RGB", (max_width, total_height))
667
+ y = 0
668
+ for img in images:
669
+ new_img.paste(img, (0, y))
670
+ y += img.height
671
+ else:
672
+ return {"error": f"Unsupported combination operation {operation}"}
673
+
674
+ result_path = save_image(new_img)
675
+ result_base64 = encode_image(result_path)
676
+ return {"combined_image": result_base64}
677
+
678
+ except Exception as e:
679
+ return {"error": str(e)}
680
+
681
 
682
  # load the system prompt from the file
683
  with open("system_prompt.txt", "r", encoding="utf-8") as f:
684
  system_prompt = f.read()
685
+ print(system_prompt)
686
 
687
  # System message
688
  sys_msg = SystemMessage(content=system_prompt)
689
 
690
  # build a retriever
691
+ embeddings = HuggingFaceEmbeddings(
692
+ model_name="sentence-transformers/all-mpnet-base-v2"
693
+ ) # dim=768
694
  supabase: Client = create_client(
695
+ os.environ.get("SUPABASE_URL"), os.environ.get("SUPABASE_SERVICE_ROLE_KEY")
696
+ )
697
  vector_store = SupabaseVectorStore(
698
  client=supabase,
699
+ embedding=embeddings,
700
+ table_name="documents2",
701
+ query_name="match_documents_2",
702
  )
703
  create_retriever_tool = create_retriever_tool(
704
  retriever=vector_store.as_retriever(),
 
707
  )
708
 
709
 
 
710
  tools = [
711
+ web_search,
712
+ wiki_search,
713
+ arxiv_search,
714
  multiply,
715
  add,
716
  subtract,
717
  divide,
718
  modulus,
719
+ power,
720
+ square_root,
721
+ save_and_read_file,
722
+ download_file_from_url,
723
+ extract_text_from_image,
724
+ analyze_csv_file,
725
+ analyze_excel_file,
726
+ execute_code_multilang,
727
+ analyze_image,
728
+ transform_image,
729
+ draw_on_image,
730
+ generate_simple_image,
731
+ combine_images,
732
  ]
733
 
734
+
735
  # Build graph function
736
+ def build_graph(provider: str = "groq"):
737
  """Build the graph"""
738
  # Load environment variables from .env file
739
+ if provider == "groq":
 
 
 
740
  # Groq https://console.groq.com/docs/models
741
+ llm = ChatGroq(model="qwen-qwq-32b", temperature=0)
742
  elif provider == "huggingface":
743
  # TODO: Add huggingface endpoint
744
  llm = ChatHuggingFace(
745
  llm=HuggingFaceEndpoint(
746
+ repo_id="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
747
+ task="text-generation", # for chat‐style use “text-generation”
748
+ max_new_tokens=1024,
749
+ do_sample=False,
750
+ repetition_penalty=1.03,
751
  temperature=0,
752
  ),
753
+ verbose=True,
754
  )
755
  else:
756
+ raise ValueError("Invalid provider. Choose 'groq' or 'huggingface'.")
757
  # Bind tools to LLM
758
  llm_with_tools = llm.bind_tools(tools)
759
 
 
761
  def assistant(state: MessagesState):
762
  """Assistant node"""
763
  return {"messages": [llm_with_tools.invoke(state["messages"])]}
 
 
 
 
 
 
 
 
 
 
764
 
765
  def retriever(state: MessagesState):
766
+ """Retriever node"""
767
+ similar_question = vector_store.similarity_search(state["messages"][0].content)
768
 
769
+ if similar_question: # Check if the list is not empty
770
+ example_msg = HumanMessage(
771
+ content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}",
772
+ )
773
+ return {"messages": [sys_msg] + state["messages"] + [example_msg]}
774
  else:
775
+ # Handle the case when no similar questions are found
776
+ return {"messages": [sys_msg] + state["messages"]}
 
 
 
 
 
 
 
 
 
 
 
 
 
777
 
778
  builder = StateGraph(MessagesState)
779
  builder.add_node("retriever", retriever)
780
+ builder.add_node("assistant", assistant)
781
+ builder.add_node("tools", ToolNode(tools))
782
+ builder.add_edge(START, "retriever")
783
+ builder.add_edge("retriever", "assistant")
784
+ builder.add_conditional_edges(
785
+ "assistant",
786
+ tools_condition,
787
+ )
788
+ builder.add_edge("tools", "assistant")
789
 
790
  # Compile graph
791
  return builder.compile()
792
+
793
+
794
+ # test
795
+ if __name__ == "__main__":
796
+ question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
797
+ graph = build_graph(provider="groq")
798
+ messages = [HumanMessage(content=question)]
799
+ messages = graph.invoke({"messages": messages})
800
+ for m in messages["messages"]:
801
+ m.pretty_print()
app.py CHANGED
@@ -4,6 +4,7 @@ import inspect
4
  import gradio as gr
5
  import requests
6
  import pandas as pd
 
7
  from langchain_core.messages import HumanMessage
8
  from agent import build_graph
9
 
@@ -25,11 +26,11 @@ class BasicAgent:
25
 
26
  def __call__(self, question: str) -> str:
27
  print(f"Agent received question (first 50 chars): {question[:50]}...")
 
28
  messages = [HumanMessage(content=question)]
29
- result = self.graph.invoke({"messages": messages})
30
- answer = result['messages'][-1].content
31
- return answer # kein [14:] mehr nötig!
32
-
33
 
34
 
35
  def run_and_submit_all( profile: gr.OAuthProfile | None):
@@ -92,6 +93,9 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
92
  if not task_id or question_text is None:
93
  print(f"Skipping item with missing task_id or question: {item}")
94
  continue
 
 
 
95
  try:
96
  submitted_answer = agent(question_text)
97
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
@@ -159,11 +163,9 @@ with gr.Blocks() as demo:
159
  gr.Markdown(
160
  """
161
  **Instructions:**
162
-
163
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
164
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
165
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
166
-
167
  ---
168
  **Disclaimers:**
169
  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).
@@ -206,4 +208,4 @@ if __name__ == "__main__":
206
  print("-"*(60 + len(" App Starting ")) + "\n")
207
 
208
  print("Launching Gradio Interface for Basic Agent Evaluation...")
209
- demo.launch(debug=True, share=False)
 
4
  import gradio as gr
5
  import requests
6
  import pandas as pd
7
+ import time
8
  from langchain_core.messages import HumanMessage
9
  from agent import build_graph
10
 
 
26
 
27
  def __call__(self, question: str) -> str:
28
  print(f"Agent received question (first 50 chars): {question[:50]}...")
29
+ # Wrap the question in a HumanMessage from langchain_core
30
  messages = [HumanMessage(content=question)]
31
+ messages = self.graph.invoke({"messages": messages})
32
+ answer = messages['messages'][-1].content
33
+ return answer[14:]
 
34
 
35
 
36
  def run_and_submit_all( profile: gr.OAuthProfile | None):
 
93
  if not task_id or question_text is None:
94
  print(f"Skipping item with missing task_id or question: {item}")
95
  continue
96
+
97
+ # time.sleep(10)
98
+
99
  try:
100
  submitted_answer = agent(question_text)
101
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
 
163
  gr.Markdown(
164
  """
165
  **Instructions:**
 
166
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
167
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
168
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
169
  ---
170
  **Disclaimers:**
171
  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).
 
208
  print("-"*(60 + len(" App Starting ")) + "\n")
209
 
210
  print("Launching Gradio Interface for Basic Agent Evaluation...")
211
+ demo.launch(debug=True, share=False)
code_interpreter.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import sys
4
+ import uuid
5
+ import base64
6
+ import traceback
7
+ import contextlib
8
+ import tempfile
9
+ import subprocess
10
+ import sqlite3
11
+ from typing import Dict, List, Any, Optional, Union
12
+ import numpy as np
13
+ import pandas as pd
14
+ import matplotlib.pyplot as plt
15
+ from PIL import Image
16
+
17
+ class CodeInterpreter:
18
+ def __init__(self, allowed_modules=None, max_execution_time=30, working_directory=None):
19
+ """Initialize the code interpreter with safety measures."""
20
+ self.allowed_modules = allowed_modules or [
21
+ "numpy", "pandas", "matplotlib", "scipy", "sklearn",
22
+ "math", "random", "statistics", "datetime", "collections",
23
+ "itertools", "functools", "operator", "re", "json",
24
+ "sympy", "networkx", "nltk", "PIL", "pytesseract",
25
+ "cmath", "uuid", "tempfile", "requests", "urllib"
26
+ ]
27
+ self.max_execution_time = max_execution_time
28
+ self.working_directory = working_directory or os.path.join(os.getcwd())
29
+ if not os.path.exists(self.working_directory):
30
+ os.makedirs(self.working_directory)
31
+
32
+ self.globals = {
33
+ "__builtins__": __builtins__,
34
+ "np": np,
35
+ "pd": pd,
36
+ "plt": plt,
37
+ "Image": Image,
38
+ }
39
+ self.temp_sqlite_db = os.path.join(tempfile.gettempdir(), "code_exec.db")
40
+
41
+ def execute_code(self, code: str, language: str = "python") -> Dict[str, Any]:
42
+ """Execute the provided code in the selected programming language."""
43
+ language = language.lower()
44
+ execution_id = str(uuid.uuid4())
45
+
46
+ result = {
47
+ "execution_id": execution_id,
48
+ "status": "error",
49
+ "stdout": "",
50
+ "stderr": "",
51
+ "result": None,
52
+ "plots": [],
53
+ "dataframes": []
54
+ }
55
+
56
+ try:
57
+ if language == "python":
58
+ return self._execute_python(code, execution_id)
59
+ elif language == "bash":
60
+ return self._execute_bash(code, execution_id)
61
+ elif language == "sql":
62
+ return self._execute_sql(code, execution_id)
63
+ elif language == "c":
64
+ return self._execute_c(code, execution_id)
65
+ elif language == "java":
66
+ return self._execute_java(code, execution_id)
67
+ else:
68
+ result["stderr"] = f"Unsupported language: {language}"
69
+ except Exception as e:
70
+ result["stderr"] = str(e)
71
+
72
+ return result
73
+
74
+ def _execute_python(self, code: str, execution_id: str) -> dict:
75
+ output_buffer = io.StringIO()
76
+ error_buffer = io.StringIO()
77
+ result = {
78
+ "execution_id": execution_id,
79
+ "status": "error",
80
+ "stdout": "",
81
+ "stderr": "",
82
+ "result": None,
83
+ "plots": [],
84
+ "dataframes": []
85
+ }
86
+
87
+ try:
88
+ exec_dir = os.path.join(self.working_directory, execution_id)
89
+ os.makedirs(exec_dir, exist_ok=True)
90
+ plt.switch_backend('Agg')
91
+
92
+ with contextlib.redirect_stdout(output_buffer), contextlib.redirect_stderr(error_buffer):
93
+ exec_result = exec(code, self.globals)
94
+
95
+ if plt.get_fignums():
96
+ for i, fig_num in enumerate(plt.get_fignums()):
97
+ fig = plt.figure(fig_num)
98
+ img_path = os.path.join(exec_dir, f"plot_{i}.png")
99
+ fig.savefig(img_path)
100
+ with open(img_path, "rb") as img_file:
101
+ img_data = base64.b64encode(img_file.read()).decode('utf-8')
102
+ result["plots"].append({
103
+ "figure_number": fig_num,
104
+ "data": img_data
105
+ })
106
+
107
+ for var_name, var_value in self.globals.items():
108
+ if isinstance(var_value, pd.DataFrame) and len(var_value) > 0:
109
+ result["dataframes"].append({
110
+ "name": var_name,
111
+ "head": var_value.head().to_dict(),
112
+ "shape": var_value.shape,
113
+ "dtypes": str(var_value.dtypes)
114
+ })
115
+
116
+ result["status"] = "success"
117
+ result["stdout"] = output_buffer.getvalue()
118
+ result["result"] = exec_result
119
+
120
+ except Exception as e:
121
+ result["status"] = "error"
122
+ result["stderr"] = f"{error_buffer.getvalue()}\n{traceback.format_exc()}"
123
+
124
+ return result
125
+
126
+ def _execute_bash(self, code: str, execution_id: str) -> dict:
127
+ try:
128
+ completed = subprocess.run(
129
+ code, shell=True, capture_output=True, text=True, timeout=self.max_execution_time
130
+ )
131
+ return {
132
+ "execution_id": execution_id,
133
+ "status": "success" if completed.returncode == 0 else "error",
134
+ "stdout": completed.stdout,
135
+ "stderr": completed.stderr,
136
+ "result": None,
137
+ "plots": [],
138
+ "dataframes": []
139
+ }
140
+ except subprocess.TimeoutExpired:
141
+ return {
142
+ "execution_id": execution_id,
143
+ "status": "error",
144
+ "stdout": "",
145
+ "stderr": "Execution timed out.",
146
+ "result": None,
147
+ "plots": [],
148
+ "dataframes": []
149
+ }
150
+
151
+ def _execute_sql(self, code: str, execution_id: str) -> dict:
152
+ result = {
153
+ "execution_id": execution_id,
154
+ "status": "error",
155
+ "stdout": "",
156
+ "stderr": "",
157
+ "result": None,
158
+ "plots": [],
159
+ "dataframes": []
160
+ }
161
+ try:
162
+ conn = sqlite3.connect(self.temp_sqlite_db)
163
+ cur = conn.cursor()
164
+ cur.execute(code)
165
+ if code.strip().lower().startswith("select"):
166
+ columns = [description[0] for description in cur.description]
167
+ rows = cur.fetchall()
168
+ df = pd.DataFrame(rows, columns=columns)
169
+ result["dataframes"].append({
170
+ "name": "query_result",
171
+ "head": df.head().to_dict(),
172
+ "shape": df.shape,
173
+ "dtypes": str(df.dtypes)
174
+ })
175
+ else:
176
+ conn.commit()
177
+
178
+ result["status"] = "success"
179
+ result["stdout"] = "Query executed successfully."
180
+
181
+ except Exception as e:
182
+ result["stderr"] = str(e)
183
+ finally:
184
+ conn.close()
185
+
186
+ return result
187
+
188
+ def _execute_c(self, code: str, execution_id: str) -> dict:
189
+ temp_dir = tempfile.mkdtemp()
190
+ source_path = os.path.join(temp_dir, "program.c")
191
+ binary_path = os.path.join(temp_dir, "program")
192
+
193
+ try:
194
+ with open(source_path, "w") as f:
195
+ f.write(code)
196
+
197
+ compile_proc = subprocess.run(
198
+ ["gcc", source_path, "-o", binary_path],
199
+ capture_output=True, text=True, timeout=self.max_execution_time
200
+ )
201
+ if compile_proc.returncode != 0:
202
+ return {
203
+ "execution_id": execution_id,
204
+ "status": "error",
205
+ "stdout": compile_proc.stdout,
206
+ "stderr": compile_proc.stderr,
207
+ "result": None,
208
+ "plots": [],
209
+ "dataframes": []
210
+ }
211
+
212
+ run_proc = subprocess.run(
213
+ [binary_path],
214
+ capture_output=True, text=True, timeout=self.max_execution_time
215
+ )
216
+ return {
217
+ "execution_id": execution_id,
218
+ "status": "success" if run_proc.returncode == 0 else "error",
219
+ "stdout": run_proc.stdout,
220
+ "stderr": run_proc.stderr,
221
+ "result": None,
222
+ "plots": [],
223
+ "dataframes": []
224
+ }
225
+ except Exception as e:
226
+ return {
227
+ "execution_id": execution_id,
228
+ "status": "error",
229
+ "stdout": "",
230
+ "stderr": str(e),
231
+ "result": None,
232
+ "plots": [],
233
+ "dataframes": []
234
+ }
235
+
236
+ def _execute_java(self, code: str, execution_id: str) -> dict:
237
+ temp_dir = tempfile.mkdtemp()
238
+ source_path = os.path.join(temp_dir, "Main.java")
239
+
240
+ try:
241
+ with open(source_path, "w") as f:
242
+ f.write(code)
243
+
244
+ compile_proc = subprocess.run(
245
+ ["javac", source_path],
246
+ capture_output=True, text=True, timeout=self.max_execution_time
247
+ )
248
+ if compile_proc.returncode != 0:
249
+ return {
250
+ "execution_id": execution_id,
251
+ "status": "error",
252
+ "stdout": compile_proc.stdout,
253
+ "stderr": compile_proc.stderr,
254
+ "result": None,
255
+ "plots": [],
256
+ "dataframes": []
257
+ }
258
+
259
+ run_proc = subprocess.run(
260
+ ["java", "-cp", temp_dir, "Main"],
261
+ capture_output=True, text=True, timeout=self.max_execution_time
262
+ )
263
+ return {
264
+ "execution_id": execution_id,
265
+ "status": "success" if run_proc.returncode == 0 else "error",
266
+ "stdout": run_proc.stdout,
267
+ "stderr": run_proc.stderr,
268
+ "result": None,
269
+ "plots": [],
270
+ "dataframes": []
271
+ }
272
+ except Exception as e:
273
+ return {
274
+ "execution_id": execution_id,
275
+ "status": "error",
276
+ "stdout": "",
277
+ "stderr": str(e),
278
+ "result": None,
279
+ "plots": [],
280
+ "dataframes": []
281
+ }
explore_metadata.ipynb ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 9,
6
+ "id": "a600d7fc",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import json \n",
11
+ "with open('metadata.jsonl', 'r') as f: \n",
12
+ " json_list = list(f)\n",
13
+ "\n",
14
+ "json_QA = []\n",
15
+ "for json_str in json_list: \n",
16
+ " json_data = json.loads(json_str)\n",
17
+ " json_QA.append(json_data)"
18
+ ]
19
+ },
20
+ {
21
+ "cell_type": "code",
22
+ "execution_count": 10,
23
+ "id": "fa5d8eb8",
24
+ "metadata": {},
25
+ "outputs": [
26
+ {
27
+ "name": "stdout",
28
+ "output_type": "stream",
29
+ "text": [
30
+ "==================================================\n",
31
+ "Task ID: d1af70ea-a9a4-421a-b9cc-94b5e02f1788\n",
32
+ "Question: As of the 2020 census, what was the population difference between the largest county seat and smallest county seat, by land area of the county seat, in Washington state? For population figures, please use the official data from data.census.gov. Please report the integer difference.\n",
33
+ "Level: 2\n",
34
+ "Final Answer: 736455\n",
35
+ "Annotator Metadata: \n",
36
+ " ├── Steps: \n",
37
+ " │ ├── Step 1: Using a web browser, access a search engine and conduct a search, \"Washington cities by area\"\n",
38
+ " │ ├── Step 2: Navigate to the second search result, https://en.wikipedia.org/wiki/List_of_municipalities_in_Washington\n",
39
+ " │ ├── Step 3: Evaluate the page contents, finding the largest and smallest county seats by land area, Seattle and Cathlamet\n",
40
+ " │ ├── Step 4: Using a web browser, navigate to https://data.census.gov/\n",
41
+ " │ ├── Step 5: Using the website's search area, conduct a search, Seattle, Washington\n",
42
+ " │ ├── Step 6: Record the reported 2020 Decennial Census population of Seattle, Washington, 737,015\n",
43
+ " │ ├── Step 7: Using the website's search area, conduct a search, Cathlamet, Washington\n",
44
+ " │ ├── Step 8: Record the reported 2020 Decennial Census population of Cathlamet, Washington, 560\n",
45
+ " │ ├── Step 9: Using a calculator, find the difference in populations,\n",
46
+ " │ ├── \n",
47
+ " │ ├── 737,015 - 560\n",
48
+ " │ ├── 736,455\n",
49
+ " │ ├── Step 10: Report the correct answer to my user in the requested format, \"736,455\"\n",
50
+ " ├── Number of steps: 10\n",
51
+ " ├── How long did this take?: 5 minutes\n",
52
+ " ├── Tools:\n",
53
+ " │ ├── 1. A web browser\n",
54
+ " │ ├── 2. A search engine\n",
55
+ " │ ├── 3. A calculator\n",
56
+ " └── Number of tools: 3\n",
57
+ "==================================================\n"
58
+ ]
59
+ }
60
+ ],
61
+ "source": [
62
+ "import random\n",
63
+ "random_samples = random.sample(json_QA, 1)\n",
64
+ "for sample in random_samples:\n",
65
+ " print(\"=\" * 50)\n",
66
+ " print(f\"Task ID: {sample['task_id']}\")\n",
67
+ " print(f\"Question: {sample['Question']}\")\n",
68
+ " print(f\"Level: {sample['Level']}\")\n",
69
+ " print(f\"Final Answer: {sample['Final answer']}\")\n",
70
+ " print(f\"Annotator Metadata: \")\n",
71
+ " print(f\" ├── Steps: \")\n",
72
+ " for step in sample['Annotator Metadata']['Steps'].split('\\n'):\n",
73
+ " print(f\" │ ├── {step}\")\n",
74
+ " print(f\" ├── Number of steps: {sample['Annotator Metadata']['Number of steps']}\")\n",
75
+ " print(f\" ├── How long did this take?: {sample['Annotator Metadata']['How long did this take?']}\")\n",
76
+ " print(f\" ├── Tools:\")\n",
77
+ " for tool in sample['Annotator Metadata']['Tools'].split('\\n'):\n",
78
+ " print(f\" │ ├── {tool}\")\n",
79
+ " print(f\" └── Number of tools: {sample['Annotator Metadata']['Number of tools']}\")\n",
80
+ "print(\"=\" * 50)"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "execution_count": 11,
86
+ "id": "05076516",
87
+ "metadata": {},
88
+ "outputs": [],
89
+ "source": [
90
+ "import os\n",
91
+ "from dotenv import load_dotenv\n",
92
+ "from langchain_huggingface import HuggingFaceEmbeddings\n",
93
+ "from langchain_community.vectorstores import SupabaseVectorStore\n",
94
+ "from supabase.client import Client, create_client\n",
95
+ "\n",
96
+ "\n",
97
+ "load_dotenv()\n",
98
+ "embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\") # dim=768\n",
99
+ "\n",
100
+ "supabase_url = os.environ.get(\"SUPABASE_URL\")\n",
101
+ "supabase_key = os.environ.get(\"SUPABASE_SERVICE_ROLE_KEY\")\n",
102
+ "supabase: Client = create_client(supabase_url, supabase_key)"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "execution_count": 20,
108
+ "id": "aa1402e3",
109
+ "metadata": {},
110
+ "outputs": [],
111
+ "source": [
112
+ "from langchain.schema import Document\n",
113
+ "docs = []\n",
114
+ "cnt = 0 \n",
115
+ "for sample in json_QA:\n",
116
+ " content = f\"Question : {sample['Question']}\\n\\nFinal answer : {sample['Final answer']}\"\n",
117
+ " doc = {\n",
118
+ " \"id\" : cnt,\n",
119
+ " \"content\" : content,\n",
120
+ " \"metadata\" : {\n",
121
+ " \"source\" : sample['task_id']\n",
122
+ " },\n",
123
+ " \"embedding\" : embeddings.embed_query(content),\n",
124
+ " }\n",
125
+ " docs.append(doc)\n",
126
+ " cnt += 1\n",
127
+ "\n",
128
+ "# upload the documents to the vector database\n",
129
+ "try:\n",
130
+ " response = (\n",
131
+ " supabase.table(\"documents2\")\n",
132
+ " .insert(docs)\n",
133
+ " .execute()\n",
134
+ " )\n",
135
+ "except Exception as exception:\n",
136
+ " print(\"Error inserting data into Supabase:\", exception)\n",
137
+ "\n",
138
+ "# # Save the documents (a list of dict) into a csv file, and manually upload it to Supabase\n",
139
+ "# import pandas as pd\n",
140
+ "# df = pd.DataFrame(docs)\n",
141
+ "# df.to_csv('supabase_docs.csv',index=False)"
142
+ ]
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "execution_count": 41,
147
+ "id": "9aa7eb5e",
148
+ "metadata": {},
149
+ "outputs": [],
150
+ "source": [
151
+ "# add items to vector database\n",
152
+ "vector_store = SupabaseVectorStore(\n",
153
+ " client=supabase,\n",
154
+ " embedding= embeddings,\n",
155
+ " table_name=\"documents2\",\n",
156
+ " query_name=\"match_documents_2\",\n",
157
+ ")\n",
158
+ "retriever = vector_store.as_retriever()"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "execution_count": 42,
164
+ "id": "9eecafd1",
165
+ "metadata": {},
166
+ "outputs": [],
167
+ "source": [
168
+ "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?\"\n",
169
+ "# matched_docs = vector_store.similarity_search(query, k=2)\n",
170
+ "docs = retriever.invoke(query)"
171
+ ]
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "execution_count": 43,
176
+ "id": "ff917840",
177
+ "metadata": {},
178
+ "outputs": [
179
+ {
180
+ "data": {
181
+ "text/plain": [
182
+ "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')"
183
+ ]
184
+ },
185
+ "execution_count": 43,
186
+ "metadata": {},
187
+ "output_type": "execute_result"
188
+ }
189
+ ],
190
+ "source": [
191
+ "docs[0]"
192
+ ]
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "execution_count": 44,
197
+ "id": "01c8f337",
198
+ "metadata": {},
199
+ "outputs": [
200
+ {
201
+ "name": "stdout",
202
+ "output_type": "stream",
203
+ "text": [
204
+ "List of tools used in all samples:\n",
205
+ "Total number of tools used: 83\n",
206
+ " ├── web browser: 107\n",
207
+ " ├── image recognition tools (to identify and parse a figure with three axes): 1\n",
208
+ " ├── search engine: 101\n",
209
+ " ├── calculator: 34\n",
210
+ " ├── unlambda compiler (optional): 1\n",
211
+ " ├── a web browser.: 2\n",
212
+ " ├── a search engine.: 2\n",
213
+ " ├── a calculator.: 1\n",
214
+ " ├── microsoft excel: 5\n",
215
+ " ├── google search: 1\n",
216
+ " ├── ne: 9\n",
217
+ " ├── pdf access: 7\n",
218
+ " ├── file handling: 2\n",
219
+ " ├── python: 3\n",
220
+ " ├── image recognition tools: 12\n",
221
+ " ├── jsonld file access: 1\n",
222
+ " ├── video parsing: 1\n",
223
+ " ├── python compiler: 1\n",
224
+ " ├── video recognition tools: 3\n",
225
+ " ├── pdf viewer: 7\n",
226
+ " ├── microsoft excel / google sheets: 3\n",
227
+ " ├── word document access: 1\n",
228
+ " ├── tool to extract text from images: 1\n",
229
+ " ├── a word reversal tool / script: 1\n",
230
+ " ├── counter: 1\n",
231
+ " ├── excel: 3\n",
232
+ " ├── image recognition: 5\n",
233
+ " ├── color recognition: 3\n",
234
+ " ├── excel file access: 3\n",
235
+ " ├── xml file access: 1\n",
236
+ " ├── access to the internet archive, web.archive.org: 1\n",
237
+ " ├── text processing/diff tool: 1\n",
238
+ " ├── gif parsing tools: 1\n",
239
+ " ├── a web browser: 7\n",
240
+ " ├── a search engine: 7\n",
241
+ " ├── a speech-to-text tool: 2\n",
242
+ " ├── code/data analysis tools: 1\n",
243
+ " ├── audio capability: 2\n",
244
+ " ├── pdf reader: 1\n",
245
+ " ├── markdown: 1\n",
246
+ " ├── a calculator: 5\n",
247
+ " ├── access to wikipedia: 3\n",
248
+ " ├── image recognition/ocr: 3\n",
249
+ " ├── google translate access: 1\n",
250
+ " ├── ocr: 4\n",
251
+ " ├── bass note data: 1\n",
252
+ " ├── text editor: 1\n",
253
+ " ├── xlsx file access: 1\n",
254
+ " ├── powerpoint viewer: 1\n",
255
+ " ├── csv file access: 1\n",
256
+ " ├── calculator (or use excel): 1\n",
257
+ " ├── computer algebra system: 1\n",
258
+ " ├── video processing software: 1\n",
259
+ " ├── audio processing software: 1\n",
260
+ " ├── computer vision: 1\n",
261
+ " ├── google maps: 1\n",
262
+ " ├── access to excel files: 1\n",
263
+ " ├── calculator (or ability to count): 1\n",
264
+ " ├── a file interface: 3\n",
265
+ " ├── a python ide: 1\n",
266
+ " ├── spreadsheet editor: 1\n",
267
+ " ├── tools required: 1\n",
268
+ " ├── b browser: 1\n",
269
+ " ├── image recognition and processing tools: 1\n",
270
+ " ├── computer vision or ocr: 1\n",
271
+ " ├── c++ compiler: 1\n",
272
+ " ├── access to google maps: 1\n",
273
+ " ├── youtube player: 1\n",
274
+ " ├── natural language processor: 1\n",
275
+ " ├── graph interaction tools: 1\n",
276
+ " ├── bablyonian cuniform -> arabic legend: 1\n",
277
+ " ├── access to youtube: 1\n",
278
+ " ├── image search tools: 1\n",
279
+ " ├── calculator or counting function: 1\n",
280
+ " ├── a speech-to-text audio processing tool: 1\n",
281
+ " ├── access to academic journal websites: 1\n",
282
+ " ├── pdf reader/extracter: 1\n",
283
+ " ├── rubik's cube model: 1\n",
284
+ " ├── wikipedia: 1\n",
285
+ " ├── video capability: 1\n",
286
+ " ├── image processing tools: 1\n",
287
+ " ├── age recognition software: 1\n",
288
+ " ├── youtube: 1\n"
289
+ ]
290
+ }
291
+ ],
292
+ "source": [
293
+ "# list of the tools used in all the samples\n",
294
+ "from collections import Counter, OrderedDict\n",
295
+ "\n",
296
+ "tools = []\n",
297
+ "for sample in json_QA:\n",
298
+ " for tool in sample['Annotator Metadata']['Tools'].split('\\n'):\n",
299
+ " tool = tool[2:].strip().lower()\n",
300
+ " if tool.startswith(\"(\"):\n",
301
+ " tool = tool[11:].strip()\n",
302
+ " tools.append(tool)\n",
303
+ "tools_counter = OrderedDict(Counter(tools))\n",
304
+ "print(\"List of tools used in all samples:\")\n",
305
+ "print(\"Total number of tools used:\", len(tools_counter))\n",
306
+ "for tool, count in tools_counter.items():\n",
307
+ " print(f\" ├── {tool}: {count}\")"
308
+ ]
309
+ }
310
+ ],
311
+ "metadata": {
312
+ "kernelspec": {
313
+ "display_name": "env",
314
+ "language": "python",
315
+ "name": "python3"
316
+ },
317
+ "language_info": {
318
+ "codemirror_mode": {
319
+ "name": "ipython",
320
+ "version": 3
321
+ },
322
+ "file_extension": ".py",
323
+ "mimetype": "text/x-python",
324
+ "name": "python",
325
+ "nbconvert_exporter": "python",
326
+ "pygments_lexer": "ipython3",
327
+ "version": "3.11.9"
328
+ }
329
+ },
330
+ "nbformat": 4,
331
+ "nbformat_minor": 5
332
+ }
image_processing.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import base64
4
+ import uuid
5
+ from PIL import Image
6
+
7
+ # Helper functions for image processing
8
+ def encode_image(image_path: str) -> str:
9
+ """Convert an image file to base64 string."""
10
+ with open(image_path, "rb") as image_file:
11
+ return base64.b64encode(image_file.read()).decode("utf-8")
12
+
13
+
14
+ def decode_image(base64_string: str) -> Image.Image:
15
+ """Convert a base64 string to a PIL Image."""
16
+ image_data = base64.b64decode(base64_string)
17
+ return Image.open(io.BytesIO(image_data))
18
+
19
+
20
+ def save_image(image: Image.Image, directory: str = "image_outputs") -> str:
21
+ """Save a PIL Image to disk and return the path."""
22
+ os.makedirs(directory, exist_ok=True)
23
+ image_id = str(uuid.uuid4())
24
+ image_path = os.path.join(directory, f"{image_id}.png")
25
+ image.save(image_path)
26
+ return image_path
requirements.txt CHANGED
@@ -15,4 +15,6 @@ arxiv
15
  pymupdf
16
  wikipedia
17
  pgvector
18
- python-dotenv
 
 
 
15
  pymupdf
16
  wikipedia
17
  pgvector
18
+ python-dotenv
19
+ pytesseract
20
+ matplotlib
supabase_docs.csv CHANGED
The diff for this file is too large to render. See raw diff
 
system_prompt.txt CHANGED
@@ -1,17 +1,5 @@
1
- You are a helpful assistant tasked with answering questions using a set of tools.
2
-
3
- Your final answer must strictly follow this format:
4
- FINAL ANSWER: [ANSWER]
5
-
6
- Only write the answer in that exact format. Do not explain anything. Do not include any other text.
7
-
8
- If you are provided with a similar question and its final answer, and the current question is **exactly the same**, then simply return the same final answer without using any tools.
9
-
10
- Only use tools if the current question is different from the similar one.
11
-
12
- Examples:
13
- - FINAL ANSWER: FunkMonk
14
- - FINAL ANSWER: Paris
15
- - FINAL ANSWER: 128
16
-
17
- If you do not follow this format exactly, your response will be considered incorrect.
 
1
+ You are a helpful assistant tasked with answering questions using a set of tools.
2
+ Now, I will ask you a question. Report your thoughts, and finish your answer with the following template:
3
+ FINAL ANSWER: [YOUR FINAL ANSWER].
4
+ 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 rules above for each element (number or string), ensure there is exactly one space after each comma.
5
+ Your answer should only start with "FINAL ANSWER: ", then follows with the answer.
 
 
 
 
 
 
 
 
 
 
 
 
test.ipynb DELETED
@@ -1,684 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "id": "d0cc4adf",
6
- "metadata": {},
7
- "source": [
8
- "### Question data"
9
- ]
10
- },
11
- {
12
- "cell_type": "code",
13
- "execution_count": 2,
14
- "id": "14e3f417",
15
- "metadata": {},
16
- "outputs": [],
17
- "source": [
18
- "# Load metadata.jsonl\n",
19
- "import json\n",
20
- "# Load the metadata.jsonl file\n",
21
- "with open('metadata.jsonl', 'r') as jsonl_file:\n",
22
- " json_list = list(jsonl_file)\n",
23
- "\n",
24
- "json_QA = []\n",
25
- "for json_str in json_list:\n",
26
- " json_data = json.loads(json_str)\n",
27
- " json_QA.append(json_data)"
28
- ]
29
- },
30
- {
31
- "cell_type": "code",
32
- "execution_count": 3,
33
- "id": "5e2da6fc",
34
- "metadata": {},
35
- "outputs": [
36
- {
37
- "name": "stdout",
38
- "output_type": "stream",
39
- "text": [
40
- "==================================================\n",
41
- "Task ID: ed58682d-bc52-4baa-9eb0-4eb81e1edacc\n",
42
- "Question: What is the last word before the second chorus of the King of Pop's fifth single from his sixth studio album?\n",
43
- "Level: 2\n",
44
- "Final Answer: stare\n",
45
- "Annotator Metadata: \n",
46
- " ├── Steps: \n",
47
- " │ ├── 1. Google searched \"King of Pop\".\n",
48
- " │ ├── 2. Clicked on Michael Jackson's Wikipedia.\n",
49
- " │ ├── 3. Scrolled down to \"Discography\".\n",
50
- " │ ├── 4. Clicked on the sixth album, \"Thriller\".\n",
51
- " │ ├── 5. Looked under \"Singles from Thriller\".\n",
52
- " │ ├── 6. Clicked on the fifth single, \"Human Nature\".\n",
53
- " │ ├── 7. Google searched \"Human Nature Michael Jackson Lyrics\".\n",
54
- " │ ├── 8. Looked at the opening result with full lyrics sourced by Musixmatch.\n",
55
- " │ ├── 9. Looked for repeating lyrics to determine the chorus.\n",
56
- " │ ├── 10. Determined the chorus begins with \"If they say\" and ends with \"Does he do me that way?\"\n",
57
- " │ ├── 11. Found the second instance of the chorus within the lyrics.\n",
58
- " │ ├── 12. Noted the last word before the second chorus - \"stare\".\n",
59
- " ├── Number of steps: 12\n",
60
- " ├── How long did this take?: 20 minutes\n",
61
- " ├── Tools:\n",
62
- " │ ├── Web Browser\n",
63
- " └── Number of tools: 1\n",
64
- "==================================================\n"
65
- ]
66
- }
67
- ],
68
- "source": [
69
- "# randomly select 3 samples\n",
70
- "# {\"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\"}}\n",
71
- "\n",
72
- "import random\n",
73
- "# random.seed(42)\n",
74
- "random_samples = random.sample(json_QA, 1)\n",
75
- "for sample in random_samples:\n",
76
- " print(\"=\" * 50)\n",
77
- " print(f\"Task ID: {sample['task_id']}\")\n",
78
- " print(f\"Question: {sample['Question']}\")\n",
79
- " print(f\"Level: {sample['Level']}\")\n",
80
- " print(f\"Final Answer: {sample['Final answer']}\")\n",
81
- " print(f\"Annotator Metadata: \")\n",
82
- " print(f\" ├── Steps: \")\n",
83
- " for step in sample['Annotator Metadata']['Steps'].split('\\n'):\n",
84
- " print(f\" │ ├── {step}\")\n",
85
- " print(f\" ├── Number of steps: {sample['Annotator Metadata']['Number of steps']}\")\n",
86
- " print(f\" ├── How long did this take?: {sample['Annotator Metadata']['How long did this take?']}\")\n",
87
- " print(f\" ├── Tools:\")\n",
88
- " for tool in sample['Annotator Metadata']['Tools'].split('\\n'):\n",
89
- " print(f\" │ ├── {tool}\")\n",
90
- " print(f\" └── Number of tools: {sample['Annotator Metadata']['Number of tools']}\")\n",
91
- "print(\"=\" * 50)"
92
- ]
93
- },
94
- {
95
- "cell_type": "code",
96
- "execution_count": 56,
97
- "id": "4bb02420",
98
- "metadata": {},
99
- "outputs": [],
100
- "source": [
101
- "### build a vector database based on the metadata.jsonl\n",
102
- "# https://python.langchain.com/docs/integrations/vectorstores/supabase/\n",
103
- "import os\n",
104
- "from dotenv import load_dotenv\n",
105
- "from langchain_huggingface import HuggingFaceEmbeddings\n",
106
- "from langchain_community.vectorstores import SupabaseVectorStore\n",
107
- "from supabase.client import Client, create_client\n",
108
- "\n",
109
- "\n",
110
- "load_dotenv()\n",
111
- "embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\") # dim=768\n",
112
- "\n",
113
- "supabase_url = os.environ.get(\"SUPABASE_URL\")\n",
114
- "supabase_key = os.environ.get(\"SUPABASE_SERVICE_KEY\")\n",
115
- "supabase: Client = create_client(supabase_url, supabase_key)"
116
- ]
117
- },
118
- {
119
- "cell_type": "code",
120
- "execution_count": null,
121
- "id": "a070b955",
122
- "metadata": {},
123
- "outputs": [],
124
- "source": [
125
- "# wrap the metadata.jsonl's questions and answers into a list of document\n",
126
- "from langchain.schema import Document\n",
127
- "docs = []\n",
128
- "for sample in json_QA:\n",
129
- " content = f\"Question : {sample['Question']}\\n\\nFinal answer : {sample['Final answer']}\"\n",
130
- " doc = {\n",
131
- " \"content\" : content,\n",
132
- " \"metadata\" : { # meatadata的格式必须时source键,否则会报错\n",
133
- " \"source\" : sample['task_id']\n",
134
- " },\n",
135
- " \"embedding\" : embeddings.embed_query(content),\n",
136
- " }\n",
137
- " docs.append(doc)\n",
138
- "\n",
139
- "# upload the documents to the vector database\n",
140
- "try:\n",
141
- " response = (\n",
142
- " supabase.table(\"documents\")\n",
143
- " .insert(docs)\n",
144
- " .execute()\n",
145
- " )\n",
146
- "except Exception as exception:\n",
147
- " print(\"Error inserting data into Supabase:\", exception)\n",
148
- "\n",
149
- "# ALTERNATIVE : Save the documents (a list of dict) into a csv file, and manually upload it to Supabase\n",
150
- "# import pandas as pd\n",
151
- "# df = pd.DataFrame(docs)\n",
152
- "# df.to_csv('supabase_docs.csv', index=False)"
153
- ]
154
- },
155
- {
156
- "cell_type": "code",
157
- "execution_count": 54,
158
- "id": "77fb9dbb",
159
- "metadata": {},
160
- "outputs": [],
161
- "source": [
162
- "# add items to vector database\n",
163
- "vector_store = SupabaseVectorStore(\n",
164
- " client=supabase,\n",
165
- " embedding= embeddings,\n",
166
- " table_name=\"documents\",\n",
167
- " query_name=\"match_documents_langchain\",\n",
168
- ")\n",
169
- "retriever = vector_store.as_retriever()"
170
- ]
171
- },
172
- {
173
- "cell_type": "code",
174
- "execution_count": 55,
175
- "id": "12a05971",
176
- "metadata": {},
177
- "outputs": [
178
- {
179
- "name": "stderr",
180
- "output_type": "stream",
181
- "text": [
182
- "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
183
- "To disable this warning, you can either:\n",
184
- "\t- Avoid using `tokenizers` before the fork if possible\n",
185
- "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"
186
- ]
187
- },
188
- {
189
- "data": {
190
- "text/plain": [
191
- "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')"
192
- ]
193
- },
194
- "execution_count": 55,
195
- "metadata": {},
196
- "output_type": "execute_result"
197
- }
198
- ],
199
- "source": [
200
- "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?\"\n",
201
- "# matched_docs = vector_store.similarity_search(query, 2)\n",
202
- "docs = retriever.invoke(query)\n",
203
- "docs[0]"
204
- ]
205
- },
206
- {
207
- "cell_type": "code",
208
- "execution_count": 31,
209
- "id": "1eae5ba4",
210
- "metadata": {},
211
- "outputs": [
212
- {
213
- "name": "stdout",
214
- "output_type": "stream",
215
- "text": [
216
- "List of tools used in all samples:\n",
217
- "Total number of tools used: 83\n",
218
- " ├── web browser: 107\n",
219
- " ├── image recognition tools (to identify and parse a figure with three axes): 1\n",
220
- " ├── search engine: 101\n",
221
- " ├── calculator: 34\n",
222
- " ├── unlambda compiler (optional): 1\n",
223
- " ├── a web browser.: 2\n",
224
- " ├── a search engine.: 2\n",
225
- " ├── a calculator.: 1\n",
226
- " ├── microsoft excel: 5\n",
227
- " ├── google search: 1\n",
228
- " ├── ne: 9\n",
229
- " ├── pdf access: 7\n",
230
- " ├── file handling: 2\n",
231
- " ├── python: 3\n",
232
- " ├── image recognition tools: 12\n",
233
- " ├── jsonld file access: 1\n",
234
- " ├── video parsing: 1\n",
235
- " ├── python compiler: 1\n",
236
- " ├── video recognition tools: 3\n",
237
- " ├── pdf viewer: 7\n",
238
- " ├── microsoft excel / google sheets: 3\n",
239
- " ├── word document access: 1\n",
240
- " ├── tool to extract text from images: 1\n",
241
- " ├── a word reversal tool / script: 1\n",
242
- " ├── counter: 1\n",
243
- " ├── excel: 3\n",
244
- " ├── image recognition: 5\n",
245
- " ├── color recognition: 3\n",
246
- " ├── excel file access: 3\n",
247
- " ├── xml file access: 1\n",
248
- " ├── access to the internet archive, web.archive.org: 1\n",
249
- " ├── text processing/diff tool: 1\n",
250
- " ├── gif parsing tools: 1\n",
251
- " ├── a web browser: 7\n",
252
- " ├── a search engine: 7\n",
253
- " ├── a speech-to-text tool: 2\n",
254
- " ├── code/data analysis tools: 1\n",
255
- " ├── audio capability: 2\n",
256
- " ├── pdf reader: 1\n",
257
- " ├── markdown: 1\n",
258
- " ├── a calculator: 5\n",
259
- " ├── access to wikipedia: 3\n",
260
- " ├── image recognition/ocr: 3\n",
261
- " ├── google translate access: 1\n",
262
- " ├── ocr: 4\n",
263
- " ├── bass note data: 1\n",
264
- " ├── text editor: 1\n",
265
- " ├── xlsx file access: 1\n",
266
- " ├── powerpoint viewer: 1\n",
267
- " ├── csv file access: 1\n",
268
- " ├── calculator (or use excel): 1\n",
269
- " ├── computer algebra system: 1\n",
270
- " ├── video processing software: 1\n",
271
- " ├── audio processing software: 1\n",
272
- " ├── computer vision: 1\n",
273
- " ├── google maps: 1\n",
274
- " ├── access to excel files: 1\n",
275
- " ├── calculator (or ability to count): 1\n",
276
- " ├── a file interface: 3\n",
277
- " ├── a python ide: 1\n",
278
- " ├── spreadsheet editor: 1\n",
279
- " ├── tools required: 1\n",
280
- " ├── b browser: 1\n",
281
- " ├── image recognition and processing tools: 1\n",
282
- " ├── computer vision or ocr: 1\n",
283
- " ├── c++ compiler: 1\n",
284
- " ├── access to google maps: 1\n",
285
- " ├── youtube player: 1\n",
286
- " ├── natural language processor: 1\n",
287
- " ├── graph interaction tools: 1\n",
288
- " ├── bablyonian cuniform -> arabic legend: 1\n",
289
- " ├── access to youtube: 1\n",
290
- " ├── image search tools: 1\n",
291
- " ├── calculator or counting function: 1\n",
292
- " ├── a speech-to-text audio processing tool: 1\n",
293
- " ├── access to academic journal websites: 1\n",
294
- " ├── pdf reader/extracter: 1\n",
295
- " ├── rubik's cube model: 1\n",
296
- " ├── wikipedia: 1\n",
297
- " ├── video capability: 1\n",
298
- " ├── image processing tools: 1\n",
299
- " ├── age recognition software: 1\n",
300
- " ├── youtube: 1\n"
301
- ]
302
- }
303
- ],
304
- "source": [
305
- "# list of the tools used in all the samples\n",
306
- "from collections import Counter, OrderedDict\n",
307
- "\n",
308
- "tools = []\n",
309
- "for sample in json_QA:\n",
310
- " for tool in sample['Annotator Metadata']['Tools'].split('\\n'):\n",
311
- " tool = tool[2:].strip().lower()\n",
312
- " if tool.startswith(\"(\"):\n",
313
- " tool = tool[11:].strip()\n",
314
- " tools.append(tool)\n",
315
- "tools_counter = OrderedDict(Counter(tools))\n",
316
- "print(\"List of tools used in all samples:\")\n",
317
- "print(\"Total number of tools used:\", len(tools_counter))\n",
318
- "for tool, count in tools_counter.items():\n",
319
- " print(f\" ├── {tool}: {count}\")"
320
- ]
321
- },
322
- {
323
- "cell_type": "markdown",
324
- "id": "5efee12a",
325
- "metadata": {},
326
- "source": [
327
- "#### Graph"
328
- ]
329
- },
330
- {
331
- "cell_type": "code",
332
- "execution_count": 55,
333
- "id": "7fe573cc",
334
- "metadata": {},
335
- "outputs": [],
336
- "source": [
337
- "system_prompt = \"\"\"\n",
338
- "You are a helpful assistant tasked with answering questions using a set of tools.\n",
339
- "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. \n",
340
- "You need to provide a step-by-step explanation of how you arrived at the answer.\n",
341
- "==========================\n",
342
- "Here is a few examples showing you how to answer the question step by step.\n",
343
- "\"\"\"\n",
344
- "for i, samples in enumerate(random_samples):\n",
345
- " 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\"\n",
346
- "system_prompt += \"\\n==========================\\n\"\n",
347
- "system_prompt += \"Now, please answer the following question step by step.\\n\"\n",
348
- "\n",
349
- "# save the system_prompt to a file\n",
350
- "with open('system_prompt.txt', 'w') as f:\n",
351
- " f.write(system_prompt)"
352
- ]
353
- },
354
- {
355
- "cell_type": "code",
356
- "execution_count": 56,
357
- "id": "d6beb0da",
358
- "metadata": {},
359
- "outputs": [
360
- {
361
- "name": "stdout",
362
- "output_type": "stream",
363
- "text": [
364
- "\n",
365
- "You are a helpful assistant tasked with answering questions using a set of tools.\n",
366
- "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. \n",
367
- "You need to provide a step-by-step explanation of how you arrived at the answer.\n",
368
- "==========================\n",
369
- "Here is a few examples showing you how to answer the question step by step.\n",
370
- "\n",
371
- "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.\n",
372
- "Steps:\n",
373
- "1. Search the web for \"ASEAN bloc\".\n",
374
- "2. Click the Wikipedia result for the ASEAN Free Trade Area.\n",
375
- "3. Scroll down to find the list of member states.\n",
376
- "4. Click into the Wikipedia pages for each member state, and note its capital.\n",
377
- "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.\n",
378
- "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.\n",
379
- "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.\n",
380
- "8. Return to the Wikipedia page for each country. Click the GPS coordinates for each capital to get the coordinates in decimal notation.\n",
381
- "9. Place all these coordinates into a spreadsheet.\n",
382
- "10. Write formulas to calculate the distance between each capital.\n",
383
- "11. Write formula to get the largest distance value in the spreadsheet.\n",
384
- "12. Note which two capitals that value corresponds to: Jakarta and Naypyidaw.\n",
385
- "13. Return to the Wikipedia pages to see which countries those respective capitals belong to: Indonesia, Myanmar.\n",
386
- "Tools:\n",
387
- "1. Search engine\n",
388
- "2. Web browser\n",
389
- "3. Microsoft Excel / Google Sheets\n",
390
- "Final Answer: Indonesia, Myanmar\n",
391
- "\n",
392
- "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.\n",
393
- "Steps:\n",
394
- "Step 1: Evaluate the position of the pieces in the chess position\n",
395
- "Step 2: Report the best move available for black: \"Rd5\"\n",
396
- "Tools:\n",
397
- "1. Image recognition tools\n",
398
- "Final Answer: Rd5\n",
399
- "\n",
400
- "==========================\n",
401
- "Now, please answer the following question step by step.\n",
402
- "\n"
403
- ]
404
- }
405
- ],
406
- "source": [
407
- "# load the system prompt from the file\n",
408
- "with open('system_prompt.txt', 'r') as f:\n",
409
- " system_prompt = f.read()\n",
410
- "print(system_prompt)"
411
- ]
412
- },
413
- {
414
- "cell_type": "code",
415
- "execution_count": null,
416
- "id": "42fde0f8",
417
- "metadata": {},
418
- "outputs": [],
419
- "source": [
420
- "import dotenv\n",
421
- "from langgraph.graph import MessagesState, START, StateGraph\n",
422
- "from langgraph.prebuilt import tools_condition\n",
423
- "from langgraph.prebuilt import ToolNode\n",
424
- "from langchain_google_genai import ChatGoogleGenerativeAI\n",
425
- "from langchain_huggingface import HuggingFaceEmbeddings\n",
426
- "from langchain_community.tools.tavily_search import TavilySearchResults\n",
427
- "from langchain_community.document_loaders import WikipediaLoader\n",
428
- "from langchain_community.document_loaders import ArxivLoader\n",
429
- "from langchain_community.vectorstores import SupabaseVectorStore\n",
430
- "from langchain.tools.retriever import create_retriever_tool\n",
431
- "from langchain_core.messages import HumanMessage, SystemMessage\n",
432
- "from langchain_core.tools import tool\n",
433
- "from supabase.client import Client, create_client\n",
434
- "\n",
435
- "# Define the retriever from supabase\n",
436
- "load_dotenv()\n",
437
- "embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\") # dim=768\n",
438
- "\n",
439
- "supabase_url = os.environ.get(\"SUPABASE_URL\")\n",
440
- "supabase_key = os.environ.get(\"SUPABASE_SERVICE_KEY\")\n",
441
- "supabase: Client = create_client(supabase_url, supabase_key)\n",
442
- "vector_store = SupabaseVectorStore(\n",
443
- " client=supabase,\n",
444
- " embedding= embeddings,\n",
445
- " table_name=\"documents\",\n",
446
- " query_name=\"match_documents_langchain\",\n",
447
- ")\n",
448
- "\n",
449
- "question_retrieve_tool = create_retriever_tool(\n",
450
- " vector_store.as_retriever(),\n",
451
- " \"Question Retriever\",\n",
452
- " \"Find similar questions in the vector database for the given question.\",\n",
453
- ")\n",
454
- "\n",
455
- "@tool\n",
456
- "def multiply(a: int, b: int) -> int:\n",
457
- " \"\"\"Multiply two numbers.\n",
458
- "\n",
459
- " Args:\n",
460
- " a: first int\n",
461
- " b: second int\n",
462
- " \"\"\"\n",
463
- " return a * b\n",
464
- "\n",
465
- "@tool\n",
466
- "def add(a: int, b: int) -> int:\n",
467
- " \"\"\"Add two numbers.\n",
468
- " \n",
469
- " Args:\n",
470
- " a: first int\n",
471
- " b: second int\n",
472
- " \"\"\"\n",
473
- " return a + b\n",
474
- "\n",
475
- "@tool\n",
476
- "def subtract(a: int, b: int) -> int:\n",
477
- " \"\"\"Subtract two numbers.\n",
478
- " \n",
479
- " Args:\n",
480
- " a: first int\n",
481
- " b: second int\n",
482
- " \"\"\"\n",
483
- " return a - b\n",
484
- "\n",
485
- "@tool\n",
486
- "def divide(a: int, b: int) -> int:\n",
487
- " \"\"\"Divide two numbers.\n",
488
- " \n",
489
- " Args:\n",
490
- " a: first int\n",
491
- " b: second int\n",
492
- " \"\"\"\n",
493
- " if b == 0:\n",
494
- " raise ValueError(\"Cannot divide by zero.\")\n",
495
- " return a / b\n",
496
- "\n",
497
- "@tool\n",
498
- "def modulus(a: int, b: int) -> int:\n",
499
- " \"\"\"Get the modulus of two numbers.\n",
500
- " \n",
501
- " Args:\n",
502
- " a: first int\n",
503
- " b: second int\n",
504
- " \"\"\"\n",
505
- " return a % b\n",
506
- "\n",
507
- "@tool\n",
508
- "def wiki_search(query: str) -> str:\n",
509
- " \"\"\"Search Wikipedia for a query and return maximum 2 results.\n",
510
- " \n",
511
- " Args:\n",
512
- " query: The search query.\"\"\"\n",
513
- " search_docs = WikipediaLoader(query=query, load_max_docs=2).load()\n",
514
- " formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
515
- " [\n",
516
- " f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content}\\n</Document>'\n",
517
- " for doc in search_docs\n",
518
- " ])\n",
519
- " return {\"wiki_results\": formatted_search_docs}\n",
520
- "\n",
521
- "@tool\n",
522
- "def web_search(query: str) -> str:\n",
523
- " \"\"\"Search Tavily for a query and return maximum 3 results.\n",
524
- " \n",
525
- " Args:\n",
526
- " query: The search query.\"\"\"\n",
527
- " search_docs = TavilySearchResults(max_results=3).invoke(query=query)\n",
528
- " formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
529
- " [\n",
530
- " f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content}\\n</Document>'\n",
531
- " for doc in search_docs\n",
532
- " ])\n",
533
- " return {\"web_results\": formatted_search_docs}\n",
534
- "\n",
535
- "@tool\n",
536
- "def arvix_search(query: str) -> str:\n",
537
- " \"\"\"Search Arxiv for a query and return maximum 3 result.\n",
538
- " \n",
539
- " Args:\n",
540
- " query: The search query.\"\"\"\n",
541
- " search_docs = ArxivLoader(query=query, load_max_docs=3).load()\n",
542
- " formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
543
- " [\n",
544
- " f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content[:1000]}\\n</Document>'\n",
545
- " for doc in search_docs\n",
546
- " ])\n",
547
- " return {\"arvix_results\": formatted_search_docs}\n",
548
- "\n",
549
- "@tool\n",
550
- "def similar_question_search(question: str) -> str:\n",
551
- " \"\"\"Search the vector database for similar questions and return the first results.\n",
552
- " \n",
553
- " Args:\n",
554
- " question: the question human provided.\"\"\"\n",
555
- " matched_docs = vector_store.similarity_search(query, 3)\n",
556
- " formatted_search_docs = \"\\n\\n---\\n\\n\".join(\n",
557
- " [\n",
558
- " f'<Document source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\"/>\\n{doc.page_content[:1000]}\\n</Document>'\n",
559
- " for doc in matched_docs\n",
560
- " ])\n",
561
- " return {\"similar_questions\": formatted_search_docs}\n",
562
- "\n",
563
- "tools = [\n",
564
- " multiply,\n",
565
- " add,\n",
566
- " subtract,\n",
567
- " divide,\n",
568
- " modulus,\n",
569
- " wiki_search,\n",
570
- " web_search,\n",
571
- " arvix_search,\n",
572
- " question_retrieve_tool\n",
573
- "]\n",
574
- "\n",
575
- "llm = ChatGoogleGenerativeAI(model=\"gemini-2.0-flash\")\n",
576
- "llm_with_tools = llm.bind_tools(tools)"
577
- ]
578
- },
579
- {
580
- "cell_type": "code",
581
- "execution_count": null,
582
- "id": "7dd0716c",
583
- "metadata": {},
584
- "outputs": [],
585
- "source": [
586
- "# load the system prompt from the file\n",
587
- "with open('system_prompt.txt', 'r') as f:\n",
588
- " system_prompt = f.read()\n",
589
- "\n",
590
- "\n",
591
- "# System message\n",
592
- "sys_msg = SystemMessage(content=system_prompt)\n",
593
- "\n",
594
- "# Node\n",
595
- "def assistant(state: MessagesState):\n",
596
- " \"\"\"Assistant node\"\"\"\n",
597
- " return {\"messages\": [llm_with_tools.invoke([sys_msg] + state[\"messages\"])]}\n",
598
- "\n",
599
- "# Build graph\n",
600
- "builder = StateGraph(MessagesState)\n",
601
- "builder.add_node(\"assistant\", assistant)\n",
602
- "builder.add_node(\"tools\", ToolNode(tools))\n",
603
- "builder.add_edge(START, \"assistant\")\n",
604
- "builder.add_conditional_edges(\n",
605
- " \"assistant\",\n",
606
- " # If the latest message (result) from assistant is a tool call -> tools_condition routes to tools\n",
607
- " # If the latest message (result) from assistant is a not a tool call -> tools_condition routes to END\n",
608
- " tools_condition,\n",
609
- ")\n",
610
- "builder.add_edge(\"tools\", \"assistant\")\n",
611
- "\n",
612
- "# Compile graph\n",
613
- "graph = builder.compile()\n"
614
- ]
615
- },
616
- {
617
- "cell_type": "code",
618
- "execution_count": 49,
619
- "id": "f4e77216",
620
- "metadata": {},
621
- "outputs": [
622
- {
623
- "data": {
624
- "image/png": "iVBORw0KGgoAAAANSUhEUgAAANgAAAD5CAIAAADKsmwpAAAQAElEQVR4nOydB1wUR9vA5zrcwdGOXqRIFRC7gkZsxK7YguU1xhgTJcVXjVETNSYajCbGYCxYYuJnjYliYq+xRo2xIIqAgNI7HFzh+vfo5UVEQEzYuzl2/r/7HXu7e7dX/jwz88zsLFun0yECwdiwEYGAAUREAhYQEQlYQEQkYAERkYAFREQCFpikiAq5pixfKavWyKrVarVOrTSBDBTPnMnmMviWbL6Q5ehuhgjPYkoiSqtU6TekmcmSqjKVpS2Hb8mC31Voy0GmkArValDRQ4WsWsrhMbPvy7yCBd4hcLNAhCcwTCKhrdXoLv9WVpqvsHPhegdbuLY1R6ZMjUyTlSzNTZflZ9aED7Xz7WCJaI8JiHj3ivj3fSXhw+w6RNqg1gWE9suHyhQyTdR/nMwtWIjG4C7i7/uKzfjM7kNEqPVSWqBIXJc38HUnN18+oitYi3hyR5GTl1lIhBWiAQfW5fWKFolceIiW4Cti4vq8tmEWweG0sFDPgXW5IRHW8KkR/WAiLLmQWO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bGk/SvWY2e+9CXGiIhY4O7Hn/iRx6N70rRb0sxreTbO5soaLZvLZnHZDCamnexMFlMlV2pUGqTTVhTIoV0c1EkQ1N3zZWdG1ENExIg2QYI2T7K+Rdk1T6YuVtfItAoZJSPH/j3mFjoGky0Q8vhCtrOXE4f7r6p5REQccfQwc/RAtKJhEblmDC0y4WFXAmsOk2Xyw8ZoRcPh1NKGU/LIhHMK2SkSWyfTPq+AbjQsooM7z3THocolapErz8Ka1DpMiUYjomtbs/O/NGuuT9w4tSO/y4Dm5lEJmNDU9Zrv/iFOvyVp39vOxpHLYuOe+q6RaapKlZcOFg+c7OjgQceJjkyaF1w4POuu9Na5ysKsGhYb66LaSsSpKld5Bgk6D7CBblxEMDVeIGItCjnWffM6LTITkO5KE6a5IhIIlEKalgQsICISsICISMACIiIBC4iIBCwgIhKw4P8BAAD//2v4e7oAAAAGSURBVAMA1x7mMDWkAPIAAAAASUVORK5CYII=",
625
- "text/plain": [
626
- "<IPython.core.display.Image object>"
627
- ]
628
- },
629
- "metadata": {},
630
- "output_type": "display_data"
631
- }
632
- ],
633
- "source": [
634
- "from IPython.display import Image, display\n",
635
- "\n",
636
- "display(Image(graph.get_graph(xray=True).draw_mermaid_png()))"
637
- ]
638
- },
639
- {
640
- "cell_type": "code",
641
- "execution_count": null,
642
- "id": "5987d58c",
643
- "metadata": {},
644
- "outputs": [],
645
- "source": [
646
- "question = \"\"\n",
647
- "messages = [HumanMessage(content=question)]\n",
648
- "messages = graph.invoke({\"messages\": messages})"
649
- ]
650
- },
651
- {
652
- "cell_type": "code",
653
- "execution_count": null,
654
- "id": "330cbf17",
655
- "metadata": {},
656
- "outputs": [],
657
- "source": [
658
- "for m in messages['messages']:\n",
659
- " m.pretty_print()"
660
- ]
661
- }
662
- ],
663
- "metadata": {
664
- "kernelspec": {
665
- "display_name": "aiagent",
666
- "language": "python",
667
- "name": "python3"
668
- },
669
- "language_info": {
670
- "codemirror_mode": {
671
- "name": "ipython",
672
- "version": 3
673
- },
674
- "file_extension": ".py",
675
- "mimetype": "text/x-python",
676
- "name": "python",
677
- "nbconvert_exporter": "python",
678
- "pygments_lexer": "ipython3",
679
- "version": "3.12.9"
680
- }
681
- },
682
- "nbformat": 4,
683
- "nbformat_minor": 5
684
- }