Search Monorepos and get relevant answers
Code-Graph-RAG:面向任意代码库的基于图的 RAG 系统
一个精准的检索增强生成(RAG)系统,它利用 Tree-sitter 分析多语言代码库,构建全面的知识图谱,并支持以自然语言查询代码库结构和关系,同时具备编辑能力。
最新动态 🔥
- PHP 语言支持:新增完整的 PHP 语言支持——类、接口、特征、枚举、命名空间、PHP 8 属性以及调用图分析。由 @rs-ipps 贡献。
- C 语言支持:新增完整的 C 语言支持——函数、结构体、联合体、枚举、预处理器包含以及调用图分析。由 @dj0nes 贡献。
- 即时可视化任何 GitHub 仓库! 只需将任意仓库 URL 中的
github.com改为gitcgr.com——就是这样,只需改 3 个字母!即可获得整个代码库结构的交互式图谱。立即尝试:gitcgr.com
🚀 功能特性
- 多语言支持:
| 语言 | 状态 | 扩展名 | 函数 | 类/结构体 | 模块 | 包检测 | 附加特性 |
|---|---|---|---|---|---|---|---|
| C | 完全支持 | .c | ✓ | ✓ | ✓ | ✓ | 函数、结构体、联合体、枚举、预处理器包含 |
| C++ | 完全支持 | .cpp, .h, .hpp, .cc, .cxx, .hxx, .hh, .ixx, .cppm, .ccm | ✓ | ✓ | ✓ | ✓ | 构造函数、析构函数、运算符重载、模板、Lambda 表达式、C++20 模块、命名空间 |
| Java | 完全支持 | .java | ✓ | ✓ | ✓ | - | 泛型、注解、现代特性(记录/密封类)、并发、反射 |
| JavaScript | 完全支持 | .js, .jsx | ✓ | ✓ | ✓ | - | ES6 模块、CommonJS、原型方法、对象方法、箭头函数 |
| Lua | 完全支持 | .lua | ✓ | - | ✓ | - | 局部/全局函数、元表、闭包、协程 |
| PHP | 完全支持 | .php | ✓ | ✓ | ✓ | - | 类、接口、特征、枚举、命名空间、PHP 8 属性 |
| Python | 完全支持 | .py | ✓ | ✓ | ✓ | ✓ | 类型推断、装饰器、嵌套函数 |
| Rust | 完全支持 | .rs | ✓ | ✓ | ✓ | ✓ | impl 块、关联函数 |
| TypeScript | 完全支持 | .ts, .tsx | ✓ | ✓ | ✓ | - | 接口、类型别名、枚举、命名空间、ES6/CommonJS 模块 |
| C# | 开发中 | .cs | ✓ | ✓ | ✓ | - | 类、接口、泛型(计划中) |
| Go | 开发中 | .go | ✓ | ✓ | ✓ | - | 方法、类型声明 |
| Scala | 开发中 | .scala, .sc | ✓ | ✓ | ✓ | - | 样例类、对象 |
- 🌳 Tree-sitter 解析:使用 Tree-sitter 进行稳健的、语言无关的 AST 解析
- 📊 知识图谱存储:使用 Memgraph 将代码库结构存储为互联图谱
- 🗣️ 自然语言查询:用通俗易懂的英语提问有关代码库的问题
- 🤖 AI 驱动的 Cypher 生成:支持云模型(Google Gemini)、本地模型(Ollama)和 OpenAI 模型,实现自然语言到 Cypher 的转换
- 🤖 OpenAI 集成:利用 OpenAI 模型增强 AI 功能。
- 📝 代码片段检索:检索找到的函数/方法的实际源代码片段
- ✍️ 高级文件编辑:基于 AST 的函数定位实现精准代码替换,提供可视化差异预览和精确代码块修改
- ⚡️ Shell 命令执行:可执行终端命令,用于运行测试或使用 CLI 工具等任务。
- 🚀 交互式代码优化:AI 驱动的代码库优化,结合特定语言的最佳实践和交互式审批工作流
- 📚 参考引导式优化:使用您自己的编码标准和架构文档来指导优化建议
- 🔗 依赖分析:解析
pyproject.toml以了解外部依赖 - 🎯 嵌套函数支持:处理复杂的嵌套函数和类层次结构
- 🔄 语言无关设计:所有支持语言采用统一的图谱模式
🏗️ 架构
该系统包含两个主要组件:
- 多语言解析器:基于 Tree-sitter 的解析系统,用于分析代码库并将数据导入 Memgraph
- RAG 系统(
codebase_rag/):用于查询存储的知识图谱的交互式命令行界面
📋 前提条件
- Python 3.12+
- Docker 与 Docker Compose(用于 Memgraph)
- cmake(构建 pymgclient 依赖项所需)
- ripgrep(
rg)(用于 shell 命令文本搜索所需) - 对于云模型:Google Gemini API 密钥
- 对于本地模型:已安装并运行 Ollama
uv包管理器
安装 cmake 和 ripgrep
在 macOS 上:
brew install cmake ripgrep
在 Linux(Ubuntu/Debian)系统上:
sudo apt-get update
sudo apt-get install cmake ripgrep
在 Linux(CentOS/RHEL)上:
sudo yum install cmake
sudo dnf install ripgrep
# Note: ripgrep may need to be installed from EPEL or via cargo
🛠️ 安装
git clone https://github.com/vitali87/code-graph-rag.git
cd code-graph-rag
- 安装依赖项:
基础 Python 支持:
uv sync
若需完整的多语言支持:
uv sync --extra treesitter-full
用于开发(包括测试和预提交钩子):
make dev
这会安装所有依赖项并自动设置预提交钩子。
这将为所有支持的语言安装 Tree-sitter 语法(请参阅多语言支持部分)。
- 设置环境变量:
cp .env.example .env
# Edit .env with your configuration (see options below)
配置选项
全新的显式提供程序配置支持为编排器和cypher模型混合使用不同的提供程序。
选项1:全Ollama(本地模型)
# .env file
ORCHESTRATOR_PROVIDER=ollama
ORCHESTRATOR_MODEL=llama3.2
ORCHESTRATOR_ENDPOINT=http://localhost:11434/v1
CYPHER_PROVIDER=ollama
CYPHER_MODEL=codellama
CYPHER_ENDPOINT=http://localhost:11434/v1
选项 2:所有 OpenAI 模型
# .env file
ORCHESTRATOR_PROVIDER=openai
ORCHESTRATOR_MODEL=gpt-4o
ORCHESTRATOR_API_KEY=sk-your-openai-key
CYPHER_PROVIDER=openai
CYPHER_MODEL=gpt-4o-mini
CYPHER_API_KEY=sk-your-openai-key
选项 3:所有 Google 模型
# .env file
ORCHESTRATOR_PROVIDER=google
ORCHESTRATOR_MODEL=gemini-2.5-pro
ORCHESTRATOR_API_KEY=your-google-api-key
CYPHER_PROVIDER=google
CYPHER_MODEL=gemini-2.5-flash
CYPHER_API_KEY=your-google-api-key
选项 4:混合提供商
# .env file - Google orchestrator + Ollama cypher
ORCHESTRATOR_PROVIDER=google
ORCHESTRATOR_MODEL=gemini-2.5-pro
ORCHESTRATOR_API_KEY=your-google-api-key
CYPHER_PROVIDER=ollama
CYPHER_MODEL=codellama
CYPHER_ENDPOINT=http://localhost:11434/v1
从 Google AI Studio 获取您的 Google API 密钥。
安装并运行 Ollama:
# Install Ollama (macOS/Linux)
curl -fsSL https://ollama.ai/install.sh | sh
# Pull required models
ollama pull llama3.2
# Or try other models like:
# ollama pull llama3
# ollama pull mistral
# ollama pull codellama
# Ollama will automatically start serving on localhost:11434
注意:本地模型可保障隐私且无需 API 费用,但与 Gemini 等云模型相比,其准确性可能较低。
- 启动 Memgraph 数据库:
docker compose up -d
- 验证安装:
# If installed from PyPI:
cgr --help
# If running from source:
uv run cgr --help
注意:从源代码(克隆的仓库)运行时,请在以下所有
cgr命令前添加uv run,例如uv run cgr start ...
🛠️ Makefile 命令
使用 Makefile 执行常见开发任务:
| 命令 | 描述 |
|---|---|
make help |
显示此帮助信息 |
make all |
安装完整开发环境所需的所有组件(依赖项、语法、钩子、测试) |
make install |
安装项目依赖项,包含完整语言支持 |
make python |
仅安装项目的 Python 依赖项 |
make dev |
设置开发环境(安装依赖项 + pre-commit 钩子) |
make test |
仅运行单元测试(快速,无需 Docker) |
make test-parallel |
并行运行单元测试(快速,无需 Docker) |
make test-integration |
运行集成测试(需要 Docker) |
make test-all |
运行所有测试,包括集成测试和端到端测试(需要 Docker) |
make test-parallel-all |
并行运行所有测试,包括集成测试和端到端测试(需要 Docker) |
make clean |
清理构建产物和缓存 |
make build-grammars |
构建语法子模块 |
make watch |
监视仓库变化并实时更新图谱 |
make readme |
从代码库重新生成 README.md |
make lint |
运行 ruff 检查 |
make format |
运行 ruff 格式化 |
make typecheck |
使用 ty 运行类型检查 |
make check |
运行所有检查:代码规范、类型检查、测试 |
make pre-commit |
本地运行所有 pre-commit 检查(提交前的全面测试) |
🎯 使用方法
Code-Graph-RAG 系统提供四种主要操作模式:
- 解析与摄入:从代码库构建知识图谱
- 交互式查询:用自然语言询问有关代码的问题
- 导出与分析:导出图谱数据以进行程序化分析
- AI 优化:获取 AI 驱动的代码优化建议
- 编辑:通过精确目标定位执行精准的代码替换和修改
步骤 1:解析仓库
将多语言仓库解析并摄入知识图谱:
对于第一个仓库(全新开始):
cgr start --repo-path /path/to/repo1 --update-graph --clean
对于其他代码库(保留现有数据):
cgr start --repo-path /path/to/repo2 --update-graph
cgr start --repo-path /path/to/repo3 --update-graph
控制 Memgraph 批量刷新:
# Flush every 5,000 records instead of the default from settings
cgr start --repo-path /path/to/repo --update-graph \
--batch-size 5000
系统会自动检测并处理所有受支持语言的文件(详见多语言支持部分)。
第二步:查询代码库
交互模式:
启动交互式 RAG 命令行界面:
cgr start --repo-path /path/to/your/repo
非交互模式(单次查询):
运行单个查询后退出,输出将发送至标准输出(对脚本编写很有用):
python -m codebase_rag.main start --repo-path /path/to/your/repo \
--ask-agent "What functions call UserService.create_user?"
步骤 2.5:实时图谱更新(可选)
在积极开发过程中,您可以使用实时更新器使知识图谱自动与代码变更保持同步。当您正在积极修改代码并希望 AI 助手始终基于最新的代码库结构工作时,此功能尤其有用。
功能说明:
- 监控您的仓库以获取文件变更(创建、修改、删除)
- 自动实时更新知识图谱
- 通过重新计算所有函数调用关系来保持一致性
- 过滤掉不相关的文件(如
.git、node_modules等)
使用方法:
在单独的终端中运行实时更新器:
# Using Python directly
python realtime_updater.py /path/to/your/repo
# Or using the Makefile
make watch REPO_PATH=/path/to/your/repo
使用自定义 Memgraph 设置:
# Python
python realtime_updater.py /path/to/your/repo --host localhost --port 7687 --batch-size 1000
# Makefile
make watch REPO_PATH=/path/to/your/repo HOST=localhost PORT=7687 BATCH_SIZE=1000
多终端工作流:
# Terminal 1: Start the realtime updater
python realtime_updater.py ~/my-project
# Terminal 2: Run the AI assistant
cgr start --repo-path ~/my-project
性能说明: 更新器目前会在每次文件变更时重新计算所有 CALLS 关系以确保一致性。这能防止“孤岛”问题(即某个文件的变更未反映在其他文件的关系中),但在频繁变更的超大型代码库中可能会影响性能。注意: 此行为的优化工作正在进行中。
CLI 参数:
repo_path(必填):要监控的仓库路径--host:Memgraph 主机(默认:localhost)--port:Memgraph 端口(默认:7687)--batch-size:刷新到 Memgraph 之前缓冲的节点/关系数量
指定自定义模型:
# Use specific local models
cgr start --repo-path /path/to/your/repo \
--orchestrator ollama:llama3.2 \
--cypher ollama:codellama
# Use specific Gemini models
cgr start --repo-path /path/to/your/repo \
--orchestrator google:gemini-2.0-flash-thinking-exp-01-21 \
--cypher google:gemini-2.5-flash-lite-preview-06-17
# Use mixed providers
cgr start --repo-path /path/to/your/repo \
--orchestrator google:gemini-2.0-flash-thinking-exp-01-21 \
--cypher ollama:codellama
示例查询(支持所有语言):
- "Show me all classes that contain 'user' in their name"
- "Find functions related to database operations"
- "What methods does the User class have?"
- "Show me functions that handle authentication"
- "List all TypeScript components"
- "Find Rust structs and their methods"
- "Show me Go interfaces and implementations"
- "Find all C++ operator overloads in the Matrix class"
- "Show me C++ template functions with their specializations"
- "List all C++ namespaces and their contained classes"
- "Find C++ lambda expressions used in algorithms"
- "Add logging to all database connection functions"
- "Refactor the User class to use dependency injection"
- "Convert these Python functions to async/await pattern"
- "Add error handling to authentication methods"
- "Optimize this function for better performance"
步骤 3:导出图谱数据
为了实现程序化访问并与其他工具集成,您可以将整个知识图谱导出为 JSON 格式:
在图谱更新期间导出:
cgr start --repo-path /path/to/repo --update-graph --clean -o my_graph.json
导出现有图谱而不更新:
cgr export -o my_graph.json
可选:在导出期间调整 Memgraph 批处理:
cgr export -o my_graph.json --batch-size 5000
使用导出的数据:
from codebase_rag.graph_loader import load_graph
# Load the exported graph
graph = load_graph("my_graph.json")
# Get summary statistics
summary = graph.summary()
print(f"Total nodes: {summary['total_nodes']}")
print(f"Total relationships: {summary['total_relationships']}")
# Find specific node types
functions = graph.find_nodes_by_label("Function")
classes = graph.find_nodes_by_label("Class")
# Analyze relationships
for func in functions[:5]:
relationships = graph.get_relationships_for_node(func.node_id)
print(f"Function {func.properties['name']} has {len(relationships)} relationships")
示例分析脚本:
python examples/graph_export_example.py my_graph.json
这提供了一种可靠的、程序化的方式来访问您的代码库结构,不受LLM限制,非常适合:
- 与其他工具集成
- 自定义分析脚本
- 构建文档生成器
- 创建代码指标仪表板
步骤4:代码优化
如需借助AI力量进行代码库优化并获取最佳实践指导:
特定语言的基本优化:
cgr optimize python --repo-path /path/to/your/repo
结合参考文档进行优化:
cgr optimize python \
--repo-path /path/to/your/repo \
--reference-document /path/to/best_practices.md
使用特定模型进行优化:
cgr optimize javascript \
--repo-path /path/to/frontend \
--orchestrator google:gemini-2.0-flash-thinking-exp-01-21
# Optional: override Memgraph batch flushing during optimization
cgr optimize javascript --repo-path /path/to/frontend \
--batch-size 5000
支持优化的语言:
所有支持的语言:python、javascript、typescript、rust、go、java、scala、c、cpp
工作原理:
- 分析阶段:智能体使用知识图谱分析您的代码库结构
- 模式识别:识别常见的反模式、性能问题和改进机会
- 最佳实践应用:应用特定于语言的最佳实践和模式
- 交互式审批:在实施前呈现每个优化建议供您审批
- 引导式实施:实施已批准的更改并提供详细说明
优化会话示例:
Starting python optimization session...
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ The agent will analyze your python codebase and propose specific ┃
┃ optimizations. You'll be asked to approve each suggestion before ┃
┃ implementation. Type 'exit' or 'quit' to end the session. ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
🔍 Analyzing codebase structure...
📊 Found 23 Python modules with potential optimizations
💡 Optimization Suggestion #1:
File: src/data_processor.py
Issue: Using list comprehension in a loop can be optimized
Suggestion: Replace with generator expression for memory efficiency
[y/n] Do you approve this optimization?
参考文档支持: 您可以提供参考文档(如编码标准、架构指南或最佳实践文档)来指导优化过程:
# Use company coding standards
cgr optimize python \
--reference-document ./docs/coding_standards.md
# Use architectural guidelines
cgr optimize java \
--reference-document ./ARCHITECTURE.md
# Use performance best practices
cgr optimize rust \
--reference-document ./docs/performance_guide.md
在提出优化建议时,智能体将参考您的文档内容,确保建议符合项目标准和架构决策。
常用 CLI 参数:
--orchestrator:指定主操作的 provider:model(例如google:gemini-2.0-flash-thinking-exp-01-21、ollama:llama3.2)--cypher:指定图查询的 provider:model(例如google:gemini-2.5-flash-lite-preview-06-17、ollama:codellama)--repo-path:代码库路径(默认为当前目录)--batch-size:覆盖 Memgraph 刷新批处理大小(默认为设置中的MEMGRAPH_BATCH_SIZE)--reference-document:参考文档路径(仅用于优化)
🔌 MCP 服务器(Claude Code 集成)
Code-Graph-RAG 可以作为 MCP(模型上下文协议)服务器运行,实现与 Claude Code 及其他 MCP 客户端的无缝集成。
快速设置
claude mcp add --transport stdio code-graph-rag \
--env TARGET_REPO_PATH=/absolute/path/to/your/project \
--env CYPHER_PROVIDER=openai \
--env CYPHER_MODEL=gpt-4 \
--env CYPHER_API_KEY=your-api-key \
-- uv run --directory /path/to/code-graph-rag code-graph-rag mcp-server
可用工具
| 工具 | 描述 |
|---|---|
list_projects |
列出知识图谱数据库中所有已索引的项目。返回已索引的项目名称列表。 |
delete_project |
从知识图谱数据库中删除特定项目。此操作会移除与该项目相关的所有节点,同时保留其他项目。请先使用 list_projects 查看可用项目。 |
wipe_database |
警告:完全清空整个数据库,删除所有已索引的项目。此操作无法撤销。删除单个项目请使用 delete_project。 |
index_repository |
警告:清除当前项目的所有数据,包括其嵌入向量。解析并将仓库数据摄入 Memgraph 知识图谱。增量更新请使用 update_repository。仅在明确要求时使用。 |
update_repository |
在不清空现有数据的情况下更新 Memgraph 知识图谱中的仓库。用于增量更新。 |
query_code_graph |
使用自然语言查询代码库知识图谱。除非您知道要搜索的类/函数的确切名称,否则请使用 semantic_search。可提问如“哪些函数调用了 UserService.create_user?”或“显示所有实现 Repository 接口的类”。 |
get_code_snippet |
通过限定名检索函数、类或方法的源代码。返回源代码、文件路径、行号和文档字符串。 |
surgical_replace_code |
使用 diff-match-patch 精确替换文件中的代码块。仅修改确切的目标块,其余内容保持不变。 |
read_file |
读取项目中文件的内容。支持大文件分页。 |
write_file |
将内容写入文件,若文件不存在则创建。 |
list_directory |
列出项目中目录的内容。 |
semantic_search |
根据描述函数用途的自然语言查询执行语义搜索,返回带有相似度分数的潜在匹配列表。需要安装 'semantic' 扩展。 |
ask_agent |
向 RAG 智能体询问有关代码库的问题。将完整的 RAG 流程(图谱查询、LLM 响应)包装为 MCP 工具。 |
示例用法
> Index this repository
> What functions call UserService.create_user?
> Update the login function to add rate limiting
有关详细的设置步骤,请参见 Claude 代码设置指南。
📊 图结构
知识图谱采用以下节点类型及关系:
节点类型
| 标签 | 属性 |
|---|---|
| Project | {name: string} |
| Package | {qualified_name: string, name: string, path: string, absolute_path: string} |
| Folder | {path: string, name: string, absolute_path: string} |
| File | {path: string, name: string, extension: string, absolute_path: string} |
| Module | {qualified_name: string, name: string, path: string, absolute_path: string} |
| Class | {qualified_name: string, name: string, decorators: list[string], path: string, absolute_path: string} |
| Function | {qualified_name: string, name: string, decorators: list[string], path: string, absolute_path: string} |
| Method | {qualified_name: string, name: string, decorators: list[string], path: string, absolute_path: string} |
| Interface | {qualified_name: string, name: string, path: string, absolute_path: string} |
| Enum | {qualified_name: string, name: string, path: string, absolute_path: string} |
| Type | {qualified_name: string, name: string} |
| Union | {qualified_name: string, name: string} |
| ModuleInterface | {qualified_name: string, name: string, path: string, absolute_path: string} |
| ModuleImplementation | {qualified_name: string, name: string, path: string, absolute_path: string, implements_module: string} |
| ExternalPackage | {name: string, version_spec: string} |
语言特定映射
- C:
enum_specifier、function_definition、struct_specifier、union_specifier - C++:
class_specifier、declaration、enum_specifier、field_declaration、function_definition、lambda_expression、struct_specifier、template_declaration、union_specifier - Java:
annotation_type_declaration、class_declaration、constructor_declaration、enum_declaration、interface_declaration、method_declaration、record_declaration - JavaScript:
arrow_function、class、class_declaration、function_declaration、function_expression、generator_function_declaration、method_definition - Lua:
function_declaration、function_definition - PHP:
anonymous_function、arrow_function、class_declaration、enum_declaration、function_definition、interface_declaration、method_declaration、trait_declaration - Python:
class_definition、function_definition - Rust:
closure_expression、enum_item、function_item、function_signature_item、impl_item、struct_item、trait_item、type_item、union_item - TypeScript:
abstract_class_declaration、arrow_function、class、class_declaration、enum_declaration、function_declaration、function_expression、function_signature、generator_function_declaration、interface_declaration、internal_module、method_definition、type_alias_declaration - C#:
anonymous_method_expression、class_declaration、constructor_declaration、destructor_declaration、enum_declaration、function_pointer_type、interface_declaration、lambda_expression、local_function_statement、method_declaration、struct_declaration - Go:
function_declaration、method_declaration、type_declaration - Scala:
class_definition、function_declaration、function_definition、object_definition、trait_definition
关系
| 来源 | 关系 | 目标 |
|---|---|---|
| 项目、包、文件夹 | CONTAINS_PACKAGE | 包 |
| 项目、包、文件夹 | CONTAINS_FOLDER | 文件夹 |
| 项目、包、文件夹 | CONTAINS_FILE | 文件 |
| 项目、包、文件夹 | CONTAINS_MODULE | 模块 |
| 模块 | DEFINES | 类、函数 |
| 类 | DEFINES_METHOD | 方法 |
| 模块 | IMPORTS | 模块 |
| 模块 | EXPORTS | 类、函数 |
| 模块 | EXPORTS_MODULE | ModuleInterface |
| 模块 | IMPLEMENTS_MODULE | ModuleImplementation |
| 类 | INHERITS | 类 |
| 类 | IMPLEMENTS | 接口 |
| 方法 | OVERRIDES | 方法 |
| ModuleImplementation | IMPLEMENTS | ModuleInterface |
| 项目 | DEPENDS_ON_EXTERNAL | 外部包 |
| 函数、方法 | CALLS | 函数、方法 |
🔧 配置
配置通过 .env 文件中的环境变量进行管理:
特定提供商设置
编排器模型配置
ORCHESTRATOR_PROVIDER:提供商名称(google、openai、ollama)ORCHESTRATOR_MODEL:模型 ID(例如:gemini-2.5-pro、gpt-4o、llama3.2)ORCHESTRATOR_API_KEY:提供商的 API 密钥(如需要)ORCHESTRATOR_ENDPOINT:自定义端点 URL(如需要)ORCHESTRATOR_PROJECT_ID:Google Cloud 项目 ID(适用于 Vertex AI)ORCHESTRATOR_REGION:Google Cloud 区域(默认:us-central1)ORCHESTRATOR_PROVIDER_TYPE:Google 提供商类型(gla或vertex)ORCHESTRATOR_THINKING_BUDGET:推理模型的思考预算ORCHESTRATOR_SERVICE_ACCOUNT_FILE:服务账户文件路径(适用于 Vertex AI)
Cypher 模型配置
CYPHER_PROVIDER:提供商名称(google、openai、ollama)CYPHER_MODEL:模型 ID(例如:gemini-2.5-flash、gpt-4o-mini、codellama)CYPHER_API_KEY:提供商的 API 密钥(如需要)CYPHER_ENDPOINT:自定义端点 URL(如需要)CYPHER_PROJECT_ID:Google Cloud 项目 ID(适用于 Vertex AI)CYPHER_REGION:Google Cloud 区域(默认:us-central1)CYPHER_PROVIDER_TYPE:Google 提供商类型(gla或vertex)CYPHER_THINKING_BUDGET:推理模型的思考预算CYPHER_SERVICE_ACCOUNT_FILE:服务账户文件路径(适用于 Vertex AI)
系统设置
MEMGRAPH_HOST:Memgraph 主机名(默认值:localhost)MEMGRAPH_PORT:Memgraph 端口(默认值:7687)MEMGRAPH_HTTP_PORT:Memgraph HTTP 端口(默认值:7444)LAB_PORT:Memgraph Lab 端口(默认值:3000)MEMGRAPH_BATCH_SIZE:Memgraph 操作的批处理大小(默认值:1000)TARGET_REPO_PATH:默认仓库路径(默认值:.)LOCAL_MODEL_ENDPOINT:Ollama 的备用端点(默认值:http://localhost:11434/v1)
自定义忽略模式
您可以通过在仓库根目录创建 .cgrignore 文件来指定需要排除的其他目录:
# Comments start with #
vendor
.custom_cache
my_build_output
- 每行一个目录名
- 以
#开头的行为注释 - 空行将被忽略
- 模式为精确的目录名匹配(非通配符)
.cgrignore中的模式会与--exclude标志以及自动检测到的目录合并
核心依赖
- loguru:让 Python 日志记录变得(极其)简单
- mcp:模型上下文协议 SDK
- pydantic-ai:用于将 Pydantic 与 LLM 结合使用的代理框架/适配层
- pydantic-settings:使用 Pydantic 进行设置管理
- pymgclient:Memgraph 数据库的 Python 语言适配器
- python-dotenv:从 .env 文件读取键值对并将其设置为环境变量
- tiktoken:用于令牌计数和上下文窗口管理的快速 BPE 令牌器
- toml:Tom 的简洁、直观标记语言(Tom's Obvious, Minimal Language)的 Python 库
- tree-sitter-python:tree-sitter 的 Python 语法
- tree-sitter:Tree-sitter 解析库的 Python 绑定
- watchdog:文件系统事件监控
- typer:Typer,构建出色的命令行界面。易于编码。基于 Python 类型提示。
- rich:在终端中渲染富文本、表格、进度条、语法高亮、Markdown 等内容
- prompt-toolkit:用于在 Python 中构建强大交互式命令行的库
- diff-match-patch:Google 的 Diff Match and Patch 库的重新打包版本
- click:可组合的命令行界面工具包
- protobuf
- defusedxml:为 Python 标准库模块提供 XML 炸弹防护
- huggingface-hub:用于在 huggingface.co 中心下载和发布模型、数据集及其他仓库的客户端库
🤖 智能代理工作流与工具
该智能代理采用精心设计的工作流,确保其在操作时具备上下文感知和精准性,尤其是在修改文件系统时。
核心工具
智能代理可使用一系列工具来理解和交互代码库:
| 工具 | 描述 |
|---|---|
query_graph |
使用自然语言问题查询代码库知识图谱。可用通俗英语询问类、函数、方法、依赖关系或代码结构。例如:“查找所有相互调用的函数”、“user 模块中有哪些类”、“显示调用链最长的函数”。 |
read_file |
读取基于文本的文件内容。对于 PDF 或图像等文档,请改用 'analyze_document' 工具。 |
create_file |
创建包含内容的新文件。重要提示:请先检查文件是否存在!会完全覆盖文件且不显示差异。仅用于创建新文件,不用于修改现有文件。 |
replace_code |
精确替换文件中的特定代码块。需要提供精确的目标代码和替换内容。仅修改指定的代码块,文件其余部分保持不变。真正的精准补丁。 |
list_directory |
列出目录内容以浏览代码库。 |
analyze_document |
分析文档(PDF、图像)以回答有关其内容的问题。 |
execute_shell |
执行允许列表中的 shell 命令。只读命令无需批准即可运行;写入操作需要用户确认。 |
semantic_search |
根据描述函数用途的自然语言查询执行语义搜索,返回带有相似度分数的潜在匹配列表。 |
get_function_source |
使用特定函数或方法的内部节点 ID 检索其源代码,该 ID 通常从语义搜索结果中获取。 |
get_code_snippet |
使用函数、类或方法的完整限定名检索其源代码。 |
智能安全的文件编辑
该智能体采用基于AST的函数定位技术,并结合Tree-sitter实现精准的代码修改。其功能包括:
- 修改前的可视化差异预览
- 精准补丁,仅修改目标代码块
- 多语言支持,覆盖所有受支持的语言
- 安全沙箱,防止编辑项目目录外的文件
- 智能函数匹配,支持限定名和行号匹配
🌍 多语言支持
添加新语言
Code-Graph-RAG能够轻松添加任何拥有Tree-sitter语法的语言支持。系统会自动处理语法编译和集成过程。
⚠️ 建议:尽管您可以自行添加语言,但我们建议等待官方的完整支持,以确保最佳的解析质量、全面的功能覆盖以及稳健的集成。上述标记为“开发中”的语言将获得专门的优化和测试。
💡 请求支持:如果您希望某一特定语言获得官方支持,请通过提交issue提出您的语言需求。
快速开始:添加语言
使用内置的语言管理工具添加任何Tree-sitter支持的语言:
# Add a language using the standard tree-sitter repository
cgr language add-grammar <language-name>
# Examples:
cgr language add-grammar c-sharp
cgr language add-grammar php
cgr language add-grammar ruby
cgr language add-grammar kotlin
自定义语法仓库
适用于托管在标准 tree-sitter 组织外部的语言:
# Add a language from a custom repository
cgr language add-grammar --grammar-url https://github.com/custom/tree-sitter-mylang
自动执行的操作
添加语言时,该工具会自动执行以下操作:
- 下载语法:将 tree-sitter 语法仓库克隆为 git 子模块
- 检测配置:从
tree-sitter.json中自动提取语言元数据 - 分析节点类型:自动识别以下 AST 节点类型:
- 函数/方法(
method_declaration、function_definition等) - 类/结构体(
class_declaration、struct_declaration等) - 模块/文件(
compilation_unit、source_file等) - 函数调用(
call_expression、method_invocation等)
- 函数/方法(
- 编译绑定:从语法源代码构建 Python 绑定
- 更新配置:将该语言添加到
codebase_rag/language_config.py - 启用解析:使该语言可立即用于代码库分析
示例:添加 C# 支持
$ cgr language add-grammar c-sharp
🔍 Using default tree-sitter URL: https://github.com/tree-sitter/tree-sitter-c-sharp
🔄 Adding submodule from https://github.com/tree-sitter/tree-sitter-c-sharp...
✅ Successfully added submodule at grammars/tree-sitter-c-sharp
Auto-detected language: c-sharp
Auto-detected file extensions: ['cs']
Auto-detected node types:
Functions: ['destructor_declaration', 'method_declaration', 'constructor_declaration']
Classes: ['struct_declaration', 'enum_declaration', 'interface_declaration', 'class_declaration']
Modules: ['compilation_unit', 'file_scoped_namespace_declaration', 'namespace_declaration']
Calls: ['invocation_expression']
✅ Language 'c-sharp' has been added to the configuration!
📝 Updated codebase_rag/language_config.py
语言管理
# List all configured languages
cgr language list-languages
# Remove a language (this also removes the git submodule unless --keep-submodule is specified)
cgr language remove-language <language-name>
语言配置
系统采用配置驱动的方式提供语言支持。每种语言在 codebase_rag/language_config.py 中按以下结构定义:
"language-name": LanguageConfig(
name="language-name",
file_extensions=[".ext1", ".ext2"],
function_node_types=["function_declaration", "method_declaration"],
class_node_types=["class_declaration", "struct_declaration"],
module_node_types=["compilation_unit", "source_file"],
call_node_types=["call_expression", "method_invocation"],
),
故障排除
未找到语法:如果自动 URL 无法使用,请使用自定义 URL:
cgr language add-grammar --grammar-url https://github.com/custom/tree-sitter-mylang
版本不兼容:如果遇到 “Incompatible Language version” 错误,请更新 tree-sitter 包:
uv add tree-sitter@latest
缺失的节点类型:该工具会自动检测常见的节点模式,但如有需要,您可以在 language_config.py 中手动调整配置。
📦 构建二进制文件
您可以使用 build_binary.py 脚本构建应用程序的二进制文件。此脚本使用 PyInstaller 将应用程序及其依赖项打包为单个可执行文件。
python build_binary.py
生成的二进制文件将位于 dist 目录中。
🐛 调试
-
检查 Memgraph 连接:
- 确保 Docker 容器正在运行:
docker-compose ps - 验证 Memgraph 在端口 7687 上可访问
- 确保 Docker 容器正在运行:
-
在 Memgraph Lab 中查看数据库:
- 打开 http://localhost:3000
- 连接至 memgraph:7687
-
对于本地模型:
- 验证 Ollama 正在运行:
ollama list - 检查模型是否已下载:
ollama pull llama3 - 测试 Ollama API:
curl http://localhost:11434/v1/models - 查看 Ollama 日志:
ollama logs
- 验证 Ollama 正在运行:
🤝 贡献
详细的贡献指南请参见 CONTRIBUTING.md。
良好的首个 PR 可从 TODO 问题中选取。
🙋♂️ 支持
遇到问题或有疑问时:
- 查看日志以获取错误详情
- 验证 Memgraph 连接
- 确保所有环境变量均已设置
- 检查图模式是否符合您的预期
💼 企业服务
Code-Graph-RAG 是开源软件,可免费使用。对于有更多需求的组织,我们提供完全托管的云托管解决方案和本地部署:
- 云托管部署 — 为图数据库和 AI 代理连接提供托管云基础设施。零基础设施开销 — 我们负责扩展、更新和可用性,让您的团队可以专注于构建。
- 本地及气隙部署 — 在您自己的环境中完全部署 Code-Graph-RAG,包括气隙网络。为受监管行业和对安全敏感的组织提供完全的数据主权。
我们还提供定制开发、集成咨询、技术支持合同和团队培训。
在 code-graph-rag.com 查看方案和定价 →
Star History
Fork History
项目介绍
搜索单体仓库,获取相关答案【此简介由AI生成】
下载使用量
项目总下载次数(含Clone、Pull、 zip 包及 release 下载),每日凌晨更新