C"h W UddlZddlZddlZddlmZmZmZmZmZddl m Z ddl m Z m Z ddlmZddlmZmZmZddlmZddlmZdd lmZejeZd ed ed efd Zdaeee d<da!eee d<da"eee d<dZdeedeed eefdZ#d[deded efdZ$ d\deddee%dee%d efdZ&d]dede%d eeeeffd Z'd^d"ed#e(d efd$Z)ded edzfd%Z*e j+e$d&d'(Z,e j+e&d)d*(Z-e j+e'd+d,(Z.e j+e)d-d.(Z/e j+e*d/d0(Z0d e fd1Z1ed2krej2ej3d34ejd54ej5ejd64ej5ejd74ej6e7d8d9gZ8d:e8DZ9e9r$e:d;d<;e9d=dS d>d?zZ<e:d@e$ee:dGe>e:dHe'dIJZ?e:dKe?e:dLe)dMdNOZ@e:dPe@ddQdRe:dSdTZAe*eAZBe:dUeAdVeBe:dWdXZCe*eCZDe:dUeCdVeDdSdS#eE$rZFe:dYeFYdZF[FdSdZF[FwwxYwdS)_N)ListDictOptionalUnionLiteral) ReActAgent) FunctionToolQueryEngineTool) GoogleGenAI)DocumentVectorStoreIndexSettings)SentenceSplitter)RetrieverQueryEngine)VectorIndexRetrieverfilenamedefault_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)rr script_dir prompt_pathfpromptes K/Users/aedelon/Workspace/GAIA_Agent/agents/long_context_management_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 _context_index _context_text_context_sourceloaded_contexttextsourcec$||tksttdt |d||a|a t dd}|t_ttg}tj |d atd n`#t$r0}t d |d dadadaYd}~dSd}~wwxYwttd dStS)z@Builds or retrieves the VectorStoreIndex for the loaded context.Nz.Building new context index from text (length:  chars). Source: i) chunk_size chunk_overlap)r1T) show_progressz!Context index built successfully.zFailed to build context index: rz%No context loaded or index built yet.)r.r-r r!lenr/rr node_parserr r from_documentsr$r%r#)r1r2splitter documentsr*s r+_build_or_get_indexr>/s+ T]22n6L iSYYiiagiijjj   '4sKKKH#+H !}5556I-1>>L N N N!N M"O44444    >???t sA#B++ C%5%C  C% provided_textctdt|d|t||}|rd|dt|dSdS)zSLoads text into the agent's context and builds an index. Replaces existing context.z"Loading new text context (length: r4)r1r2z2Successfully loaded and indexed text context from z (Length: z chars).z9Error: Failed to load or index the provided text context.)r r!r9r>)r1r2indexs r+load_text_contextrBLsp KKYSYYYYQWYYZZZ T& 9 9 9E KiFiiVYZ^V_V_iiiiJJstandard detail_level)briefrDdetailed max_length min_lengthc ^tdStdtdt td|| |dkrd}|pd}n|d krd }|pd }nd }|pd}|pt |d z}t jdd}t jd}|stddSt}d|d|d|d|d } t|dd}td|| |}|j } tdt | d| S#t$r.} td| dd | cYd} ~ Sd} ~ wwxYw)!aSummarizes the currently loaded long text context. Args: detail_level (str): Level of detail: "brief" (1-2 sentences), "standard" (1-2 paragraphs), "detailed" (multiple paragraphs). max_length (Optional[int]): Approximate maximum words (overrides detail_level if set). min_length (Optional[int]): Approximate minimum words. Returns: str: The summary or an error message. NzJError: No long context has been loaded yet. Use 'load_text_context' first.z$Summarizing loaded context (Source: z , Length: z chars). Detail: rF2 rGir5g333333?CONTEXT_LLM_MODELgemini-2.5-pro-preview-03-25GEMINI_API_KEYz/GEMINI_API_KEY not found for summarization LLM.zError: GEMINI_API_KEY not set.zrSummarize the following text concisely, focusing on the main points and key information. Aim for a length between z and z* words. The requested level of detail is 'z '. TEXT: z SUMMARY:皙?api_keymodel temperaturezUsing summarization LLM: z)Summarization successful (output length: z words).z&LLM call failed during summarization: TrzError during summarization: )r.r r!r/r9intrgetenvr%r completer1stripsplitr$) rErHrI llm_modelgemini_api_keytext_to_summarizer)llmresponsesummaryr*s r+summarize_long_contextraWsI[[ KKFFFRUVcRdRdFFxDFFGGG 7 " "J#)rJJ Z ' 'J#*sJJJ#)rJ4s:#344J -/MNNIY/00N 0 FGGG// & 2$. 2 25? 2 2-9 2 2$ 2 2 2  2.8Vdhiii ; ;;<<<<<''-%%'' ^GMMOO@T@T^^^___ 222 AaAAD QQQ1a111111112sBE44 F,>#F'!F,'F,rLquery max_resultsc$td|d|t}|dS t||dz}t j|}d|}||}d |jd D}|d|}td t|d |r|nd gS#t$r.} t d| dd| cYd} ~ Sd} ~ wwxYw)aExtracts specific information or answers a question based on the loaded long context using the index. Args: query (str): The question or description of information to extract (e.g., "List all decisions made", "What was mentioned about Project X?"). max_results (int): Maximum number of distinct pieces of information or text snippets to return. Returns: List[str]: A list of extracted text snippets or answers, or str: Error message. z"Extracting information for query: z# from loaded context. Max results: NKError: No context loaded or index available. Use 'load_text_context' first.rAsimilarity_top_k) retrieverzBased *only* on the provided context, extract the key information or answer the following query. List distinct findings or provide relevant text snippets. Query: c^g|]*}||+S)rY).0items r+ z+extract_key_information..s2bbbDUYU_U_UaUab4::<<bbbrC zExtraction successful. Found z items.z@No specific information found matching the query in the context.z%Error during information extraction: TrzError during extraction: ) r r!r>rr from_argsrbr_rZr9r$r%) rbrcrAri query_engineextraction_promptr_extracted_items final_resultsr*s r+extract_key_informationrusr KKlUll_jllmmm  ! !E }\\/)u{UVWWW ,5 888 IBGII%%&788 cbH4E4K4KD4Q4Qbbb(  5  OC 4F4FOOOPPP -w}}4v3ww /// @Q@@4 PPP.1......../sB"C D!#D D D?topic thresholdchtd|d|t}|dS t|d}||}g}|D]:}|j|kr-||j:|stddSd |}td t|d |S#t$r.}t d |d d|cYd}~Sd}~wwxYw)aFilters the loaded long context, retaining sections relevant to the topic using the index. Args: topic (str): The topic or query to filter relevance by. threshold (float): Similarity threshold (0.0 to 1.0) for relevance. Higher means more strict. Returns: str: The filtered text containing only relevant sections, or an error message. z1Filtering loaded context for relevance to topic: z . Threshold: Nrergz2No sections found meeting the relevance threshold.zJNo content found matching the specified relevance threshold for the topic.z --- z5Filtering successful. Combined relevant text length: z chars.z"Error during relevance filtering: TrzError during filtering: ) r r!r>rretrievescoreappendnode get_contentrr9r$r%) rwrxrAriretrieved_nodesrelevant_textsnode_with_score filtered_textr*s r+filter_by_relevancerst KKcEccXaccddd  ! !E }\\.(urJJJ #,,U33.  O$ 11%%o&:&F&F&H&HIIII ` KKL M M M__&**>::  gCP]L^L^ggghhh ... =!== MMM-!--------.s%BC97AC99 D1#D,&D1,D1c`td|t}|dS |d}||}|j}tdd|vs,d|vsd |vr"td |d |S|S#t$r.}t d |d d|cYd}~Sd}~wwxYw)aAnswers a specific question based on the information contained within the loaded long context using the index. Args: query (str): The question to answer. Returns: str: The answer derived from the context, or an error/"not found" message. z$Querying loaded context index with: Nre)rhzContext query successful.z don't knowzno informationzcontext does not mentionz/Query response suggests information not found: z;The loaded context does not seem to contain the answer to: zError during context query: TrzError querying context: ) r r!r>as_query_enginerbr_rYlowerr#r$r%)rbrArqr_answerr*s r+query_context_indexrsR KK>u>>???  ! !E }\\ .,,a,@@ %%e,,"((** /000 6<<>> ) )-=-O-OSmqwq}q}qqSS ^^VfVV W W WYRWYY Y ... 7A77$ GGG-!--------.s$CC53C55 D-?#D("D-(D-rBzLoads/replaces the long text context for the agent and builds an internal index. Input: text (str), Optional: source (str). Output: Status message (str).)fnname descriptionrazSummarizes the currently loaded long text context. Input: Optional: detail_level ('brief', 'standard', 'detailed'), max_length (int), min_length (int). Output: Summary (str) or error.ruzExtracts specific information or answers questions from the loaded context using its index. Input: query (str), Optional: max_results (int). Output: List[str] of findings or error string.rzFilters the loaded context to retain only sections relevant to a topic, using the index. Input: topic (str), Optional: threshold (float 0-1). Output: Filtered text (str) or error.rzAnswers a specific question based *only* on the loaded long context using its index. Input: query (str). Output: Answer (str) or error/'not found' message.ctdtjdd}tjd}|s)tdt d t |dd}td ||t_d }td |}||krt d tttttg}gd }t!dd||||}td|S#t"$r%}td|dd}~wwxYw)z.Initializes the Long Context Management Agent.z*Initializing LongContextManagementAgent...CONTEXT_AGENT_LLM_MODELrOrPz8GEMINI_API_KEY not found for LongContextManagementAgent.z9GEMINI_API_KEY must be set for LongContextManagementAgentrQrRzUsing agent LLM: zTYou are LongContextManagementAgent... [Default prompt content - replace with actual]z3../prompts/long_context_management_agent_prompt.txtzDUsing default/fallback system prompt for LongContextManagementAgent.) planner_agenttext_analyzer_agentreasoning_agentresearch_agentlong_context_management_agenta3Manages and processes long textual context efficiently. Handles large documents, transcripts, or datasets by summarizing (`summarize_long_context`), extracting key information (`extract_key_information`), filtering relevant content (`filter_by_relevance`), and answering questions based on the context (`query_context_index`). Supports internal indexing for efficient retrieval and repeated queries. Optimized for chunked input processing and contextual distillation. Only relies on the provided input and avoids external augmentation unless explicitly requested.)rrtoolsr^ system_promptcan_handoff_toz4LongContextManagementAgent initialized successfully.z8Error during LongContextManagementAgent initialization: TrN)r r!rrWr% ValueErrorr rr^r,r#load_context_toolsummarize_context_toolextract_info_toolfilter_context_toolquery_context_toolrr$) agent_llm_modelr\r^default_system_promptrrvalid_handoffsagentr*s r+(initialize_long_context_management_agentr1s KK<===i 9;YZZOY/00N V OPPPTUUU0.8Vdhiii 999::: "x-.cez{{ 1 1 1 ^^b c c c  "        0O ')      JKKK  SPQSS^b ccc s0CD22 E!< EE!__main__z4%(asctime)s - %(name)s - %(levelname)s - %(message)s)levelformatz%llama_index.core.indices.vector_storezllama_index.core.query_enginezllama_index.core.token_counterz@Running long_context_management_agent.py directly for testing...rPc:g|]}tj||Srk)rrW)rlkeys r+rnrn{s%GGGC #GCGGGrCz1Error: Required environment variable(s) not set: z, z. Cannot run test.a Meeting Minutes - Project Phoenix - April 28, 2025 Attendees: Alice, Bob, Charlie, David Agenda: Review Q1 results, Plan Q2 roadmap, Budget allocation Q1 Results Discussion: Alice presented the sales figures. Sales increased by 15% compared to Q4 2024, exceeding the target of 10%. Bob highlighted the success of the marketing campaign launched in February. Customer acquisition cost decreased by 5%. Charlie noted a slight dip in user engagement metrics in March, possibly due to a recent UI change. Action Item: David to investigate the engagement dip. Q2 Roadmap Planning: The team discussed potential features for Q2. Feature A (enhanced reporting) was prioritized. Feature B (mobile app improvements) was deferred to Q3. Alice emphasized the need for stability improvements. Bob suggested focusing on performance optimization. Decision: Q2 focus will be on Feature A and performance/stability improvements. Budget Allocation: Charlie presented the proposed budget. An additional $50,000 was requested for cloud infrastructure scaling due to increased usage. David questioned the necessity of the full amount. After discussion, the team approved an additional $40,000 for infrastructure. Decision: Allocate $40,000 extra for Q2 infrastructure. Next Steps: David to report on engagement metrics by May 5th. Alice to finalize Q2 feature specifications by May 10th. Meeting adjourned. rz Testing load_text_context...zMeeting Minutes Test)r2Errorz* Testing summarize_long_context (brief)...rF)rEzBrief Summary: z/ Testing extract_key_information (decisions)...z&List all decisions made in the meeting)rbzDecisions Extracted: z( Testing filter_by_relevance (budget)...zbudget allocationgffffff?)rwrxz(Filtered Budget Text (first 300 chars): i,z...z* Testing query_context_index (Q1 sales)...z"What was the sales increase in Q1?z Answer to 'z': z3 Testing query_context_index (non-existent info)...zWho is the CEO?zError during testing: )Nr0)r?)rDNN)rL)rv)Grloggingjsontypingrrrrrllama_index.core.agent.workflowrllama_index.core.toolsr r llama_index.llms.google_genair llama_index.corer r rllama_index.core.node_parserrllama_index.core.query_enginerllama_index.core.retrieversr getLogger__name__r strr,r-__annotations__r.r/r>rBrVrarufloatrr from_defaultsrrrrrr basicConfigINFOsetLevelWARNINGERRORr! required_keys missing_keysprintr long_text load_status summary_brief decisions budget_text sales_query sales_answernon_existent_querynon_existent_answerr$r*rkrCr+rs  77777777777777666666@@@@@@@@555555AAAAAAAAAA999999>>>>>><<<<<<  8 $ $C&.2)*111# x}###!%#%%%hsmHSMaijza{:KKCKK3KKKKU_7;7;;2;21P)Q;2'/};2'/};2@C;2;2;2;2z,/,/3,/S,/%S SVBW,/,/,/,/\$.$.s$.u$.$.$.$.$.L.s.sTz....6/L.  S 43 ! O /L. " j 1l0  e 0\/  Q <*<<<<~ zGgl3ijjjjG=>>GGXXXG566??PPPG677@@OOO KKRSSS&&MGG=GGGLH0 m$))LBYBYmmmnnnnnE 089I> E2 3 3 3++I>TUUUK E+   k))CDDD 6 6G L L L 7 77888HIII33:bccc 9i99:::ABBB118KWZ[[[ X+dsdBSXXXYYYCDDDB 22;?? BKBBLBBCCCLMMM%6"&9&9:L&M&M#P$6PP;NPPQQQQQ3*)> 0 0 0 E.1.. / / / / / / / / / 0gs C7MM% M  M%