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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
from langchain_core.tools import tool
from langchain_tavily import TavilySearch
from langchain_community.document_loaders import WikipediaLoader

from youtube_transcript_api import YouTubeTranscriptApi
from PIL import Image, ImageDraw, ImageFont, ImageEnhance, ImageFilter
from typing import List, Dict, Any, Optional
from urllib.parse import urlparse

from code_interpreter_26042026 import CodeInterpreter
from tool_logger_26042026 import log_tool
from bs4 import BeautifulSoup
from dotenv import load_dotenv

interpreter_instance = CodeInterpreter()

from image_proccessing_26042026 import *

import os
import re
import cmath
import requests
import tempfile
import subprocess
import pytesseract
import numpy as np
import pandas as pd

load_dotenv()

@tool
def run_python_from_url(file_url: str) -> str:
    """
    Download and execute a Python script from a URL.

    Use this when:
    - A Python file needs to be executed remotely
    - The task explicitly involves running external scripts

    Do NOT use for:
    - Simple calculations
    - Inline code execution (use execute_code_multilang instead)

    Input: URL to .py file
    Output: execution result
    """
    try:
        # Download file
        response = requests.get(file_url)
        print("response ",response, "file_url ", file_url)
        response.raise_for_status()

        # Save to temp file
        with tempfile.NamedTemporaryFile(delete=False, suffix=".py") as tmp:
            tmp.write(response.content)
            tmp_path = tmp.name

        # Execute file
        result = subprocess.run(
            ["python", tmp_path],
            capture_output=True,
            text=True,
            timeout=10
        )

        output = result.stdout.strip()

        if not output:
            output = result.stderr.strip()
            
        log_tool("run_python_from_url", file_url, output)
        return output if output else "No output"

    except Exception as e:
        log_tool("run_python_from_url", file_url, f"ERROR: {str(e)}")
        return f"ERROR: {str(e)}"
    
@tool
def fetch_task_file(task_id: str) -> str:
    """
    MUST USE when a question mentions an attached file.

    Input:
    - task_id (string)

    Returns:
    - local file path of downloaded file

    After using this tool:
    - You should analyze or execute the file depending on type
    """
    try:
        url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
        response = requests.get(url)
        
        print("fetch task file ",response, "taskid ",task_id, "url ", url)
        
        if response.status_code != 200:
            return f"ERROR: {response.text}"
        
        # Try to detect filename (fallback)
        filename = f"{task_id}"
        
        # Save file
        filepath = f"./downloadsHuggingFace/{filename}"
        os.makedirs("./downloadsHuggingFace", exist_ok=True)
        
        with open(filepath, "wb") as f:
            f.write(response.content)
        
        return filepath

    except Exception as e:
        log_tool("fetch_task_file", task_id, f"ERROR: {str(e)}")
        return f"ERROR: {str(e)}"
    
    
# def web_search_raw(query: str) -> str:
#     import requests
#     from bs4 import BeautifulSoup
#     import urllib.parse

#     url = "https://duckduckgo.com/html/"
#     headers = {"User-Agent": "Mozilla/5.0"}
#     params = {"q": query}

#     res = requests.get(url, params=params, headers=headers, timeout=10)
#     soup = BeautifulSoup(res.text, "html.parser")
#     print("web search response ", res.text, "query ",query)
#     results = []

#     for r in soup.select(".result__body")[:7]:
#         title = r.select_one(".result__title")
#         snippet = r.select_one(".result__snippet")
#         link = r.select_one("a.result__a")

#         if not link:
#             continue

#         raw_url = link.get("href", "")

#         if "uddg=" in raw_url:
#             raw_url = urllib.parse.unquote(raw_url.split("uddg=")[-1])

#         results.append({
#             "title": title.get_text(strip=True) if title else "",
#             "snippet": snippet.get_text(strip=True) if snippet else "",
#             "url": raw_url
#         })

#     return results


def duckduckgo_search(query: str):
    import requests

    url = "https://api.duckduckgo.com/"
    params = {"q": query, "format": "json", "no_html": 1}

    res = requests.get(url, params=params, timeout=10)
    data = res.json()

    results = []

    if data.get("AbstractText"):
        results.append({
            "title": data.get("Heading", ""),
            "snippet": data.get("AbstractText", ""),
            "url": data.get("AbstractURL", "")
        })

    return results

