gorag

package module
v2.0.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 26, 2026 License: MIT Imports: 20 Imported by: 0

README

GoRAG

A Local RAG (Retrieval-Augmented Generation) Toolkit

Go Version Go Reference

English | 中文文档


GoRAG is a local-first RAG toolkit with both CLI and Go API, supporting semantic vector search, graph-based retrieval, and hybrid indexing.


Features

  • Semantic Search: Multi-dimension vector matching on Title / Summary / Content
  • Graph Search: Multi-hop neighbor traversal via knowledge graph, native Cypher support
  • Hybrid Indexing (Hyper): Dual pipeline orchestration of semantic + graph, fused search results
  • LLM Enhancement: Automatic title/summary/tag generation for chunks, entity and relation extraction
  • Region System: Automatic directory-to-Region mapping, auto-generated README summaries
  • Incremental Indexing: mtime+size+hash change detection, re-index only changed files
  • Incremental LLM Processing: Per-chunk status tracking, resume from breakpoint, auto-reprocess on content change
  • Progress Tracking: SQLite metadata store for real-time index and LLM status
  • Multi-format Support: PDF / DOCX / HTML / EPUB / PPTX / Markdown / CSV / XLSX / JSON / YAML / images / code
  • Zero CGO: Pure Go, painless cross-compilation

Installation

Homebrew

brew install DotNetAge/homebrew-gorag/gorag

From source

go install github.com/DotNetAge/gorag/v2/cmd@latest

Pre-built binaries

Download from GitHub Releases.


Quick Start

CLI

# 1. Initialize a RAG library in your project
cd my-project
grag init

# 2. Index files
grag index .

# 3. Semantic search
grag query "What is GoRAG"

# 4. Check status
grag status

# 5. Optional: enable LLM enhancement
export GORAG_API_KEY=sk-xxx
grag update . --llm-url https://api.openai.com/v1 --llm-model gpt-4o-mini

# 6. Graph exploration
grag nodes ./src -n 2

# 7. Directory tree
grag tree

Go API

import gorag "github.com/DotNetAge/gorag/v2"

svc, err := gorag.NewRAGService("./my-project.rag")
if err != nil {
    log.Fatal(err)
}
defer svc.Stop()

ctx := context.Background()
svc.IndexerSvc().Index(ctx, "./docs")

hit, _ := svc.Querier().Query(ctx, "RAG architecture design", "")
result, _ := svc.Explorer().Nodes(ctx, "./docs", 2)

CLI Reference

Command Description
grag init [-t type] Initialize a RAG library
grag index [path] Index files or directories
grag update [path] [llm-options] Incremental update + LLM enhancement
grag query <text> [-f] [-k] Semantic search (multi-keyword with |)
grag chunks [-p] [-s] [-f] Paginated chunk listing
grag nodes [dir] [-n] Directory-level multi-hop graph query
grag cypher <query> Run Cypher graph query
grag status [-s] [-f] [--summary] Index and LLM processing status
grag tree Directory tree view
grag info Library information
grag doctor Configuration diagnostics
grag logs View logs

Core Concepts

.rag Library

Each RAG project corresponds to a .rag directory:

.rag/
├── config.yml          # Configuration (indexer type, model path, LLM, etc.)
├── meta.db             # SQLite metadata store (document/chunk status)
├── vectors/            # Vector store
├── graph/              # Graph store (graph/hyper indexer only)
├── logs/               # Runtime logs
└── model/              # Embedding model file

Indexer Types

Type Description
semantic Pure vector semantic indexing
graph Pure graph structure indexing
hyper Semantic + graph hybrid indexing (default)

Chunk

The smallest indexable unit with Title, Summary, Content, Tags, Source, RegionID.

Region

A directory-level semantic abstraction. Each indexed directory maps to a Region node:

  • RegionID: SHA256 hash of the absolute directory path
  • Auto-README: System generates summary README.md for directories without one

Architecture

┌──────────────────────────────────────────┐
│              CLI (grag)                  │
│   cmd/main.go + cmd/info.go             │
└────────────────┬─────────────────────────┘
                 │
┌────────────────▼─────────────────────────┐
│         IndexingService (Aggregate)       │
│  ┌─────────────────────────────────────┐  │
│  │  IndexerSvc · QuerySvc · GraphSvc  │  │
│  │  AdminSvc  · RegionSvc · LLMSvc    │  │
│  └─────────────────────────────────────┘  │
└────────────────┬─────────────────────────┘
                 │
    ┌────────────┼────────────┐
    ▼            ▼            ▼
 Semantic    Graph       Hyper(Orchestrator)
 Indexer    Indexer     ┌────┴────┐
                        ▼         ▼
                    Semantic   Graph
                    Indexer    Indexer
  • SemanticIndexer: Chunk → vectorize → write to VectorStore
  • GraphIndexer: Entities/relationships → write to GraphStore
  • HyperIndexer: Orchestrates semantic + graph pipelines, supports Summarizer / Refiller injection

LLM Enhancement

grag update runs a two-phase incremental LLM pipeline:

  1. Summarizer: Generates Title / Summary / Tags for document-class chunks
  2. Refiller: Extracts entities and relationships based on registered Schemas, writes to GraphStore

Configuration:

grag update . \
  --llm-key <API_KEY> \
  --llm-url https://api.openai.com/v1 \
  --llm-model gpt-4o-mini \
  --schema ./schemas

Environment variable: GORAG_API_KEY


Documentation


License

GoRAG is released under the MIT License.

Documentation

Index

Constants

View Source
const (
	GORAG_MODEL_PATH = "GORAG_MODEL_PATH"
	GORAG_BASE_URL   = "GORAG_BASE_URL"
	GORAG_API_KEY    = "GORAG_API_KEY"
	GORAG_AUTH_TOKEN = "GORAG_AUTH_TOKEN"
	GORAG_MODEL      = "GORAG_MODEL"
)

环境变量常量

Variables

View Source
var DataExts = []string{
	".csv", ".xls", ".xlsx",
	".json", ".yaml", ".yml",
	".xml", ".toml", ".log",
	".eml", ".msg",
}

DataExts 可索引的数据类文件扩展名列表(解析为 JSON 字符串)。

涵盖:csv/xls/xlsx/json/yaml/yml/xml/toml/log/eml/msg。 这些文件不进入 TextExts,因为它们的归一化策略不同(输出 JSON 字符串而非原文)。

View Source
var TextExts = []string{
	".txt", ".md", ".json", ".yaml", ".yml",
	".html", ".xml", ".css",
	".go", ".py", ".js", ".ts", ".java", ".c", ".cpp", ".h",
	".sh", ".bash", ".zsh",
	".sql", ".conf", ".cfg", ".ini",
}

TextExts 可索引的文本文件扩展名列表

Functions

func Abs added in v2.0.13

func Abs(n int) int

Abs 返回 int 绝对值。

func CalcDirSizes added in v2.0.13

func CalcDirSizes(dataDir string) map[string]int64

CalcDirSizes 递归计算各子目录大小。

func CheckModel

func CheckModel(modelId, modelFile string) (string, error)

CheckModel 检查模型文件是否存在,不存在则从 HuggingFace 下载

func ComputeChunkContentHash added in v2.0.13

func ComputeChunkContentHash(content string) string

ComputeChunkContentHash 计算分片内容的简短哈希(SHA256 前 16 位十六进制)。

func ComputeFileHash added in v2.0.13

func ComputeFileHash(absPath string) (string, error)

ComputeFileHash 计算文件的 SHA256 哈希值。

func Contains added in v2.0.13

func Contains(slice []string, val string) bool

Contains 检查字符串切片是否包含指定值。

func DirExists added in v2.0.13

func DirExists(path string) bool

DirExists 判断路径是否为已存在目录。

func DirSize added in v2.0.13

func DirSize(path string) int64

DirSize 递归计算目录总大小。

func FileExists added in v2.0.13

func FileExists(path string) bool

FileExists 判断文件是否存在(目录返回 false)。

func FilterHitBySourcePrefix added in v2.0.13

func FilterHitBySourcePrefix(hit *core.Hit, filterPath string) *core.Hit

FilterHitBySourcePrefix 按 source 路径前缀过滤命中结果。

func GetGraphCount added in v2.0.13

func GetGraphCount(dbPath string) (nodes int64, edges int64)

GetGraphCount 获取图索引的节点和边数量。

func GetVectorCount added in v2.0.13

func GetVectorCount(dbPath string) int

GetVectorCount 获取向量索引中的条目数。

func HasAPIKey added in v2.0.13

func HasAPIKey(ragDir string) bool

HasAPIKey 检查是否已设置 API Key(不返回具体值,用于 grag doctor)。

func Init added in v2.0.13

func Init(ragDir string) error

Init 在指定路径创建数据目录结构。 物理结构 = config.yml + .api_key + .ragignore + .lock + meta.db + vectors/ + graphs/ + logs/。

已存在的目录会被复用(不报错),但缺失的子目录和文件会被补齐。

func IsDataFile added in v2.0.13

func IsDataFile(filename string) bool

IsDataFile 判断是否为可索引的数据类文件(CSV / XLSX / JSON / 等)。

数据类文件的归一化策略是输出 JSON 字符串(不同于文本类输出原文)。 与 IsTextFile 是并列关系。

func IsIndexableFile added in v2.0.13

func IsIndexableFile(filename string) bool

IsIndexableFile 判断文件是否应被索引(文本类 + 数据类)。 这是 ScanDir 与 index 单文件入口的统一判断入口。

func IsTextFile added in v2.0.13

func IsTextFile(filename string) bool

IsTextFile 判断是否为可索引的文本文件

func LoadRagignore added in v2.0.13

func LoadRagignore(ragDir string) []string

LoadRagignore 从 .rag 目录加载 .ragignore 忽略规则。 返回非空、非注释的规则行列表。文件不存在时返回空切片。

func MatchRagignoreDir added in v2.0.13

func MatchRagignoreDir(dirPath, scanRoot string, patterns []string) bool

MatchRagignoreDir 判断目录是否匹配任一 .ragignore 规则。 规则支持目录匹配(尾随 /)和文件名匹配。

func MatchRagignoreEntry added in v2.0.13

func MatchRagignoreEntry(name, rel string, patterns []string) bool

MatchRagignoreEntry 是 matchRagignoreEntry 的导出版本,供 webapi 等外部包使用。

func Open

func Open(ragDir string, opts ...RAGOption) (indexer.Indexer, error)

Open 打开已存在的数据目录。 opts 可注入 WithLLM、WithEmbeddingModelFile 等。

行为:

  • 加载 config.yml
  • 根据 cfg.Indexer.Type 创建索引器
  • 若有 LLM 配置,则创建 gochat 客户端并注入 GraphIndexer/HyperIndexer

func QueryGraphCount added in v2.0.13

func QueryGraphCount(ctx context.Context, db *api.DB, query string) int64

QueryGraphCount 执行图查询获取计数值。

func ResolveAPIKey added in v2.0.13

func ResolveAPIKey(ragDir string) (string, error)

ResolveAPIKey 解析 LLM API Key,按四级回退策略:

  1. 环境变量 GORAG_API_KEY(最高优先级,CI/CD 友好)
  2. .rag/.api_key 文件(grag config llm APIKey 写入位置,权限 600)
  3. 外部文件引用(cfg.LLM.APIKeyFile,自定义路径)
  4. 系统 keychain(macOS,可选)

API Key 不进 config.yml,独立存于 .rag/.api_key 文件。

func SaveConfig added in v2.0.13

func SaveConfig(ragDir string, cfg *Config) error

SaveConfig 更新 .rag 目录的 config.yml(公开 API,供 grag config 调用)

func ScanDir added in v2.0.13

func ScanDir(dir string, basePatterns []string) ([]string, error)

ScanDir 扫描目录下的所有文本文件,跳过 .ragignore 匹配的目录。

支持层级 .ragignore:每个目录可放置自己的 .ragignore,规则叠加生效。 basePatterns 来自 .rag 库目录的全局规则,作为根目录的默认规则。每个子目录的 本地 .ragignore 规则会附加到父目录规则之上,子目录规则不影响平级目录。

func SourceHasPrefix added in v2.0.13

func SourceHasPrefix(source, filterPath string) bool

SourceHasPrefix 判断 chunk.Source 是否以指定绝对路径开头。 filterPath 必须是已经转换后的绝对路径。 为了避免 /foo 匹配到 /foobar 这类部分路径,函数会自动确保 filterPath 以路径分隔符结尾。

func TimePtr added in v2.0.13

func TimePtr(t time.Time) *time.Time

TimePtr 返回 time.Time 的指针。

func TopChunkScore added in v2.0.13

func TopChunkScore(hits []core.ChunkHit) float32

TopChunkScore 返回 ChunkHit 切片中的最高分。

func WriteAPIKey added in v2.0.13

func WriteAPIKey(ragDir, apiKey string) error

WriteAPIKey 写入 API Key 到 .rag/.api_key 文件(权限 600)。 API Key 文件权限强制 600(仅 owner 可读写)。

Types

type Config

