How can I use Prismatic Ranked Recursive Summarization to build a knowledge graph of my code from different lenses, to provide a better context to a llm
Assistant
Prismatic Ranked Recursive Summarization is a concept that can be very useful for organizing and contextualizing information from your code to create a knowledge graph that serves as an effective input for a large language model (LLM). To achieve this, you can follow these steps:
Steps to Implement Prismatic Ranked Recursive Summarization for Knowledge Graph Construction
Code Analysis and Data Extraction:
Analyze your codebase to extract essential elements such as functions, classes, methods, dependencies, and documentation comments.
Capture metadata, such as file structures, import relationships, and usage patterns.
Define Lenses:
Choose different "lenses" through which to view your code. These might include:
Functional Lens: Understanding the functionality of different code sections.
Structural Lens: Looking at how classes and modules are structured.
Dependency Lens: Observing the relationships and dependencies among various components.
Temporal Lens: Tracking changes in the code over time or the evolution of specific features.
Summarization:
For each lens, perform summarization using a ranked approach where you identify the most important elements of the code.
You can do this recursively, summarizing lower-level components (like functions) before summarizing higher-level structures (like modules or entire packages).
Use statistical approaches or NLP techniques (for example, using embeddings and similarity scores) to rank the significance of each piece of information.
Graph Construction:
Construct a knowledge graph where:
Nodes represent code elements (functions, classes, modules, etc.).
Edges represent relationships (e.g., function calls, inheritance, imports).
Use the summaries gathered from each lens to enrich the nodes and edges with context-specific metadata or attributes (like purpose, complexity, known bugs, etc.).
Integrating Different Lenses:
Create a unified framework for integrating insights from different lenses. Ensure that the keys and relationships from each lens can be aligned and merged into a coherent graph structure.
For example, a function may have multiple representations: as a callable method in its class, as part of a larger workflow, and as a dependency for specific processes.
Context Enrichment:
Using the insights from the knowledge graph, enrich your understanding of the code by providing explanations, relationships, and relevant documentation directly linked to the code elements.
Use techniques like embeddings for code documentation, invocations, and historical context to provide rich, contextual information for the LLM.
Querying the Knowledge Graph for LLM:
When integrating with an LLM, structure the query effectively by using the relationships and embeddings from the knowledge graph.
You may represent specific questions or tasks using the graph, allowing the LLM to access relevant context and information by navigating the graph rather than just flat code.
Feedback Loop:
Implement a feedback loop where LLM outputs provide insights or corrections that can be used to iteratively improve the knowledge graph structure and the summarization strategy.
Additional Considerations
Tooling:
Consider using tools like Neo4j for the graph database or libraries like NetworkX for graph manipulation in Python.
You can use static code analysis tools (like SonarQube or ESLint) to gather metrics and insights that can inform your summarization.
Version Control:
Keep track of code changes over time in your knowledge graph. This means you could query historical states of the graph to understand how relationships or functionalities have changed.
User-Defined Annotations:
Allow developers to annotate parts of the code. These annotations can be dynamically integrated into your knowledge graph, providing additional context that could be beneficial for the LLM.
This structured approach to Prismatic Ranked Recursive Summarization can help you create a nuanced understanding of your codebase, which, when combined with an LLM, can significantly enhance how you interact with and derive value from your code.
User
Create a Python script that can generate this nuanced understanding. I would like the output to be in a format that a llm can leverage
Assistant
Creating a Python script that generates a nuanced understanding of a codebase and outputs it in a format suitable for a large language model (LLM) involves multiple components. Below is a simplified script that accomplishes this task, focusing mainly on extracting code elements and generating a structured summary.
This script will analyze a directory containing Python files and construct a knowledge representation in JSON format, which is easily digestible by LLMs.
Python Script for Code Analysis and Summary Generation
python
User
I want this to work with any code not just python
Assistant
To create a script that can analyze various programming languages and generate a knowledge graph, you would need to handle code parsing for different syntaxes. Since a universal approach is complex and each language has its own syntax and structure, the script will handle the most common elements: functions/methods, classes, and imports.
You can use libraries like antlr4 or tree-sitter to parse multiple programming languages. In the example below, I've provided a Python script that can be adapted to analyze different languages by leveraging a custom parsing function for each language.
Here's an expanded version of the script that can be configured to work with multiple languages. For simplicity, I'll demonstrate using Python as a reference and outline how to add support for additional languages.
Multi-Language Code Analyzer Script
python
User
Use treesitter
Assistant
Using Tree-sitter, a powerful parsing library that provides incremental parsing and is capable of parsing multiple programming languages, can help create a knowledge graph for various programming languages. Below, I've adapted the previous Python script to utilize Tree-sitter for parsing.
To use the Tree-sitter library in Python, you need to install the tree-sitter package and import the appropriate grammars for the languages you want to analyze.
Here's how you can set this up:
Step 1: Install Prerequisites
You need to install the necessary libraries. You can do this using pip:
bash
pip install tree-sitter
You'll also need to clone or download the grammars for the languages you want to analyze from the tree-sitter/tree-sitter repository or their respective repositories.
For example, to get parser grammars for JavaScript and Python, you would do:
Make sure to place the grammars in a known directory.
Step 2: Implement the Multi-Language Analyzer
Here's the revised Python script that uses Tree-sitter for analyzing Python and JavaScript. You can extend this to other languages by creating similar analyzer classes.
python
User
Are you handling the different lenses for the summarization
Assistant
To extend the previous Tree-sitter example such that it handles different lenses for summarization, you can create a more structured approach to summarize the codebase using context-aware views (or "lenses"). Each lens provides a different perspective — such as functionality, structure, or dependencies.
Here's how you can incorporate different lenses into the analysis:
Lenses Overview
Functional Lens: Focuses on what the functions do, their parameters, and their return values.
Structural Lens: Provides information about the overall architecture, including classes and their relationships.
Dependency Lens: Highlights imports and dependencies between the modules.
Enhanced Python Script with Lenses
We can modify the existing code to include multiple lenses. Below, I’ll show you an updated version of the code that generates summaries from these different lenses:
python
User
Add data flow and security lenses
Assistant
To add Data Flow and Security lenses to the existing code analysis script, we need to define what each lens will analyze and how to implement that analysis effectively.
Data Flow Lens
This lens focuses on how data moves through the program. It might include:
Function calls: Identifying which functions take inputs and which produce outputs.
Variable assignments: Tracking where variables are defined and how they're modified.
Security Lens
This lens would examine code for common security concerns, such as:
Potential vulnerabilities: Identifying use of insecure functions or patterns (e.g., direct string interpolation in SQL queries).
Data leaks: Understanding where sensitive information might be inadvertently exposed.
Updated Script with Additional Lenses
Here’s how the code could be extended to include Data Flow and Security lenses:
python
User
What other lenses would you suggest. I want the llm to have a complete grasp of the codebase so it can help code
Assistant
When designing a multi-lens analysis of a codebase to provide a comprehensive view that aids a large language model (LLM) in understanding and assisting with coding tasks, several additional lenses can be helpful. Each lens captures a specific aspect of the code structure, behavior, and practices, contributing to a better overall understanding. Here are some additional lenses you might consider:
1. Complexity Lens
Purpose: Analyze the complexity of the code by measuring metrics such as cyclomatic complexity, function length, or depth of nesting.
Elements to Capture:
Number of branches in control flow statements (if, for, while).
Depth of function calls (how many functions call other functions).
Overall lines of code (LOC) per function and class.
2. Testing Lens
Purpose: Provide insights into the testing strategy, including the presence of unit tests, integration tests, and overall test coverage.
Elements to Capture:
Files or functions that contain test cases.
Frameworks used for testing (like pytest, unittest, etc.).
The ratio of test cases to production code (test coverage).
3. Documentation Lens
Purpose: Assess the presence and quality of documentation within the codebase.
Elements to Capture:
Docstrings for functions, classes, and modules.
Presence of markdown files (like README) and comments.
Documentation generation tools being employed (if any).
4. Configuration Lens
Purpose: Analyze configuration files and settings for the project, including dependencies, environment variables, and build configurations.
Dependencies declared in configuration files (e.g., requirements.txt, package.json).
Build scripts or CI/CD configurations.
5. Performance Lens
Purpose: Identify performance bottlenecks and analyze the efficiency of algorithms used in the code.
Elements to Capture:
Not yet included in a published release.
import os
import ast
import json
from typing import List, Dict
class CodeAnalyzer(ast.NodeVisitor):
def __init__(self):
self.functions = []
self.classes = []
self.imports = []
def visit_FunctionDef(self, node):
self.functions.append({
'name': node.name,
'args': [arg.arg for arg in node.args.args],
'docstring': ast.get_docstring(node),
'line_number': node.lineno
})
self.generic_visit(node)
def visit_ClassDef(self, node):
methods = []
for item in node.body:
if isinstance(item, ast.FunctionDef):
methods.append(item.name)
self.classes.append({
'name': node.name,
'methods': methods,
'docstring': ast.get_docstring(node),
'line_number': node.lineno
})
self.generic_visit(node)
def visit_Import(self, node):
for n in node.names:
self.imports.append(n.name)
self.generic_visit(node)
def visit_ImportFrom(self, node):
self.imports.append(f"{node.module}.{', '.join(n.name for n in node.names)}")
self.generic_visit(node)
def analyze_code(directory: str) -> Dict:
analyzer = CodeAnalyzer()
for filename in os.listdir(directory):
if filename.endswith('.py'):
with open(os.path.join(directory, filename), 'r') as f:
tree = ast.parse(f.read(), filename=filename)
analyzer.visit(tree)
return {
'functions': analyzer.functions,
'classes': analyzer.classes,
'imports': analyzer.imports,
'directory': directory
}
def create_knowledge_graph(code_summary: Dict) -> str:
graph_representation = {
"nodes": [],
"edges": []
}
# Add function nodes
for function in code_summary['functions']:
graph_representation['nodes'].append({
'id': function['name'],
'type': 'function',
'docstring': function['docstring'] or '',
'line_number': function['line_number']
})
# Add class nodes with their methods
for cls in code_summary['classes']:
graph_representation['nodes'].append({
'id': cls['name'],
'type': 'class',
'docstring': cls['docstring'] or '',
'methods': cls['methods']
})
# Add import nodes
for imp in code_summary['imports']:
graph_representation['nodes'].append({
'id': imp,
'type': 'import'
})
# Create edges for method relationships and imports
for cls in code_summary['classes']:
for method in cls['methods']:
graph_representation['edges'].append({
'from': cls['name'],
'to': method,
'relation': 'contains_method'
})
for function in code_summary['functions']:
for cls in code_summary['classes']:
if function['name'] in cls['methods']:
graph_representation['edges'].append({
'from': cls['name'],
'to': function['name'],
'relation': 'contains_method'
})
return json.dumps(graph_representation, indent=2)
if __name__ == "__main__":
directory = "your_code_directory" # Change this to your actual code directory
code_summary = analyze_code(directory)
knowledge_graph = create_knowledge_graph(code_summary)
# Save the generated knowledge graph to a file
output_file = "knowledge_graph.json"
with open(output_file, "w") as f:
f.write(knowledge_graph)
print(f"Knowledge graph saved to {output_file}")
Key Components of the Script:
AST Usage: The script uses Python's Abstract Syntax Tree (AST) module to parse Python files, which allows it to easily extract functions, classes, and import statements without executing them.
CodeAnalyzer Class: This class is a subclass of ast.NodeVisitor. It collects information about functions, classes, and imports as it traverses the parsed tree.
analyze_code Function: This function iterates through Python files in a given directory, parsing each one and creating a summary of its elements.
create_knowledge_graph Function: This function takes the code summary and constructs a knowledge graph in JSON format, representing nodes (functions, classes, imports) and edges (relationships).
File Output: Finally, the generated knowledge graph is saved to a JSON file, which can be easily ingested by LLMs or other systems for further analysis.
Usage:
Save the script to a .py file.
Update the directory variable with the path to your code directory.
Run the script. It will create a file named knowledge_graph.json containing the structured representation of your codebase.
This output format is JSON, which is a standard format widely used for data interchange and is compatible with many programming environments, making it suitable for LLMs to process. You can add more sophisticated features or enrich the graph with additional details as necessary.
import os
import json
from typing import List, Dict
class CodeAnalyzer:
def __init__(self, language: str):
self.language = language
self.functions = []
self.classes = []
self.imports = []
def analyze(self, code: str):
# To be overridden by specific language analyzers
raise NotImplementedError("analyze method not implemented for this language.")
def get_summary(self) -> Dict:
return {
'functions': self.functions,
'classes': self.classes,
'imports': self.imports,
}
class PythonAnalyzer(CodeAnalyzer):
def __init__(self):
super().__init__("Python")
def analyze(self, code: str):
import ast
tree = ast.parse(code)
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
self.functions.append({
'name': node.name,
'args': [arg.arg for arg in node.args.args],
'docstring': ast.get_docstring(node),
'line_number': node.lineno
})
elif isinstance(node, ast.ClassDef):
methods = [n.name for n in node.body if isinstance(n, ast.FunctionDef)]
self.classes.append({
'name': node.name,
'methods': methods,
'docstring': ast.get_docstring(node),
'line_number': node.lineno
})
elif isinstance(node, (ast.Import, ast.ImportFrom)):
import_names = [n.name for n in node.names] if isinstance(node, ast.Import) else [f"{node.module}.{n.name}" for n in node.names]
self.imports.extend(import_names)
# You can implement additional analyzers for other languages like JavaScript, Java, C#, etc.
class JavaScriptAnalyzer(CodeAnalyzer):
def __init__(self):
super().__init__("JavaScript")
def analyze(self, code: str):
# Placeholder: Use an actual JS parser
# For example, you could integrate with a JavaScript parser library
# Like Babel or Acorn in Node.js
pass # Implement JS parsing similarly
# Function to dynamically invoke the correct analyzer based on the file extension
def get_language_analyzer(file_extension: str) -> CodeAnalyzer:
analyzers = {
'.py': PythonAnalyzer,
'.js': JavaScriptAnalyzer,
# Add more languages and their corresponding analyzers here
}
return analyzers.get(file_extension.lower(), None)
def analyze_code(directory: str) -> Dict:
summary = {}
for filename in os.listdir(directory):
file_extension = os.path.splitext(filename)[1]
analyzer_class = get_language_analyzer(file_extension)
if analyzer_class is not None:
with open(os.path.join(directory, filename), 'r') as f:
code = f.read()
analyzer = analyzer_class()
analyzer.analyze(code)
summary[filename] = analyzer.get_summary()
return summary
def create_knowledge_graph(code_summary: Dict) -> str:
graph_representation = {
"nodes": [],
"edges": []
}
# Add function nodes
for file, elements in code_summary.items():
for function in elements['functions']:
graph_representation['nodes'].append({
'id': f"{file}:{function['name']}",
'type': 'function',
'docstring': function['docstring'] or '',
'line_number': function['line_number']
})
for cls in elements['classes']:
graph_representation['nodes'].append({
'id': f"{file}:{cls['name']}",
'type': 'class',
'docstring': cls['docstring'] or '',
'methods': cls['methods']
})
for imp in elements['imports']:
graph_representation['nodes'].append({
'id': f"{file}:{imp}",
'type': 'import'
})
# Create edges for method relationships and imports
for cls in elements['classes']:
for method in cls['methods']:
graph_representation['edges'].append({
'from': f"{file}:{cls['name']}",
'to': f"{file}:{method}",
'relation': 'contains_method'
})
return json.dumps(graph_representation, indent=2)
if __name__ == "__main__":
directory = "your_code_directory" # Change this to your actual code directory
code_summary = analyze_code(directory)
knowledge_graph = create_knowledge_graph(code_summary)
# Save the generated knowledge graph to a file
output_file = "knowledge_graph.json"
with open(output_file, "w") as f:
f.write(knowledge_graph)
print(f"Knowledge graph saved to {output_file}")
Key Concepts in the Script:
Base Class (CodeAnalyzer): This serves as a prototype for language-specific analyzers, requiring an analyze method that subclasses must implement.
Language-Specific Analyzers:
PythonAnalyzer: Uses ast to parse Python code and extract functions, classes, and imports.
JavaScriptAnalyzer: Placeholder for JavaScript (or any other language). You'll need to implement parsing logic, which could involve using a JavaScript parsing library (e.g., using Node.js).
Dynamic Language Handling: The get_language_analyzer function maps file extensions to analyzers, allowing for easy extensibility. You can create additional analyzers for other languages you want to support.
Knowledge Graph Creation: The script generates a JSON representation of the knowledge graph, where nodes represent functions, classes, and imports, and edges represent their relationships.
Extensibility: You can easily extend the script by adding new analyzers for different programming languages, each handling the specific code structure and syntax for that language.
Usage:
Save this script and the necessary analyzers.
Update the directory variable with the path to your code directory.
Run the script. It will generate a knowledge graph in knowledge_graph.json.
Note: The JavaScript and other language parsers here are placeholders. For languages like Java or C#, you will need to integrate appropriate parsers that can read and extract information similarly to how the Python analyzer does.
import os
import json
from tree_sitter import Language, Parser
# Build the language libraries beforehand
# Assuming you've built the languages stubs using tree-sitter CLI
# For example:
# gcc -shared -o my-languages.so tree-sitter-python/src/parser.c tree-sitter-javascript/src/parser.c -I tree-sitter-python/include -I tree-sitter-javascript/include
Language.build_library(
# Store the library in the `build` directory
'build/my-languages.so',
# Include one or more languages
[
'tree-sitter-python',
'tree-sitter-javascript',
]
)
PY_LANGUAGE = Language('build/my-languages.so', 'python')
JS_LANGUAGE = Language('build/my-languages.so', 'javascript')
class CodeAnalyzer:
def __init__(self, language):
self.language = language
self.functions = []
self.classes = []
self.imports = []
def analyze(self, code):
parser = Parser()
parser.set_language(self.language)
tree = parser.parse(bytes(code, "utf8"))
# Go through the Tree-sitter nodes
self.extract_info(tree.root_node)
def extract_info(self, node):
for child in node.children:
if child.type == 'function_definition':
name_node = child.child_by_field_name('name')
if name_node:
self.functions.append({
'name': code[name_node.start_byte:name_node.end_byte],
})
elif child.type == 'class_definition':
name_node = child.child_by_field_name('name')
if name_node:
methods = []
for method in child.children:
if method.type == 'function_definition':
methods.append(code[method.child_by_field_name('name').start_byte:method.child_by_field_name('name').end_byte])
self.classes.append({
'name': code[name_node.start_byte:name_node.end_byte],
'methods': methods
})
elif child.type == 'import_statement':
self.imports.append(code[child.start_byte:child.end_byte])
# Recurse deeper
self.extract_info(child)
def get_summary(self):
return {
'functions': self.functions,
'classes': self.classes,
'imports': self.imports,
}
def get_language_analyzer(file_extension):
analyzers = {
'.py': CodeAnalyzer(PY_LANGUAGE),
'.js': CodeAnalyzer(JS_LANGUAGE),
# Add more languages and their corresponding analyzer classes here
}
return analyzers.get(file_extension.lower(), None)
def analyze_code(directory):
summary = {}
for filename in os.listdir(directory):
file_extension = os.path.splitext(filename)[1]
analyzer = get_language_analyzer(file_extension)
if analyzer is not None:
with open(os.path.join(directory, filename), 'r') as f:
code = f.read()
analyzer.analyze(code)
summary[filename] = analyzer.get_summary()
return summary
def create_knowledge_graph(code_summary):
graph_representation = {
"nodes": [],
"edges": []
}
# Add function and class nodes
for file, elements in code_summary.items():
for function in elements['functions']:
graph_representation['nodes'].append({
'id': f"{file}:{function['name']}",
'type': 'function'
})
for cls in elements['classes']:
graph_representation['nodes'].append({
'id': f"{file}:{cls['name']}",
'type': 'class',
'methods': cls['methods']
})
for imp in elements['imports']:
graph_representation['nodes'].append({
'id': f"{file}:{imp}",
'type': 'import'
})
# Create edges for method relationships
for cls in elements['classes']:
for method in cls['methods']:
graph_representation['edges'].append({
'from': f"{file}:{cls['name']}",
'to': f"{file}:{method}",
'relation': 'contains_method'
})
return json.dumps(graph_representation, indent=2)
if __name__ == "__main__":
directory = "your_code_directory" # Change this to your actual code directory
code_summary = analyze_code(directory)
knowledge_graph = create_knowledge_graph(code_summary)
# Save the generated knowledge graph to a file
output_file = "knowledge_graph.json"
with open(output_file, "w") as f:
f.write(knowledge_graph)
print(f"Knowledge graph saved to {output_file}")
Key Components:
Tree-sitter Configuration:
You build a shared library from the grammars. The script uses Language.build_library to create a library that contains the grammar for the languages you're interested in (Python and JavaScript are used in this example).
CodeAnalyzer Class:
This class is now parented by parsing using Tree-sitter, recognizing constructs such as functions, classes, and imports.
The extract_info method recursively traverses the parse tree and extracts relevant information.
Parser Initialization:
The parser is set up to use the appropriate language according to the file being analyzed.
Dynamic Language Handling:
The function get_language_analyzer maps file types to the corresponding analyzers.
Knowledge Graph Creation:
This part remains similar to the previous implementation but now uses the results obtained via Tree-sitter parsing.
Usage:
Ensure you have built the Tree-sitter grammars for the languages you want and have the build/my-languages.so available.
Save the script to a .py file.
Update the directory variable with the path to your code directory.
Run the script to generate the knowledge_graph.json.
Additional Languages:
To add support for more languages, add their respective grammars using the Tree-sitter grammars and duplicate the CodeAnalyzer class logic accordingly. Adjust the parsing logic in the extract_info method to fit the syntax of each language.
Note:
The Tree-sitter API and grammar specifics can vary, check the latest documentation for more advanced parsing needs or techniques. The script serves as a foundational example and may need adjustments based on specific language grammars and logic requirements.
import os
import json
from tree_sitter import Language, Parser
# Build the language libraries beforehand
Language.build_library(
'build/my-languages.so',
[
'tree-sitter-python',
'tree-sitter-javascript',
]
)
PY_LANGUAGE = Language('build/my-languages.so', 'python')
JS_LANGUAGE = Language('build/my-languages.so', 'javascript')
class CodeAnalyzer:
def __init__(self, language):
self.language = language
self.functions = []
self.classes = []
self.imports = []
def analyze(self, code):
parser = Parser()
parser.set_language(self.language)
tree = parser.parse(bytes(code, "utf8"))
self.extract_info(tree.root_node, code)
def extract_info(self, node, code):
for child in node.children:
if child.type == 'function_definition':
name_node = child.child_by_field_name('name')
if name_node:
self.functions.append({
'name': code[name_node.start_byte:name_node.end_byte],
'params': [code[param.start_byte:param.end_byte] for param in child.child_by_field_name('parameters').children if param.type == 'identifier'],
'docstring': '',
'line_number': child.start_point[0] + 1 # 1-based line number
})
elif child.type == 'class_definition':
name_node = child.child_by_field_name('name')
if name_node:
methods = []
for method in child.children:
if method.type == 'function_definition':
methods.append(code[method.child_by_field_name('name').start_byte:method.child_by_field_name('name').end_byte])
self.classes.append({
'name': code[name_node.start_byte:name_node.end_byte],
'methods': methods
})
elif child.type == 'import_statement':
self.imports.append(code[child.start_byte:child.end_byte])
# Recurse deeper
self.extract_info(child, code)
def get_summary(self):
return {
'functions': self.functions,
'classes': self.classes,
'imports': self.imports,
}
class Lenses:
@staticmethod
def functional_lens(code_summary):
functional_view = []
for file, elements in code_summary.items():
for function in elements['functions']:
functional_view.append({
'function_name': function['name'],
'params': function['params'],
'line_number': function['line_number']
})
return functional_view
@staticmethod
def structural_lens(code_summary):
structural_view = []
for file, elements in code_summary.items():
for cls in elements['classes']:
structural_view.append({
'class_name': cls['name'],
'methods': cls['methods']
})
return structural_view
@staticmethod
def dependency_lens(code_summary):
dependency_view = []
for file, elements in code_summary.items():
for imp in elements['imports']:
dependency_view.append({
'import_statement': imp
})
return dependency_view
def get_language_analyzer(file_extension):
analyzers = {
'.py': CodeAnalyzer(PY_LANGUAGE),
'.js': CodeAnalyzer(JS_LANGUAGE),
}
return analyzers.get(file_extension.lower(), None)
def analyze_code(directory):
summary = {}
for filename in os.listdir(directory):
file_extension = os.path.splitext(filename)[1]
analyzer = get_language_analyzer(file_extension)
if analyzer is not None:
with open(os.path.join(directory, filename), 'r') as f:
code = f.read()
analyzer.analyze(code)
summary[filename] = analyzer.get_summary()
return summary
if __name__ == "__main__":
directory = "your_code_directory" # Change this to your actual code directory
code_summary = analyze_code(directory)
# Generate lens-specific summaries
functional_summary = Lenses.functional_lens(code_summary)
structural_summary = Lenses.structural_lens(code_summary)
dependency_summary = Lenses.dependency_lens(code_summary)
# Output summaries
output_summary = {
'functional': functional_summary,
'structural': structural_summary,
'dependencies': dependency_summary
}
# Save the generated summaries to a file
output_file = "summaries.json"
with open(output_file, "w") as f:
json.dump(output_summary, f, indent=2)
print(f"Summaries saved to {output_file}")
Key Enhancements:
Multiple Lenses Implementation:
The Lenses class defines three static methods to generate summaries based on the three lenses (functional, structural, and dependency).
Each lens takes code_summary as input and returns a different perspective on the data.
Functional Lens:
Collects information about each function, including name, parameters, and line number.
Structural Lens:
Collects class names and their methods to give a view of the structure of the code.
Dependency Lens:
Extracts and provides a list of import statements, giving insight into dependencies at a higher level.
Output Summaries:
The final output combines results from all lenses into a single JSON object saved to summaries.json.
Usage:
Ensure that Tree-sitter grammars are set up properly and that you have built the shared library.
Save the modified script to a .py file.
Set the directory variable to your applicable code directory and run the script.
Extensibility:
You can easily add new lenses or modify existing ones to extract additional insights from your code as needed.
Similarly, you can extend the functionality to support more programming languages by creating additional analyzers and integrating them into the lens structure.
This structure provides a comprehensive approach to analyzing code from multiple perspectives, which can be particularly useful for improving the context provided to an LLM.
import os
import json
from tree_sitter import Language, Parser
# Build the language libraries beforehand (as explained previously)
Language.build_library(
'build/my-languages.so',
[
'tree-sitter-python',
'tree-sitter-javascript',
]
)
PY_LANGUAGE = Language('build/my-languages.so', 'python')
JS_LANGUAGE = Language('build/my-languages.so', 'javascript')
class CodeAnalyzer:
def __init__(self, language):
self.language = language
self.functions = {}
self.classes = []
self.imports = []
self.data_flow = []
self.security_issues = []
def analyze(self, code):
parser = Parser()
parser.set_language(self.language)
tree = parser.parse(bytes(code, "utf8"))
self.extract_info(tree.root_node, code)
def extract_info(self, node, code):
for child in node.children:
if child.type == 'function_definition':
name_node = child.child_by_field_name('name')
if name_node:
func_name = code[name_node.start_byte:name_node.end_byte]
self.functions[func_name] = {
'name': func_name,
'params': [code[param.start_byte:param.end_byte] for param in child.child_by_field_name('parameters').children if param.type == 'identifier'],
'line_number': child.start_point[0] + 1,
'data_flows': [], # To track variable data flow
}
elif child.type == 'class_definition':
name_node = child.child_by_field_name('name')
if name_node:
methods = []
for method in child.children:
if method.type == 'function_definition':
methods.append(code[method.child_by_field_name('name').start_byte:method.child_by_field_name('name').end_byte])
self.classes.append({
'name': code[name_node.start_byte:name_node.end_byte],
'methods': methods
})
elif child.type == 'import_statement':
self.imports.append(code[child.start_byte:child.end_byte])
elif child.type == 'variable_declaration':
# Capture variable declarations for data flow tracking
for var in child.children:
if var.type == 'identifier':
self.data_flow.append(code[var.start_byte:var.end_byte])
elif child.type == 'expression_statement':
# You may want to also check for function calls here
for expression in child.children:
if expression.type == 'call_expression':
self.functions[code[expression.child_by_field_name('function').start_byte:expression.child_by_field_name('function').end_byte]]['data_flows'].append('called')
elif child.type == 'if_statement':
# Potential security analysis for insecure patterns
if 'eval' in code[child.start_byte:child.end_byte]:
self.security_issues.append({
'issue': 'Potential use of eval',
'location': f'{child.start_point[0] + 1}:{child.start_point[1]}'
})
# Recurse deeper
self.extract_info(child, code)
def get_summary(self):
return {
'functions': self.functions,
'classes': self.classes,
'imports': self.imports,
'data_flow': self.data_flow,
'security_issues': self.security_issues
}
class Lenses:
@staticmethod
def functional_lens(code_summary):
functional_view = []
for file, elements in code_summary.items():
for function, details in elements['functions'].items():
functional_view.append({
'function_name': details['name'],
'params': details['params'],
'line_number': details['line_number'],
'data_flows': details['data_flows']
})
return functional_view
@staticmethod
def structural_lens(code_summary):
structural_view = []
for file, elements in code_summary.items():
for cls in elements['classes']:
structural_view.append({
'class_name': cls['name'],
'methods': cls['methods']
})
return structural_view
@staticmethod
def dependency_lens(code_summary):
dependency_view = []
for file, elements in code_summary.items():
for imp in elements['imports']:
dependency_view.append({
'import_statement': imp
})
return dependency_view
@staticmethod
def data_flow_lens(code_summary):
data_flow_view = []
for file, elements in code_summary.items():
for variable in elements['data_flow']:
data_flow_view.append({
'variable': variable
})
return data_flow_view
@staticmethod
def security_lens(code_summary):
security_view = []
for file, elements in code_summary.items():
for issue in elements['security_issues']:
security_view.append({
'issue': issue['issue'],
'location': issue['location']
})
return security_view
def get_language_analyzer(file_extension):
analyzers = {
'.py': CodeAnalyzer(PY_LANGUAGE),
'.js': CodeAnalyzer(JS_LANGUAGE),
}
return analyzers.get(file_extension.lower(), None)
def analyze_code(directory):
summary = {}
for filename in os.listdir(directory):
file_extension = os.path.splitext(filename)[1]
analyzer = get_language_analyzer(file_extension)
if analyzer is not None:
with open(os.path.join(directory, filename), 'r') as f:
code = f.read()
analyzer.analyze(code)
summary[filename] = analyzer.get_summary()
return summary
if __name__ == "__main__":
directory = "your_code_directory" # Change this to your actual code directory
code_summary = analyze_code(directory)
# Generate lens-specific summaries
functional_summary = Lenses.functional_lens(code_summary)
structural_summary = Lenses.structural_lens(code_summary)
dependency_summary = Lenses.dependency_lens(code_summary)
data_flow_summary = Lenses.data_flow_lens(code_summary)
security_summary = Lenses.security_lens(code_summary)
# Output summaries
output_summary = {
'functional': functional_summary,
'structural': structural_summary,
'dependencies': dependency_summary,
'data_flow': data_flow_summary,
'security': security_summary
}
# Save the generated summaries to a file
output_file = "summaries.json"
with open(output_file, "w") as f:
json.dump(output_summary, f, indent=2)
print(f"Summaries saved to {output_file}")
Explanations of Added Lenses:
Data Flow Lens:
This lens collects data about variable declarations and usages. It captures variable names upon declaration and notes instances where functions that might change them were called.
It gathers information about how data flows from one part of the code to another, which can be critical for understanding both the logic and the impact of the code.
Security Lens:
The security lens currently checks for the presence of potentially insecure patterns, such as the use of eval, and can be extended to include more checks (like SQL injection vulnerabilities, direct access to sensitive types, etc.).
It collects issues into a structured format that includes the type of issue and its location within the code.
Outputting Lenses:
Each lens has its own summarization method within the Lenses class to output specific formats for functional, structural, dependency, data flow, and security insights.
The final summary output includes all these perspectives, saved as a JSON file.
Usage:
Build and configure the Tree-sitter libraries as previously discussed.
Save the updated script and configure the directory variable.
Run the script, which will generate a summaries.json file containing comprehensive insights from all defined lenses.
Extensibility:
The security checks and data flow tracking can be expanded with more sophisticated analysis using additional heuristics or integrating external security linters.
For other languages, you can implement analogous methods to extract relevant information and maintain the lens structure to ensure comprehensive coverage across different codebases.
Performance-critical functions or methods.
Any profiling information (e.g., time complexity of algorithms).
Data structures used and their efficiency.
6. Concurrency/Synchronicity Lens
Purpose: Understand how the code manages concurrent tasks or asynchronous operations.
Elements to Capture:
Use of asynchronous programming constructs (e.g., async/await, threads, or locks).
Potential race conditions or deadlocks identified in the code flow.
7. Compliance Lens
Purpose: Check the code against compliance requirements for coding standards or regulatory needs.
Elements to Capture:
Coding style guidelines being adhered to (e.g., PEP 8 for Python).
Use of linters and static analysis tools (e.g., ESLint, RuboCop).
Security compliance checks.
8. Deployment Lens
Purpose: Understand deployment strategies and scripts used for deploying the application.
Purpose: Collect information about how the code is being used in practice, such as instances of method calls.
Elements to Capture:
Tracking how functions are invoked in different files or contexts.
Mapping dependencies or interactions between different components.
10. Change History Lens
Purpose: Analyze the change history of the codebase, which can provide insights into how the code has evolved over time.
Elements to Capture:
Commit history (e.g., using version control data).
Frequency of changes per file and major refactoring instances.
Authors or contributors involved in different parts of the code.
Incorporating Additional Lenses into Your Tool
To incorporate additional lenses into your existing code analysis tool, you will generally follow these steps:
Define the Purpose: Clarify what you want to achieve with each lens.
Identify Elements to Capture: Determine what data will be relevant for that lens.
Implement Analysis Logic: Add logic to your current script to apply these lenses to your codebase, ensuring you're leveraging Tree-sitter or another parsing technique where applicable.
Output Structure: Ensure that the output structure accommodates insights from new lenses in a clear and queryable format.
Conclusion
By implementing these additional lenses and ensuring that insights from these various perspectives are encoded in a way that a LLM can leverage, you create a much richer understanding of the codebase. This comprehensive understanding can lead to more effective code suggestions, debugging assistance, and overall clearer communication about the code's structure and functionality. Remember to continually adapt and refine these lenses based on team goals, changes in the codebase, and advancements in tooling and methodology.