C"h2ddlZddlZddlmZmZddlmZddlmZddl m Z ej e Z dededefd Zd edeefd Zd eeeefdefd ZdedefdZejeddZejeddZejeddZdefdZe dkrejejde dejds eddS eddZeeZed eed!d"d#d$d%d&d$d'd(d$gZeeZed)edS#e $rZ!ed*e!YdZ![!dSdZ![!wwxYwdS)+N)ListDict) ReActAgent) FunctionTool) GoogleGenAIfilenamedefault_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 : Texc_info) ospathdirname__file__joinopenreadloggerinfoFileNotFoundErrorwarning Exceptionerror)rr script_dir prompt_pathfpromptes ;/Users/aedelon/Workspace/GAIA_Agent/agents/planner_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  objectivecVtd|dddtjdd}tjd}|stdd Sd |d } t |dd }td|||}|j d}g}|D]}|}|s|rU|d r;d|ddvr/| ddd} n4| dr|dd} n|} | r| | |st ddStdt|d|S#t$r.} td| dd| cYd} ~ Sd} ~ wwxYw)z Generate a list of sub-steps (4-8) from the given objective using an LLM. Args: objective (str): The research or task objective. Returns: List[str]: A list of sub-steps as strings, or an error message list. zGenerating plan for objective: Ndz...PLANNER_TOOL_LLM_MODELgemini-2.5-pro-preview-03-25GEMINI_API_KEYz/GEMINI_API_KEY not found for planning tool LLM.z+Error: GEMINI_API_KEY not set for planning.zYou are a research assistant. Given an objective, break it down into a list of 4-8 concise, actionable sub-steps. Ensure the steps are logically ordered. Objective: z$ Sub-steps (one per line, numbered):皙?api_keymodel temperaturezUsing planning LLM:  r.z- z-LLM generated no sub-steps for the objective.z$Error: Failed to generate sub-steps.z Generated z sub-steps.z!LLM call failed during planning: TrzError during planning: )rrrgetenvrrcompletetextstripsplitisdigit startswithappendrlenr) r$planner_llm_modelgemini_api_key input_promptllmresponselines sub_stepsliner6r!s r"planrE!sn KKF)DSD/FFFGGG ":+<>>???<< -- ##%%++D11  ' 'D::<r?r@rAr!s r"synthesize_and_reportrR^s KKHS\\HHHIII 4CDDD33Nw''TT 6::j-!A#--88H&;<<SacSSXSS!SSvSSSSI&=?]^^Y/00N > GHHH==     L..8Vdhiii C,ACCDDD<< -- +,,,} ... =!== MMM-!--------.s A$E00 F(:#F#F(#F(questionc(td|ddtjd}|stddStjdd}d |d } t |dd }td |||}td|jS#t$r.}td|dd|cYd}~Sd}~wwxYw)a Answer any question by following this strict format: 1. Include your chain of thought (your reasoning steps). 2. End your reply with the exact template: FINAL ANSWER: [YOUR FINAL ANSWER] YOUR FINAL ANSWER must be: - A number, or - As few words as possible, or - A comma-separated list of numbers and/or strings. Formatting rules: * If asked for a number, do not use commas or units (e.g., $, %), unless explicitly requested. * If asked for a string, do not include articles or abbreviations (e.g., city names), and write digits in plain text. * If asked for a comma-separated list, apply the above rules to each element. This tool should be invoked immediately after completing the final planning sub-step. zAnswering question: Nr&r)z0GEMINI_API_KEY not set for answer_question tool.zError: GEMINI_API_KEY not set.ANSWER_TOOL_LLM_MODELr(aBYou are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use commas for thousands or any units like $ or % unless specified. If you are asked for a string, omit articles and abbreviations, and write digits in plain text. If you are asked for a comma separated list, apply these rules to each element. Question: z Answer:r*r+zUsing answer LLM: zAnswer generated successfully.z*LLM call failed during answer generation: Trz Error during answer generation: ) rrrr4rrr5r6r)rSr> model_nameassistant_promptr@rAr!s r"answer_questionrXsH  KK7x~77888Y/00N 0 GHHH//24RSSJ    6.8Vdhiii 555666<< 011 4555} 666 E!EEPT UUU5!555555556s4A$C D##D D DrRzAggregates results from multiple sub-steps into a final coherent report. Input: results (List[Dict[str, str]]) where each dict has "sub_step" and "answer". Output: A unified report (str) or error message.)fnname descriptiongenerate_substepsuDecomposes a high-level objective into a concise roadmap of 4–8 actionable sub-steps using an LLM. Input: objective (str). Output: List of sub-step strings (List[str]) or error list.rXuAnswers any question and returns the full text, always ending with ‘FINAL ANSWER: ...’ in accordance with the formatting rules.ctdtjdd}tjd}|s)tdt d t |dd}td |d }td |}||krtd ttg}gd }tdd||||}td|S#t$r%}td|dd}~wwxYw)zInitializes the Planner Agent.zInitializing PlannerAgent...PLANNER_AGENT_LLM_MODELr(r)z*GEMINI_API_KEY not found for PlannerAgent.z+GEMINI_API_KEY must be set for PlannerAgentr*r+zUsing agent LLM: zFYou are PlannerAgent... [Default prompt content - replace with actual]z#../prompts/planner_agent_prompt.txtz6Using default/fallback system prompt for PlannerAgent.) code_agentresearch_agent math_agent role_agentimage_analyzer_agenttext_analyzer_agentreasoning_agentlong_context_management_agentadvanced_validation_agentvideo_analyzer_agent planner_agentzStrategically plans tasks by breaking down objectives into sub-steps using `generate_substeps`. Orchestrates execution by handing off sub-steps to specialized agents. Synthesizes final results using `synthesize_and_report`.)rZr[toolsr@ system_promptcan_handoff_toz&PlannerAgent initialized successfully.z*Error during PlannerAgent initialization: TrN) rrrr4r ValueErrorrr#rgenerate_substeps_toolsynthesize_toolrr) agent_llm_modelr>r@default_system_promptrkrjvalid_handoffsagentr!s r"initialize_planner_agentrtsz KK.///i 9;YZZOY/00N H ABBBFGGG-.8Vdhiii 999:::"j-.SUjkk 1 1 1 ^^T U U U(9     K')      <===  E!EEPT UUU s0B#D E D>>E__main__z4%(asctime)s - %(name)s - %(levelname)s - %(message)s)levelformatz0Running planner_agent.py directly for testing...r)zDError: GEMINI_API_KEY environment variable not set. Cannot run test.z Testing plan generation...zCAnalyze the market trends for electric vehicles in Europe for 2024.zGenerated Sub-steps: z Testing synthesis...z(Identify key EV manufacturers in Europe.zTesla, VW, Stellantis, Renault.)rIrJzFind recent sales data.z,EV sales grew 25% year-over-year in Q1 2024.zAnalyze government incentives.z2Germany reduced subsidies, France maintained them.zSynthesized Report: zError during testing: )"rloggingtypingrrllama_index.core.agent.workflowrllama_index.core.toolsrllama_index.llms.google_genair getLogger__name__rstrr#rErRrX from_defaultsrornrt basicConfigINFOrr4printtest_objectivesubsteps test_resultsreportrr!r"rs 666666//////555555  8 $ $C&;-C;-DI;-;-;-;-z/.4S#X#7/.C/./././.b/6c/6c/6/6/6/6d-,,  ; 43  ^ -,,  K 9*9999x zGgl3ijjjj KKBCCC 29% & &0 TUUUUU 0 E0 1 1 1bNtN++H E5855 6 6 6 E* + + +GStuu6Bpqq=I}~~L +*<88F E2&22 3 3 3 3 3  0 0 0 E.1.. / / / / / / / / / 0;s8AEE0E++E0