AI-Powered Code Optimization Options in Code-Graph-RAG: A Complete Guide

Code-Graph-RAG provides an LLM-driven optimization workflow that automatically scans codebases, surfaces performance and maintainability issues, and applies approved fixes—all from the command line.

Code-Graph-RAG is an open-source retrieval-augmented generation (RAG) tool for codebases that adds a dedicated optimization engine. This feature lets developers run AI-powered code optimization without leaving their terminal, leveraging a knowledge graph built from source code structure.

How the Code-Graph-RAG Optimization Engine Works

The optimization pipeline combines static analysis with large language models through five coordinated stages.

1. Parsing and Graph Ingestion

Code-Graph-RAG uses Tree-sitter to extract abstract syntax trees from source files. The parser supports 13 languages:

  • Python
  • JavaScript / TypeScript
  • Rust
  • Go
  • Java
  • Scala
  • C / C++

Functions, classes, modules, and call relationships are stored in a Memgraph knowledge graph. This structural representation enables context-aware analysis that surface-level linters cannot match.

2. Interactive Optimization Session

The optimization entry point resides in codebase_rag/cli.py. When you execute cgr optimize, the CLI prepares the LLM orchestrator, loads the graph from Memgraph, and starts an async optimization loop.

3. Pattern Recognition via Graph Queries

The agent queries the knowledge graph for anti-patterns such as:

  • Eager list comprehensions in hot paths
  • Un-cached heavy loops
  • Missing constexpr in C++
  • Sub-optimal move semantics

The system also respects project-specific standards when you provide a reference document.

4. Suggestion and Approval

Each finding includes a concise description. The agent prompts for confirmation ([y/n]) before proceeding. Skip this interactively with --no-confirm for CI/CD pipelines.

5. Patch Generation and Application

Approved suggestions become diffs using diff-match-patch, applied in-place with explanatory commit-style messages.

CLI Options for AI-Powered Code Optimization

Option Purpose
--repo-path Target repository path (default: current directory)
--reference-document Markdown file with project coding standards
--orchestrator LLM provider:model for optimization decisions (e.g., google:gemini-3.6-flash)
--cypher Separate LLM for Cypher graph query generation
--batch-size Override Memgraph flush batch size for large repositories
--no-confirm Apply suggestions without prompting
--no-instructions Suppress the initial instructional banner

All options are documented in the official Code Optimisation guide.

Optimization Workflow Examples

Basic Python Optimization

cgr optimize python --repo-path ./my-python-app

Java with Custom Best Practices

cgr optimize java \
    --repo-path ./my-java-service \
    --reference-document ./docs/ARCHITECTURE.md

Rust with Specific LLM and Auto-Apply

cgr optimize rust \
    --repo-path ./rust-lib \
    --orchestrator google:gemini-3.6-flash \
    --no-confirm

Programmatic API for Code Optimization

The same optimization engine is available via main_optimize_async in codebase_rag/main.py:

from codebase_rag.main import main_optimize_async
import asyncio

async def run():
    await main_optimize_async(
        language="python",
        repo_path="./my-python-app",
        reference_document=None,
        orchestrator="openai:gpt-4o-mini",
        no_confirm=False,
    )

asyncio.run(run())

This function drives the identical optimization loop used by the CLI, enabling integration into custom tooling or automated workflows.

Key Implementation Files

File Responsibility
codebase_rag/cli.py Typer CLI definition; parses optimize command arguments and launches the optimization loop
codebase_rag/main.py Core async implementation with run_optimization_loop and main_optimize_async
docs/guide/code-optimization.md User documentation for the optimization command
docs/architecture/overview.md System architecture covering parser, Memgraph, and RAG components

Summary

  • Code-Graph-RAG adds AI-powered code optimization through a dedicated cgr optimize command
  • The engine builds a Memgraph knowledge graph from Tree-sitter ASTs across 13 languages
  • Dual LLM configuration lets you separate optimization logic (--orchestrator) from query generation (--cypher)
  • Interactive approval flows ensure human oversight, bypassable with --no-confirm
  • Programmatic access via main_optimize_async enables custom integrations

Frequently Asked Questions

What languages does Code-Graph-RAG optimization support?

Code-Graph-RAG supports 13 languages through Tree-sitter: Python, JavaScript, TypeScript, Rust, Go, Java, Scala, C, C++, and others. The parser extracts complete AST structures for graph-based analysis regardless of language.

How does the AI optimization engine find performance issues?

The engine queries the Memgraph knowledge graph for structural anti-patterns—inefficient data structures, redundant computations, and missing optimizations. It combines these graph queries with LLM reasoning to generate contextual suggestions tailored to your specific codebase.

Can I use my own coding standards with the optimizer?

Yes. Pass a markdown file to --reference-document containing your team's architecture decisions or best practices. The optimization agent incorporates this context when evaluating suggestions, ensuring alignment with project conventions.

Is it possible to run Code-Graph-RAG optimization in CI/CD pipelines?

Absolutely. Use --no-confirm to bypass interactive prompts and apply approved changes automatically. The --orchestrator flag lets you specify exact LLM versions for reproducible results, and the programmatic API (main_optimize_async) enables custom workflow integration.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →