File size: 19,830 Bytes
0665120 6ec5ba5 54445b2 0665120 c1f76b3 9f0ce5d 10401bb 0743897 10401bb 20a8abb 10401bb 525d0af e9ea4e6 719ebfc 7757fd2 20a8abb 7757fd2 da6f5ec 2b88e37 525d0af 8f21da5 525d0af dff7f0b ac4bd43 c0b37e6 2b88e37 c0b37e6 4f954bb f062434 4f954bb 5229784 4f954bb 7757fd2 4f954bb 43f6cfc f062434 4f954bb 988c224 4f954bb 43f6cfc b3e2f8f 4f954bb c0b37e6 461be22 f062434 89237eb c0b37e6 4f954bb c0b37e6 10401bb c0b37e6 2fbdec9 7757fd2 2fbdec9 c0b37e6 2fbdec9 43f6cfc f062434 29fc519 c0b37e6 988c224 c0b37e6 461be22 b4335d5 461be22 f062434 89237eb 0743897 ac4bd43 a906357 ac4bd43 191ab68 96f1066 73709a3 43f6cfc a906357 ac4bd43 c0b37e6 988c224 c0b37e6 461be22 4f954bb c0b37e6 461be22 4f954bb c0b37e6 20a8abb c0b37e6 461be22 20a8abb c0b37e6 20a8abb c0b37e6 461be22 20a8abb 461be22 20a8abb 461be22 20a8abb 89237eb c0b37e6 4f954bb c0b37e6 6ec5ba5 20a8abb c0b37e6 2fbdec9 20a8abb 2fbdec9 c0b37e6 43f6cfc 6ec5ba5 20a8abb 6ec5ba5 c0b37e6 20a8abb c0b37e6 461be22 f062434 89237eb c0b37e6 4f954bb c0b37e6 f062434 c0b37e6 f062434 c0b37e6 10401bb 2fbdec9 7757fd2 2fbdec9 c0b37e6 43f6cfc f062434 6ec5ba5 c0b37e6 988c224 c0b37e6 0580b57 c0b37e6 461be22 f062434 89237eb c0b37e6 4f954bb c0b37e6 10401bb c0b37e6 2fbdec9 7757fd2 2fbdec9 c0b37e6 436fe44 4f954bb 6ec5ba5 f062434 6ec5ba5 c0b37e6 988c224 c0b37e6 461be22 1d64dcf f062434 89237eb 1d64dcf 4f954bb 1d64dcf 89237eb 1d64dcf 6c7c564 1d64dcf 7757fd2 1d64dcf 436fe44 4f954bb 6ec5ba5 f062434 6ec5ba5 1d64dcf 988c224 1d64dcf 525d0af bbf983a 1d64dcf 525d0af bbf983a 1d64dcf 525d0af 1d64dcf 461be22 f062434 89237eb 525d0af 4f954bb 525d0af bbf983a b2bb491 525d0af 6c7c564 525d0af 89237eb 525d0af 7757fd2 525d0af 6ec5ba5 525d0af 43f6cfc 525d0af 6ec5ba5 9fd5429 f062434 6ec5ba5 525d0af 988c224 525d0af 1f724b0 6e4221a 92d2a24 525d0af 92d2a24 525d0af 6e4221a 525d0af f062434 89237eb b3e2f8f 4f954bb 525d0af e9ea4e6 5037b00 525d0af c0b37e6 a5ad8ac 525d0af c0b37e6 2fbdec9 7757fd2 2fbdec9 2db2535 c0b37e6 436fe44 c0b37e6 525d0af 43f6cfc 525d0af f062434 6ec5ba5 c0b37e6 988c224 719ebfc 3320f03 f062434 3320f03 b3e2f8f 5a4c17e b3e2f8f 719ebfc b3e2f8f b178f11 f062434 b3e2f8f 988c224 b3e2f8f |
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 |
# References:
# https://docs.crewai.com/introduction
# https://ai.google.dev/gemini-api/docs
import base64, chess, os, 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,
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 _media_analysis_tool(tool_name: str, model: str, question: str, file_path: str) -> str:
print(f"๐ ๏ธ AITools: {tool_name}: question={question}, file_path={file_path}")
try:
client = AITools._get_client()
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)
response = client.models.generate_content(
model=model,
contents=[file, question],
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_level=THINKING_LEVEL_MEDIA_ANALYSIS
)
)
)
result = response.text
print(f"๐ ๏ธ AITools: {tool_name}: result={result}")
return result
except Exception as e:
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(f"๐ ๏ธ AITools: web_search_tool: question={question}")
try:
client = AITools._get_client()
response = client.models.generate_content(
model=LLM_WEB_SEARCH,
contents=question,
config=types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())],
thinking_config=types.ThinkingConfig(
thinking_level=THINKING_LEVEL_WEB_SEARCH
)
)
)
result = response.text
print(f"๐ ๏ธ AITools: web_search_tool: result={result}")
return result
except Exception as e:
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(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: 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(f"๐ ๏ธ AITools: youtube_analysis_tool: question={question}, url={url}")
try:
client = AITools._get_client()
result = client.models.generate_content(
model=LLM_YOUTUBE_ANALYSIS,
contents=types.Content(
parts=[types.Part(file_data=types.FileData(file_uri=url)),
types.Part(text=question)]
),
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_level=THINKING_LEVEL_YOUTUBE_ANALYSIS
)
)
)
print(f"๐ ๏ธ AITools: youtube_analysis_tool: result={result}")
return result
except Exception as e:
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(f"๐ ๏ธ AITools: document_analysis_tool: question={question}, file_path={file_path}")
try:
client = AITools._get_client()
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]
response = client.models.generate_content(
model=LLM_DOCUMENT_ANALYSIS,
contents=contents,
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_level=THINKING_LEVEL_DOCUMENT_ANALYSIS
)
)
)
result = response.text
print(f"๐ ๏ธ AITools: document_analysis_tool: result={result}")
return result
except Exception as e:
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(f"๐ ๏ธ AITools: code_generation_and_execution_tool: question={question}, json_data={json_data}")
try:
client = AITools._get_client()
response = client.models.generate_content(
model=LLM_CODE_GENERATION,
contents=[f"{question}\n{json_data}"],
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution)],
thinking_config=types.ThinkingConfig(
thinking_level=THINKING_LEVEL_CODE_GENERATION
)
),
)
result = AITools._extract_execution_result(response)
print(f"๐ ๏ธ AITools: code_generation_and_execution_tool: result={result}")
return result
except Exception as e:
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(f"๐ ๏ธ AITools: code_execution_tool: question={question}, file_path={file_path}")
try:
client = AITools._get_client()
file = client.files.upload(file=file_path)
response = client.models.generate_content(
model=LLM_CODE_EXECUTION,
contents=[file, question],
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution)],
thinking_config=types.ThinkingConfig(
thinking_level=THINKING_LEVEL_CODE_EXECUTION
)
),
)
result = AITools._extract_execution_result(response)
print(f"๐ ๏ธ AITools: code_execution_tool: result={result}")
return result
except Exception as e:
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(f"๐ ๏ธ AITools: img_to_fen_tool: question={question}, file_path={file_path}, active_color={active_color}")
try:
client = AITools._get_client()
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),
)
)
]
)
response = client.models.generate_content(
model=LLM_IMAGE_TO_FEN,
contents=[content],
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_level=THINKING_LEVEL_IMAGE_TO_FEN
)
)
)
result = None
for part in response.parts:
if part.text is not None:
result = part.text
break
board = chess.Board(result) # FEN validation
print(f"๐ ๏ธ AITools: img_to_fen_tool: result={result}")
return result
except Exception as e:
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(f"๐ ๏ธ AITools: algebraic_notation_tool: question={question}, file_path={file_path}, position_evaluation={position_evaluation}")
try:
client = AITools._get_client()
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),
)
)
]
)
response = client.models.generate_content(
model=LLM_ALGEBRAIC_NOTATION,
contents=[content],
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_level=THINKING_LEVEL_ALGEBRAIC_NOTATION
)
)
)
result = None
for part in response.parts:
if part.text is not None:
result = part.text
break
print(f"๐ ๏ธ AITools: algebraic_notation_tool: result={result}")
return result
except Exception as e:
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(f"๐ ๏ธ AITools: final_answer_tool: question={question}, answer={answer}")
try:
client = AITools._get_client()
prompt = PROMPT_FINAL_ANSWER.format(question=question, answer=answer)
response = client.models.generate_content(
model=LLM_FINAL_ANSWER,
contents=[prompt],
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(
thinking_level=THINKING_LEVEL_FINAL_ANSWER
)
)
)
result = response.text.strip()
print(f"๐ ๏ธ AITools: final_answer_tool: result={result}")
return result
except Exception as e:
print(f"โ ๏ธ AITools: final_answer_tool: exception={str(e)}")
raise RuntimeError(f"Processing failed: {str(e)}") |