def web_search_raw(query: str):
    import requests
    from bs4 import BeautifulSoup
    import urllib.parse
    import random
    import time

    USER_AGENTS = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122.0.0.0 Safari/537.36",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/121.0.0.0 Safari/537.36",
        "Mozilla/5.0 (X11; Linux x86_64) Gecko/20100101 Firefox/123.0"
    ]

    url = "https://duckduckgo.com/html/"
    params = {"q": query}

    headers = {
        "User-Agent": random.choice(USER_AGENTS),
        "Accept-Language": "en-US,en;q=0.9",
        "Accept": "text/html,application/xhtml+xml",
        "Connection": "keep-alive",
    }

    session = requests.Session()

    # delay to avoid detection
    time.sleep(random.uniform(1.5, 3.5))

    res = session.get(url, params=params, headers=headers, timeout=10)

    # 🚨 detect bot block
    if "anomaly" in res.text.lower() or "captcha" in res.text.lower():
        return "BOT_DETECTED"

    soup = BeautifulSoup(res.text, "html.parser")

    results = []

    for r in soup.select(".result__body")[:5]:
        title = r.select_one(".result__title")
        snippet = r.select_one(".result__snippet")
        link = r.select_one("a.result__a")

        if not link:
            continue

        raw_url = link.get("href", "")

        if "uddg=" in raw_url:
            raw_url = urllib.parse.unquote(raw_url.split("uddg=")[-1])

        results.append({
            "title": title.get_text(strip=True) if title else "",
            "snippet": snippet.get_text(strip=True) if snippet else "",
            "url": raw_url
        })

    return results

@tool
def search(query: str) -> str:
    """Search the web for real-world information.

    Use this when:
    - The question requires external knowledge (people, places, events, facts)
    - The question involves current or recent information
    - You are unsure about factual accuracy

    Do NOT use this when:
    - The answer can be derived from reasoning or math
    - The task involves files, images, or code execution

    Input: search query string
    Output: list of web results with titles and snippets"""

    try:
        tavily = TavilySearch(
            max_results=5,
            topic="general",
            search_depth="basic",   # cheaper + faster
            include_answer=True     # gives direct answer
        )

        response = tavily.invoke({"query": query})

        # ---- Handle errors ----
        if isinstance(response, dict) and response.get("error"):
            return f"Search Error: {response['error']}"

        results = response.get("results", [])
        answer = response.get("answer", None)

        if not results:
            return "No relevant results found."

        # ---- Format nicely for LLM ----
        formatted = []

        if answer:
            formatted.append(f"🔎 QUICK ANSWER:\n{answer}\n")

        for r in results:
            formatted.append(
                f"Title: {r.get('title','')}\n"
                f"Snippet: {r.get('content','')}\n"
                f"Source: {r.get('url','')}\n"
            )

        final_output = "\n---\n".join(formatted)

        # ---- Log ----
        log_tool("web_search", query, {"results": final_output})

        return final_output

    except Exception as e:
        error_msg = f"Search failed: {str(e)}"
        log_tool("web_search", query, error_msg)
        return error_msg

# @tool
# def search(query: str) -> str:
#     """Search the web for real-world information.

#     Use this when:
#     - The question requires external knowledge (people, places, events, facts)
#     - The question involves current or recent information
#     - You are unsure about factual accuracy

#     Do NOT use this when:
#     - The answer can be derived from reasoning or math
#     - The task involves files, images, or code execution

#     Input: search query string
#     Output: list of web results with titles and snippets"""
#     results = web_search_raw(query)
    
#     print("search results ", results)

#     if not results or results == "BOT_DETECTED":
#         # return "No results found."
#         print("⚠️ DuckDuckGo blocked → fallback")
#         return duckduckgo_search(query)

#     formatted = []
#     for r in results:
#         formatted.append(
#             f"{r.get('title','')}\n{r.get('snippet','')}\n{r.get('link','')}"
#         )
#     log_tool("search", query, {"web_results": formatted})
#     return "\n\n".join(formatted)

@tool
def youtube_transcript(url: str) -> str:
    """Extract transcript text from a YouTube video.

    Use this when:
    - The user asks about content from a specific YouTube video
    - You need to summarize or analyze a video

    Do NOT use this for:
    - General web search
    - Non-YouTube links

    Input: YouTube video URL
    Output: transcript text"""
    try:
        video_id = None

       # Case 1: watch?v=
        match = re.search(r"v=([^&]+)", url)
        if match:
            video_id = match.group(1)

        # Case 2: youtu.be/
        if not video_id:
            match = re.search(r"youtu\.be/([^?&]+)", url)
            if match:
                video_id = match.group(1)

        # Case 3: shorts/
        if not video_id:
            match = re.search(r"shorts/([^?&]+)", url)
            if match:
                video_id = match.group(1)

        # Case 4: embed/
        if not video_id:
            match = re.search(r"embed/([^?&]+)", url)
            if match:
                video_id = match.group(1)

        if not video_id:
            raise ValueError("Could not extract video ID from URL")

        transcript = YouTubeTranscriptApi().fetch(video_id)

        text = " ".join([t.text for t in transcript])
        
        print("youtube transcript text ", text)

        log_tool("youtube_transcript", url, text)

        return text[:5000] if text else "No transcript available"

    except Exception as e:
        print("youtube transcript err ", e)
        log_tool("youtube_transcript", url, f"Transcript error: {str(e)}")
        return f"Transcript error: {str(e)}"
    
# @tool
# def wiki_search(query: str) -> str:
#     """Search Wikipedia (safe fallback)"""
#     try:
#         import wikipedia
#         log_tool("wiki_search", query, wikipedia.summary(query, sentences=2))
#         return wikipedia.summary(query, sentences=2)
#     except Exception as e:
#         log_tool("wiki_search", query, f"ERROR: {str(e)}")
#         return f"ERROR: {str(e)}"

# @tool
# def wiki_search(query: str) -> str:
#     """
#     Search Wikipedia and return detailed page content including discography when available.
#     """
#     try:
#         import wikipedia

#         # Get best page
#         page = wikipedia.page(query, auto_suggest=True)

#         content = page.content[:5000]  # limit for LLM

#         log_tool("wiki_search", query, content)

#         return content

#     except Exception as e:
#         log_tool("wiki_search", query, f"ERROR: {str(e)}")
#         return f"ERROR: {str(e)}"

@tool
def wiki_search(query: str) -> str:
    """
    Wikipedia search with strict size control to avoid token overflow.
    """
    try:
        import wikipedia

        MAX_CHARS = 5000  # SAFE LIMIT

        def trim(text):
            return text[:MAX_CHARS]

        # ---------- DIRECT ----------
        try:
            page = wikipedia.page(query, auto_suggest=True)
            content = trim(page.content)

            log_tool("wiki_direct", query, content)
            return f"### {page.title}\n{content}"

        except wikipedia.DisambiguationError as e:
            options = e.options[:5]

            for option in options:
                try:
                    page = wikipedia.page(option, auto_suggest=False)
                    content = trim(page.content)

                    log_tool("wiki_disambiguation", query, option)
                    return f"### {page.title}\n{content}"
                except:
                    continue

        except:
            pass

        # ---------- SEARCH ----------
        results = wikipedia.search(query)

        combined = ""
        for title in results[:3]:  # 🔥 reduce results
            try:
                page = wikipedia.page(title, auto_suggest=False)

                chunk = f"\n\n### {title}\n{page.content[:1500]}"

                # 🔥 stop before overflow
                if len(combined) + len(chunk) > MAX_CHARS:
                    break

                combined += chunk

            except:
                continue

        log_tool("wiki_search_fallback", query, combined[:1000])
        return combined

    except Exception as e:
        log_tool("wiki_error", query, str(e))
        return f"ERROR: {str(e)}"
    
@tool
def wiki_discography(query: str) -> str:
    """
    Search Wikipedia specifically for discography or album lists of an artist.
    """
    try:
        import wikipedia

        page = wikipedia.page(query + " discography", auto_suggest=True)

        content = page.content

        log_tool("wiki_discography", query, content)

        return content

    except Exception as e:
        log_tool("wiki_discography", query, f"ERROR: {str(e)}")
        return f"ERROR: {str(e)}"

### =============== MATHEMATICAL TOOLS =============== ###


