How to Optimize Python Code with Code-Graph-RAG: A Complete Guide
Code-Graph-RAG transforms Python repositories into knowledge graphs to enable AI-driven code optimization, applying AST-safe patches only after explicit interactive approval.
Code-graph-rag (CG-RAG) by vitali87 is an open-source framework that converts your Python codebase into a queryable knowledge graph. By combining Tree-sitter parsing with retrieval-augmented generation (RAG), it identifies performance bottlenecks and suggests optimizations based on language-specific best practices. The entire pipeline runs locally, ensuring your source code never leaves your environment.
The Six-Phase Optimization Pipeline
The optimization workflow follows a strict architectural pipeline that mirrors CG-RAG’s query and editing capabilities. Each phase is implemented across the codebase_rag/ module and documented in the code optimization guide.
Phase 1: Parsing and Graph Construction
CG-RAG uses a Tree-sitter parser to walk every Python file in your repository. It extracts AST nodes—functions, classes, imports, and call graphs—and persists them into a Memgraph database using a language-agnostic schema. This graph structure enables semantic traversal of code relationships that static linters cannot capture.
Phase 2: Natural-Language to Cypher Translation
When you invoke the optimizer, the CLI sends your natural-language request to the RAG layer. The system translates intent into Cypher queries that retrieve relevant AST subgraphs from Memgraph. According to the source in [codebase_rag/cli.py](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cli.py#L877), the optimize function orchestrates this retrieval before passing context to the language model.
Phase 3: LLM-Powered Code Analysis
Retrieved code snippets are fed to a local or remote LLM (configurable via --orchestrator). The model evaluates snippets against language-specific best practices—such as replacing list comprehensions with generator expressions inside loops—and generates a ranked list of optimization suggestions with specific line references.
Phase 4: Interactive Approval
Safety is enforced through an interactive approval step. Each suggestion requires explicit user confirmation (y/n) before any modification occurs. This prevents automated changes that might alter program semantics or break existing interfaces.
Phase 5: AST-Based Patch Application
Approved optimizations are converted into AST patches via the editing utilities in codebase_rag/editing/patcher.py. Unlike text-based find-and-replace, AST patching modifies the abstract syntax tree directly, preserving formatting, import ordering, and type-hint integrity. This approach eliminates syntax errors common in regex-based refactoring tools.
Phase 6: Graph and Code Synchronization
After patch application, the affected nodes in Memgraph are updated immediately. This synchronization ensures the knowledge graph remains consistent with the on-disk source, allowing subsequent optimization passes to operate on the latest codebase state.
CLI Optimization Commands
The fastest way to optimize Python code is through the cgr optimize command. Below are the supported patterns according to the CLI reference.
Basic Repository Optimization
cgr optimize python --repo-path /path/to/your/repo
This command ingests the repository, queries the graph for anti-patterns, and initiates the interactive approval workflow.
Using Custom Reference Documents
Supply a markdown file containing project-specific standards or domain constraints:
cgr optimize python \
--repo-path /path/to/your/repo \
--reference-document ./team_best_practices.md
Selecting Alternative LLM Models
Override the default model by specifying an orchestrator string:
cgr optimize python \
--repo-path /path/to/your/repo \
--orchestrator openai:gpt-4o-mini
Programmatic Optimization with the Python SDK
For integration into CI/CD pipelines or custom workflows, use the Python SDK to inspect candidates before applying patches.
from cgr.sdk.graph_loader import GraphLoader
from cgr.sdk.semantic_search import SemanticSearch
# Load the existing knowledge graph for the repository
loader = GraphLoader(repo_path="/path/to/your/repo")
graph = loader.load()
# Semantic search for specific anti-patterns
search = SemanticSearch(graph)
candidates = search.search("list comprehension inside loop", language="python")
# Inspect candidates before optimization
for node in candidates:
print(f"{node['file']}:{node['line']} – {node['name']}")
The SDK returns structured node data that you can filter, audit, or feed into custom optimization logic before invoking the patcher.
Key Source Files
Understanding the implementation requires reference to the following files in the vitali87/code-graph-rag repository:
-
codebase_rag/cli.py– Implements thecgr optimizecommand interface and orchestrates the six-phase pipeline. The coreoptimizefunction is located at line 877. -
docs/guide/code-optimization.md– User-facing documentation explaining optimization strategies, supported languages, and approval workflows. -
docs/guide/cli-reference.md– Exhaustive reference for CLI flags including--repo-path,--reference-document, and--orchestrator. -
codebase_rag/editing/patcher.py– Contains the AST patch application logic that safely modifies source files while preserving syntax and formatting. -
codebase_rag/graph_loader.py– Handles loading and synchronization of the Memgraph knowledge graph from repository state. -
README.md– High-level architecture overview describing how Tree-sitter parsing and Memgraph storage enable the optimization features.
Summary
- Code-Graph-RAG converts Python codebases into Memgraph knowledge graphs using Tree-sitter parsers.
- The
cgr optimizecommand translates natural language into Cypher queries to retrieve relevant code contexts. - An LLM analyzes retrieved snippets and suggests performance improvements based on best practices.
- Interactive approval (
y/n) is mandatory before any change is applied. - AST patches modify the syntax tree directly, ensuring formatting and imports remain intact.
- The graph database stays synchronized with source files after every patch application.
- All components run locally (Memgraph, Qdrant for embeddings, and configurable LLM backends).
Frequently Asked Questions
How does code-graph-rag prevent breaking my code during optimization?
The system uses AST-based patching via codebase_rag/editing/patcher.py rather than text replacement. By manipulating the abstract syntax tree, it ensures that modifications respect Python’s grammar, preserving indentation, comments, and import structures that regex-based tools often corrupt.
Can I use code-graph-rag with private repositories or offline environments?
Yes. The optimization pipeline runs entirely locally using Memgraph for graph storage and Qdrant for semantic search. You only need network access if you choose a cloud-based LLM orchestrator; local models like Ollama or LM Studio are fully supported offline.
What types of Python optimizations does the tool detect?
The LLM identifies common anti-patterns such as unnecessary list materialization, suboptimal loop constructs, redundant imports, and inefficient data structure usage. You can tailor detection by providing a custom --reference-document containing project-specific performance guidelines.
How do I integrate code-graph-rag into an automated CI/CD pipeline?
While the CLI requires interactive approval by default, the Python SDK (cgr.sdk) allows programmatic access to the graph and patcher. You can script the optimization flow, implement custom approval heuristics, and apply patches non-interactively using the SDK’s GraphLoader and editing utilities.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →