File size: 27,707 Bytes
a8c8fe8
 
 
 
 
e2e1a46
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
911c6dc
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
911c6dc
 
 
 
a8c8fe8
ad6d84e
a8c8fe8
 
911c6dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c8fe8
 
911c6dc
 
 
 
 
 
 
 
 
 
5a4de97
911c6dc
 
 
 
a8c8fe8
 
 
 
7a12106
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d84e
a8c8fe8
 
911c6dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c8fe8
 
911c6dc
 
 
 
 
 
 
 
 
 
5a4de97
911c6dc
 
 
 
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d84e
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a12106
a8c8fe8
ad6d84e
 
a8c8fe8
ad6d84e
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d84e
a8c8fe8
 
911c6dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c8fe8
 
911c6dc
 
 
 
ad6d84e
911c6dc
 
 
5a4de97
911c6dc
 
 
 
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d84e
a8c8fe8
 
911c6dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c8fe8
911c6dc
 
 
 
 
 
 
 
 
 
 
5a4de97
911c6dc
 
 
 
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d84e
a8c8fe8
 
911c6dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a4de97
911c6dc
 
 
 
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d84e
a8c8fe8
 
911c6dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a4de97
911c6dc
 
 
 
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d84e
a8c8fe8
 
911c6dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c8fe8
911c6dc
 
 
 
 
 
 
 
a8c8fe8
911c6dc
 
 
 
 
a8c8fe8
 
911c6dc
a8c8fe8
911c6dc
 
 
 
a8c8fe8
e2e1a46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
911c6dc
a8c8fe8
911c6dc
 
 
 
ad6d84e
911c6dc
 
 
5a4de97
911c6dc
 
 
 
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d84e
a8c8fe8
 
911c6dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c8fe8
911c6dc
 
 
 
 
 
 
 
a8c8fe8
911c6dc
 
 
 
 
a8c8fe8
 
911c6dc
 
 
 
 
 
a8c8fe8
911c6dc
 
 
 
ad6d84e
911c6dc
 
 
5a4de97
911c6dc
 
 
 
a8c8fe8
 
 
 
 
 
 
 
 
 
 
 
 
ad6d84e
 
a8c8fe8
 
911c6dc
 
a8c8fe8
911c6dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c8fe8
911c6dc
 
ad6d84e
911c6dc
 
 
 
 
 
 
 
5a4de97
911c6dc
 
 
 
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
# References:

# https://docs.crewai.com/introduction
# https://ai.google.dev/gemini-api/docs

import base64, chess, os, re, time
from agents.models.llms import (
    LLM_WEB_SEARCH,
    LLM_WEB_BROWSER,
    LLM_IMAGE_ANALYSIS,
    LLM_AUDIO_ANALYSIS,
    LLM_VIDEO_ANALYSIS,
    LLM_YOUTUBE_ANALYSIS,
    LLM_DOCUMENT_ANALYSIS,
    LLM_CODE_GENERATION,
    LLM_CODE_EXECUTION,
    LLM_IMAGE_TO_FEN,
    LLM_ALGEBRAIC_NOTATION,
    LLM_FINAL_ANSWER,
    LLM_FALLBACK,

    THINKING_LEVEL_WEB_SEARCH,
    THINKING_LEVEL_MEDIA_ANALYSIS,
    THINKING_LEVEL_YOUTUBE_ANALYSIS,
    THINKING_LEVEL_DOCUMENT_ANALYSIS,
    THINKING_LEVEL_CODE_GENERATION,
    THINKING_LEVEL_CODE_EXECUTION,
    THINKING_LEVEL_IMAGE_TO_FEN,
    THINKING_LEVEL_ALGEBRAIC_NOTATION,
    THINKING_LEVEL_FINAL_ANSWER
)
from agents.models.prompts import (
    PROMPT_IMG_TO_FEN,
    PROMPT_ALGEBRAIC_NOTATION,
    PROMPT_FINAL_ANSWER
)
from crewai.tools import tool
from crewai_tools import StagehandTool
from google import genai
from google.genai import types
from utils.utils import (
    read_docx_text,
    read_pptx_text,
    is_ext
)