@tool
def multiply(a: float, b: float) -> float:
    """
    Perform precise multiplication.

    Use this when:
    - Exact arithmetic is required

    Do NOT use for:
    - Estimation or reasoning

    Input: two numbers
    Output: result
    """
    return a * b


@tool
def add(a: float, b: float) -> float:
    """
    Perform precise addition.

    Use this when:
    - Exact arithmetic is required

    Do NOT use for:
    - Estimation or reasoning

    Input: two numbers
    Output: result
    """
    return a + b


@tool
def subtract(a: float, b: float) -> int:
    """
    Perform precise subtraction.

    Use this when:
    - Exact arithmetic is required

    Do NOT use for:
    - Estimation or reasoning

    Input: two numbers
    Output: result
    """
    return a - b


@tool
def divide(a: float, b: float) -> float:
    """
    Perform precise addition.

    Use this when:
    - Exact arithmetic is required

    Do NOT use for:
    - Estimation or reasoning

    Input: two numbers
    Output: result
    """
    if b == 0:
        raise ValueError("Cannot divided by zero.")
    return a / b


@tool
def modulus(a: int, b: int) -> int:
    """
    Perform precise modulus.

    Use this when:
    - Exact arithmetic is required

    Do NOT use for:
    - Estimation or reasoning

    Input: two numbers
    Output: result
    """
    return a % b


@tool
def power(a: float, b: float) -> float:
    """
    Perform precise power.

    Use this when:
    - Exact arithmetic is required

    Do NOT use for:
    - Estimation or reasoning

    Input: two numbers
    Output: result
    """
    return a**b


@tool
def square_root(a: float) -> float | complex:
    """
    Perform precise square_root.

    Use this when:
    - Exact arithmetic is required

    Do NOT use for:
    - Estimation or reasoning

    Input: two numbers
    Output: result
    """
    if a >= 0:
        return a**0.5
    return cmath.sqrt(a)

### ============== IMAGE PROCESSING AND GENERATION TOOLS =============== ###


@tool
def analyze_image(image_base64: str) -> Dict[str, Any]:
    """
    Analyze image properties (size, colors, brightness).

    Use this when:
    - You need metadata or insights about an image

    Do NOT use for:
    - editing or transforming images

    Input: base64 image
    Output: analysis data
    """
    try:
        img = decode_image(image_base64)
        width, height = img.size
        mode = img.mode

        if mode in ("RGB", "RGBA"):
            arr = np.array(img)
            avg_colors = arr.mean(axis=(0, 1))
            dominant = ["Red", "Green", "Blue"][np.argmax(avg_colors[:3])]
            brightness = avg_colors.mean()
            color_analysis = {
                "average_rgb": avg_colors.tolist(),
                "brightness": brightness,
                "dominant_color": dominant,
            }
        else:
            color_analysis = {"note": f"No color analysis for mode {mode}"}

        thumbnail = img.copy()
        thumbnail.thumbnail((100, 100))
        thumb_path = save_image(thumbnail, "thumbnails")
        thumbnail_base64 = encode_image(thumb_path)

        log_tool("analyze_image", image_base64, {
            "dimensions": (width, height),
            "mode": mode,
            "color_analysis": color_analysis,
            "thumbnail": thumbnail_base64,
        }) 
        return {
            "dimensions": (width, height),
            "mode": mode,
            "color_analysis": color_analysis,
            "thumbnail": thumbnail_base64,
        }
    except Exception as e:
        log_tool("analyze_image", image_base64, f"ERROR: {str(e)}")
        return {"error": str(e)}


