devsu commited on
Commit
a8df249
·
verified ·
1 Parent(s): 9ec646b

Create agent.py

Browse files
Files changed (1) hide show
  1. agent.py +795 -0
agent.py ADDED
@@ -0,0 +1,795 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import base64
16
+ import time
17
+ from e2b_code_interpreter import Sandbox
18
+ from pydantic.v1 import BaseModel, Field
19
+
20
+ """Langraph"""
21
+ from langgraph.graph import StateGraph, MessagesState
22
+ from langchain_community.tools.tavily_search import TavilySearchResults
23
+ from langchain_community.document_loaders import WikipediaLoader
24
+ from langchain_community.document_loaders import ArxivLoader
25
+ from langgraph.prebuilt import ToolNode, tools_condition
26
+ from langchain_google_genai import ChatGoogleGenerativeAI
27
+ from langchain_core.messages import SystemMessage, HumanMessage, ToolMessage
28
+ from langchain_core.tools import tool
29
+ from langchain_core.tools import Tool
30
+
31
+ load_dotenv()
32
+
33
+ # Helper functions for image processing
34
+ def encode_image(image_path: str) -> str:
35
+ """Convert an image file to base64 string."""
36
+ with open(image_path, "rb") as image_file:
37
+ return base64.b64encode(image_file.read()).decode("utf-8")
38
+
39
+
40
+ def decode_image(base64_string: str) -> Image.Image:
41
+ """Convert a base64 string to a PIL Image."""
42
+ image_data = base64.b64decode(base64_string)
43
+ return Image.open(io.BytesIO(image_data))
44
+
45
+
46
+ def save_image(image: Image.Image, directory: str = "image_outputs") -> str:
47
+ """Save a PIL Image to disk and return the path."""
48
+ os.makedirs(directory, exist_ok=True)
49
+ image_id = str(uuid.uuid4())
50
+ image_path = os.path.join(directory, f"{image_id}.png")
51
+ image.save(image_path)
52
+ return image_path
53
+
54
+ ### =============== BROWSER TOOLS =============== ###
55
+
56
+
57
+ @tool
58
+ def wiki_search(query: str) -> str:
59
+ """Search Wikipedia for a query and return maximum 2 results.
60
+
61
+ Args:
62
+ query: The search query."""
63
+ search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
64
+ formatted_search_docs = "\n\n---\n\n".join(
65
+ [
66
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
67
+ for doc in search_docs
68
+ ]
69
+ )
70
+ return {"wiki_results": formatted_search_docs}
71
+
72
+
73
+ @tool
74
+ def web_search(query: str) -> str:
75
+ """Search Tavily for a query and return maximum 3 results.
76
+
77
+ Args:
78
+ query: The search query."""
79
+ search_docs = TavilySearchResults(max_results=3).invoke({'query':query})
80
+ formatted_search_docs = "\n\n---\n\n".join(
81
+ [
82
+ f'<Document source="{doc["url"]}" page=""/>\n{doc["content"]}\n</Document>'
83
+ for doc in search_docs
84
+ ])
85
+ return {"web_results": formatted_search_docs}
86
+
87
+
88
+ @tool
89
+ def arxiv_search(query: str) -> str:
90
+ """Search Arxiv for a query and return maximum 3 result.
91
+
92
+ Args:
93
+ query: The search query."""
94
+ search_docs = ArxivLoader(query=query, load_max_docs=3).load()
95
+ formatted_search_docs = "\n\n---\n\n".join(
96
+ [
97
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
98
+ for doc in search_docs
99
+ ]
100
+ )
101
+ return {"arxiv_results": formatted_search_docs}
102
+
103
+
104
+ ### =============== CODE INTERPRETER TOOLS =============== ###
105
+
106
+
107
+ class RichToolMessage(ToolMessage):
108
+ raw_output: dict
109
+
110
+
111
+ class LangchainCodeInterpreterToolInput(BaseModel):
112
+ code: str = Field(description="Python code to execute.")
113
+
114
+
115
+ class CodeInterpreterFunctionTool:
116
+ """
117
+ This class calls arbitrary code against a Python Jupyter notebook.
118
+ It requires an E2B_API_KEY to create a sandbox.
119
+ """
120
+
121
+ tool_name: str = "code_interpreter"
122
+
123
+ def __init__(self):
124
+ # Instantiate the E2B sandbox - this is a long lived object
125
+ # that's pinging E2B cloud to keep the sandbox alive.
126
+ if "E2B_API_KEY" not in os.environ:
127
+ raise Exception(
128
+ "Code Interpreter tool called while E2B_API_KEY environment variable is not set. Please get your E2B api key here https://e2b.dev/docs and set the E2B_API_KEY environment variable."
129
+ )
130
+ self.code_interpreter = Sandbox()
131
+
132
+ def close(self):
133
+ self.code_interpreter.kill()
134
+
135
+ def call(self, parameters: dict, **kwargs: Any):
136
+ code = parameters.get("code", "")
137
+ print(f"***Code Interpreting...\n{code}\n====")
138
+ execution = self.code_interpreter.run_code(code)
139
+ return {
140
+ "results": execution.results,
141
+ "stdout": execution.logs.stdout,
142
+ "stderr": execution.logs.stderr,
143
+ "error": execution.error,
144
+ }
145
+
146
+ # langchain does not return a dict as a parameter, only a code string
147
+ def langchain_call(self, code: str):
148
+ return self.call({"code": code})
149
+
150
+ def to_langchain_tool(self) -> Tool:
151
+ tool = Tool(
152
+ name=self.tool_name,
153
+ description="Execute python code in a Jupyter notebook cell and returns any rich data (eg charts), stdout, stderr, and error.",
154
+ func=self.langchain_call,
155
+ )
156
+ tool.args_schema = LangchainCodeInterpreterToolInput
157
+ return tool
158
+
159
+ @staticmethod
160
+ def format_to_tool_message(
161
+ tool_call_id: str,
162
+ output: dict,
163
+ ) -> RichToolMessage:
164
+ """
165
+ Format the output of the CodeInterpreter tool to be returned as a RichToolMessage.
166
+ """
167
+
168
+ # TODO: Add info about the results for the LLM
169
+ content = json.dumps(
170
+ {k: v for k, v in output.items() if k not in ("results")}, indent=2
171
+ )
172
+
173
+ return RichToolMessage(
174
+ content=content,
175
+ raw_output=output,
176
+ tool_call_id=tool_call_id,
177
+ )
178
+
179
+
180
+ ### =============== MATHEMATICAL TOOLS =============== ###
181
+
182
+
183
+ @tool
184
+ def multiply(a: float, b: float) -> float:
185
+ """
186
+ Multiplies two numbers.
187
+
188
+ Args:
189
+ a (float): the first number
190
+ b (float): the second number
191
+ """
192
+ return a * b
193
+
194
+
195
+ @tool
196
+ def add(a: float, b: float) -> float:
197
+ """
198
+ Adds two numbers.
199
+
200
+ Args:
201
+ a (float): the first number
202
+ b (float): the second number
203
+ """
204
+ return a + b
205
+
206
+
207
+ @tool
208
+ def subtract(a: float, b: float) -> int:
209
+ """
210
+ Subtracts two numbers.
211
+
212
+ Args:
213
+ a (float): the first number
214
+ b (float): the second number
215
+ """
216
+ return a - b
217
+
218
+
219
+ @tool
220
+ def divide(a: float, b: float) -> float:
221
+ """
222
+ Divides two numbers.
223
+
224
+ Args:
225
+ a (float): the first float number
226
+ b (float): the second float number
227
+ """
228
+ if b == 0:
229
+ raise ValueError("Cannot divided by zero.")
230
+ return a / b
231
+
232
+
233
+ @tool
234
+ def modulus(a: int, b: int) -> int:
235
+ """
236
+ Get the modulus of two numbers.
237
+
238
+ Args:
239
+ a (int): the first number
240
+ b (int): the second number
241
+ """
242
+ return a % b
243
+
244
+
245
+ @tool
246
+ def power(a: float, b: float) -> float:
247
+ """
248
+ Get the power of two numbers.
249
+
250
+ Args:
251
+ a (float): the first number
252
+ b (float): the second number
253
+ """
254
+ return a**b
255
+
256
+
257
+ @tool
258
+ def square_root(a: float) -> float | complex:
259
+ """
260
+ Get the square root of a number.
261
+
262
+ Args:
263
+ a (float): the number to get the square root of
264
+ """
265
+ if a >= 0:
266
+ return a**0.5
267
+ return cmath.sqrt(a)
268
+
269
+
270
+ ### =============== DOCUMENT PROCESSING TOOLS =============== ###
271
+
272
+
273
+ @tool
274
+ def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
275
+ """
276
+ Save content to a file and return the path.
277
+
278
+ Args:
279
+ content (str): the content to save to the file
280
+ filename (str, optional): the name of the file. If not provided, a random name file will be created.
281
+ """
282
+ temp_dir = tempfile.gettempdir()
283
+ if filename is None:
284
+ temp_file = tempfile.NamedTemporaryFile(delete=False, dir=temp_dir)
285
+ filepath = temp_file.name
286
+ else:
287
+ filepath = os.path.join(temp_dir, filename)
288
+
289
+ with open(filepath, "w") as f:
290
+ f.write(content)
291
+
292
+ return f"File saved to {filepath}. You can read this file to process its contents."
293
+
294
+
295
+ @tool
296
+ def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
297
+ """
298
+ Download a file from a URL and save it to a temporary location.
299
+
300
+ Args:
301
+ url (str): the URL of the file to download.
302
+ filename (str, optional): the name of the file. If not provided, a random name file will be created.
303
+ """
304
+ try:
305
+ # Parse URL to get filename if not provided
306
+ if not filename:
307
+ path = urlparse(url).path
308
+ filename = os.path.basename(path)
309
+ if not filename:
310
+ filename = f"downloaded_{uuid.uuid4().hex[:8]}"
311
+
312
+ # Create temporary file
313
+ temp_dir = tempfile.gettempdir()
314
+ filepath = os.path.join(temp_dir, filename)
315
+
316
+ # Download the file
317
+ response = requests.get(url, stream=True)
318
+ response.raise_for_status()
319
+
320
+ # Save the file
321
+ with open(filepath, "wb") as f:
322
+ for chunk in response.iter_content(chunk_size=8192):
323
+ f.write(chunk)
324
+
325
+ return f"File downloaded to {filepath}. You can read this file to process its contents."
326
+ except Exception as e:
327
+ return f"Error downloading file: {str(e)}"
328
+
329
+
330
+ @tool
331
+ def extract_text_from_image(image_path: str) -> str:
332
+ """
333
+ Extract text from an image using OCR library pytesseract (if available).
334
+
335
+ Args:
336
+ image_path (str): the path to the image file.
337
+ """
338
+ try:
339
+ # Open the image
340
+ image = Image.open(image_path)
341
+
342
+ # Extract text from the image
343
+ text = pytesseract.image_to_string(image)
344
+
345
+ return f"Extracted text from image:\n\n{text}"
346
+ except Exception as e:
347
+ return f"Error extracting text from image: {str(e)}"
348
+
349
+
350
+ @tool
351
+ def analyze_csv_file(file_path: str, query: str) -> str:
352
+ """
353
+ Analyze a CSV file using pandas and answer a question about it.
354
+
355
+ Args:
356
+ file_path (str): the path to the CSV file.
357
+ query (str): Question about the data
358
+ """
359
+ try:
360
+ # Read the CSV file
361
+ df = pd.read_csv(file_path)
362
+
363
+ # Run various analyses based on the query
364
+ result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
365
+ result += f"Columns: {', '.join(df.columns)}\n\n"
366
+
367
+ # Add summary statistics
368
+ result += "Summary statistics:\n"
369
+ result += str(df.describe())
370
+
371
+ return result
372
+
373
+ except Exception as e:
374
+ return f"Error analyzing CSV file: {str(e)}"
375
+
376
+
377
+ @tool
378
+ def analyze_excel_file(file_path: str, query: str) -> str:
379
+ """
380
+ Analyze an Excel file using pandas and answer a question about it.
381
+
382
+ Args:
383
+ file_path (str): the path to the Excel file.
384
+ query (str): Question about the data
385
+ """
386
+ try:
387
+ # Read the Excel file
388
+ df = pd.read_excel(file_path)
389
+
390
+ # Run various analyses based on the query
391
+ result = (
392
+ f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
393
+ )
394
+ result += f"Columns: {', '.join(df.columns)}\n\n"
395
+
396
+ # Add summary statistics
397
+ result += "Summary statistics:\n"
398
+ result += str(df.describe())
399
+
400
+ return result
401
+
402
+ except Exception as e:
403
+ return f"Error analyzing Excel file: {str(e)}"
404
+
405
+
406
+ ### ============== IMAGE PROCESSING AND GENERATION TOOLS =============== ###
407
+
408
+
409
+ @tool
410
+ def analyze_image(image_base64: str) -> Dict[str, Any]:
411
+ """
412
+ Analyze basic properties of an image (size, mode, color analysis, thumbnail preview).
413
+
414
+ Args:
415
+ image_base64 (str): Base64 encoded image string
416
+
417
+ Returns:
418
+ Dictionary with analysis result
419
+ """
420
+ try:
421
+ img = decode_image(image_base64)
422
+ width, height = img.size
423
+ mode = img.mode
424
+
425
+ if mode in ("RGB", "RGBA"):
426
+ arr = np.array(img)
427
+ avg_colors = arr.mean(axis=(0, 1))
428
+ dominant = ["Red", "Green", "Blue"][np.argmax(avg_colors[:3])]
429
+ brightness = avg_colors.mean()
430
+ color_analysis = {
431
+ "average_rgb": avg_colors.tolist(),
432
+ "brightness": brightness,
433
+ "dominant_color": dominant,
434
+ }
435
+ else:
436
+ color_analysis = {"note": f"No color analysis for mode {mode}"}
437
+
438
+ thumbnail = img.copy()
439
+ thumbnail.thumbnail((100, 100))
440
+ thumb_path = save_image(thumbnail, "thumbnails")
441
+ thumbnail_base64 = encode_image(thumb_path)
442
+
443
+ return {
444
+ "dimensions": (width, height),
445
+ "mode": mode,
446
+ "color_analysis": color_analysis,
447
+ "thumbnail": thumbnail_base64,
448
+ }
449
+ except Exception as e:
450
+ return {"error": str(e)}
451
+
452
+
453
+ @tool
454
+ def transform_image(
455
+ image_base64: str, operation: str, params: Optional[Dict[str, Any]] = None
456
+ ) -> Dict[str, Any]:
457
+ """
458
+ Apply transformations: resize, rotate, crop, flip, brightness, contrast, blur, sharpen, grayscale.
459
+
460
+ Args:
461
+ image_base64 (str): Base64 encoded input image
462
+ operation (str): Transformation operation
463
+ params (Dict[str, Any], optional): Parameters for the operation
464
+
465
+ Returns:
466
+ Dictionary with transformed image (base64)
467
+ """
468
+ try:
469
+ img = decode_image(image_base64)
470
+ params = params or {}
471
+
472
+ if operation == "resize":
473
+ img = img.resize(
474
+ (
475
+ params.get("width", img.width // 2),
476
+ params.get("height", img.height // 2),
477
+ )
478
+ )
479
+ elif operation == "rotate":
480
+ img = img.rotate(params.get("angle", 90), expand=True)
481
+ elif operation == "crop":
482
+ img = img.crop(
483
+ (
484
+ params.get("left", 0),
485
+ params.get("top", 0),
486
+ params.get("right", img.width),
487
+ params.get("bottom", img.height),
488
+ )
489
+ )
490
+ elif operation == "flip":
491
+ if params.get("direction", "horizontal") == "horizontal":
492
+ img = img.transpose(Image.FLIP_LEFT_RIGHT)
493
+ else:
494
+ img = img.transpose(Image.FLIP_TOP_BOTTOM)
495
+ elif operation == "adjust_brightness":
496
+ img = ImageEnhance.Brightness(img).enhance(params.get("factor", 1.5))
497
+ elif operation == "adjust_contrast":
498
+ img = ImageEnhance.Contrast(img).enhance(params.get("factor", 1.5))
499
+ elif operation == "blur":
500
+ img = img.filter(ImageFilter.GaussianBlur(params.get("radius", 2)))
501
+ elif operation == "sharpen":
502
+ img = img.filter(ImageFilter.SHARPEN)
503
+ elif operation == "grayscale":
504
+ img = img.convert("L")
505
+ else:
506
+ return {"error": f"Unknown operation: {operation}"}
507
+
508
+ result_path = save_image(img)
509
+ result_base64 = encode_image(result_path)
510
+ return {"transformed_image": result_base64}
511
+
512
+ except Exception as e:
513
+ return {"error": str(e)}
514
+
515
+
516
+ @tool
517
+ def draw_on_image(
518
+ image_base64: str, drawing_type: str, params: Dict[str, Any]
519
+ ) -> Dict[str, Any]:
520
+ """
521
+ Draw shapes (rectangle, circle, line) or text onto an image.
522
+
523
+ Args:
524
+ image_base64 (str): Base64 encoded input image
525
+ drawing_type (str): Drawing type
526
+ params (Dict[str, Any]): Drawing parameters
527
+
528
+ Returns:
529
+ Dictionary with result image (base64)
530
+ """
531
+ try:
532
+ img = decode_image(image_base64)
533
+ draw = ImageDraw.Draw(img)
534
+ color = params.get("color", "red")
535
+
536
+ if drawing_type == "rectangle":
537
+ draw.rectangle(
538
+ [params["left"], params["top"], params["right"], params["bottom"]],
539
+ outline=color,
540
+ width=params.get("width", 2),
541
+ )
542
+ elif drawing_type == "circle":
543
+ x, y, r = params["x"], params["y"], params["radius"]
544
+ draw.ellipse(
545
+ (x - r, y - r, x + r, y + r),
546
+ outline=color,
547
+ width=params.get("width", 2),
548
+ )
549
+ elif drawing_type == "line":
550
+ draw.line(
551
+ (
552
+ params["start_x"],
553
+ params["start_y"],
554
+ params["end_x"],
555
+ params["end_y"],
556
+ ),
557
+ fill=color,
558
+ width=params.get("width", 2),
559
+ )
560
+ elif drawing_type == "text":
561
+ font_size = params.get("font_size", 20)
562
+ try:
563
+ font = ImageFont.truetype("arial.ttf", font_size)
564
+ except IOError:
565
+ font = ImageFont.load_default()
566
+ draw.text(
567
+ (params["x"], params["y"]),
568
+ params.get("text", "Text"),
569
+ fill=color,
570
+ font=font,
571
+ )
572
+ else:
573
+ return {"error": f"Unknown drawing type: {drawing_type}"}
574
+
575
+ result_path = save_image(img)
576
+ result_base64 = encode_image(result_path)
577
+ return {"result_image": result_base64}
578
+
579
+ except Exception as e:
580
+ return {"error": str(e)}
581
+
582
+
583
+ @tool
584
+ def generate_simple_image(
585
+ image_type: str,
586
+ width: int = 500,
587
+ height: int = 500,
588
+ params: Optional[Dict[str, Any]] = None,
589
+ ) -> Dict[str, Any]:
590
+ """
591
+ Generate a simple image (gradient, noise, pattern, chart).
592
+
593
+ Args:
594
+ image_type (str): Type of image
595
+ width (int), height (int)
596
+ params (Dict[str, Any], optional): Specific parameters
597
+
598
+ Returns:
599
+ Dictionary with generated image (base64)
600
+ """
601
+ try:
602
+ params = params or {}
603
+
604
+ if image_type == "gradient":
605
+ direction = params.get("direction", "horizontal")
606
+ start_color = params.get("start_color", (255, 0, 0))
607
+ end_color = params.get("end_color", (0, 0, 255))
608
+
609
+ img = Image.new("RGB", (width, height))
610
+ draw = ImageDraw.Draw(img)
611
+
612
+ if direction == "horizontal":
613
+ for x in range(width):
614
+ r = int(
615
+ start_color[0] + (end_color[0] - start_color[0]) * x / width
616
+ )
617
+ g = int(
618
+ start_color[1] + (end_color[1] - start_color[1]) * x / width
619
+ )
620
+ b = int(
621
+ start_color[2] + (end_color[2] - start_color[2]) * x / width
622
+ )
623
+ draw.line([(x, 0), (x, height)], fill=(r, g, b))
624
+ else:
625
+ for y in range(height):
626
+ r = int(
627
+ start_color[0] + (end_color[0] - start_color[0]) * y / height
628
+ )
629
+ g = int(
630
+ start_color[1] + (end_color[1] - start_color[1]) * y / height
631
+ )
632
+ b = int(
633
+ start_color[2] + (end_color[2] - start_color[2]) * y / height
634
+ )
635
+ draw.line([(0, y), (width, y)], fill=(r, g, b))
636
+
637
+ elif image_type == "noise":
638
+ noise_array = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8)
639
+ img = Image.fromarray(noise_array, "RGB")
640
+
641
+ else:
642
+ return {"error": f"Unsupported image_type {image_type}"}
643
+
644
+ result_path = save_image(img)
645
+ result_base64 = encode_image(result_path)
646
+ return {"generated_image": result_base64}
647
+
648
+ except Exception as e:
649
+ return {"error": str(e)}
650
+
651
+
652
+ @tool
653
+ def combine_images(
654
+ images_base64: List[str], operation: str, params: Optional[Dict[str, Any]] = None
655
+ ) -> Dict[str, Any]:
656
+ """
657
+ Combine multiple images (collage, stack, blend).
658
+
659
+ Args:
660
+ images_base64 (List[str]): List of base64 images
661
+ operation (str): Combination type
662
+ params (Dict[str, Any], optional)
663
+
664
+ Returns:
665
+ Dictionary with combined image (base64)
666
+ """
667
+ try:
668
+ images = [decode_image(b64) for b64 in images_base64]
669
+ params = params or {}
670
+
671
+ if operation == "stack":
672
+ direction = params.get("direction", "horizontal")
673
+ if direction == "horizontal":
674
+ total_width = sum(img.width for img in images)
675
+ max_height = max(img.height for img in images)
676
+ new_img = Image.new("RGB", (total_width, max_height))
677
+ x = 0
678
+ for img in images:
679
+ new_img.paste(img, (x, 0))
680
+ x += img.width
681
+ else:
682
+ max_width = max(img.width for img in images)
683
+ total_height = sum(img.height for img in images)
684
+ new_img = Image.new("RGB", (max_width, total_height))
685
+ y = 0
686
+ for img in images:
687
+ new_img.paste(img, (0, y))
688
+ y += img.height
689
+ else:
690
+ return {"error": f"Unsupported combination operation {operation}"}
691
+
692
+ result_path = save_image(new_img)
693
+ result_base64 = encode_image(result_path)
694
+ return {"combined_image": result_base64}
695
+
696
+ except Exception as e:
697
+ return {"error": str(e)}
698
+
699
+ # System message
700
+ sys_msg = SystemMessage(content=os.getenv("SYSTEM_PROMPT"))
701
+
702
+ code_interpreter = CodeInterpreterFunctionTool()
703
+ code_interpreter_tool = code_interpreter.to_langchain_tool()
704
+
705
+ tools = [
706
+ web_search,
707
+ wiki_search,
708
+ arxiv_search,
709
+ multiply,
710
+ add,
711
+ subtract,
712
+ divide,
713
+ modulus,
714
+ power,
715
+ square_root,
716
+ save_and_read_file,
717
+ download_file_from_url,
718
+ extract_text_from_image,
719
+ analyze_csv_file,
720
+ analyze_excel_file,
721
+ analyze_image,
722
+ transform_image,
723
+ draw_on_image,
724
+ generate_simple_image,
725
+ combine_images,
726
+ code_interpreter_tool
727
+ ]
728
+
729
+
730
+ # Build graph function
731
+ def build_graph(provider: str = "groq"):
732
+ """Build the graph"""
733
+ llm = ChatGoogleGenerativeAI(
734
+ model= "gemini-2.0-flash",
735
+ temperature=1.0,
736
+ max_retries=2,
737
+ google_api_key=os.getenv("GOOGLE_APY_KEY")
738
+ )
739
+ # Bind tools to LLM
740
+ llm_with_tools = llm.bind_tools(tools)
741
+
742
+ # Node
743
+ def assistant(state: MessagesState):
744
+ """Assistant node"""
745
+ return {"messages": [llm_with_tools.invoke([sys_msg] + state["messages"])]}
746
+
747
+ builder = StateGraph(MessagesState)
748
+ builder.add_node("assistant", assistant)
749
+ builder.add_node("tools", ToolNode(tools))
750
+ builder.set_entry_point("assistant")
751
+ builder.add_conditional_edges(
752
+ "assistant",
753
+ tools_condition,
754
+ )
755
+ builder.add_edge("tools", "assistant")
756
+
757
+ # Compile graph
758
+ return builder.compile()
759
+
760
+
761
+ # test
762
+ if __name__ == "__main__":
763
+
764
+ questions_url = f"https://agents-course-unit4-scoring.hf.space/questions"
765
+
766
+ # 2. Fetch Questions
767
+ print(f"Fetching questions from: {questions_url}")
768
+ try:
769
+ response = requests.get(questions_url, timeout=15)
770
+ response.raise_for_status()
771
+ questions_data = response.json()
772
+ if not questions_data:
773
+ print("Fetched questions list is empty.")
774
+ print(f"Fetched {len(questions_data)} questions.")
775
+ for question in questions_data:
776
+ task_id = question.get("task_id")
777
+ question_text = question.get("question")
778
+ # print(f"Task ID: {task_id}, Question: {question_text}\n")
779
+ except requests.exceptions.RequestException as e:
780
+ print(f"Error fetching questions: {e}")
781
+ except requests.exceptions.JSONDecodeError as e:
782
+ print(f"Error decoding JSON response from questions endpoint: {e}")
783
+ print(f"Response text: {response.text[:500]}")
784
+ except Exception as e:
785
+ print(f"An unexpected error occurred fetching questions: {e}")
786
+
787
+ # question = questions_data[0].get('question')
788
+ for item in questions_data:
789
+ question = item.get("question")
790
+ graph = build_graph()
791
+ messages = [HumanMessage(content=question)]
792
+ messages = graph.invoke({"messages": messages})
793
+ for m in messages["messages"]:
794
+ m.pretty_print()
795
+ time.sleep(4.1)