Skip to main content
Glama
knowledge_graph.cpython-310.pyc19.9 kB
o �}�g-~�@s�dZddlZddlZddlZddlZddlZddlmZm Z m Z m Z m Z m Z mZddlmZddlZddlZddlmZddlmZddlmZejejd �e�e�ZGd d �d ee�ZGd d �d ee�Z Gdd�dee�Z!Gdd�d�Z"dS)z� Knowledge Graph Module Implements the core knowledge graph functionality for storing code components and their relationships using LlamaIndex. �N)�Dict�List�Optional�Any�Union�Set�Tuple)�Enum�)�config)�LlamaIndexManager)�Document)�levelc@�$eZdZdZdZdZdZdZdZdS)� ComponentType�file�classZfunction�methodZvariable�moduleN) �__name__� __module__� __qualname__ZFILEZCLASSZFUNCTIONZMETHODZVARIABLEZMODULE�rr�Z/Users/sparshdrolia/Sparsh personal/persistent-code-mcp/persistent_code/knowledge_graph.pyr�rc@seZdZdZdZdZdS)�ComponentStatusZplanned�partial� implementedN)rrr�PLANNED�PARTIAL� IMPLEMENTEDrrrrr'src@r)�RelationshipTypeZimportsZcallsZinherits�containsZ depends_onZ implementsN) rrrZIMPORTSZCALLSZINHERITSZCONTAINS� DEPENDS_ONZ IMPLEMENTSrrrrr!,rr!c@sDeZdZdZdKdedefdd�Zdedeeeeeffd d �Z d e ee fdefd d �Z de jddfdededede dede ee fdefdd�Z    dLdedeedee deedee ee fdef dd�Z dKdededede ee fdef dd�ZdMded ede ee ffd!d"�Z  #dNded$eeed%edee ee ffd&d'�Z  (dOd)ed*eeed+edee ee ffd,d-�Z dPded.e d/edefd0d1�Z  dQd2e ee fd3eede ee ffd4d5�Z 6 7dRd8ed+edee ee ffd9d:�Zd;d<�Zd=d>�Zd?d@�ZdAdB�Z dCdD�Z!dEdF�Z"dGdH�Z#dIdJ�Z$dS)S�KnowledgeGraphzSA graph-based storage for code components and their relationships using LlamaIndex.N� project_name� storage_dirc Cs�||_|ptj�tj�tj�tj�t���d�|_tj|jdd�tj�|j|�|_ tj|j dd�tj�|j |�d��|_ tj�|j |�d��|_ t � �|_t||j t|jd�|_|j��rc|jjnd|_|j��ro|jjnd|_i|_|��dS)z�Initialize a new knowledge graph for a project. Args: project_name: Name of the project storage_dir: Directory to store the graph data (default: ./storage) ZstorageT��exist_okz_nx_graph.jsonz_components.json)r%� project_dir�config_instanceZtriple_extract_fnN)r%�os�path�join�dirname�abspath�__file__r&�makedirsr)� nx_graph_file�components_file�nx�DiGraph�graphr r*�_extract_triples�llama_index_manager� is_available�kg_index� embed_model� components�load)�selfr%r&rrr�__init__7s$, � zKnowledgeGraph.__init__�document�returncCs�g}|j}|�d�}|�d�}|�d�}|r|r|s|S|�|d|f�|�d�}|r3|�|d|f�|�dg�}|D] } |�|d| f�q;|�d �} | rU|�|d | f�|�d g�} | D]} | �d |�} | �d �}| �d �}|r{|r{|�| ||f�q]|S)aExtract relationship triples for LlamaIndex KG from document metadata. Args: document: LlamaIndex document with component data in metadata Returns: List of (subject, predicate, object) triples �id�name�typeZis_a�status� has_status�basesZ inherits_from� contained_in� relationships�source�relation�target)�metadata�get�append)r>r@ZtriplesrM� component_id�component_name�component_typerErG�baserHrIZrelrJrKrLrrrr7bs4            �zKnowledgeGraph._extract_triples�component_datacCs>|�dd�}|�dd�}|�d|��}t|||�d�d�}|S)z�Convert a component to a LlamaIndex document. Args: component_data: Component data dictionary Returns: LlamaIndex Document � code_text�� descriptionz rB)�textrM�doc_id)rNr )r>rTZcomponent_textZcomponent_descZ full_text�docrrr�_component_to_document�s �z%KnowledgeGraph._component_to_documentrVrCrRrUrErWrMc Cs�tt���}||||||tj����tj����d|pid� }|jj|fi|��||j|<|j � �r>|� |�} |j � | �|� �|S)aAdd a new component to the graph. Args: name: Name of the component component_type: Type of component (file, class, function, etc.) code_text: The actual code text (optional) status: Implementation status (planned, partial, implemented) description: Semantic description of the component metadata: Additional metadata as key-value pairs Returns: component_id: Unique identifier for the component r ) rBrCrDrErWrU� created_at� last_modified�versionrM)�str�uuid�uuid4�datetime�now� isoformatr6�add_noder<r8r9r[Z add_document�save) r>rCrRrUrErWrMrPrTrZrrr� add_component�s&   �    zKnowledgeGraph.add_componentrPcCs�||jvrdSt|jj|�}|dur||d<|dur||d<|dur'||d<|dur2|d�|�tj����|d<|dd 7<|jj|�|�||j|<|j� �ra|� |�}|j� |�|� �d S) a�Update an existing component in the graph. Args: component_id: ID of the component to update code_text: New code text (if changed) status: New implementation status (if changed) description: New description (if changed) metadata: New or updated metadata Returns: success: Whether the update was successful FNrUrErWrMr]r^r T) r6�dict�nodes�updaterbrcrdr<r8r9r[Zupdate_documentrf)r>rPrUrErWrMrTrZrrr�update_component�s(     zKnowledgeGraph.update_component� source_id� target_id�relationship_typec Cs�||jvs ||jvr dStt���}||tj����|pid�}|jj||fi|��|j� �rP|jj |� d�}|jj |� d�}t|�� �} |j� || |�|��|S)a�Create a relationship between two components. Args: source_id: ID of the source component target_id: ID of the target component relationship_type: Type of relationship metadata: Additional metadata for the relationship Returns: relationship_id: Unique identifier for the relationship N)rBrDr\rMrC)r6r_r`rarbrcrd�add_edger8r9rirN�lower� add_triplerf) r>rlrmrnrMZrelationship_id� edge_dataZ source_nameZ target_namerKrrr�add_relationship"s   �  zKnowledgeGraph.add_relationshipF�include_relatedc Cs�||jvrdSt|jj|�}|rYg}|jj|dd�D]\}}}t|jj|�}|�||d��q||d<g} |jj|dd�D]\}} }t|jj| �} | �| |d��q?| |d<|S)a Retrieve a component by ID. Args: component_id: ID of the component include_related: Whether to include related components Returns: component: Component data including code and metadata NT��data)� componentZ relationshipZincoming_relationshipsZoutgoing_relationships)r6rhri�in_edgesrO� out_edges) r>rPrtrwZincomingrl�_rrZ source_dataZoutgoingrmZ target_datarrr� get_componentQs*  � �zKnowledgeGraph.get_componentr �relationship_types�depthc s���jvrgS�fdd���dkrCt���jj�dd�D]\}}}�|�r*��|�q�jj�dd�D]\}}}�|�rA��|�q3nt��������fdd����d�g}�D] } |�t�jj| ��qZ|S)afFind components related to a given component. Args: component_id: ID of the component relationship_types: Types of relationships to consider (None for all) depth: How many levels of relationships to traverse Returns: related_components: List of related components cs�durdS|�d��vS)NTrD)rN)rr)r|rr� matches_type�sz<KnowledgeGraph.find_related_components.<locals>.matches_typer Trucs�|�krdS�jj|dd�D]\}}}�|�r'|�kr'��|��||d�q�jj|dd�D]\}}}�|�rI|�krI��|��||d�q0dS)NTrur )r6ry�addrx)�node_idZ current_depthrzrmrrrl)rPr}�dfsr~� related_idsr>rrr��s � ��z3KnowledgeGraph.find_related_components.<locals>.dfs)r6�setryrrxrOrhri) r>rPr|r}rzrmrrrlZrelated_componentsZ related_idr)rPr}r�r~r�r|r>r�find_related_componentsxs*   � �� z&KnowledgeGraph.find_related_components� �query�component_types�limitcCs�g}t��}|dkr |}|j��rot�d|���|jj||dd�}|D]&\}}|�d�} | rK| |jvrK|j| } |rD| �d�|vrDq%|� || f�q%|ro|j dd�d d �d d �|d |�D�} t�dt | ��d��| St�d�|j j d d�D]S\} } |r�| �d�|vr�q{d}|��} | �dd���}| |vr�d}| |kr�d}||7}| | �dd���vr�|d7}| | �dd���vr�|d7}|dkr�|� || f�q{|j dd�d d �dd �|d |�D�S)a+Search the codebase semantically. Args: query: Search query component_types: Types of components to search limit: Maximum number of results Returns: matching_components: Ranked list of matching components �z Performing semantic search for: �)r�Zsimilarity_top_krBrDcS�|dS�Nrr��xrrr�<lambda>��z,KnowledgeGraph.search_code.<locals>.<lambda>T��key�reversecS�g|]}|d�qS�r r��.0�mrrr� <listcomp>��z.KnowledgeGraph.search_code.<locals>.<listcomp>NzSemantic search found z matcheszUsing basic text searchrurrCrV�rWrUr cSr�r�rr�rrrr�r�cSr�r�rr�rrrr�r�)r*Zget_similarity_top_kr8r9�logger�infoZsemantic_searchrNr<rO�sort�lenr6rirp)r>r�r�r�ZmatchesZ config_limitZsearch_resultsZscore�resultrYrTZsemantic_resultsrPZ query_lowerrQZ name_scorerrr� search_code�sX �   � �zKnowledgeGraph.search_code� new_status�notescCs�||jvrdS||jj|d<d|jj|vrg|jj|d<|jj|d�|tj����|d��t|jj|�|j|<|j� �rZ|jj|� d�}t |�� �}|j� |d|�|��dS)a;Update implementation status of a component. Args: component_id: ID of the component new_status: New implementation status notes: Optional notes about the status change Returns: success: Whether the update was successful FrEZstatus_history)rEZ timestampr�rCrFT)r6rirOrbrcrdrhr<r8r9rNr_rprqrf)r>rPr�r�rQZ status_valuerrr� update_statuss"  �  zKnowledgeGraph.update_status�filters�groupingcCs6tjdtjdtjdi}g}|jjdd�D]6\}}|r6d}|��D]\}} ||vr2||| kr2d}nq |r6q|�dtj�} || d7<|�|�qt |�|dd�} | ddkrq|tj} |tjd } | | | dd | d <|r�i}|D]}|�|d �}||vr�g||<||�|�qw|| d <| S|| d<| S)a(Retrieve implementation status across the project. Args: filters: Filters to apply to components grouping: How to group the results (e.g., by type) Returns: status_summary: Summary of project implementation status rTruFrEr )�total_components� status_counts�implementation_percentager�g�?�dr��unknownZgrouped_componentsr<) rrrr r6ri�itemsrNrOr�)r>r�r�r�Zfiltered_componentsrzrTZskipr��valuerEZsummaryrrZgroupedrwZ group_keyrrr�get_project_statusCsJ�� �   �z!KnowledgeGraph.get_project_status� dependenciesr�� priority_typecCs�g}|jjdd�D]\}}|�d�}|tjtjfvr!|�||f�q |dkr�g}|D]K\}}g}|jj|dd�D]\} } } | �d�tj krU|jj| �d�} |�| | f�q8t |�} t dd�|D��}| dkrjd }n|| }|�||f�q*|j d d �dd �d d�|d|�D�}|S|dkr�g}|D]\} }|�dd�}|�di��dt |��}|�||f�q�|j dd �d�dd�|d|�D�}|Sddl }dd�|�|t|t |���D�}|S)a/Suggest logical next components to implement. Args: priority_type: How to prioritize tasks ("dependencies" or "complexity") limit: Maximum number of tasks to suggest Returns: suggested_tasks: List of suggested next tasks TrurEr�rDcss"�|] \}}|tjkrdVqdS)r N)rr )r�rzrErrr� <genexpr>�s� �z1KnowledgeGraph.find_next_tasks.<locals>.<genexpr>rg�?cSr�r�rr�rrrr��r�z0KnowledgeGraph.find_next_tasks.<locals>.<lambda>r�cS�g|]\}}|�qSrr�r�rz�comprrrr��r�z2KnowledgeGraph.find_next_tasks.<locals>.<listcomp>N� complexityrUrVrMcSr�r�rr�rrrr��r�)r�cSr�rrr�rrrr��r�cSr�rrr�rrrr��r�)r6rirNrrrrOryr!r#r��sumr��randomZsample�min)r>r�r�ZpendingrPrTrEZsorted_pendingr�rzrmrrZ target_statusZ total_depsZimplemented_depsZ dep_scoreZ suggestedrUr�r�rrr�find_next_tasks�sH  � ��  � zKnowledgeGraph.find_next_taskscCs,|��|��|j��r|j��dSdS)z!Save the knowledge graph to disk.N)�_save_nx_graph�_save_componentsr8r9rf)r>rrrrf�s  �zKnowledgeGraph.savec CsV|jtj����ggd�}|jjdd�D]0\}}i}|��D]\}}t|tt t t t t f�s1|dur6|||<qt|�||<q|d�|�q|jjdd�D]5\}}} i}| ��D]\}}t|tt t t t t f�sj|duro|||<qWt|�||<qW|d�|||d��qLt|jd��} tj|| d d �Wd�n1s�wYt�d |j���dS) z Save the NetworkX graph to disk.)r%Zsaved_atri�edgesTruNrir�)rJrLrv�wr��ZindentzSaved NetworkX graph to )r%rbrcrdr6rir�� isinstancer_�int�float�bool�listrhrOr��openr2�json�dumpr�r�) r>rvr�� node_dataZserializable_datar�r�rJrLrr�frrrr��s6 �   ��zKnowledgeGraph._save_nx_graphcCsTt|jd��}tj|j|dd�Wd�n1swYt�d|j���dS)z'Save the components dictionary to disk.r�r�r�NzSaved components to )r�r3r�r�r<r�r��r>r�rrrr�s�zKnowledgeGraph._save_componentscCsBtj�|jd�}tj|dd�|jjj|d�t� d|���dS)z,Save the LlamaIndex knowledge graph to disk.Z llama_indexTr'�� persist_dirzSaved LlamaIndex to N) r+r,r-r)r1r:�storage_contextZpersistr�r�)r>r�rrr�_save_llama_indexsz KnowledgeGraph._save_llama_indexcCsVtj�|j�r |��tj�|j�r|��|j��}|r)|jj |_ |jj |_ dSdS)z#Load the knowledge graph from disk.N) r+r,�existsr2�_load_nx_graphr3�_load_componentsr8r=r:r;)r>Zllama_index_loadedrrrr=s  �zKnowledgeGraph.loadc Cs�t|jd�� }t�|�}Wd�n1swYt��|_|�dg�D]}|�d�}|jj |fi|��q&|�dg�D]}|d}|d}|d}|jj ||fi|��q>t � d |j���dS) z"Load the NetworkX graph from disk.�rNrirBr�rJrLrvzLoaded NetworkX graph from ) r�r2r�r=r4r5r6rN�popreror�r�) r>r�rvr�r�ZedgerJrLrrrrrr�,s �  zKnowledgeGraph._load_nx_graphcCsNt|jd��}t�|�|_Wd�n1swYt�d|j���dS)z)Load the components dictionary from disk.r�NzLoaded components from )r�r3r�r=r<r�r�r�rrrr�Cs�zKnowledgeGraph._load_componentscCs8tj|d�}tj||j|jdd�|_t�d|���dS)z�Load the LlamaIndex knowledge graph from disk. Args: persist_dir: Directory where index is persisted r�T)r�r;Zkg_triple_extract_fnZinclude_embeddingszLoaded LlamaIndex from N) ZStorageContextZ from_defaultsZKnowledgeGraphIndexZ from_storager;r7r:r�r�)r>r�r�rrr�_load_llama_indexKs��z KnowledgeGraph._load_llama_index)N)NNNN)F)Nr )Nr�)rV)NN)r�r�)%rrr�__doc__r_r?r rrr7rrr[rrrrgrr�rkr!rsr{r�r�r�r�r�r�rfr�r�r�r=r�r�r�rrrrr$4s� +4������ � �9������ �@���� � � /)�� �� �F�� �� �[���� �0� ��  �E��� �F .  r$)#r�r+r�rbZnetworkxr4Ztempfile�typingrrrrrrrZenumr r`Zloggingr r*r8r Zllama_index.corer Z basicConfigZINFOZ getLoggerrr�r_rrr!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