@tool
def transform_image(
    image_base64: str, operation: str, params: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
    """
    Modify an image (resize, rotate, crop, etc.)

    Use this when:
    - The task requires changing an image

    Input: image + operation
    Output: transformed image
    """
    try:
        img = decode_image(image_base64)
        params = params or {}

        if operation == "resize":
            img = img.resize(
                (
                    params.get("width", img.width // 2),
                    params.get("height", img.height // 2),
                )
            )
        elif operation == "rotate":
            img = img.rotate(params.get("angle", 90), expand=True)
        elif operation == "crop":
            img = img.crop(
                (
                    params.get("left", 0),
                    params.get("top", 0),
                    params.get("right", img.width),
                    params.get("bottom", img.height),
                )
            )
        elif operation == "flip":
            if params.get("direction", "horizontal") == "horizontal":
                img = img.transpose(Image.FLIP_LEFT_RIGHT)
            else:
                img = img.transpose(Image.FLIP_TOP_BOTTOM)
        elif operation == "adjust_brightness":
            img = ImageEnhance.Brightness(img).enhance(params.get("factor", 1.5))
        elif operation == "adjust_contrast":
            img = ImageEnhance.Contrast(img).enhance(params.get("factor", 1.5))
        elif operation == "blur":
            img = img.filter(ImageFilter.GaussianBlur(params.get("radius", 2)))
        elif operation == "sharpen":
            img = img.filter(ImageFilter.SHARPEN)
        elif operation == "grayscale":
            img = img.convert("L")
        else:
            return {"error": f"Unknown operation: {operation}"}

        result_path = save_image(img)
        result_base64 = encode_image(result_path)
        log_tool("transform_image", {"operation": operation, "params": params}, result_base64)
        return {"transformed_image": result_base64}

    except Exception as e:
        log_tool("transform_image", {"operation": operation, "params": params}, f"ERROR: {str(e)}")
        return {"error": str(e)}


@tool
def draw_on_image(
    image_base64: str, drawing_type: str, params: Dict[str, Any]
) -> Dict[str, Any]:
    """
    Draw shapes (rectangle, circle, line) or text onto an image.
    Use this when:
    - Annotation or overlay is needed
    Args:
        image_base64 (str): Base64 encoded input image
        drawing_type (str): Drawing type
        params (Dict[str, Any]): Drawing parameters
    Returns:
        Dictionary with result image (base64)
    """
    try:
        img = decode_image(image_base64)
        draw = ImageDraw.Draw(img)
        color = params.get("color", "red")

        if drawing_type == "rectangle":
            draw.rectangle(
                [params["left"], params["top"], params["right"], params["bottom"]],
                outline=color,
                width=params.get("width", 2),
            )
        elif drawing_type == "circle":
            x, y, r = params["x"], params["y"], params["radius"]
            draw.ellipse(
                (x - r, y - r, x + r, y + r),
                outline=color,
                width=params.get("width", 2),
            )
        elif drawing_type == "line":
            draw.line(
                (
                    params["start_x"],
                    params["start_y"],
                    params["end_x"],
                    params["end_y"],
                ),
                fill=color,
                width=params.get("width", 2),
            )
        elif drawing_type == "text":
            font_size = params.get("font_size", 20)
            try:
                font = ImageFont.truetype("arial.ttf", font_size)
            except IOError:
                font = ImageFont.load_default()
            draw.text(
                (params["x"], params["y"]),
                params.get("text", "Text"),
                fill=color,
                font=font,
            )
        else:
            return {"error": f"Unknown drawing type: {drawing_type}"}

        result_path = save_image(img)
        result_base64 = encode_image(result_path)
        log_tool("draw_on_image", {"drawing_type": drawing_type, "params": params}, result_base64)
        return {"result_image": result_base64}

    except Exception as e:
        log_tool("draw_on_image", {"drawing_type": drawing_type, "params": params}, f"ERROR: {str(e)}") 
        return {"error": str(e)}


@tool
def generate_simple_image(
    image_type: str,
    width: int = 500,
    height: int = 500,
    params: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """
    Generate a simple image (gradient, noise, pattern, chart).
    Args:
        image_type (str): Type of image
        width (int), height (int)
        params (Dict[str, Any], optional): Specific parameters
    Returns:
        Dictionary with generated image (base64)
    """
    try:
        params = params or {}

        if image_type == "gradient":
            direction = params.get("direction", "horizontal")
            start_color = params.get("start_color", (255, 0, 0))
            end_color = params.get("end_color", (0, 0, 255))

            img = Image.new("RGB", (width, height))
            draw = ImageDraw.Draw(img)

            if direction == "horizontal":
                for x in range(width):
                    r = int(
                        start_color[0] + (end_color[0] - start_color[0]) * x / width
                    )
                    g = int(
                        start_color[1] + (end_color[1] - start_color[1]) * x / width
                    )
                    b = int(
                        start_color[2] + (end_color[2] - start_color[2]) * x / width
                    )
                    draw.line([(x, 0), (x, height)], fill=(r, g, b))
            else:
                for y in range(height):
                    r = int(
                        start_color[0] + (end_color[0] - start_color[0]) * y / height
                    )
                    g = int(
                        start_color[1] + (end_color[1] - start_color[1]) * y / height
                    )
                    b = int(
                        start_color[2] + (end_color[2] - start_color[2]) * y / height
                    )
                    draw.line([(0, y), (width, y)], fill=(r, g, b))

        elif image_type == "noise":
            noise_array = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8)
            img = Image.fromarray(noise_array, "RGB")

        else:
            return {"error": f"Unsupported image_type {image_type}"}

        result_path = save_image(img)
        result_base64 = encode_image(result_path)
        log_tool("generate_simple_image", {"image_type": image_type, "params": params}, result_base64)
        return {"generated_image": result_base64}

    except Exception as e:
        log_tool("generate_simple_image", {"image_type": image_type, "params": params}, f"ERROR: {str(e)}")
        return {"error": str(e)}


@tool
def combine_images(
    images_base64: List[str], operation: str, params: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
    """
    Combine multiple images (collage, stack, blend).
    Args:
        images_base64 (List[str]): List of base64 images
        operation (str): Combination type
        params (Dict[str, Any], optional)
    Returns:
        Dictionary with combined image (base64)
    """
    try:
        images = [decode_image(b64) for b64 in images_base64]
        params = params or {}

        if operation == "stack":
            direction = params.get("direction", "horizontal")
            if direction == "horizontal":
                total_width = sum(img.width for img in images)
                max_height = max(img.height for img in images)
                new_img = Image.new("RGB", (total_width, max_height))
                x = 0
                for img in images:
                    new_img.paste(img, (x, 0))
                    x += img.width
            else:
                max_width = max(img.width for img in images)
                total_height = sum(img.height for img in images)
                new_img = Image.new("RGB", (max_width, total_height))
                y = 0
                for img in images:
                    new_img.paste(img, (0, y))
                    y += img.height
        else:
            return {"error": f"Unsupported combination operation {operation}"}

        result_path = save_image(new_img)
        result_base64 = encode_image(result_path)
        log_tool("combine_images", {"operation": operation, "params": params}, result_base64)
        return {"combined_image": result_base64}

    except Exception as e:
        log_tool("combine_images", {"operation": operation, "params": params}, f"ERROR: {str(e)}")
        return {"error": str(e)}
    
    
    ### =============== CODE INTERPRETER TOOLS =============== ###


@tool
def execute_code_multilang(code: str, language: str = "python") -> str:
    """Execute code in Python, Bash, SQL, C, or Java.

    Use this when:
    - The task requires code execution
    - Logic is complex or requires runtime evaluation
    - Data processing or scripting is needed

    Do NOT use for:
    - Simple math (use math tools)
    - General reasoning

    Input: code + language
    Output: execution result (stdout, errors, etc.)
    """
    supported_languages = ["python", "bash", "sql", "c", "java"]
    language = language.lower()

    if language not in supported_languages:
        return f"❌ Unsupported language: {language}. Supported languages are: {', '.join(supported_languages)}"

    result = interpreter_instance.execute_code(code, language=language)

    response = []

    if result["status"] == "success":
        response.append(f"✅ Code executed successfully in **{language.upper()}**")

        if result.get("stdout"):
            response.append(
                "\n**Standard Output:**\n```\n" + result["stdout"].strip() + "\n```"
            )

        if result.get("stderr"):
            response.append(
                "\n**Standard Error (if any):**\n```\n"
                + result["stderr"].strip()
                + "\n```"
            )

        if result.get("result") is not None:
            response.append(
                "\n**Execution Result:**\n```\n"
                + str(result["result"]).strip()
                + "\n```"
            )

        if result.get("dataframes"):
            for df_info in result["dataframes"]:
                response.append(
                    f"\n**DataFrame `{df_info['name']}` (Shape: {df_info['shape']})**"
                )
                df_preview = pd.DataFrame(df_info["head"])
                response.append("First 5 rows:\n```\n" + str(df_preview) + "\n```")

        if result.get("plots"):
            response.append(
                f"\n**Generated {len(result['plots'])} plot(s)** (Image data returned separately)"
            )

    else:
        response.append(f"❌ Code execution failed in **{language.upper()}**")
        if result.get("stderr"):
            response.append(
                "\n**Error Log:**\n```\n" + result["stderr"].strip() + "\n```"
            )
    log_tool("execute_code_multilang", {"code": code, "language": language}, "\n".join(response))

    return "\n".join(response)



### =============== DOCUMENT PROCESSING TOOLS =============== ###


@tool
def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
    """
    Save content to a file.

    Use this when:
    - You need to persist generated data for further processing

    Input: content + optional filename
    Output: file path
    """
    temp_dir = tempfile.gettempdir()
    if filename is None:
        temp_file = tempfile.NamedTemporaryFile(delete=False, dir=temp_dir)
        filepath = temp_file.name
    else:
        filepath = os.path.join(temp_dir, filename)

    with open(filepath, "w") as f:
        f.write(content)
    log_tool("save_and_read_file", {"content": content, "filename": filename}, f"File saved to {filepath}")
    return f"File saved to {filepath}. You can read this file to process its contents."


@tool
def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
    """
    Download a file from a URL and save it to a temporary location.
    Args:
        url (str): the URL of the file to download.
        filename (str, optional): the name of the file. If not provided, a random name file will be created.
    """
    try:
        # Parse URL to get filename if not provided
        if not filename:
            path = urlparse(url).path
            filename = os.path.basename(path)
            if not filename:
                filename = f"downloaded_{uuid.uuid4().hex[:8]}"

        # Create temporary file
        temp_dir = tempfile.gettempdir()
        filepath = os.path.join(temp_dir, filename)

        # Download the file
        response = requests.get(url, stream=True)
        response.raise_for_status()

        # Save the file
        with open(filepath, "wb") as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        log_tool("download_file_from_url", url, f"File downloaded to {filepath}")
        return f"File downloaded to {filepath}. You can read this file to process its contents."
    except Exception as e:
        log_tool("download_file_from_url", url, f"ERROR: {str(e)}")
        return f"Error downloading file: {str(e)}"


@tool
def extract_text_from_image(image_path: str) -> str:
    """
    Extract text from an image using OCR.

    Use this when:
    - The image contains readable text

    Do NOT use for:
    - Visual analysis (use analyze_image instead)

    Input: image path
    Output: extracted text
    """
    try:
        # Open the image
        image = Image.open(image_path)

        # Extract text from the image
        text = pytesseract.image_to_string(image)
        log_tool("extract_text_from_image", image_path, text)
        return f"Extracted text from image:\n\n{text}"
    except Exception as e:
        log_tool("extract_text_from_image", image_path, f"ERROR: {str(e)}")
        return f"Error extracting text from image: {str(e)}"


@tool
def analyze_csv_file(file_path: str, query: str) -> str:
    """
    Analyze a CSV file using pandas.

    Use this when:
    - The task involves structured tabular data
    - The user asks questions about CSV content

    Do NOT use for:
    - Non-tabular data

    Input: CSV path + query
    Output: summary and statistics
    """
    try:
        # Read the CSV file
        df = pd.read_csv(file_path)

        # Run various analyses based on the query
        result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
        result += f"Columns: {', '.join(df.columns)}\n\n"

        # Add summary statistics
        result += "Summary statistics:\n"
        result += str(df.describe())
        log_tool("analyze_csv_file", file_path, result)
        return result

    except Exception as e:
        log_tool("analyze_csv_file", file_path, f"ERROR: {str(e)}")
        return f"Error analyzing CSV file: {str(e)}"


@tool
def analyze_excel_file(file_path: str, query: str) -> str:
    """
    Analyze an Excel file.

    Use this when:
    - The task involves spreadsheet data

    Input: Excel file path + query
    Output: analysis and summary
    """
    try:
        # Read the Excel file
        df = pd.read_excel(file_path)

        # Run various analyses based on the query
        result = (
            f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
        )
        result += f"Columns: {', '.join(df.columns)}\n\n"

        # Add summary statistics
        result += "Summary statistics:\n"
        result += str(df.describe())
        log_tool("analyze_excel_tool", {file_path,query},result)
        return result

    except Exception as e:
        log_tool("analyze_excel_tool", {file_path,query},f"ERROR: {str(e)}")
        return f"Error analyzing Excel file: {str(e)}"