a!hn(ddlZddlZddlZddlmZmZddlmZddlm Z ddl m Z ddl m Z ddlmZddlmZdd lmZdd lmZdd lmZejeZGd d ZdadZdefdZedkrejej de!dej"ds e#ddS eZ$e#ddS#e%$rZ&e#de&YdZ&[&dSdZ&[&wwxYwdS)N)DocumentVectorStoreIndex) ReActAgent)QueryFusionRetriever) FUSION_MODES) FunctionTool)HuggingFaceEmbedding)SentenceSplitter)SentenceTransformerRerank) GoogleGenAI) BM25Retrieverc0eZdZdZdedefdZdefdZdS)RoleAgentInitializerctdtjdd|_tjdd|_tjdd|_tjdd |_tjd |_|js)t d td  td |jt|j|_ td|jt|jd|_td|jtj|jdtdfdt#t%D}t'dd}tdt)j||j d|g}tdtdt-j|jd }|d!}td"t5||gdt6jd#|_td$dS#t<$r%}t d%|d&d}~wwxYw)'Nz#Initializing RoleAgent resources...ROLE_EMBED_MODELz'Snowflake/snowflake-arctic-embed-l-v2.0ROLE_RERANKER_MODELz*Alibaba-NLP/gte-multilingual-reranker-baseROLE_PROMPT_DATASETzfka/awesome-chatgpt-promptsROLE_LLM_MODELzgemini-2.5-pro-preview-03-25GEMINI_API_KEYz2GEMINI_API_KEY not found in environment variables.zGEMINI_API_KEY must be setzLoading embed model: ) model_namezLoading reranker model: )modeltop_nzLoading dataset: train)splitz-Converting dataset to LlamaIndex Documents...c g|]T}tddd|dd|gdd|iUS) zAct: actzPrompt: prompt)textmetadata)rjoin).0iprompts_datasets 8/Users/aedelon/Workspace/GAIA_Agent/agents/role_agent.py z1RoleAgentInitializer.__init__..9s   ; 6q 9;;A?8#?    ) chunk_size chunk_overlapz-Building vector index (this may take time)...T) embed_model show_progresstransformationszVector index built.zBuilding BM25 retriever...)docstoresimilarity_top_k)r2z"Building query fusion retriever...)r2modeverbosez-RoleAgent resources initialized successfully.z0Error during RoleAgent resource initialization: exc_info)loggerinfoosgetenvembed_model_namereranker_model_name dataset_namellm_model_namegemini_api_keyerror ValueErrorr r-r rerankerdatasets load_datasetrangelenr rfrom_documentsr from_defaultsr1 as_retrieverrrRECIPROCAL_RANK retriever Exception)self documentssplitterindexbm25_retrievervector_retrieverer%s @r&__init__zRoleAgentInitializer.__init__s 9::: " *<>g h h#%9-BDp#q#q I&;=Z[[ i(8:XYY i(899" ; LLM N N N9:: :8  KKG0EGG H H H3t?TUUUD  KKM43KMM N N N5.DM KK?D,=?? @ @ @&3D4EWUUUO KKG H H H    s?3344   I(3bIIIH KKG H H H$3 ,"!) E KK- . . . KK4 5 5 5*8!"N %1111EE  KK< = = =1!>2!"!1 DN KKG H H H H H    LLOAOOZ^L _ _ _  sG>K K= K88K=queryreturnctd|ddd |j|}|j||}|rTdd|ddD}td t|d |Std d S#t$r.}t d |dd|cYd}~Sd}~wwxYw)a Instance method to retrieve and return detailed role or task information. Uses the retriever and reranker initialized in this class instance. Args: query (str): The user query describing the desired role, task, or prompt context. Returns: str: A string containing the assigned role/task description, or a message indicating no matching prompt was found. z)Role prompt retriever called with query: Ndz...) query_strz c6g|]}|S) get_content)r#nodes r&r'zERoleAgentInitializer.role_prompt_retriever_method..rs$/d/d/dt0@0@0B0B/d/d/dr(rzRetrieved and reranked z results. Returning top 3.z.No matching role prompt found after reranking.zNo matching role prompt found.z$Error during role prompt retrieval: Tr5zError retrieving role prompt: ) r7r8rKretrieverBpostprocess_nodesr"rFwarningrLr@)rMrUresultsreranked_resultstop_results_textrSs r&role_prompt_retriever_methodz1RoleAgentInitializer.role_prompt_retriever_methodcs7  Pdsd PPPQQQ 8n--e44G#}>>wRW>XX  8#);;/d/dO_`bab`bOc/d/d/d#e#e  gc:J6K6Kggghhh''OPPP77 8 8 8 LLCCCdL S S S7A77 7 7 7 7 7 7 8s$B C4C D#D=DDctdtj|jdd}d}t |j|jd}tdd |g||d g }td |S) zACreates and returns the configured ReActAgent for role selection.z)Creating RoleAgent ReActAgent instance...role_prompt_retrieverzxRetrieve and summarize the top three role or task prompts for a query using BM25 and embedding retrieval with reranking.)fnname descriptionu You are RoleAgent, an expert context‐setter that interprets user inputs and deterministically assigns the most fitting persona or task schema to guide downstream agents. For every query: 1. **Interpret Intent**: Parse the user’s instruction to understand their goal, domain, and required expertise. 2. **Retrieve & Rank**: Use the `role_prompt_retriever` tool to fetch the top role descriptions relevant to the intent. 3. **Select Role**: Based *only* on the retrieved results, choose the single best‐matching persona (e.g. “Developer Assistant,” “SEO Strategist,” “Translation Engine,” “Terminal Emulator”) without asking the user any follow-up. If no relevant role is found, state that clearly. 4. **Respond**: Output in plain text with: - **Role**: The selected persona (or "None Found"). - **Reason**: Briefly explain why this role was chosen based *only* on the retrieved text. - **Prompt**: The corresponding role prompt from the retrieved text to be used by downstream agents (or "N/A" if none found). 5. **Hand-Off**: Immediately after including the chosen prompt (or N/A) in your response, invoke `planner_agent` to begin breaking down the user’s request into actionable sub-questions. Always conclude your response with the full prompt for the next agent (or "N/A") and the invocation instruction for `planner_agent`. g?)api_keyr temperature role_agentuRoleAgent selects the most appropriate persona or task template based on the user’s query. By evaluating the question’s intent and context using a specialized retriever, it chooses or refines a prompt that aligns with the best-fitting role—whether developer, analyst, translator, planner, or otherwise—so that subsequent agents can respond effectively under the optimal role context. planner_agent)rhritoolsllm system_promptcan_handoff_toz&RoleAgent ReActAgent instance created.) r7r8rrHrdr r?r>r)rMrole_prompt_retriever_toolrproagents r& get_agentzRoleAgentInitializer.get_agent|s ?@@@&2%?0(U& & & " '%    \ ..'+,      <=== r(N)__name__ __module__ __qualname__rTstrrdrrtr[r(r&rrsdFFFP8#8#888821:111111r(rcnt(tdtatS)Nz6Instantiating RoleAgentInitializer for the first time.) _role_agent_initializer_instancer7r8rr[r(r&get_initializerr{s-'/ LMMM+?+A+A( ++r(rVcztdt}|S)zsInitializes and returns the Role Agent. Uses a singleton pattern to ensure resources are loaded only once. zinitialize_role_agent called.)r7r8r{rt) initializers r&initialize_role_agentr~s4 KK/000!##K  " ""r(__main__z4%(asctime)s - %(name)s - %(levelname)s - %(message)s)levelformatz-Running role_agent.py directly for testing...rzDError: GEMINI_API_KEY environment variable not set. Cannot run test.z0Role Agent initialized successfully for testing.zError during testing: )'r9loggingrCllama_index.corerrllama_index.core.agent.workflowrllama_index.core.retrieversr,llama_index.core.retrievers.fusion_retrieverrllama_index.core.toolsr"llama_index.embeddings.huggingfacer llama_index.core.node_parserr llama_index.core.postprocessorr llama_index.llms.google_genair llama_index.retrievers.bm25r getLoggerrur7rrzr{r~ basicConfigINFOr8r:print test_agentrLrSr[r(r&rs8 77777777666666<<<<<<EEEEEE//////CCCCCC999999DDDDDD555555555555  8 $ $SSSSSSSSp$( ,,,#z#### zGgl3ijjjj KK?@@@ 29% & & 0 TUUUUU 0..00J ED E E E E E 0 0 0 E.1.. / / / / / / / / / 0sCC8C33C8