type Config struct {
	Version   int             `yaml:"version"`   // 配置版本号
	Storage   StorageConfig   `yaml:"storage"`   // 存储路径配置
	Embedding EmbeddingConfig `yaml:"embedding"` // 向量模型配置
	LLM       LLMConfig       `yaml:"llm"`       // LLM 配置(不含 APIKey)
	Indexer   IndexerConfig   `yaml:"indexer"`   // 索引器配置
	Query     QueryConfig     `yaml:"query"`     // 查询配置
}

Config .rag 库的配置文件结构(config.yml)。 分层结构 = storage + embedding + llm + indexer + query。 api_key 不写入 config.yml,独立存于 .rag/.api_key(权限 600)。

func LoadConfig added in v2.0.13

func LoadConfig(ragDir string) (*Config, error)

LoadConfig 从 .rag 目录加载 config.yml(公开 API)

func LoadConfigRaw added in v2.0.13

func LoadConfigRaw(ragDir string) (*Config, string, error)

LoadConfigRaw 加载配置并同时返回原始 YAML 字符串(导出版本)。

type EmbeddingConfig added in v2.0.13

type EmbeddingConfig struct {
	ModelFile string `yaml:"model_file"` // ONNX 模型文件路径
	Dimension int    `yaml:"dimension"`  // 向量维度
}

EmbeddingConfig 向量模型配置

type IndexerConfig added in v2.0.13

type IndexerConfig struct {
	Type string `yaml:"type"` // semantic | graph | hyper
}

IndexerConfig 索引器配置

type LLMConfig added in v2.0.13

type LLMConfig struct {
	BaseURL        string `yaml:"base_url"`
	Model          string `yaml:"model"`
	APIKey         string `yaml:"api_key,omitempty"`      // API Key
	Language       string `yaml:"language"`               // 内容语言(如 Chinese)
	MaxTokens      int    `yaml:"max_tokens"`             // 模型最大输出 token
	ContextLength  int    `yaml:"context_length"`         // 模型上下文长度
	ThinkingBudget int    `yaml:"thinking_budget"`        // 思考模式 token 预算(0=默认)
	APIKeyFile     string `yaml:"api_key_file,omitempty"` // 外部 API Key 文件路径(可选)
}

LLMConfig LLM 配置

type QueryConfig added in v2.0.13

type QueryConfig struct {
	SemanticWeight float32 `yaml:"semantic_weight"` // 语义检索权重
	GraphWeight    float32 `yaml:"graph_weight"`    // 图检索权重
}

QueryConfig 查询配置

type RAGOption

type RAGOption func(*Config)

RAGOption Open 函数的配置选项

func WithEmbeddingModelFile

func WithEmbeddingModelFile(modelFile string) RAGOption

WithEmbeddingModelFile 设置向量模型文件路径

func WithIndexType

func WithIndexType(indexType string) RAGOption

WithIndexType 设置索引器类型

func WithLLM added in v2.0.13

func WithLLM(llmCfg LLMConfig) RAGOption

WithLLM 注入 gochat 客户端对应的 LLM 配置。 注:实际的 chat.Client 通过此函数从配置实例化并返回,供 indexer 使用。 LLM 在应用层实例化,indexer 包不再创建 LLM 客户端。

func WithName

func WithName(name string) RAGOption

WithName 设置 RAG 库命名(兼容旧 API,仅写入 Storage 命名,无实际作用)

type StorageConfig added in v2.0.13

type StorageConfig struct {
	VectorsDir string `yaml:"vectors_dir"` // 向量库目录
	GraphsDir  string `yaml:"graphs_dir"`  // 图库目录
	LogsDir    string `yaml:"logs_dir"`    // 日志目录
	MetaDB     string `yaml:"meta_db"`     // 元数据 SQLite 文件名
}

StorageConfig 存储路径配置

Directories

Path Synopsis
vue
Package core 提供 goRAG 框架的基础类型与接口。
Package core 提供 goRAG 框架的基础类型与接口。
Package indexer 定义索引器的接口与实现。
Package indexer 定义索引器的接口与实现。
Package llm 提供基于 LLM 的文本增强工具。
Package llm 提供基于 LLM 的文本增强工具。
Package logging provides structured logging capabilities for the goRAG framework.
Package logging provides structured logging capabilities for the goRAG framework.
Package result 提供检索结果的融合、去重、压缩与重排能力。
Package result 提供检索结果的融合、去重、压缩与重排能力。
store
Package view 提供基于 Cypher 的结构化视图查询能力。
Package view 提供基于 Cypher 的结构化视图查询能力。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL