Dhanushkumar commited on
Commit
18f73c8
·
verified ·
1 Parent(s): 5cd42b5

Upload 13 files

Browse files
Files changed (10) hide show
  1. .env +2 -1
  2. README.md +14 -14
  3. agent.py +803 -0
  4. app.py +211 -0
  5. code_interpreter.py +281 -0
  6. explore_metadata.ipynb +332 -0
  7. image_processing.py +26 -0
  8. requirements.txt +20 -0
  9. supabase_docs.csv +0 -0
  10. system_prompt.txt +5 -28
.env CHANGED
@@ -1,4 +1,5 @@
1
  SUPABASE_URL = https://kyeropjbpzxfcypbxqoi.supabase.co
2
  SUPABASE_SERVICE_KEY = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imt5ZXJvcGpicHp4ZmN5cGJ4cW9pIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDg0ODYzNDEsImV4cCI6MjA2NDA2MjM0MX0._7ct7b36PILtOs4ycgPk1Tgk6dKNp2bbTjB-UBA3uGg
3
  GEMINI_API_KEY = AIzaSyCA47F1nv1sF9_y5IYzu_nZM325ZnIXfKU
4
- TAVILY_API_KEY = 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
 
 
1
  SUPABASE_URL = https://kyeropjbpzxfcypbxqoi.supabase.co
2
  SUPABASE_SERVICE_KEY = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imt5ZXJvcGpicHp4ZmN5cGJ4cW9pIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDg0ODYzNDEsImV4cCI6MjA2NDA2MjM0MX0._7ct7b36PILtOs4ycgPk1Tgk6dKNp2bbTjB-UBA3uGg
3
  GEMINI_API_KEY = AIzaSyCA47F1nv1sF9_y5IYzu_nZM325ZnIXfKU
4
+ TAVILY_API_KEY = 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
5
+ GROQ_API_KEY = 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
README.md CHANGED
@@ -1,15 +1,15 @@
1
- ---
2
- title: Template Final Assignment
3
- emoji: 🕵🏻‍♂️
4
- colorFrom: indigo
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 5.25.2
8
- app_file: app.py
9
- pinned: false
10
- hf_oauth: true
11
- # optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
12
- hf_oauth_expiration_minutes: 480
13
- ---
14
-
15
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: Template Final Assignment
3
+ emoji: 🕵🏻‍♂️
4
+ colorFrom: indigo
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 5.25.2
8
+ app_file: app.py
9
+ pinned: false
10
+ hf_oauth: true
11
+ # optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
12
+ hf_oauth_expiration_minutes: 480
13
+ ---
14
+
15
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
agent.py ADDED
@@ -0,0 +1,803 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
37
+ from langchain.tools.retriever import create_retriever_tool
38
+ from supabase.client import Client, create_client
39
+
40
+ load_dotenv()
41
+
42
+ ### =============== BROWSER TOOLS =============== ###
43
+ os.environ["TAVILY_API_KEY"] = "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"
44
+ os.environ["GOOGLE_API_KEY"] = "AIzaSyCA47F1nv1sF9_y5IYzu_nZM325ZnIXfKU"
45
+ os.environ["GROQ_API_KEY"] = "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"
46
+ @tool
47
+ def wiki_search(query: str) -> str:
48
+ """Search Wikipedia for a query and return maximum 2 results.
49
+
50
+ Args:
51
+ query: The search query."""
52
+ search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
53
+ formatted_search_docs = "\n\n---\n\n".join(
54
+ [
55
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
56
+ for doc in search_docs
57
+ ]
58
+ )
59
+ return {"wiki_results": formatted_search_docs}
60
+
61
+
62
+ @tool
63
+ def web_search(query: str) -> str:
64
+ """Search Tavily for a query and return maximum 3 results.
65
+
66
+ Args:
67
+ query: The search query."""
68
+ search_docs = TavilySearchResults(max_results=3).invoke(query=query)
69
+ formatted_search_docs = "\n\n---\n\n".join(
70
+ [
71
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
72
+ for doc in search_docs
73
+ ]
74
+ )
75
+ return {"web_results": formatted_search_docs}
76
+
77
+
78
+ @tool
79
+ def arxiv_search(query: str) -> str:
80
+ """Search Arxiv for a query and return maximum 3 result.
81
+
82
+ Args:
83
+ query: The search query."""
84
+ search_docs = ArxivLoader(query=query, load_max_docs=3).load()
85
+ formatted_search_docs = "\n\n---\n\n".join(
86
+ [
87
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
88
+ for doc in search_docs
89
+ ]
90
+ )
91
+ return {"arxiv_results": formatted_search_docs}
92
+
93
+
94
+ ### =============== CODE INTERPRETER TOOLS =============== ###
95
+
96
+
97
+ @tool
98
+ def execute_code_multilang(code: str, language: str = "python") -> str:
99
+ """Execute code in multiple languages (Python, Bash, SQL, C, Java) and return results.
100
+
101
+ Args:
102
+ code (str): The source code to execute.
103
+ language (str): The language of the code. Supported: "python", "bash", "sql", "c", "java".
104
+
105
+ Returns:
106
+ A string summarizing the execution results (stdout, stderr, errors, plots, dataframes if any).
107
+ """
108
+ supported_languages = ["python", "bash", "sql", "c", "java"]
109
+ language = language.lower()
110
+
111
+ if language not in supported_languages:
112
+ return f"❌ Unsupported language: {language}. Supported languages are: {', '.join(supported_languages)}"
113
+
114
+ result = interpreter_instance.execute_code(code, language=language)
115
+
116
+ response = []
117
+
118
+ if result["status"] == "success":
119
+ response.append(f"✅ Code executed successfully in **{language.upper()}**")
120
+
121
+ if result.get("stdout"):
122
+ response.append(
123
+ "\n**Standard Output:**\n```\n" + result["stdout"].strip() + "\n```"
124
+ )
125
+
126
+ if result.get("stderr"):
127
+ response.append(
128
+ "\n**Standard Error (if any):**\n```\n"
129
+ + result["stderr"].strip()
130
+ + "\n```"
131
+ )
132
+
133
+ if result.get("result") is not None:
134
+ response.append(
135
+ "\n**Execution Result:**\n```\n"
136
+ + str(result["result"]).strip()
137
+ + "\n```"
138
+ )
139
+
140
+ if result.get("dataframes"):
141
+ for df_info in result["dataframes"]:
142
+ response.append(
143
+ f"\n**DataFrame `{df_info['name']}` (Shape: {df_info['shape']})**"
144
+ )
145
+ df_preview = pd.DataFrame(df_info["head"])
146
+ response.append("First 5 rows:\n```\n" + str(df_preview) + "\n```")
147
+
148
+ if result.get("plots"):
149
+ response.append(
150
+ f"\n**Generated {len(result['plots'])} plot(s)** (Image data returned separately)"
151
+ )
152
+
153
+ else:
154
+ response.append(f"❌ Code execution failed in **{language.upper()}**")
155
+ if result.get("stderr"):
156
+ response.append(
157
+ "\n**Error Log:**\n```\n" + result["stderr"].strip() + "\n```"
158
+ )
159
+
160
+ return "\n".join(response)
161
+
162
+
163
+ ### =============== MATHEMATICAL TOOLS =============== ###
164
+
165
+
166
+ @tool
167
+ def multiply(a: float, b: float) -> float:
168
+ """
169
+ Multiplies two numbers.
170
+
171
+ Args:
172
+ a (float): the first number
173
+ b (float): the second number
174
+ """
175
+ return a * b
176
+
177
+
178
+ @tool
179
+ def add(a: float, b: float) -> float:
180
+ """
181
+ Adds two numbers.
182
+
183
+ Args:
184
+ a (float): the first number
185
+ b (float): the second number
186
+ """
187
+ return a + b
188
+
189
+
190
+ @tool
191
+ def subtract(a: float, b: float) -> int:
192
+ """
193
+ Subtracts two numbers.
194
+
195
+ Args:
196
+ a (float): the first number
197
+ b (float): the second number
198
+ """
199
+ return a - b
200
+
201
+
202
+ @tool
203
+ def divide(a: float, b: float) -> float:
204
+ """
205
+ Divides two numbers.
206
+
207
+ Args:
208
+ a (float): the first float number
209
+ b (float): the second float number
210
+ """
211
+ if b == 0:
212
+ raise ValueError("Cannot divided by zero.")
213
+ return a / b
214
+
215
+
216
+ @tool
217
+ def modulus(a: int, b: int) -> int:
218
+ """
219
+ Get the modulus of two numbers.
220
+
221
+ Args:
222
+ a (int): the first number
223
+ b (int): the second number
224
+ """
225
+ return a % b
226
+
227
+
228
+ @tool
229
+ def power(a: float, b: float) -> float:
230
+ """
231
+ Get the power of two numbers.
232
+
233
+ Args:
234
+ a (float): the first number
235
+ b (float): the second number
236
+ """
237
+ return a**b
238
+
239
+
240
+ @tool
241
+ def square_root(a: float) -> float | complex:
242
+ """
243
+ Get the square root of a number.
244
+
245
+ Args:
246
+ a (float): the number to get the square root of
247
+ """
248
+ if a >= 0:
249
+ return a**0.5
250
+ return cmath.sqrt(a)
251
+
252
+
253
+ ### =============== DOCUMENT PROCESSING TOOLS =============== ###
254
+
255
+
256
+ @tool
257
+ def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
258
+ """
259
+ Save content to a file and return the path.
260
+
261
+ Args:
262
+ content (str): the content to save to the file
263
+ filename (str, optional): the name of the file. If not provided, a random name file will be created.
264
+ """
265
+ temp_dir = tempfile.gettempdir()
266
+ if filename is None:
267
+ temp_file = tempfile.NamedTemporaryFile(delete=False, dir=temp_dir)
268
+ filepath = temp_file.name
269
+ else:
270
+ filepath = os.path.join(temp_dir, filename)
271
+
272
+ with open(filepath, "w") as f:
273
+ f.write(content)
274
+
275
+ return f"File saved to {filepath}. You can read this file to process its contents."
276
+
277
+
278
+ @tool
279
+ def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
280
+ """
281
+ Download a file from a URL and save it to a temporary location.
282
+
283
+ Args:
284
+ url (str): the URL of the file to download.
285
+ filename (str, optional): the name of the file. If not provided, a random name file will be created.
286
+ """
287
+ try:
288
+ # Parse URL to get filename if not provided
289
+ if not filename:
290
+ path = urlparse(url).path
291
+ filename = os.path.basename(path)
292
+ if not filename:
293
+ filename = f"downloaded_{uuid.uuid4().hex[:8]}"
294
+
295
+ # Create temporary file
296
+ temp_dir = tempfile.gettempdir()
297
+ filepath = os.path.join(temp_dir, filename)
298
+
299
+ # Download the file
300
+ response = requests.get(url, stream=True)
301
+ response.raise_for_status()
302
+
303
+ # Save the file
304
+ with open(filepath, "wb") as f:
305
+ for chunk in response.iter_content(chunk_size=8192):
306
+ f.write(chunk)
307
+
308
+ return f"File downloaded to {filepath}. You can read this file to process its contents."
309
+ except Exception as e:
310
+ return f"Error downloading file: {str(e)}"
311
+
312
+
313
+ @tool
314
+ def extract_text_from_image(image_path: str) -> str:
315
+ """
316
+ Extract text from an image using OCR library pytesseract (if available).
317
+
318
+ Args:
319
+ image_path (str): the path to the image file.
320
+ """
321
+ try:
322
+ # Open the image
323
+ image = Image.open(image_path)
324
+
325
+ # Extract text from the image
326
+ text = pytesseract.image_to_string(image)
327
+
328
+ return f"Extracted text from image:\n\n{text}"
329
+ except Exception as e:
330
+ return f"Error extracting text from image: {str(e)}"
331
+
332
+
333
+ @tool
334
+ def analyze_csv_file(file_path: str, query: str) -> str:
335
+ """
336
+ Analyze a CSV file using pandas and answer a question about it.
337
+
338
+ Args:
339
+ file_path (str): the path to the CSV file.
340
+ query (str): Question about the data
341
+ """
342
+ try:
343
+ # Read the CSV file
344
+ df = pd.read_csv(file_path)
345
+
346
+ # Run various analyses based on the query
347
+ result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
348
+ result += f"Columns: {', '.join(df.columns)}\n\n"
349
+
350
+ # Add summary statistics
351
+ result += "Summary statistics:\n"
352
+ result += str(df.describe())
353
+
354
+ return result
355
+
356
+ except Exception as e:
357
+ return f"Error analyzing CSV file: {str(e)}"
358
+
359
+
360
+ @tool
361
+ def analyze_excel_file(file_path: str, query: str) -> str:
362
+ """
363
+ Analyze an Excel file using pandas and answer a question about it.
364
+
365
+ Args:
366
+ file_path (str): the path to the Excel file.
367
+ query (str): Question about the data
368
+ """
369
+ try:
370
+ # Read the Excel file
371
+ df = pd.read_excel(file_path)
372
+
373
+ # Run various analyses based on the query
374
+ result = (
375
+ f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
376
+ )
377
+ result += f"Columns: {', '.join(df.columns)}\n\n"
378
+
379
+ # Add summary statistics
380
+ result += "Summary statistics:\n"
381
+ result += str(df.describe())
382
+
383
+ return result
384
+
385
+ except Exception as e:
386
+ return f"Error analyzing Excel file: {str(e)}"
387
+
388
+
389
+ ### ============== IMAGE PROCESSING AND GENERATION TOOLS =============== ###
390
+
391
+
392
+ @tool
393
+ def analyze_image(image_base64: str) -> Dict[str, Any]:
394
+ """
395
+ Analyze basic properties of an image (size, mode, color analysis, thumbnail preview).
396
+
397
+ Args:
398
+ image_base64 (str): Base64 encoded image string
399
+
400
+ Returns:
401
+ Dictionary with analysis result
402
+ """
403
+ try:
404
+ img = decode_image(image_base64)
405
+ width, height = img.size
406
+ mode = img.mode
407
+
408
+ if mode in ("RGB", "RGBA"):
409
+ arr = np.array(img)
410
+ avg_colors = arr.mean(axis=(0, 1))
411
+ dominant = ["Red", "Green", "Blue"][np.argmax(avg_colors[:3])]
412
+ brightness = avg_colors.mean()
413
+ color_analysis = {
414
+ "average_rgb": avg_colors.tolist(),
415
+ "brightness": brightness,
416
+ "dominant_color": dominant,
417
+ }
418
+ else:
419
+ color_analysis = {"note": f"No color analysis for mode {mode}"}
420
+
421
+ thumbnail = img.copy()
422
+ thumbnail.thumbnail((100, 100))
423
+ thumb_path = save_image(thumbnail, "thumbnails")
424
+ thumbnail_base64 = encode_image(thumb_path)
425
+
426
+ return {
427
+ "dimensions": (width, height),
428
+ "mode": mode,
429
+ "color_analysis": color_analysis,
430
+ "thumbnail": thumbnail_base64,
431
+ }
432
+ except Exception as e:
433
+ return {"error": str(e)}
434
+
435
+
436
+ @tool
437
+ def transform_image(
438
+ image_base64: str, operation: str, params: Optional[Dict[str, Any]] = None
439
+ ) -> Dict[str, Any]:
440
+ """
441
+ Apply transformations: resize, rotate, crop, flip, brightness, contrast, blur, sharpen, grayscale.
442
+
443
+ Args:
444
+ image_base64 (str): Base64 encoded input image
445
+ operation (str): Transformation operation
446
+ params (Dict[str, Any], optional): Parameters for the operation
447
+
448
+ Returns:
449
+ Dictionary with transformed image (base64)
450
+ """
451
+ try:
452
+ img = decode_image(image_base64)
453
+ params = params or {}
454
+
455
+ if operation == "resize":
456
+ img = img.resize(
457
+ (
458
+ params.get("width", img.width // 2),
459
+ params.get("height", img.height // 2),
460
+ )
461
+ )
462
+ elif operation == "rotate":
463
+ img = img.rotate(params.get("angle", 90), expand=True)
464
+ elif operation == "crop":
465
+ img = img.crop(
466
+ (
467
+ params.get("left", 0),
468
+ params.get("top", 0),
469
+ params.get("right", img.width),
470
+ params.get("bottom", img.height),
471
+ )
472
+ )
473
+ elif operation == "flip":
474
+ if params.get("direction", "horizontal") == "horizontal":
475
+ img = img.transpose(Image.FLIP_LEFT_RIGHT)
476
+ else:
477
+ img = img.transpose(Image.FLIP_TOP_BOTTOM)
478
+ elif operation == "adjust_brightness":
479
+ img = ImageEnhance.Brightness(img).enhance(params.get("factor", 1.5))
480
+ elif operation == "adjust_contrast":
481
+ img = ImageEnhance.Contrast(img).enhance(params.get("factor", 1.5))
482
+ elif operation == "blur":
483
+ img = img.filter(ImageFilter.GaussianBlur(params.get("radius", 2)))
484
+ elif operation == "sharpen":
485
+ img = img.filter(ImageFilter.SHARPEN)
486
+ elif operation == "grayscale":
487
+ img = img.convert("L")
488
+ else:
489
+ return {"error": f"Unknown operation: {operation}"}
490
+
491
+ result_path = save_image(img)
492
+ result_base64 = encode_image(result_path)
493
+ return {"transformed_image": result_base64}
494
+
495
+ except Exception as e:
496
+ return {"error": str(e)}
497
+
498
+
499
+ @tool
500
+ def draw_on_image(
501
+ image_base64: str, drawing_type: str, params: Dict[str, Any]
502
+ ) -> Dict[str, Any]:
503
+ """
504
+ Draw shapes (rectangle, circle, line) or text onto an image.
505
+
506
+ Args:
507
+ image_base64 (str): Base64 encoded input image
508
+ drawing_type (str): Drawing type
509
+ params (Dict[str, Any]): Drawing parameters
510
+
511
+ Returns:
512
+ Dictionary with result image (base64)
513
+ """
514
+ try:
515
+ img = decode_image(image_base64)
516
+ draw = ImageDraw.Draw(img)
517
+ color = params.get("color", "red")
518
+
519
+ if drawing_type == "rectangle":
520
+ draw.rectangle(
521
+ [params["left"], params["top"], params["right"], params["bottom"]],
522
+ outline=color,
523
+ width=params.get("width", 2),
524
+ )
525
+ elif drawing_type == "circle":
526
+ x, y, r = params["x"], params["y"], params["radius"]
527
+ draw.ellipse(
528
+ (x - r, y - r, x + r, y + r),
529
+ outline=color,
530
+ width=params.get("width", 2),
531
+ )
532
+ elif drawing_type == "line":
533
+ draw.line(
534
+ (
535
+ params["start_x"],
536
+ params["start_y"],
537
+ params["end_x"],
538
+ params["end_y"],
539
+ ),
540
+ fill=color,
541
+ width=params.get("width", 2),
542
+ )
543
+ elif drawing_type == "text":
544
+ font_size = params.get("font_size", 20)
545
+ try:
546
+ font = ImageFont.truetype("arial.ttf", font_size)
547
+ except IOError:
548
+ font = ImageFont.load_default()
549
+ draw.text(
550
+ (params["x"], params["y"]),
551
+ params.get("text", "Text"),
552
+ fill=color,
553
+ font=font,
554
+ )
555
+ else:
556
+ return {"error": f"Unknown drawing type: {drawing_type}"}
557
+
558
+ result_path = save_image(img)
559
+ result_base64 = encode_image(result_path)
560
+ return {"result_image": result_base64}
561
+
562
+ except Exception as e:
563
+ return {"error": str(e)}
564
+
565
+
566
+ @tool
567
+ def generate_simple_image(
568
+ image_type: str,
569
+ width: int = 500,
570
+ height: int = 500,
571
+ params: Optional[Dict[str, Any]] = None,
572
+ ) -> Dict[str, Any]:
573
+ """
574
+ Generate a simple image (gradient, noise, pattern, chart).
575
+
576
+ Args:
577
+ image_type (str): Type of image
578
+ width (int), height (int)
579
+ params (Dict[str, Any], optional): Specific parameters
580
+
581
+ Returns:
582
+ Dictionary with generated image (base64)
583
+ """
584
+ try:
585
+ params = params or {}
586
+
587
+ if image_type == "gradient":
588
+ direction = params.get("direction", "horizontal")
589
+ start_color = params.get("start_color", (255, 0, 0))
590
+ end_color = params.get("end_color", (0, 0, 255))
591
+
592
+ img = Image.new("RGB", (width, height))
593
+ draw = ImageDraw.Draw(img)
594
+
595
+ if direction == "horizontal":
596
+ for x in range(width):
597
+ r = int(
598
+ start_color[0] + (end_color[0] - start_color[0]) * x / width
599
+ )
600
+ g = int(
601
+ start_color[1] + (end_color[1] - start_color[1]) * x / width
602
+ )
603
+ b = int(
604
+ start_color[2] + (end_color[2] - start_color[2]) * x / width
605
+ )
606
+ draw.line([(x, 0), (x, height)], fill=(r, g, b))
607
+ else:
608
+ for y in range(height):
609
+ r = int(
610
+ start_color[0] + (end_color[0] - start_color[0]) * y / height
611
+ )
612
+ g = int(
613
+ start_color[1] + (end_color[1] - start_color[1]) * y / height
614
+ )
615
+ b = int(
616
+ start_color[2] + (end_color[2] - start_color[2]) * y / height
617
+ )
618
+ draw.line([(0, y), (width, y)], fill=(r, g, b))
619
+
620
+ elif image_type == "noise":
621
+ noise_array = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8)
622
+ img = Image.fromarray(noise_array, "RGB")
623
+
624
+ else:
625
+ return {"error": f"Unsupported image_type {image_type}"}
626
+
627
+ result_path = save_image(img)
628
+ result_base64 = encode_image(result_path)
629
+ return {"generated_image": result_base64}
630
+
631
+ except Exception as e:
632
+ return {"error": str(e)}
633
+
634
+
635
+ @tool
636
+ def combine_images(
637
+ images_base64: List[str], operation: str, params: Optional[Dict[str, Any]] = None
638
+ ) -> Dict[str, Any]:
639
+ """
640
+ Combine multiple images (collage, stack, blend).
641
+
642
+ Args:
643
+ images_base64 (List[str]): List of base64 images
644
+ operation (str): Combination type
645
+ params (Dict[str, Any], optional)
646
+
647
+ Returns:
648
+ Dictionary with combined image (base64)
649
+ """
650
+ try:
651
+ images = [decode_image(b64) for b64 in images_base64]
652
+ params = params or {}
653
+
654
+ if operation == "stack":
655
+ direction = params.get("direction", "horizontal")
656
+ if direction == "horizontal":
657
+ total_width = sum(img.width for img in images)
658
+ max_height = max(img.height for img in images)
659
+ new_img = Image.new("RGB", (total_width, max_height))
660
+ x = 0
661
+ for img in images:
662
+ new_img.paste(img, (x, 0))
663
+ x += img.width
664
+ else:
665
+ max_width = max(img.width for img in images)
666
+ total_height = sum(img.height for img in images)
667
+ new_img = Image.new("RGB", (max_width, total_height))
668
+ y = 0
669
+ for img in images:
670
+ new_img.paste(img, (0, y))
671
+ y += img.height
672
+ else:
673
+ return {"error": f"Unsupported combination operation {operation}"}
674
+
675
+ result_path = save_image(new_img)
676
+ result_base64 = encode_image(result_path)
677
+ return {"combined_image": result_base64}
678
+
679
+ except Exception as e:
680
+ return {"error": str(e)}
681
+
682
+
683
+ # load the system prompt from the file
684
+ with open("system_prompt.txt", "r", encoding="utf-8") as f:
685
+ system_prompt = f.read()
686
+ print(system_prompt)
687
+
688
+ # System message
689
+ sys_msg = SystemMessage(content=system_prompt)
690
+
691
+ # build a retriever
692
+ embeddings = HuggingFaceEmbeddings(
693
+ model_name="sentence-transformers/all-mpnet-base-v2"
694
+ ) # dim=768
695
+ supabase_url = "https://kyeropjbpzxfcypbxqoi.supabase.co"
696
+ supabase_key = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imt5ZXJvcGpicHp4ZmN5cGJ4cW9pIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDg0ODYzNDEsImV4cCI6MjA2NDA2MjM0MX0._7ct7b36PILtOs4ycgPk1Tgk6dKNp2bbTjB-UBA3uGg"
697
+ supabase: Client = create_client(supabase_url, supabase_key)
698
+
699
+ vector_store = SupabaseVectorStore(
700
+ client=supabase,
701
+ embedding=embeddings,
702
+ table_name="documents2",
703
+ query_name="match_documents_2",
704
+ )
705
+ create_retriever_tool = create_retriever_tool(
706
+ retriever=vector_store.as_retriever(),
707
+ name="Question Search",
708
+ description="A tool to retrieve similar questions from a vector store.",
709
+ )
710
+
711
+
712
+ tools = [
713
+ web_search,
714
+ wiki_search,
715
+ arxiv_search,
716
+ multiply,
717
+ add,
718
+ subtract,
719
+ divide,
720
+ modulus,
721
+ power,
722
+ square_root,
723
+ save_and_read_file,
724
+ download_file_from_url,
725
+ extract_text_from_image,
726
+ analyze_csv_file,
727
+ analyze_excel_file,
728
+ execute_code_multilang,
729
+ analyze_image,
730
+ transform_image,
731
+ draw_on_image,
732
+ generate_simple_image,
733
+ combine_images,
734
+ ]
735
+
736
+
737
+ # Build graph function
738
+ def build_graph(provider: str = "groq"):
739
+ """Build the graph"""
740
+ # Load environment variables from .env file
741
+ if provider == "groq":
742
+ # Groq https://console.groq.com/docs/models
743
+ llm = ChatGroq(model="qwen-qwq-32b", temperature=0)
744
+ elif provider == "huggingface":
745
+ # TODO: Add huggingface endpoint
746
+ llm = ChatHuggingFace(
747
+ llm=HuggingFaceEndpoint(
748
+ repo_id="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
749
+ task="text-generation", # for chat‐style use “text-generation”
750
+ max_new_tokens=1024,
751
+ do_sample=False,
752
+ repetition_penalty=1.03,
753
+ temperature=0,
754
+ ),
755
+ verbose=True,
756
+ )
757
+ else:
758
+ raise ValueError("Invalid provider. Choose 'groq' or 'huggingface'.")
759
+ # Bind tools to LLM
760
+ llm_with_tools = llm.bind_tools(tools)
761
+
762
+ # Node
763
+ def assistant(state: MessagesState):
764
+ """Assistant node"""
765
+ return {"messages": [llm_with_tools.invoke(state["messages"])]}
766
+
767
+ def retriever(state: MessagesState):
768
+ """Retriever node"""
769
+ similar_question = vector_store.similarity_search(state["messages"][0].content)
770
+
771
+ if similar_question: # Check if the list is not empty
772
+ example_msg = HumanMessage(
773
+ content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}",
774
+ )
775
+ return {"messages": [sys_msg] + state["messages"] + [example_msg]}
776
+ else:
777
+ # Handle the case when no similar questions are found
778
+ return {"messages": [sys_msg] + state["messages"]}
779
+
780
+ builder = StateGraph(MessagesState)
781
+ builder.add_node("retriever", retriever)
782
+ builder.add_node("assistant", assistant)
783
+ builder.add_node("tools", ToolNode(tools))
784
+ builder.add_edge(START, "retriever")
785
+ builder.add_edge("retriever", "assistant")
786
+ builder.add_conditional_edges(
787
+ "assistant",
788
+ tools_condition,
789
+ )
790
+ builder.add_edge("tools", "assistant")
791
+
792
+ # Compile graph
793
+ return builder.compile()
794
+
795
+
796
+ # test
797
+ if __name__ == "__main__":
798
+ question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
799
+ graph = build_graph(provider="groq")
800
+ messages = [HumanMessage(content=question)]
801
+ messages = graph.invoke({"messages": messages})
802
+ for m in messages["messages"]:
803
+ m.pretty_print()
app.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Basic Agent Evaluation Runner"""
2
+ import os
3
+ import inspect
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
+
11
+
12
+
13
+ # (Keep Constants as is)
14
+ # --- Constants ---
15
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
16
+
17
+ # --- Basic Agent Definition ---
18
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
19
+
20
+
21
+ class BasicAgent:
22
+ """A langgraph agent."""
23
+ def __init__(self):
24
+ print("BasicAgent initialized.")
25
+ self.graph = build_graph()
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):
37
+ """
38
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
39
+ and displays the results.
40
+ """
41
+ # --- Determine HF Space Runtime URL and Repo URL ---
42
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
43
+
44
+ if profile:
45
+ username= f"{profile.username}"
46
+ print(f"User logged in: {username}")
47
+ else:
48
+ print("User not logged in.")
49
+ return "Please Login to Hugging Face with the button.", None
50
+
51
+ api_url = DEFAULT_API_URL
52
+ questions_url = f"{api_url}/questions"
53
+ submit_url = f"{api_url}/submit"
54
+
55
+ # 1. Instantiate Agent ( modify this part to create your agent)
56
+ try:
57
+ agent = BasicAgent()
58
+ except Exception as e:
59
+ print(f"Error instantiating agent: {e}")
60
+ return f"Error initializing agent: {e}", None
61
+ # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
62
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
63
+ print(agent_code)
64
+
65
+ # 2. Fetch Questions
66
+ print(f"Fetching questions from: {questions_url}")
67
+ try:
68
+ response = requests.get(questions_url, timeout=15)
69
+ response.raise_for_status()
70
+ questions_data = response.json()
71
+ if not questions_data:
72
+ print("Fetched questions list is empty.")
73
+ return "Fetched questions list is empty or invalid format.", None
74
+ print(f"Fetched {len(questions_data)} questions.")
75
+ except requests.exceptions.RequestException as e:
76
+ print(f"Error fetching questions: {e}")
77
+ return f"Error fetching questions: {e}", None
78
+ except requests.exceptions.JSONDecodeError as e:
79
+ print(f"Error decoding JSON response from questions endpoint: {e}")
80
+ print(f"Response text: {response.text[:500]}")
81
+ return f"Error decoding server response for questions: {e}", None
82
+ except Exception as e:
83
+ print(f"An unexpected error occurred fetching questions: {e}")
84
+ return f"An unexpected error occurred fetching questions: {e}", None
85
+
86
+ # 3. Run your Agent
87
+ results_log = []
88
+ answers_payload = []
89
+ print(f"Running agent on {len(questions_data)} questions...")
90
+ for item in questions_data:
91
+ task_id = item.get("task_id")
92
+ question_text = item.get("question")
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})
102
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
103
+ except Exception as e:
104
+ print(f"Error running agent on task {task_id}: {e}")
105
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
106
+
107
+ if not answers_payload:
108
+ print("Agent did not produce any answers to submit.")
109
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
110
+
111
+ # 4. Prepare Submission
112
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
113
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
114
+ print(status_update)
115
+
116
+ # 5. Submit
117
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
118
+ try:
119
+ response = requests.post(submit_url, json=submission_data, timeout=60)
120
+ response.raise_for_status()
121
+ result_data = response.json()
122
+ final_status = (
123
+ f"Submission Successful!\n"
124
+ f"User: {result_data.get('username')}\n"
125
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
126
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
127
+ f"Message: {result_data.get('message', 'No message received.')}"
128
+ )
129
+ print("Submission successful.")
130
+ results_df = pd.DataFrame(results_log)
131
+ return final_status, results_df
132
+ except requests.exceptions.HTTPError as e:
133
+ error_detail = f"Server responded with status {e.response.status_code}."
134
+ try:
135
+ error_json = e.response.json()
136
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
137
+ except requests.exceptions.JSONDecodeError:
138
+ error_detail += f" Response: {e.response.text[:500]}"
139
+ status_message = f"Submission Failed: {error_detail}"
140
+ print(status_message)
141
+ results_df = pd.DataFrame(results_log)
142
+ return status_message, results_df
143
+ except requests.exceptions.Timeout:
144
+ status_message = "Submission Failed: The request timed out."
145
+ print(status_message)
146
+ results_df = pd.DataFrame(results_log)
147
+ return status_message, results_df
148
+ except requests.exceptions.RequestException as e:
149
+ status_message = f"Submission Failed: Network error - {e}"
150
+ print(status_message)
151
+ results_df = pd.DataFrame(results_log)
152
+ return status_message, results_df
153
+ except Exception as e:
154
+ status_message = f"An unexpected error occurred during submission: {e}"
155
+ print(status_message)
156
+ results_df = pd.DataFrame(results_log)
157
+ return status_message, results_df
158
+
159
+
160
+ # --- Build Gradio Interface using Blocks ---
161
+ with gr.Blocks() as demo:
162
+ gr.Markdown("# Basic Agent Evaluation Runner")
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).
172
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
173
+ """
174
+ )
175
+
176
+ gr.LoginButton()
177
+
178
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
179
+
180
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
181
+ # Removed max_rows=10 from DataFrame constructor
182
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
183
+
184
+ run_button.click(
185
+ fn=run_and_submit_all,
186
+ outputs=[status_output, results_table]
187
+ )
188
+
189
+ if __name__ == "__main__":
190
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
191
+ # Check for SPACE_HOST and SPACE_ID at startup for information
192
+ space_host_startup = os.getenv("SPACE_HOST")
193
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
194
+
195
+ if space_host_startup:
196
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
197
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
198
+ else:
199
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
200
+
201
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
202
+ print(f"✅ SPACE_ID found: {space_id_startup}")
203
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
204
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
205
+ else:
206
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
207
+
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 ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ requests
3
+ langchain
4
+ langchain-community
5
+ langchain-core
6
+ langchain-google-genai
7
+ langchain-huggingface
8
+ langchain-groq
9
+ langchain-tavily
10
+ langchain-chroma
11
+ langgraph
12
+ huggingface_hub
13
+ supabase
14
+ arxiv
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,28 +1,5 @@
1
-
2
- You are a helpful assistant tasked with answering questions using a set of tools.
3
- 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.
4
- You need to provide a step-by-step explanation of how you arrived at the answer.
5
- ==========================
6
- Here is a few examples showing you how to answer the question step by step.
7
-
8
- Question 1: In the 2015 Metropolitan Museum of Art exhibition titled after the Chinese zodiac animal of 2015, how many of the "twelve animals of the Chinese zodiac" have a hand visible?
9
- Steps:
10
- 1. Search "2015 Chinese zodiac animal" on Google search.
11
- 2. Note the animal (ram).
12
- 3. Search "Metropolitan Museum of Art" on Google search.
13
- 4. Open the Metropolitan Museum of Art website.
14
- 5. Click "Exhibitions" under "Exhibitions and Events"
15
- 6. Click "Past".
16
- 7. Set the year to 2015.
17
- 8. Scroll to find the exhibit mentioning rams and click "Celebration of the Year of the Ram".
18
- 9. Click "View All Objects".
19
- 10. Click "Twelve animals of the Chinese zodiac" to open the image.
20
- 11. Count how many have a visible hand.
21
- Tools:
22
- 1. Web browser
23
- 2. Search engine
24
- 3. Image recognition tools
25
- Final Answer: 11
26
-
27
- ==========================
28
- Now, please answer the following question step by step.
 
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.