}"h9:ddlZddlZddlmZmZddlmZddlmZddl m Z ddl m Z ddl Z e jejeZdeded efd Zd ed efd Zejed dZ e ZeZes ededeDdZe ededn3#e$r+Ze dedededZ[wwxYwd efdZ!edkrej"ej#deddej$ddgZ%d e%DZ&e&r$e'd!d"(e&d#dS e!Z)e'd$dS#e$rZe'd%eYdZ[dSdZ[wwxYwdS)&N) CodeActAgent ReActAgent) FunctionTool) GoogleGenAI)OpenAI)CodeInterpreterToolSpecfilenamedefault_promptreturnc tjt}tj||}t |d5}|}td||cdddS#1swxYwYdS#t$r&t d|d|d|cYSt$r.}t d|d|d |cYd}~Sd}~wwxYw) z Loads a prompt from a text file.rz Successfully loaded prompt from Nz Prompt file z not found at z. Using default.zError loading prompt file z: Texc_info) ospathdirname__file__joinopenreadloggerinfoFileNotFoundErrorwarning Exceptionerror)r r script_dir prompt_pathfpromptes 8/Users/aedelon/Workspace/GAIA_Agent/agents/code_agent.pyload_prompt_from_filer#sl W__X.. gll:x88 +s # # qVVXXF KKH;HH I I I                   [h[[k[[[\\\  A(AAaAAD QQQsHAB#3B B#BB#BB##-D  D #D>D D r cFtd|dddtjdd}tjd}|st dd }t d |}|| } t||d d d}td|||}td|j S#t$r%}t d|dd}~wwxYw)aq Generate valid Python code from a natural language description using a configured LLM. Args: prompt (str): A clear description of the desired Python code functionality. Returns: str: A string containing the generated Python code. Raises: ValueError: If required API key is not set. Exception: If the LLM call fails. z#Generating Python code for prompt: Ndz...CODE_GEN_LLM_MODELzo4-miniOPENAI_API_KEYz/OPENAI_API_KEY environment variable is not set.a"You are a helpful assistant that writes Python code. You will be given a prompt and you must generate Python code based on that prompt. You must only generate Python code and nothing else. Do not include any explanations or any other text. Do not use any markdown. Prompt: {prompt} Code: z../prompts/code_gen_prompt.txt)r high皙?i@)modelapi_keyreasoning_effort temperature max_tokenszUsing code generation LLM: zCode generation successful.z(LLM call failed during code generation: Tr) rrrgetenv ValueErrorr#formatrcompletetextrr) r gen_llm_model gen_api_keydefault_gen_prompt_templategen_prompt_template input_promptllmgenerated_coder!s r"generate_python_coder;"sK KKGfTcTlGGGHHHI2I>>M),--K LJKKK$-00PRmnn&--V-<).0ts r" rEes1!m!mqzZlGlGl!GlGlGlGl!m!mzJCould not find 'code_interpreter' tool in CodeInterpreterToolSpec results.z1CodeInterpreterToolSpec initialized successfully.z.Failed to initialize CodeInterpreterToolSpec: TrzGCodeInterpreterToolSpec failed to initialize. Cannot create code_agent.c Dtdtjdd}tjd}|s)tdt d t ||d}td |d }td |}td d ttg||ddg}td|S#t$r%}td|dd}~wwxYw)zAInitializes the CodeActAgent, configured for safe code execution.zInitializing CodeAgent...CODE_AGENT_LLM_MODELzgemini-2.5-pro-preview-03-25GEMINI_API_KEYz@GEMINI_API_KEY not found in environment variables for CodeAgent.z(GEMINI_API_KEY must be set for CodeAgentr))r+r*r-zUsing agent LLM: u You are CodeAgent, a specialist in generating and executing Python code. Your mission: 1. **Thought**: Think step-by-step before acting and state your reasoning. 2. **Code Generation**: To produce code, call `python_code_generator` with a concise, unambiguous prompt. Review the generated code for correctness and safety. 3. **Execution & Testing**: To execute or test code, call `code_interpreter`. Provide the complete code snippet. Analyze its output (stdout, stderr, result) to verify functionality and debug errors. 4. **Iteration**: If execution fails or the result is incorrect, analyze the error, think about the fix, generate corrected code using `python_code_generator`, and execute again using `code_interpreter`. 5. **Tool Use**: Always adhere strictly to each tool’s input/output format. 6. **Final Output**: Once the code works correctly and achieves the goal, output *only* the final functional code or the final execution result, as appropriate for the task. 7. **Hand-Off**: If further logical reasoning or verification is needed, delegate to **reasoning_agent**. Otherwise, pass your final output to **planner_agent** for synthesis. **Special Instructions for Chess-Related Tasks**: - Prioritize using the Stockfish engine to solve chess problems. Ubuntu installation: `sudo apt-get install stockfish` so path is `/usr/games/stockfish` - Use `python-chess` to represent boards, generate and validate moves, and parse PGN/FEN. **Available Python Packages**: - beautifulsoup4: HTML/XML parsing and lightweight web scraping - certifi: Mozilla CA bundle for secure TLS/SSL requests - datasets: Hugging Face dataset loading and streaming - dotenv: Load environment variables from .env files - duckdb: In‑process OLAP SQL engine (analytics, Parquet, Arrow) - ffmpeg-python: Wrapper around FFmpeg for audio/video operations - gradio[oauth]: Rapid web‑UI prototyping with optional OAuth - helium: High‑level Selenium / browser automation toolkit - huggingface: Interact with Hugging Face Hub models, datasets, spaces - imageio: Read and write images, GIFs, MP4s, volumes, etc. - matplotlib: 2‑D plotting (figures, axes, annotations) - numpy: N‑dimensional arrays and vectorized math - openai-whisper: Speech‑to‑text transcription - opencv-python: Computer vision, image/video processing - openpyxl: Excel .xlsx read/write, styles, formulas - pandas: DataFrames, time series, CSV/Parquet I/O - pyarrow: Apache Arrow tables, Parquet, Flight RPC - pygame: Simple 2‑D game/graphics engine (SDL based) - python-chess: Chess move generation, PGN/FEN handling, engine UCI integration - requests: HTTP/HTTPS client with sessions and retries - scikit-learn: Machine‑learning algorithms, preprocessing, pipelines - scipy: Scientific computing, optimization, signal processing - seaborn: Statistical visualization on top of matplotlib - sqlalchemy: SQL ORM and core engine for many databases - statsmodels: Econometrics and statistical modeling (GLM, ARIMA) - stockfish: UCI interface to Stockfish chess engine - sympy: Symbolic math, algebra, calculus CAS - youtube-transcript-api: Fetch YouTube video transcripts via API - yt-dlp: Download videos/playlists from YouTube and other sites zcode_agent_system_prompt.txt code_agentu Generates Python code using `python_code_generator` and executes it safely with `code_interpreter`, then iteratively debugs and refines the code from run-time feedback. The agent can leverage the following pre-installed packages: - beautifulsoup4>=4.13.4 : HTML/XML parsing and lightweight web scraping - certifi>=2025.4.26 : Mozilla CA bundle for secure TLS/SSL requests - datasets>=3.5.1 : Hugging Face dataset loading and streaming - dotenv>=0.9.9 : Load environment variables from .env files - duckdb>=1.2.2 : In‑process OLAP SQL engine (analytics, Parquet, Arrow) - ffmpeg-python>=0.2.0 : Wrapper around FFmpeg for audio/video operations - gradio[oauth]>=5.28.0 : Rapid web‑UI prototyping with optional OAuth - helium>=5.1.1 : High‑level Selenium / browser automation toolkit - huggingface>=0.0.1 : Interact with Hugging Face Hub models, datasets, spaces - imageio>=2.37.0 : Read and write images, GIFs, MP4s, volumes, etc. - matplotlib>=3.10.1 : 2‑D plotting (figures, axes, annotations) - numpy>=2.2.5 : N‑dimensional arrays and vectorized math - openai-whisper>=20240930 : Speech‑to‑text transcription - opencv-python>=4.11.0.86 : Computer vision, image/video processing - openpyxl>=3.1.5 : Excel .xlsx read/write, styles, formulas - pandas>=2.2.3 : DataFrames, time series, CSV/Parquet I/O - pyarrow>=20.0.0 : Apache Arrow tables, Parquet, Flight RPC - pygame>=2.6.1 : Simple 2‑D game/graphics engine (SDL based) - python-chess>=1.999 : Chess move generation, PGN/FEN handling, engines - requests>=2.32.3 : HTTP/HTTPS client with sessions and retries - scikit-learn>=1.6.1 : Machine‑learning algorithms, preprocessing, pipelines - scipy>=1.15.2 : Scientific computing, optimization, signal processing - seaborn>=0.13.2 : Statistical visualization on top of matplotlib - sqlalchemy>=2.0.40 : SQL ORM and core engine for many databases - statsmodels>=0.14.4 : Econometrics and statistical modeling (GLM, ARIMA) - stockfish==3.28.0 : UCI interface to Stockfish chess engine - sympy>=1.14.0 : Symbolic math, algebra, calculus CAS - youtube-transcript-api>=1.0.3 : Fetch YouTube video transcripts via API - yt-dlp>=2025.3.31 : Download videos/playlists from YouTube and other sites Additionally, the `stockfish` package enables the agent to solve chess problems by analyzing positions, identifying tactical motifs, and calculating optimal move sequences, making it a valuable tool for chess training and analysis. planner_agentreasoning_agent)r>r?toolsr9 system_promptcan_handoff_toz#CodeAgent initialized successfully.z'Error during CodeAgent initialization: TrN) rrrr/rr0rr#rpython_code_generator_toolcode_interpreter_toolr)agent_llm_modelgemini_api_keyr9default_system_promptrNagentr!s r"initialize_code_agentrVusZ KK+,,,i 68VWWOY/00N E WXXXCDDDp"!     999:::.!`..LNcdd !RJ+%'+->?[. . . ^  9:::  BqBBT RRR s0A?C00 D: DD__main__z4%(asctime)s - %(name)s - %(levelname)s - %(message)s)levelr1z-Running code_agent.py directly for testing...rICODE_GEN_API_KEY_ENVALPAFLOW_OPENAI_API_KEYc:g|]}tj||S)rr/)rCkeys r" r^s%GGGC #GCGGGrFz1Error: Required environment variable(s) not set: z, z. Cannot run test.z0Code Agent initialized successfully for testing.zError during testing: )*rloggingllama_index.core.agent.workflowrrllama_index.core.toolsrllama_index.llms.google_genairllama_index.llms.openair"llama_index.tools.code_interpreterrdotenv load_dotenv getLogger__name__rstrr#r; from_defaultsrPcode_interpreter_spec to_tool_listcode_interpreter_tools RuntimeErrornextrQrrr!rrV basicConfigINFOr/ required_keys missing_keysprintr test_agentr\rFr"rvsA DDDDDDDD//////555555******FFFFFF   8 $ $C"------b8\7  < i33552??AA !PlNOOO D!m!m-C!m!m!mostt$|hii i KKCDDDDiii LLE!EEPTLUUU ,` a aghh i|z||||~ zGgl3ijjjj KK?@@@&yry1GIb'c'cdMGG=GGGL 0 m$))LBYBYmmmnnnnn 0..00J ED E E E E E 0 0 0 E.1.. / / / / / / / / / 0!s12A#CD&DDFF<#F77F<