Skip to main content
Glama
context_assembler.cpython-310.pyc11.4 kB
o Uy�g�N�@srdZddlmZmZmZmZmZddlZddlZ ej ej d�e� e �ZddlmZmZmZmZGdd�d�ZdS) z� Context Assembly System Responsible for assembling minimal necessary context for coding tasks, summarizing peripheral components, and prioritizing based on relevance. �)�Dict�List�Optional�Any�SetN)�level�)�KnowledgeGraph� ComponentType�ComponentStatus�RelationshipTypec @s�eZdZdZdefdd�Z  ddedeeed e d e ee ffd d �Z dd ed e d e ee ffdd�Z  ddeede d e ee ffdd�Zde ee fd efdd�Zdeded efdd�ZdS)�ContextAssemblerz<Assembles context for coding tasks from the knowledge graph.�knowledge_graphcCs ||_dS)zyInitialize the context assembler. Args: knowledge_graph: The knowledge graph to use N)r)�selfr�r�\/Users/sparshdrolia/Sparsh personal/persistent-code-mcp/persistent_code/context_assembler.py�__init__s zContextAssembler.__init__N��task_description�relevant_components� max_tokens�returnc Cs�|ggid�}|s+t�d|���|jj|dd�}dd�|D�}t�dt|��d��t|���}|D](}|j�|�}|s>q3|d �|�t|�d d ����} || 7}||d kr[nq3t �} |d D]+}|d }|jj |dd�} | D]} | d } | | vr�| dd�|d D�vr�| � | �qsqct�dt| ��d��| D]B} |j�| �}|s�q�t|�d d ����} || |kr�|� |�}||d|d <|t|���7}n |d�|�|| 7}||kr�nq�t�dt|d ��dt|d��d|�d��|S)amAssemble minimal context for a specific task. This method uses semantic search in the knowledge graph to find components relevant to the task, then assembles them into a context object with primary components, related components, and summaries if needed to stay within token limits. Args: task_description: Description of the task relevant_components: List of component IDs known to be relevant max_tokens: Maximum tokens for the context Returns: context: Assembled context information )r�primary_components�related_components� summariesz&Searching for components relevant to: �)�query�limitcS�g|]}|d�qS��idr)�.0�rrrr� <listcomp>E�z4ContextAssembler.prepare_context.<locals>.<listcomp>zFound z relevant componentsr� code_text�gffffff�?r r)� component_id�depthcSrrr)r!�crrrr#hr$z related componentsrrzAssembled context with z primary and z related components (� tokens)) �logger�infor� search_code�len�split� get_component�append�get�set�find_related_components�add�_summarize_component)rrrr�context�search_results� token_countr'� componentZcomponent_tokens� related_ids�relatedZrelated_component� related_id�summaryrrr�prepare_context"sl��   � � ��   �.z ContextAssembler.prepare_contextr'cCs�|j�|�}|s ddiSt�d|�d����|gggid�}d|vrC|�dg�D]}|d�d�tjtjfvrA|d �|d �q)n|jj |tjtjgd d �}||d <d |vrx|�d g�D]}|d�d�tjtjfvrv|d�|d �q^n:g}|jj � �D]-}|jj j |dd�D]!\} } } | |kr�| �d�tjtjfvr�|j�|�} | r�|�| �q�q�||d<|�d�} | �rg}|jj j dd�D]\}}|�d�| kr�|�d�t jkr�||kr�|�|�q�|�dd�}g}|D]}|�||�dd��}|�||f�q�|jdd�dd�dd�|dd�D�|d<d}|tt|����7}|d D] }|tt|����7}�q%|dD] }|tt|����7}�q7|dD] }|tt|����7}�qI||k�r2t�d|�d|�d��t|d�D]9\}}|�|�}||d|d <|tt|����8}|t|���7}|d |ddd!�|d|<||k�r�n�qn||k�r�t|d�D]9\}}|�|�}||d|d <|tt|����8}|t|���7}|d |ddd!�|d|<||k�r�n�q�||k�r2t|d �D]9\}}|�|�}||d|d <|tt|����8}|t|���7}|d |ddd!�|d |<||k�r0n�q�t�d"|�d��d#|�d$��|S)%aProvide context to continue implementing a component. Args: component_id: ID of the component to continue implementing max_tokens: Maximum tokens for the context Returns: context: Implementation context �errorzComponent not foundz,Preparing context to continue implementing: �name)r:� dependencies� dependents�related_implementationsr�outgoing_relationships� relationship�typerBr:r)r'�relationship_typesr(�incoming_relationshipsrCT��data�statusr&cSs|dS)Nrr)�xrrr�<lambda>�sz:ContextAssembler.continue_implementation.<locals>.<lambda>)�key�reversecSr)rr)r!�srrrr#�r$z<ContextAssembler.continue_implementation.<locals>.<listcomp>N�rDrz Token count (z) exceeds limit (z), summarizing componentsrr )r rAZ summarizedz%Assembled implementation context for z (r*)rr0r+r,r2r � DEPENDS_ON�CALLSr1r4�graph�nodes� out_edgesr � IMPLEMENTED�_simple_similarity�sortr.�strr/� enumerater6)rr'rr:r7�relrBrC�node_id�_� target_id� edge_data� dependent�component_type� implemented� node_data�component_nameZscored�implZname_similarityr9�dep�ir>rrr�continue_implementation�s� � �� ����  �� �� �       �   �   �z(ContextAssembler.continue_implementationr� component_ids�dependencies_depthc s�gigd�}g}|r%|D]}�j�|�}|r#|�d�tjkr#|�|�q n�jjjdd�D]\}}|�d�} | tjtj fvrC|�|�q-|sJddiSt � dt |��d��t ���|D] }�j|d fi|��q[|D]6}|d }g} �jjj|dd�D]\} } } | �d �tjtjfvr�| �| �q|| D] }|�vr���||�q�qkz!tt ����}|r‡fd d �|D�|d <t �dt |��d��Wn t jy�Ynwz!tt ����}|��|D]}�j�|�}|r�|d�|�q�Wnt j�y|D] }|d�|�q�Ynwg}tdd�|D��}|�rUg}t|�D]!}d}��|�D]\} } | |v�r1d}n�q$|�s;|�|��q|�sGtt|��g}|�|�|t|�8}|�st|�D]\}}�fdd �|D�|dd|d��<�qYg}t|�D]=\}}|dd|d��gd�}|D]#}�j�|�}|�r�|d�|d |d|d |d|dd���q�|�|��qw||d<t � dt |��d ��|S)!a4Generate a plan for implementing pending components. Args: component_ids: List of component IDs to include (None for all pending) dependencies_depth: How deep to analyze dependencies Returns: plan: Ordered implementation plan )�ordered_components�dependency_groups�implementation_stepsrLTrJr@zNo pending components foundzPlanning implementation for z pending componentsr rGcs*g|]}dd��fdd�|D�����qS)zDependency cycle detected: z -> csg|] }�j|d�qS)rA)rV)r!�n�� dep_graphrrr#QszGContextAssembler.get_implementation_plan.<locals>.<listcomp>.<listcomp>)�join)r!�cyclerqrrr#Qs*z<ContextAssembler.get_implementation_plan.<locals>.<listcomp>�warningsz Detected z dependency cyclesrmcss�|]}|dVqdS)r Nr)r!r:rrr� <genexpr>js�z;ContextAssembler.get_implementation_plan.<locals>.<genexpr>Fcs$g|]}�j�|�r�j�|��qSr)rr0)r!r')rrrr#�s  � �rnZgroup_rzImplement Group )�step� description� componentsryrArx)r rArGrLrxroz!Created implementation plan with z steps) rr0r2r rXr1rUrV�PLANNED�PARTIALr+r,r.�nx�DiGraph�add_noderWr rSrT�add_edge�list� simple_cycles�warning�NetworkXNoCycle�topological_sortrP�NetworkXUnfeasibler3�next�iterr\)rrkrl�planZpending_componentsr'r:r^rerLrBr_r`raZdep_id�cyclesrmrn� remaining�groupZhas_pending_depsri�stepsrwr)rrrr�get_implementation_plans��  ��  � � ���� ����  � �  � � � ��z(ContextAssembler.get_implementation_planr:c Csb|�dd�}|�dd�}|�dd�}|�dd�}|tjkr3|�di��d |d �}d |�d |��}|S|tjkr[|�di��d |d �}|�di��d d�}d|�d|�d |��}|S|tjkr�|�di��dg�} d�| dd��t| �dkrzdnd} d|�d| �d|��}|S|tjkr�|�di��d|�} d| �d |��}|S|���d|�d |��}|S)z�Create a summary of a component. Args: component: The component to summarize Returns: summary: Summary text rAzUnnamed componentrG�unknownrxzNo description availablerL�metadata� signaturez()z Function 'z': �classz Unknown classzMethod '�.�methodsz, NrRz...r&zClass 'z' with methods [z]: �pathzFile 'z ') r2r �FUNCTION�METHOD�CLASSrsr.�FILE� capitalize) rr:rArcrxrLr�r>� class_namer�� method_listr�rrrr6�s0     � �& ��z%ContextAssembler._summarize_component�str1�str2cCsPt|�����}t|�����}|r|sdS|�|�}|�|�}t|�t|�S)z�Calculate a simple similarity score between two strings. Args: str1: First string str2: Second string Returns: similarity: Similarity score between 0 and 1 g)r3�lowerr/� intersection�unionr.)rr�r�Zwords1Zwords2r�r�rrrrY�s   z#ContextAssembler._simple_similarity)Nr)r)Nr)�__name__� __module__� __qualname__�__doc__r rr[rr�intrrr?rjr�r6�floatrYrrrrr s8 �� ��  � i���  �#r )r��typingrrrrr�logging�networkxr|� basicConfig�INFO� getLoggerr�r+rr r r r r rrrr�<module>s 

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/sparshdrolia/Persistent-code-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server