class AITools():
    def _get_client():
        return genai.Client(api_key=os.environ["GEMINI_API_KEY"])

    def _is_rate_limit_error(exception):
        error_str = str(exception)
        return "429" in error_str and "RESOURCE_EXHAUSTED" in error_str

    def _media_analysis_tool(tool_name: str, model: str, question: str, file_path: str) -> str:
        print("")
        print(f"๐Ÿ› ๏ธ AITools: {tool_name}: question={question}, file_path={file_path}")
        
        client = AITools._get_client()
        current_model = model
        
        for attempt in range(2):
            try:
                file = client.files.upload(file=file_path)

                while True:
                    media_file = client.files.get(name=file.name)
                    if media_file.state == "ACTIVE":
                        break
                    elif media_file.state == "FAILED":
                        raise RuntimeError("Media file processing failed")
                    time.sleep(1)            

                config_params = {}

                if current_model != LLM_FALLBACK:
                    config_params["thinking_config"] = types.ThinkingConfig(
                        thinking_level=THINKING_LEVEL_MEDIA_ANALYSIS
                    )

                response = client.models.generate_content(
                    model=current_model,
                    contents=[file, question],
                    config=types.GenerateContentConfig(**config_params)
                )

                result = response.text
                
                print(f"๐Ÿ› ๏ธ AITools: {tool_name}: model={current_model}")
                if current_model != LLM_FALLBACK:
                    print(f"๐Ÿ› ๏ธ AITools: {tool_name}: thinking_level={THINKING_LEVEL_MEDIA_ANALYSIS}")
                print(f"๐Ÿ› ๏ธ AITools: {tool_name}: result={result}")
                
                return result
            except Exception as e:
                if attempt == 0 and AITools._is_rate_limit_error(e):
                    print(f"โš ๏ธ AITools: {tool_name}: Daily rate limit hit with {current_model}, falling back to {LLM_FALLBACK}")
                    current_model = LLM_FALLBACK
                    continue
                print(f"โš ๏ธ AITools: {tool_name}: exception={str(e)}")
                raise RuntimeError(f"Processing failed: {str(e)}")

    def _extract_execution_result(response):
        for part in response.candidates[0].content.parts:
            if part.code_execution_result is not None:
                return part.code_execution_result.output

        return None

    @tool("Web Search Tool")
    def web_search_tool(question: str) -> str:
        """Given a question only, search the web to answer the question.
    
        Args:
            question (str): Question to answer
            
        Returns:
            str: Answer to the question
            
        Raises:
            RuntimeError: If processing fails
        """
        print("")
        print(f"๐Ÿ› ๏ธ AITools: web_search_tool: question={question}")

        client = AITools._get_client()
        model = LLM_WEB_SEARCH
        
        for attempt in range(2):
            try:
                config_params = {"tools": [types.Tool(google_search=types.GoogleSearch())]}

                if model != LLM_FALLBACK:
                    config_params["thinking_config"] = types.ThinkingConfig(
                        thinking_level=THINKING_LEVEL_WEB_SEARCH
                    )

                response = client.models.generate_content(
                    model=model,
                    contents=question,
                    config=types.GenerateContentConfig(**config_params)
                )

                result = response.text
                
                print(f"๐Ÿ› ๏ธ AITools: web_search_tool: model={model}")
                if model != LLM_FALLBACK:
                    print(f"๐Ÿ› ๏ธ AITools: web_search_tool: thinking_level={THINKING_LEVEL_WEB_SEARCH}")
                print(f"๐Ÿ› ๏ธ AITools: web_search_tool: result={result}")
                
                return result
            except Exception as e:
                if attempt == 0 and AITools._is_rate_limit_error(e):
                    print(f"โš ๏ธ AITools: web_search_tool: Daily rate limit hit with {model}, falling back to {LLM_FALLBACK}")
                    model = LLM_FALLBACK
                    continue
                print(f"โš ๏ธ AITools: web_search_tool: exception={str(e)}")
                raise RuntimeError(f"Processing failed: {str(e)}")

    @tool("Web Browser Tool")
    def web_browser_tool(question: str, url: str) -> str:
        """Given a question and URL, load the URL and act, extract, or observe to answer the question.
    
        Args:
            question (str): Question about a URL
            url (str): The target URL (must be http/https). "http://"/"https://" will be auto-added if missing.
            
        Returns:
            str: Answer to the question
            
        Raises:
            RuntimeError: If processing fails
        """
        print("")
        print(f"๐Ÿ› ๏ธ AITools: web_browser_tool: question={question}, url={url}")
        
        try:
            url_str = url.strip()
            
            if not url_str.lower().startswith(("http://", "https://")):
                url_str = f"https://{url_str}"

            with StagehandTool(
                api_key=os.environ["BROWSERBASE_API_KEY"],
                project_id=os.environ["BROWSERBASE_PROJECT_ID"],
                model_api_key=os.environ["BROWSERBASE_MODEL_API_KEY"],
                model_name=LLM_WEB_BROWSER,
                dom_settle_timeout_ms=5000,
                headless=True,
                self_heal=True,
                wait_for_captcha_solves=True,
                verbose=3
            ) as stagehand_tool:
                result = stagehand_tool.run(
                    instruction=question,
                    url=url_str,
                    command_type="act" # TODO: act, extract, observe
                )

                print(f"๐Ÿ› ๏ธ AITools: web_browser_tool: model={LLM_WEB_BROWSER}")
                print(f"๐Ÿ› ๏ธ AITools: web_browser_tool: command_type=act")
                print(f"๐Ÿ› ๏ธ AITools: web_browser_tool: result={result}")

                return result
        except Exception as e:
            print(f"โš ๏ธ AITools: web_browser_tool: exception={str(e)}")
            raise RuntimeError(f"Processing failed: {str(e)}")

    @tool("Image Analysis Tool")
    def image_analysis_tool(question: str, file_path: str) -> str:
        """Given a question and image file, analyze the image to answer the question.
    
        Args:
            question (str): Question about an image file
            file_path (str): The image file path
            
        Returns:
            str: Answer to the question about the image file
            
        Raises:
            RuntimeError: If processing fails
        """
        return AITools._media_analysis_tool("image_analysis_tool", LLM_IMAGE_ANALYSIS, question, file_path)
    
    @tool("Audio Analysis Tool")
    def audio_analysis_tool(question: str, file_path: str) -> str:
        """Given a question and audio file, analyze the audio to answer the question.

        Args:
            question (str): Question about an audio file
            file_path (str): The audio file path
            
        Returns:
            str: Answer to the question about the audio file
            
        Raises:
            RuntimeError: If processing fails
        """
        return AITools._media_analysis_tool("audio_analysis_tool", LLM_AUDIO_ANALYSIS, question, file_path)
    
    @tool("Video Analysis Tool")
    def video_analysis_tool(question: str, file_path: str) -> str:
        """Given a question and video file, analyze the video to answer the question.
    
        Args:
            question (str): Question about a video file
            file_path (str): The video file path
            
        Returns:
            str: Answer to the question about the video file
            
        Raises:
            RuntimeError: If processing fails
        """
        return AITools._media_analysis_tool("video_analysis_tool", LLM_VIDEO_ANALYSIS, question, file_path)
            
    @tool("YouTube Analysis Tool")
    def youtube_analysis_tool(question: str, url: str) -> str:
        """Given a question and YouTube URL, analyze the video to answer the question.
    
        Args:
            question (str): Question about a YouTube video
            url (str): The YouTube URL
            
        Returns:
            str: Answer to the question about the YouTube video
            
        Raises:
            RuntimeError: If processing fails
        """
        print("")
        print(f"๐Ÿ› ๏ธ AITools: youtube_analysis_tool: question={question}, url={url}")
        
        client = AITools._get_client()
        model = LLM_YOUTUBE_ANALYSIS
        
        for attempt in range(2):
            try:
                config_params = {}

                if model != LLM_FALLBACK:
                    config_params["thinking_config"] = types.ThinkingConfig(
                        thinking_level=THINKING_LEVEL_YOUTUBE_ANALYSIS
                    )

                result = client.models.generate_content(
                    model=model,
                    contents=types.Content(
                        parts=[types.Part(file_data=types.FileData(file_uri=url)),
                               types.Part(text=question)]
                    ),
                    config=types.GenerateContentConfig(**config_params)
                )

                print(f"๐Ÿ› ๏ธ AITools: youtube_analysis_tool: model={model}")
                if model != LLM_FALLBACK:
                    print(f"๐Ÿ› ๏ธ AITools: youtube_analysis_tool: thinking_level={THINKING_LEVEL_YOUTUBE_ANALYSIS}")
                print(f"๐Ÿ› ๏ธ AITools: youtube_analysis_tool: result={result}")

                return result
            except Exception as e:
                if attempt == 0 and AITools._is_rate_limit_error(e):
                    print(f"โš ๏ธ AITools: youtube_analysis_tool: Daily rate limit hit with {model}, falling back to {LLM_FALLBACK}")
                    model = LLM_FALLBACK
                    continue
                print(f"โš ๏ธ AITools: youtube_analysis_tool: exception={str(e)}")
                raise RuntimeError(f"Processing failed: {str(e)}")
    
    @tool("Document Analysis Tool")
    def document_analysis_tool(question: str, file_path: str) -> str:
        """Given a question and document file, analyze the document to answer the question.
    
        Args:
            question (str): Question about a document file
            file_path (str): The document file path
            
        Returns:
            str: Answer to the question about the document file
            
        Raises:
            RuntimeError: If processing fails
        """
        print("")
        print(f"๐Ÿ› ๏ธ AITools: document_analysis_tool: question={question}, file_path={file_path}")

        client = AITools._get_client()
        model = LLM_DOCUMENT_ANALYSIS
        
        for attempt in range(2):
            try:
                contents = []
                
                if is_ext(file_path, ".docx"):
                    text_data = read_docx_text(file_path)
                    contents = [f"{question}\n{text_data}"]
                    print(f"๐Ÿ› ๏ธ Text data:\n{text_data}")
                elif is_ext(file_path, ".pptx"):
                    text_data = read_pptx_text(file_path)
                    contents = [f"{question}\n{text_data}"]
                    print(f"๐Ÿ› ๏ธ Text data:\n{text_data}")
                else:
                    file = client.files.upload(file=file_path)
                    contents = [file, question]
                
                config_params = {}

                if model != LLM_FALLBACK:
                    config_params["thinking_config"] = types.ThinkingConfig(
                        thinking_level=THINKING_LEVEL_DOCUMENT_ANALYSIS
                    )

                response = client.models.generate_content(
                    model=model,
                    contents=contents,
                    config=types.GenerateContentConfig(**config_params)
                )
              
                result = response.text
                
                print(f"๐Ÿ› ๏ธ AITools: document_analysis_tool: model={model}")
                if model != LLM_FALLBACK:
                    print(f"๐Ÿ› ๏ธ AITools: document_analysis_tool: thinking_level={THINKING_LEVEL_DOCUMENT_ANALYSIS}")
                print(f"๐Ÿ› ๏ธ AITools: document_analysis_tool: result={result}")
                
                return result
            except Exception as e:
                if attempt == 0 and AITools._is_rate_limit_error(e):
                    print(f"โš ๏ธ AITools: document_analysis_tool: Daily rate limit hit with {model}, falling back to {LLM_FALLBACK}")
                    model = LLM_FALLBACK
                    continue
                print(f"โš ๏ธ AITools: document_analysis_tool: exception={str(e)}")
                raise RuntimeError(f"Processing failed: {str(e)}")
    
    @tool("Code Generation and Execution Tool")
    def code_generation_and_execution_tool(question: str, json_data: str) -> str:
        """Given a question and JSON data, generate and execute code to answer the question.
        Args:
            question (str): Question to answer
             file_path (str): The JSON data

        Returns:
            str: Answer to the question
           
        Raises:
            RuntimeError: If processing fails
        """
        print("")
        print(f"๐Ÿ› ๏ธ AITools: code_generation_and_execution_tool: question={question}, json_data={json_data}")

        client = AITools._get_client()
        model = LLM_CODE_GENERATION
        
        for attempt in range(2):
            try:
                config_params = {"tools": [types.Tool(code_execution=types.ToolCodeExecution)]}

                if model != LLM_FALLBACK:
                    config_params["thinking_config"] = types.ThinkingConfig(
                        thinking_level=THINKING_LEVEL_CODE_GENERATION
                    )

                response = client.models.generate_content(
                    model=model,
                    contents=[f"{question}\n{json_data}"],
                    config=types.GenerateContentConfig(**config_params),
                )

                result = AITools._extract_execution_result(response)

                print(f"๐Ÿ› ๏ธ AITools: code_generation_and_execution_tool: model={model}")
                if model != LLM_FALLBACK:
                    print(f"๐Ÿ› ๏ธ AITools: code_generation_and_execution_tool: thinking_level={THINKING_LEVEL_CODE_GENERATION}")
                print(f"๐Ÿ› ๏ธ AITools: code_generation_and_execution_tool: result={result}")

                return result
            except Exception as e:
                if attempt == 0 and AITools._is_rate_limit_error(e):
                    print(f"โš ๏ธ AITools: code_generation_and_execution_tool: Daily rate limit hit with {model}, falling back to {LLM_FALLBACK}")
                    model = LLM_FALLBACK
                    continue
                print(f"โš ๏ธ AITools: code_generation_and_execution_tool: exception={str(e)}")
                raise RuntimeError(f"Processing failed: {str(e)}")

    @tool("Code Execution Tool")
    def code_execution_tool(question: str, file_path: str) -> str:
        """Given a question and Python file, execute the file to answer the question.
    
        Args:
            question (str): Question to answer
            file_path (str): The Python file path
            
        Returns:
            str: Answer to the question
            
        Raises:
            RuntimeError: If processing fails
        """
        print("")
        print(f"๐Ÿ› ๏ธ AITools: code_execution_tool: question={question}, file_path={file_path}")

        client = AITools._get_client()
        model = LLM_CODE_EXECUTION
        
        for attempt in range(2):
            try:
                file = client.files.upload(file=file_path)

                config_params = {"tools": [types.Tool(code_execution=types.ToolCodeExecution)]}

                if model != LLM_FALLBACK:
                    config_params["thinking_config"] = types.ThinkingConfig(
                        thinking_level=THINKING_LEVEL_CODE_EXECUTION
                    )

                response = client.models.generate_content(
                    model=model,
                    contents=[file, question],
                    config=types.GenerateContentConfig(**config_params),
                )

                result = AITools._extract_execution_result(response)

                print(f"๐Ÿ› ๏ธ AITools: code_execution_tool: model={model}")
                if model != LLM_FALLBACK:
                    print(f"๐Ÿ› ๏ธ AITools: code_execution_tool: thinking_level={THINKING_LEVEL_CODE_EXECUTION}")
                print(f"๐Ÿ› ๏ธ AITools: code_execution_tool: result={result}")

                return result
            except Exception as e:
                if attempt == 0 and AITools._is_rate_limit_error(e):
                    print(f"โš ๏ธ AITools: code_execution_tool: Daily rate limit hit with {model}, falling back to {LLM_FALLBACK}")
                    model = LLM_FALLBACK
                    continue
                print(f"โš ๏ธ AITools: code_execution_tool: exception={str(e)}")
                raise RuntimeError(f"Processing failed: {str(e)}")

    @tool("Image to FEN Tool")
    def img_to_fen_tool(question: str, file_path: str, active_color: str) -> str:
        """Given a chess question, image file, and active color, return the FEN.
    
        Args:
            question (str): The chess question
            file_path (str): The image file path
            active_color (str): The active color
            
        Returns:
            str: FEN of the chess position
            
        Raises:
            RuntimeError: If processing fails
        """
        print("")
        print(f"๐Ÿ› ๏ธ AITools: img_to_fen_tool: question={question}, file_path={file_path}, active_color={active_color}")

        client = AITools._get_client()
        model = LLM_IMAGE_TO_FEN
        
        for attempt in range(2):
            try:         
                with open(file_path, "rb") as f:
                    img_bytes = f.read()
                    img_b64 = base64.b64encode(img_bytes).decode("ascii")
                
                prompt = PROMPT_IMG_TO_FEN.format(question=question, active_color=active_color)

                content = types.Content(
                    parts=[
                        types.Part(text=prompt),
                        types.Part(
                            inline_data=types.Blob(
                                mime_type="image/png",
                                data=base64.b64decode(img_b64),
                            )
                        )
                    ]
                )

                config_params = {}

                if model != LLM_FALLBACK:
                    config_params["thinking_config"] = types.ThinkingConfig(
                        thinking_level=THINKING_LEVEL_IMAGE_TO_FEN
                    )

                response = client.models.generate_content(
                    model=model,
                    contents=[content],
                    config=types.GenerateContentConfig(**config_params)
                )

                result = None

                for part in response.parts:
                    if part.text is not None:
                        result = part.text
                        break

                fen_pattern = r'\b([rnbqkpRNBQKP1-8\/]+\s+[wb]\s+(?:-|[KQkq]+)\s+(?:-|[a-h][36])\s+\d+\s+\d+)\b'

                match = re.search(fen_pattern, result)
                
                if match:
                    result = match.group(1)
                else:
                    lines = result.strip().split("\n")

                    for line in lines:
                        line = line.strip()
                        
                        if "/" in line and (" w " in line or " b " in line):
                            result = line
                            break
                
                board = chess.Board(result) # FEN validation

                print(f"๐Ÿ› ๏ธ AITools: img_to_fen_tool: model={model}")
                if model != LLM_FALLBACK:
                    print(f"๐Ÿ› ๏ธ AITools: img_to_fen_tool: thinking_level={THINKING_LEVEL_IMAGE_TO_FEN}")
                print(f"๐Ÿ› ๏ธ AITools: img_to_fen_tool: result={result}")

                return result
            except Exception as e:
                if attempt == 0 and AITools._is_rate_limit_error(e):
                    print(f"โš ๏ธ AITools: img_to_fen_tool: Daily rate limit hit with {model}, falling back to {LLM_FALLBACK}")
                    model = LLM_FALLBACK
                    continue
                print(f"โš ๏ธ AITools: img_to_fen_tool: exception={str(e)}")
                raise RuntimeError(f"Processing failed: {str(e)}")

    @tool("Algebraic Notation Tool")
    def algebraic_notation_tool(question: str, file_path: str, position_evaluation: str) -> str:
        """Given a chess question, image file, and position evaluation in UCI notation, answer the question in algebraic notation.
    
        Args:
            question (str): The chess question
            file_path (str): The image file path
            position_evaluation (str): The position evaluation in UCI notation
            
        Returns:
            str: Answer to the question in algebraic notation
            
        Raises:
            RuntimeError: If processing fails
        """
        print("")
        print(f"๐Ÿ› ๏ธ AITools: algebraic_notation_tool: question={question}, file_path={file_path}, position_evaluation={position_evaluation}")

        client = AITools._get_client()
        model = LLM_ALGEBRAIC_NOTATION
        
        for attempt in range(2):
            try:
                with open(file_path, "rb") as f:
                    img_bytes = f.read()
                    img_b64 = base64.b64encode(img_bytes).decode("ascii")
                
                prompt = PROMPT_ALGEBRAIC_NOTATION.format(question=question, position_evaluation=position_evaluation)

                content = types.Content(
                    parts=[
                        types.Part(text=prompt),
                        types.Part(
                            inline_data=types.Blob(
                                mime_type="image/png",
                                data=base64.b64decode(img_b64),
                            )
                        )
                    ]
                )
                
                config_params = {}

                if model != LLM_FALLBACK:
                    config_params["thinking_config"] = types.ThinkingConfig(
                        thinking_level=THINKING_LEVEL_ALGEBRAIC_NOTATION
                    )

                response = client.models.generate_content(
                    model=model,
                    contents=[content],
                    config=types.GenerateContentConfig(**config_params)
                )

                result = None
                
                for part in response.parts:
                    if part.text is not None:
                        result = part.text
                        break

                print(f"๐Ÿ› ๏ธ AITools: algebraic_notation_tool: model={model}")
                if model != LLM_FALLBACK:
                    print(f"๐Ÿ› ๏ธ AITools: algebraic_notation_tool: thinking_level={THINKING_LEVEL_ALGEBRAIC_NOTATION}")
                print(f"๐Ÿ› ๏ธ AITools: algebraic_notation_tool: result={result}")

                return result
            except Exception as e:
                if attempt == 0 and AITools._is_rate_limit_error(e):
                    print(f"โš ๏ธ AITools: algebraic_notation_tool: Daily rate limit hit with {model}, falling back to {LLM_FALLBACK}")
                    model = LLM_FALLBACK
                    continue
                print(f"โš ๏ธ AITools: algebraic_notation_tool: exception={str(e)}")
                raise RuntimeError(f"Processing failed: {str(e)}")

    def final_answer_tool(question: str, answer: str) -> str:
        """Given a question and initial answer, get the final answer.
    
        Args:
            question (str): The question
            answer (str): The initial answer
            
        Returns:
            str: Final answer
            
        Raises:
            RuntimeError: If processing fails
        """
        print("")
        print(f"๐Ÿ› ๏ธ AITools: final_answer_tool: question={question}, answer={answer}")

        client = AITools._get_client()
        model = LLM_FINAL_ANSWER
        
        for attempt in range(2):
            try:
                prompt = PROMPT_FINAL_ANSWER.format(question=question, answer=answer)

                config_params = {}

                if model != LLM_FALLBACK:
                    config_params["thinking_config"] = types.ThinkingConfig(
                        thinking_level=THINKING_LEVEL_FINAL_ANSWER
                    )

                response = client.models.generate_content(
                    model=model, 
                    contents=[prompt],
                    config=types.GenerateContentConfig(**config_params)
                )
        
                result = response.text.strip()

                print(f"๐Ÿ› ๏ธ AITools: final_answer_tool: model={model}")
                if model != LLM_FALLBACK:
                    print(f"๐Ÿ› ๏ธ AITools: final_answer_tool: thinking_level={THINKING_LEVEL_FINAL_ANSWER}")
                print(f"๐Ÿ› ๏ธ AITools: final_answer_tool: result={result}")
                
                return result
            except Exception as e:
                if attempt == 0 and AITools._is_rate_limit_error(e):
                    print(f"โš ๏ธ AITools: final_answer_tool: Daily rate limit hit with {model}, falling back to {LLM_FALLBACK}")
                    model = LLM_FALLBACK
                    continue
                print(f"โš ๏ธ AITools: final_answer_tool: exception={str(e)}")
                raise RuntimeError(f"Processing failed: {str(e)}")