retrieval

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2025 License: Apache-2.0 Imports: 18 Imported by: 0

README

Retrieval - 检索器系统

完整的 RAG(检索增强生成)检索器实现,借鉴 LangChain 的设计理念。

概述

检索器系统提供统一的文档检索接口,支持多种检索策略和重排序算法,用于构建高质量的 RAG 应用。

核心概念

Document 文档

文档是检索系统的基本单元:

type Document struct {
    PageContent string                 // 文档内容
    Metadata    map[string]interface{} // 元数据
    ID          string                 // 唯一标识符
    Score       float64                // 检索得分
}
Retriever 检索器接口

统一的检索器接口,继承自 Runnable[string, []*Document]

type Retriever interface {
    core.Runnable[string, []*Document]
    GetRelevantDocuments(ctx context.Context, query string) ([]*Document, error)
}

支持的操作:

  • Invoke - 单个查询检索
  • Stream - 流式检索
  • Batch - 批量检索
  • Pipe - 管道连接
  • WithCallbacks - 添加回调

检索器类型

1. VectorStoreRetriever 向量存储检索器

使用向量相似度进行检索:

// 创建向量存储
vectorStore := retrieval.NewMockVectorStore()
vectorStore.AddDocuments(ctx, docs)

// 创建检索器
config := retrieval.DefaultRetrieverConfig()
config.TopK = 5

retriever := retrieval.NewVectorStoreRetriever(vectorStore, config)

// 执行检索
results, err := retriever.GetRelevantDocuments(ctx, "your query")

支持的搜索类型:

  • SearchTypeSimilarity - 相似度搜索
  • SearchTypeSimilarityScoreThreshold - 带阈值的相似度搜索
  • SearchTypeMMR - 最大边际相关性搜索
2. KeywordRetriever 关键词检索器

使用 BM25 或 TF-IDF 算法进行检索:

config := retrieval.DefaultRetrieverConfig()
config.TopK = 5

retriever := retrieval.NewKeywordRetriever(docs, config)
retriever.WithAlgorithm(retrieval.AlgorithmBM25)

results, err := retriever.GetRelevantDocuments(ctx, "your query")

支持的算法:

  • AlgorithmBM25 - BM25 算法(推荐)
  • AlgorithmTFIDF - TF-IDF 算法
3. HybridRetriever 混合检索器

结合向量检索和关键词检索:

// 创建向量检索器
vectorRetriever := retrieval.NewVectorStoreRetriever(vectorStore, config)

// 创建关键词检索器
keywordRetriever := retrieval.NewKeywordRetriever(docs, config)

// 创建混合检索器
hybrid := retrieval.NewHybridRetriever(
    vectorRetriever,
    keywordRetriever,
    0.6, // 向量权重
    0.4, // 关键词权重
    config,
)

// 设置融合策略
hybrid.WithFusionStrategy(retrieval.FusionStrategyRRF)

results, err := hybrid.GetRelevantDocuments(ctx, "your query")

支持的融合策略:

  • FusionStrategyWeightedSum - 加权求和
  • FusionStrategyRRF - 倒数排名融合(推荐)
  • FusionStrategyCombSum - 组合求和
4. MultiQueryRetriever 多查询检索器

使用 LLM 生成多个查询变体:

retriever := retrieval.NewMultiQueryRetriever(
    baseRetriever,
    llmClient,
    3, // 生成 3 个查询变体
    config,
)

results, err := retriever.GetRelevantDocuments(ctx, "your query")
5. EnsembleRetriever 集成检索器

组合多个检索器:

ensemble := retrieval.NewEnsembleRetriever(
    []retrieval.Retriever{retriever1, retriever2, retriever3},
    []float64{0.5, 0.3, 0.2}, // 权重
    config,
)

results, err := ensemble.GetRelevantDocuments(ctx, "your query")

重排序系统

Reranker 重排序器接口
type Reranker interface {
    Rerank(ctx context.Context, query string, docs []*Document) ([]*Document, error)
}
重排序器类型
1. CrossEncoderReranker 交叉编码器

使用交叉编码器模型重排序:

reranker := retrieval.NewCrossEncoderReranker("model-name", 10)
reranked, err := reranker.Rerank(ctx, query, docs)
2. MMRReranker 最大边际相关性

平衡相关性和多样性:

reranker := retrieval.NewMMRReranker(
    0.7, // lambda: 0=多样性, 1=相关性
    10,  // top-N
)
reranked, err := reranker.Rerank(ctx, query, docs)
3. LLMReranker LLM 重排序器

使用 LLM 进行重排序:

reranker := retrieval.NewLLMReranker(10)
reranked, err := reranker.Rerank(ctx, query, docs)
4. CohereReranker Cohere API

使用 Cohere Rerank API:

reranker := retrieval.NewCohereReranker(apiKey, "model-name", 10)
reranked, err := reranker.Rerank(ctx, query, docs)
RerankingRetriever 带重排序的检索器

在基础检索器上应用重排序:

// 创建基础检索器
baseRetriever := retrieval.NewKeywordRetriever(docs, config)

// 创建重排序器
reranker := retrieval.NewCrossEncoderReranker("model", 10)

// 创建带重排序的检索器
config.TopK = 5
rerankingRetriever := retrieval.NewRerankingRetriever(
    baseRetriever,
    reranker,
    20, // 初始获取 20 个候选
    config,
)

results, err := rerankingRetriever.GetRelevantDocuments(ctx, query)

高级功能

1. 回调系统

为检索过程添加监控和日志:

// 自定义回调
type MyCallback struct {
    core.BaseCallback
}

func (c *MyCallback) OnStart(ctx context.Context, input interface{}) error {
    fmt.Printf("Starting retrieval: %v\n", input)
    return nil
}

func (c *MyCallback) OnEnd(ctx context.Context, output interface{}) error {
    docs := output.([]*retrieval.Document)
    fmt.Printf("Retrieved %d documents\n", len(docs))
    return nil
}

// 使用回调
retriever := retriever.WithCallbacks(&MyCallback{})
2. 管道操作

将检索器与其他操作连接:

// 创建处理函数
filterFunc := core.NewRunnableFunc(func(ctx context.Context, docs []*retrieval.Document) ([]*retrieval.Document, error) {
    // 过滤逻辑
    filtered := make([]*retrieval.Document, 0)
    for _, doc := range docs {
        if doc.Score > 0.5 {
            filtered = append(filtered, doc)
        }
    }
    return filtered, nil
})

// 构建管道
pipeline := retriever.Pipe(filterFunc)

// 执行
results, err := pipeline.Invoke(ctx, query)
3. 批量检索

并发处理多个查询:

queries := []string{
    "query 1",
    "query 2",
    "query 3",
}

results, err := retriever.Batch(ctx, queries)
// results: [][]*Document
4. 流式检索

流式返回结果:

stream, err := retriever.Stream(ctx, query)
if err != nil {
    return err
}

for chunk := range stream {
    if chunk.Error != nil {
        // 处理错误
        continue
    }
    // 处理结果
    docs := chunk.Data
}

配置选项

RetrieverConfig
config := retrieval.DefaultRetrieverConfig()

// 设置返回的最大文档数
config.TopK = 10

// 设置最小分数阈值
config.MinScore = 0.3

// 设置检索器名称
config.Name = "my_retriever"
文档集合操作
collection := retrieval.DocumentCollection(docs)

// 按分数排序
collection.SortByScore()

// 获取前 N 个
top5 := collection.Top(5)

// 过滤
filtered := collection.Filter(func(d *retrieval.Document) bool {
    return d.Score > 0.5
})

// 去重
unique := collection.Deduplicate()

// 映射
mapped := collection.Map(func(d *retrieval.Document) *retrieval.Document {
    d.SetMetadata("processed", true)
    return d
})

完整示例

基础检索
package main

import (
    "context"
    "fmt"

    "github.com/kart-io/goagent/retrieval"
)

func main() {
    // 创建文档
    docs := []*retrieval.Document{
        retrieval.NewDocument("Kubernetes is a container orchestration platform", nil),
        retrieval.NewDocument("Docker is a containerization technology", nil),
        retrieval.NewDocument("Python is a programming language", nil),
    }

    // 创建检索器
    config := retrieval.DefaultRetrieverConfig()
    config.TopK = 2

    retriever := retrieval.NewKeywordRetriever(docs, config)

    // 执行检索
    ctx := context.Background()
    results, err := retriever.GetRelevantDocuments(ctx, "container technology")
    if err != nil {
        panic(err)
    }

    // 显示结果
    for i, doc := range results {
        fmt.Printf("%d. Score: %.4f\n", i+1, doc.Score)
        fmt.Printf("   Content: %s\n", doc.PageContent)
    }
}
混合检索 + 重排序
// 1. 创建向量检索器
vectorStore := retrieval.NewMockVectorStore()
vectorStore.AddDocuments(ctx, docs)
vectorRetriever := retrieval.NewVectorStoreRetriever(vectorStore, config)

// 2. 创建关键词检索器
keywordRetriever := retrieval.NewKeywordRetriever(docs, config)

// 3. 创建混合检索器
hybrid := retrieval.NewHybridRetriever(
    vectorRetriever,
    keywordRetriever,
    0.6, 0.4,
    config,
)
hybrid.WithFusionStrategy(retrieval.FusionStrategyRRF)

// 4. 创建重排序器
reranker := retrieval.NewMMRReranker(0.7, 10)

// 5. 创建最终检索器
finalRetriever := retrieval.NewRerankingRetriever(
    hybrid,
    reranker,
    20,
    config,
)

// 6. 执行检索
results, err := finalRetriever.GetRelevantDocuments(ctx, query)

最佳实践

1. 选择合适的检索策略
  • 向量检索: 适合语义相似度匹配
  • 关键词检索: 适合精确匹配和术语查询
  • 混合检索: 在大多数场景下提供最佳效果
  • 多查询检索: 适合复杂查询
2. 使用重排序提高质量
// 推荐的流程
baseRetriever -> 获取候选 (top-k * 2-4)
    -> Reranker -> 精排序 (top-k)
3. 配置合理的参数
config := retrieval.DefaultRetrieverConfig()
config.TopK = 5      // 通常 3-10 个结果足够
config.MinScore = 0.3 // 过滤低质量结果
4. 使用回调监控性能
metricsCallback := &MetricsCallback{}
retriever := retriever.WithCallbacks(metricsCallback)
5. 批量处理优化性能
// 批量检索比循环调用更高效
results, err := retriever.Batch(ctx, queries)

性能优化

1. 索引优化
  • 使用倒排索引加速关键词检索
  • 预计算文档向量
  • 缓存常见查询结果
2. 并发控制
config := core.RunnableConfig{
    MaxConcurrency: 10, // 限制并发数
}
retriever := retriever.WithConfig(config)
3. 结果缓存
// 实现缓存层
type CachedRetriever struct {
    *retrieval.BaseRetriever
    cache map[string][]*retrieval.Document
}

扩展指南

自定义检索器
type CustomRetriever struct {
    *retrieval.BaseRetriever
    // 自定义字段
}

func (c *CustomRetriever) GetRelevantDocuments(ctx context.Context, query string) ([]*retrieval.Document, error) {
    // 实现自定义检索逻辑
    return docs, nil
}
自定义重排序器
type CustomReranker struct {
    *retrieval.BaseReranker
}

func (c *CustomReranker) Rerank(ctx context.Context, query string, docs []*retrieval.Document) ([]*retrieval.Document, error) {
    // 实现自定义重排序逻辑
    return docs, nil
}

测试

运行测试:

cd retrieval
go test -v

运行示例:

go run examples/basic_retrieval.go
go run examples/advanced_retrieval.go

参考

相关模块

  • core - 核心 Runnable 接口和回调系统
  • llm - LLM 客户端(用于 MultiQueryRetriever)
  • chain - 链式调用(用于构建 RAG 链)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewDocument

func NewDocument(content string, metadata map[string]interface{}) *interfaces.Document

NewDocument 创建新文档

func NewDocumentWithID

func NewDocumentWithID(id, content string, metadata map[string]interface{}) *interfaces.Document

NewDocumentWithID 创建带 ID 的文档

Types

type BaseEmbedder

type BaseEmbedder struct {
	// contains filtered or unexported fields
}

BaseEmbedder 基础嵌入器实现

func NewBaseEmbedder

func NewBaseEmbedder(dimensions int) *BaseEmbedder

NewBaseEmbedder 创建基础嵌入器

func (*BaseEmbedder) Dimensions

func (e *BaseEmbedder) Dimensions() int

Dimensions 返回向量维度

type BaseReranker

type BaseReranker struct {
	Name string
}

BaseReranker 基础重排序器

func NewBaseReranker

func NewBaseReranker(name string) *BaseReranker

NewBaseReranker 创建基础重排序器

func (*BaseReranker) Rerank

func (b *BaseReranker) Rerank(ctx context.Context, query string, docs []*interfaces.Document) ([]*interfaces.Document, error)

Rerank 默认实现(不改变顺序)

type BaseRetriever

type BaseRetriever struct {
	*core.BaseRunnable[string, []*interfaces.Document]

	// TopK 返回的最大文档数
	TopK int

	// MinScore 最小分数阈值(过滤低分文档)
	MinScore float64

	// Name 检索器名称(用于日志和追踪)
	Name string
}

BaseRetriever 提供 Retriever 的基础实现

实现了 Runnable 接口的通用功能 子类只需实现 GetRelevantDocuments 方法

func NewBaseRetriever

func NewBaseRetriever() *BaseRetriever

NewBaseRetriever 创建基础检索器

func (*BaseRetriever) Batch

func (r *BaseRetriever) Batch(ctx context.Context, queries []string) ([][]*interfaces.Document, error)

Batch 批量执行

func (*BaseRetriever) FilterByScore

func (r *BaseRetriever) FilterByScore(docs []*interfaces.Document) []*interfaces.Document

FilterByScore 按分数过滤文档

func (*BaseRetriever) GetRelevantDocuments

func (r *BaseRetriever) GetRelevantDocuments(ctx context.Context, query string) ([]*interfaces.Document, error)

GetRelevantDocuments 基础实现(返回空列表)

子类应该重写此方法

func (*BaseRetriever) Invoke

func (r *BaseRetriever) Invoke(ctx context.Context, query string) ([]*interfaces.Document, error)

Invoke 执行检索(实现 Runnable 接口)

func (*BaseRetriever) LimitTopK

func (r *BaseRetriever) LimitTopK(docs []*interfaces.Document) []*interfaces.Document

LimitTopK 限制返回的文档数量

func (*BaseRetriever) Pipe

Pipe 连接到另一个 Runnable

func (*BaseRetriever) Stream

func (r *BaseRetriever) Stream(ctx context.Context, query string) (<-chan core.StreamChunk[[]*interfaces.Document], error)

Stream 流式执行(默认实现)

func (*BaseRetriever) WithCallbacks

func (r *BaseRetriever) WithCallbacks(callbacks ...core.Callback) core.Runnable[string, []*interfaces.Document]

WithCallbacks 添加回调

func (*BaseRetriever) WithConfig

WithConfig 配置 Retriever

type CohereReranker

type CohereReranker struct {
	*BaseReranker

	// APIKey Cohere API 密钥
	APIKey string

	// Model 模型名称
	Model string

	// TopN 返回前 N 个文档
	TopN int
	// contains filtered or unexported fields
}

CohereReranker Cohere Rerank API 重排序器

func NewCohereReranker

func NewCohereReranker(apiKey, model string, topN int) (*CohereReranker, error)

NewCohereReranker 创建 Cohere 重排序器

参数:

  • apiKey: Cohere API 密钥
  • model: 模型名称(可选,默认为 "rerank-english-v2.0")
  • topN: 返回前 N 个文档

返回:

  • *CohereReranker: Cohere 重排序器实例
  • error: 错误信息

func (*CohereReranker) Rerank

func (c *CohereReranker) Rerank(ctx context.Context, query string, docs []*interfaces.Document) ([]*interfaces.Document, error)

Rerank 使用 Cohere API 重新排序

参数:

  • ctx: 上下文
  • query: 查询字符串
  • docs: 待重排序的文档列表

返回:

  • []*interfaces.Document: 重排序后的文档列表
  • error: 错误信息

type CompareRankers

type CompareRankers struct {
	Rerankers []Reranker
}

CompareRankers 比较多个重排序器的性能

func (*CompareRankers) Compare

func (c *CompareRankers) Compare(ctx context.Context, query string, docs []*interfaces.Document) (map[string][]*interfaces.Document, error)

Compare 对比重排序结果

type CrossEncoderReranker

type CrossEncoderReranker struct {
	*BaseReranker

	// Model 模型名称
	Model string

	// TopN 返回前 N 个文档
	TopN int
}

CrossEncoderReranker 交叉编码器重排序器

使用交叉编码器模型计算查询和文档的相关性分数

func NewCrossEncoderReranker

func NewCrossEncoderReranker(model string, topN int) *CrossEncoderReranker

NewCrossEncoderReranker 创建交叉编码器重排序器

func (*CrossEncoderReranker) Rerank

func (c *CrossEncoderReranker) Rerank(ctx context.Context, query string, docs []*interfaces.Document) ([]*interfaces.Document, error)

Rerank 重新排序文档

type DistanceMetric

type DistanceMetric string

DistanceMetric 距离度量类型

const (
	// DistanceMetricCosine 余弦相似度
	DistanceMetricCosine DistanceMetric = "cosine"

	// DistanceMetricEuclidean 欧氏距离
	DistanceMetricEuclidean DistanceMetric = "euclidean"

	// DistanceMetricDot 点积
	DistanceMetricDot DistanceMetric = "dot"
)

type DocumentCollection

type DocumentCollection []*interfaces.Document

DocumentCollection 文档集合

func (DocumentCollection) Deduplicate

func (dc DocumentCollection) Deduplicate() DocumentCollection

Deduplicate 去重(基于 ID)

func (DocumentCollection) Filter

func (dc DocumentCollection) Filter(predicate func(*interfaces.Document) bool) DocumentCollection

Filter 过滤文档

func (DocumentCollection) Len

func (dc DocumentCollection) Len() int

Len 实现 sort.Interface

func (DocumentCollection) Less

func (dc DocumentCollection) Less(i, j int) bool

Less 按分数降序排序

func (DocumentCollection) Map

Map 映射文档

func (DocumentCollection) SortByScore

func (dc DocumentCollection) SortByScore()

SortByScore 按分数排序

func (DocumentCollection) Swap

func (dc DocumentCollection) Swap(i, j int)

Swap 交换元素

func (DocumentCollection) Top

Top 获取前 N 个文档

type DocumentWithVector

type DocumentWithVector struct {
	Document *interfaces.Document
	Vector   []float32
}

DocumentWithVector 包含向量的文档

type Embedder

type Embedder interface {
	// Embed 批量嵌入文本
	Embed(ctx context.Context, texts []string) ([][]float32, error)

	// EmbedQuery 嵌入单个查询文本
	EmbedQuery(ctx context.Context, query string) ([]float32, error)

	// Dimensions 返回向量维度
	Dimensions() int
}

Embedder 嵌入模型接口

将文本转换为向量表示,用于语义搜索和相似度计算

type EnsembleRetriever

type EnsembleRetriever struct {
	*BaseRetriever

	// Retrievers 检索器列表
	Retrievers []Retriever

	// Weights 每个检索器的权重
	Weights []float64
}

EnsembleRetriever 集成检索器

组合多个检索器,使用加权融合策略

func NewEnsembleRetriever

func NewEnsembleRetriever(
	retrievers []Retriever,
	weights []float64,
	config RetrieverConfig,
) *EnsembleRetriever

NewEnsembleRetriever 创建集成检索器

func (*EnsembleRetriever) AddRetriever

func (e *EnsembleRetriever) AddRetriever(retriever Retriever, weight float64) *EnsembleRetriever

AddRetriever 添加检索器

func (*EnsembleRetriever) GetRelevantDocuments

func (e *EnsembleRetriever) GetRelevantDocuments(ctx context.Context, query string) ([]*interfaces.Document, error)

GetRelevantDocuments 检索相关文档

func (*EnsembleRetriever) WithWeights

func (e *EnsembleRetriever) WithWeights(weights []float64) *EnsembleRetriever

WithWeights 设置权重

type FusionStrategy

type FusionStrategy string

FusionStrategy 融合策略

const (
	// FusionStrategyWeightedSum 加权求和
	FusionStrategyWeightedSum FusionStrategy = "weighted_sum"

	// FusionStrategyRRF 倒数排名融合 (Reciprocal Rank Fusion)
	FusionStrategyRRF FusionStrategy = "rrf"

	// FusionStrategyCombSum 组合求和
	FusionStrategyCombSum FusionStrategy = "comb_sum"
)

type HybridRetriever

type HybridRetriever struct {
	*BaseRetriever

	// VectorRetriever 向量检索器
	VectorRetriever Retriever

	// KeywordRetriever 关键词检索器
	KeywordRetriever Retriever

	// VectorWeight 向量检索的权重(0-1)
	VectorWeight float64

	// KeywordWeight 关键词检索的权重(0-1)
	KeywordWeight float64

	// FusionStrategy 融合策略
	FusionStrategy FusionStrategy
}

HybridRetriever 混合检索器

结合向量检索和关键词检索,使用加权融合策略

func NewHybridRetriever

func NewHybridRetriever(
	vectorRetriever, keywordRetriever Retriever,
	vectorWeight, keywordWeight float64,
	config RetrieverConfig,
) *HybridRetriever

NewHybridRetriever 创建混合检索器

func (*HybridRetriever) GetRelevantDocuments

func (h *HybridRetriever) GetRelevantDocuments(ctx context.Context, query string) ([]*interfaces.Document, error)

GetRelevantDocuments 检索相关文档

func (*HybridRetriever) WithFusionStrategy

func (h *HybridRetriever) WithFusionStrategy(strategy FusionStrategy) *HybridRetriever

WithFusionStrategy 设置融合策略

func (*HybridRetriever) WithWeights

func (h *HybridRetriever) WithWeights(vectorWeight, keywordWeight float64) *HybridRetriever

WithWeights 设置权重

type InvertedIndex

type InvertedIndex struct {
	// contains filtered or unexported fields
}

InvertedIndex 倒排索引

func NewInvertedIndex

func NewInvertedIndex() *InvertedIndex

NewInvertedIndex 创建倒排索引

func (*InvertedIndex) AddDocument

func (idx *InvertedIndex) AddDocument(docID int, terms []string)

AddDocument 添加文档到索引

func (*InvertedIndex) AverageDocLength

func (idx *InvertedIndex) AverageDocLength() float64

AverageDocLength 获取平均文档长度

func (*InvertedIndex) DocumentFrequency

func (idx *InvertedIndex) DocumentFrequency(term string) int

DocumentFrequency 获取词的文档频率(包含该词的文档数)

func (*InvertedIndex) TermFrequency

func (idx *InvertedIndex) TermFrequency(docID int, term string) int

TermFrequency 获取词在文档中的频率

type KeywordAlgorithm

type KeywordAlgorithm string

KeywordAlgorithm 关键词检索算法

const (
	// AlgorithmBM25 BM25 算法
	AlgorithmBM25 KeywordAlgorithm = "bm25"

	// AlgorithmTFIDF TF-IDF 算法
	AlgorithmTFIDF KeywordAlgorithm = "tfidf"
)

type KeywordRetriever

type KeywordRetriever struct {
	*BaseRetriever

	// Documents 文档集合
	Documents []*interfaces.Document

	// Algorithm 检索算法
	Algorithm KeywordAlgorithm

	// Index 倒排索引
	Index *InvertedIndex
}

KeywordRetriever 关键词检索器

使用 BM25 或 TF-IDF 算法进行基于关键词的检索

func NewKeywordRetriever

func NewKeywordRetriever(docs []*interfaces.Document, config RetrieverConfig) *KeywordRetriever

NewKeywordRetriever 创建关键词检索器

func (*KeywordRetriever) GetRelevantDocuments

func (k *KeywordRetriever) GetRelevantDocuments(ctx context.Context, query string) ([]*interfaces.Document, error)

GetRelevantDocuments 检索相关文档

func (*KeywordRetriever) WithAlgorithm

func (k *KeywordRetriever) WithAlgorithm(algorithm KeywordAlgorithm) *KeywordRetriever

WithAlgorithm 设置检索算法

type LLMReranker

type LLMReranker struct {
	*BaseReranker

	// TopN 返回前 N 个文档
	TopN int

	// Prompt 提示词模板
	Prompt string
}

LLMReranker LLM 重排序器

使用 LLM 对文档进行相关性判断和排序

func NewLLMReranker

func NewLLMReranker(topN int) *LLMReranker

NewLLMReranker 创建 LLM 重排序器

func (*LLMReranker) Rerank

func (l *LLMReranker) Rerank(ctx context.Context, query string, docs []*interfaces.Document) ([]*interfaces.Document, error)

Rerank 重新排序文档

type MMRReranker

type MMRReranker struct {
	*BaseReranker

	// Lambda 相关性和多样性的平衡参数(0-1)
	// 0: 只考虑多样性,1: 只考虑相关性
	Lambda float64

	// TopN 返回前 N 个文档
	TopN int
}

MMRReranker 最大边际相关性重排序器

使用 MMR 算法平衡相关性和多样性

func NewMMRReranker

func NewMMRReranker(lambda float64, topN int) *MMRReranker

NewMMRReranker 创建 MMR 重排序器

func (*MMRReranker) Rerank

func (m *MMRReranker) Rerank(ctx context.Context, query string, docs []*interfaces.Document) ([]*interfaces.Document, error)

Rerank 使用 MMR 算法重新排序

MMR = λ * Sim(D, Q) - (1-λ) * max(Sim(D, Di)) 其中 Di 是已选择的文档

type MemoryVectorStore

type MemoryVectorStore struct {
	// contains filtered or unexported fields
}

MemoryVectorStore 内存向量存储实现

线程安全的内存向量存储,支持: - 余弦相似度搜索 - 向量和文档的增删改查 - 自动向量化

func NewMemoryVectorStore

func NewMemoryVectorStore(config MemoryVectorStoreConfig) *MemoryVectorStore

NewMemoryVectorStore 创建内存向量存储

func (*MemoryVectorStore) Add

func (m *MemoryVectorStore) Add(ctx context.Context, docs []*interfaces.Document, vectors [][]float32) error

Add 添加文档和向量

func (*MemoryVectorStore) AddDocuments

func (m *MemoryVectorStore) AddDocuments(ctx context.Context, docs []*interfaces.Document) error

AddDocuments 添加文档(实现 VectorStore 接口)

func (*MemoryVectorStore) Clear

func (m *MemoryVectorStore) Clear()

Clear 清空所有文档

func (*MemoryVectorStore) Count

func (m *MemoryVectorStore) Count() int

Count 返回文档数量

func (*MemoryVectorStore) Delete

func (m *MemoryVectorStore) Delete(ctx context.Context, ids []string) error

Delete 删除文档

func (*MemoryVectorStore) Get

Get 获取文档

func (*MemoryVectorStore) GetEmbedding

func (m *MemoryVectorStore) GetEmbedding(ctx context.Context, text string) ([]float32, error)

GetEmbedding 获取嵌入向量(实现扩展接口)

func (*MemoryVectorStore) GetVector

func (m *MemoryVectorStore) GetVector(ctx context.Context, id string) ([]float32, error)

GetVector 获取文档向量

func (*MemoryVectorStore) Search

func (m *MemoryVectorStore) Search(ctx context.Context, query string, topK int) ([]*interfaces.Document, error)

Search 相似度搜索

func (*MemoryVectorStore) SearchByVector

func (m *MemoryVectorStore) SearchByVector(ctx context.Context, queryVector []float32, topK int) ([]*interfaces.Document, error)

SearchByVector 通过向量搜索

func (*MemoryVectorStore) SimilaritySearch

func (m *MemoryVectorStore) SimilaritySearch(ctx context.Context, query string, topK int) ([]*interfaces.Document, error)

SimilaritySearch 相似度搜索(实现 VectorStore 接口)

func (*MemoryVectorStore) SimilaritySearchWithScore

func (m *MemoryVectorStore) SimilaritySearchWithScore(ctx context.Context, query string, topK int) ([]*interfaces.Document, error)

SimilaritySearchWithScore 带分数的相似度搜索(实现 VectorStore 接口)

func (*MemoryVectorStore) Update

func (m *MemoryVectorStore) Update(ctx context.Context, docs []*interfaces.Document) error

Update 更新文档

type MemoryVectorStoreConfig

type MemoryVectorStoreConfig struct {
	Embedder       Embedder
	DistanceMetric DistanceMetric
}

MemoryVectorStoreConfig 内存向量存储配置

type MockVectorStore

type MockVectorStore struct {
	// contains filtered or unexported fields
}

MockVectorStore 模拟向量存储(用于测试和示例)

func NewMockVectorStore

func NewMockVectorStore() *MockVectorStore

NewMockVectorStore 创建模拟向量存储

func (*MockVectorStore) AddDocuments

func (m *MockVectorStore) AddDocuments(ctx context.Context, docs []*interfaces.Document) error

AddDocuments 添加文档

func (*MockVectorStore) Clear

func (m *MockVectorStore) Clear()

Clear 清空所有文档

func (*MockVectorStore) Delete

func (m *MockVectorStore) Delete(ctx context.Context, ids []string) error

Delete 删除文档

func (*MockVectorStore) GetAllDocuments

func (m *MockVectorStore) GetAllDocuments() []*interfaces.Document

GetAllDocuments 获取所有文档

func (*MockVectorStore) LoadDocuments

func (m *MockVectorStore) LoadDocuments(docs []*interfaces.Document)

LoadDocuments 加载文档到向量存储

func (*MockVectorStore) SimilaritySearch

func (m *MockVectorStore) SimilaritySearch(ctx context.Context, query string, topK int) ([]*interfaces.Document, error)

SimilaritySearch 相似度搜索(模拟实现)

func (*MockVectorStore) SimilaritySearchWithScore

func (m *MockVectorStore) SimilaritySearchWithScore(ctx context.Context, query string, topK int) ([]*interfaces.Document, error)

SimilaritySearchWithScore 带分数的相似度搜索

type MultiQueryRetriever

type MultiQueryRetriever struct {
	*BaseRetriever

	// BaseRetriever 基础检索器
	Retriever Retriever

	// LLMClient LLM 客户端(用于生成查询变体)
	LLMClient llm.Client

	// NumQueries 生成的查询数量
	NumQueries int

	// QueryPrompt 查询生成提示词
	QueryPrompt string
}

MultiQueryRetriever 多查询检索器

使用 LLM 生成多个查询变体,并对所有变体进行检索,最后合并结果

func NewMultiQueryRetriever

func NewMultiQueryRetriever(
	baseRetriever Retriever,
	llmClient llm.Client,
	numQueries int,
	config RetrieverConfig,
) *MultiQueryRetriever

NewMultiQueryRetriever 创建多查询检索器

func (*MultiQueryRetriever) GetRelevantDocuments

func (m *MultiQueryRetriever) GetRelevantDocuments(ctx context.Context, query string) ([]*interfaces.Document, error)

GetRelevantDocuments 检索相关文档

func (*MultiQueryRetriever) WithNumQueries

func (m *MultiQueryRetriever) WithNumQueries(num int) *MultiQueryRetriever

WithNumQueries 设置生成的查询数量

func (*MultiQueryRetriever) WithQueryPrompt

func (m *MultiQueryRetriever) WithQueryPrompt(prompt string) *MultiQueryRetriever

WithQueryPrompt 设置查询生成提示词

type QdrantConfig

type QdrantConfig struct {
	// URL Qdrant 服务地址
	URL string

	// APIKey API 密钥(如果需要)
	APIKey string

	// CollectionName 集合名称
	CollectionName string

	// VectorSize 向量维度
	VectorSize int

	// Distance 距离度量类型: cosine, euclidean, dot
	Distance string

	// Embedder 嵌入器(用于自动向量化)
	Embedder Embedder
}

QdrantConfig Qdrant 配置

type QdrantVectorStore

type QdrantVectorStore struct {
	// contains filtered or unexported fields
}

QdrantVectorStore Qdrant 向量数据库存储

提供基于 Qdrant 的向量存储实现,支持高性能的语义搜索

func NewQdrantVectorStore

func NewQdrantVectorStore(ctx context.Context, config QdrantConfig) (*QdrantVectorStore, error)

NewQdrantVectorStore 创建 Qdrant 向量存储

参数:

  • config: Qdrant 配置

返回:

  • *QdrantVectorStore: Qdrant 向量存储实例
  • error: 错误信息

func (*QdrantVectorStore) Add

func (q *QdrantVectorStore) Add(ctx context.Context, docs []*interfaces.Document, vectors [][]float32) error

Add 添加文档和向量

func (*QdrantVectorStore) AddDocuments

func (q *QdrantVectorStore) AddDocuments(ctx context.Context, docs []*interfaces.Document) error

AddDocuments 添加文档(实现 VectorStore 接口)

func (*QdrantVectorStore) Close

func (q *QdrantVectorStore) Close() error

Close 关闭连接

func (*QdrantVectorStore) Delete

func (q *QdrantVectorStore) Delete(ctx context.Context, ids []string) error

Delete 删除文档

func (*QdrantVectorStore) GetEmbedding

func (q *QdrantVectorStore) GetEmbedding(ctx context.Context, text string) ([]float32, error)

GetEmbedding 获取嵌入向量

func (*QdrantVectorStore) Search

func (q *QdrantVectorStore) Search(ctx context.Context, query string, topK int) ([]*interfaces.Document, error)

Search 相似度搜索

func (*QdrantVectorStore) SearchByVector

func (q *QdrantVectorStore) SearchByVector(ctx context.Context, queryVector []float32, topK int) ([]*interfaces.Document, error)

SearchByVector 通过向量搜索

func (*QdrantVectorStore) SimilaritySearch

func (q *QdrantVectorStore) SimilaritySearch(ctx context.Context, query string, topK int) ([]*interfaces.Document, error)

SimilaritySearch 相似度搜索(实现 VectorStore 接口)

func (*QdrantVectorStore) SimilaritySearchWithScore

func (q *QdrantVectorStore) SimilaritySearchWithScore(ctx context.Context, query string, topK int) ([]*interfaces.Document, error)

SimilaritySearchWithScore 带分数的相似度搜索(实现 VectorStore 接口)

func (*QdrantVectorStore) Update

func (q *QdrantVectorStore) Update(ctx context.Context, docs []*interfaces.Document) error

Update 更新文档

type QdrantVectorStoreOption

type QdrantVectorStoreOption func(*QdrantConfig)

QdrantVectorStoreOption Qdrant 选项函数

func WithQdrantAPIKey

func WithQdrantAPIKey(apiKey string) QdrantVectorStoreOption

WithQdrantAPIKey 设置 API 密钥

func WithQdrantDistance

func WithQdrantDistance(distance string) QdrantVectorStoreOption

WithQdrantDistance 设置距离度量

func WithQdrantEmbedder

func WithQdrantEmbedder(embedder Embedder) QdrantVectorStoreOption

WithQdrantEmbedder 设置嵌入器

type RAGChain

type RAGChain struct {
	// contains filtered or unexported fields
}

RAGChain RAG 链,组合检索和生成

func NewRAGChain

func NewRAGChain(retriever *RAGRetriever, llmClient llm.Client) *RAGChain

NewRAGChain 创建 RAG 链

参数:

  • retriever: RAG 检索器
  • llmClient: LLM 客户端(可选,如果为 nil 则仅返回检索结果)

返回:

  • *RAGChain: RAG 链实例

func (*RAGChain) Run

func (c *RAGChain) Run(ctx context.Context, query string) (string, error)

Run 执行 RAG 链

执行完整的 RAG 流程:检索相关文档 -> 格式化上下文 -> 生成答案

参数:

  • ctx: 上下文
  • query: 用户查询

返回:

  • string: 生成的答案或格式化的上下文
  • error: 错误信息

type RAGMultiQueryRetriever

type RAGMultiQueryRetriever struct {
	BaseRetriever *RAGRetriever
	NumQueries    int
	LLMClient     llm.Client // LLM 客户端用于生成查询变体
}

RAGMultiQueryRetriever RAG 多查询检索器

生成多个相关查询并合并结果,提高召回率

func NewRAGMultiQueryRetriever

func NewRAGMultiQueryRetriever(baseRetriever *RAGRetriever, numQueries int, llmClient llm.Client) *RAGMultiQueryRetriever

NewRAGMultiQueryRetriever 创建 RAG 多查询检索器

参数:

  • baseRetriever: 基础 RAG 检索器
  • numQueries: 生成的查询数量
  • llmClient: LLM 客户端(可选,如果为 nil 则只使用原始查询)

返回:

  • *RAGMultiQueryRetriever: 多查询检索器实例

func (*RAGMultiQueryRetriever) Retrieve

func (m *RAGMultiQueryRetriever) Retrieve(ctx context.Context, query string) ([]*interfaces.Document, error)

Retrieve 检索相关文档

使用 LLM 生成查询变体,然后对每个查询进行检索并合并结果

参数:

  • ctx: 上下文
  • query: 原始查询

返回:

  • []*interfaces.Document: 合并后的文档列表
  • error: 错误信息

type RAGRetriever

type RAGRetriever struct {
	// contains filtered or unexported fields
}

RAGRetriever RAG (Retrieval-Augmented Generation) 检索器

结合向量检索和生成模型,提供增强的文档检索能力

func NewRAGRetriever

func NewRAGRetriever(config RAGRetrieverConfig) (*RAGRetriever, error)

NewRAGRetriever 创建 RAG 检索器

func (*RAGRetriever) AddDocuments

func (r *RAGRetriever) AddDocuments(ctx context.Context, docs []*interfaces.Document) error

AddDocuments 添加文档到向量存储

func (*RAGRetriever) Clear

func (r *RAGRetriever) Clear() error

Clear 清空向量存储(如果支持)

func (*RAGRetriever) Retrieve

func (r *RAGRetriever) Retrieve(ctx context.Context, query string) ([]*interfaces.Document, error)

Retrieve 检索相关文档

func (*RAGRetriever) RetrieveAndFormat

func (r *RAGRetriever) RetrieveAndFormat(ctx context.Context, query string, template string) (string, error)

RetrieveAndFormat 检索并格式化为 Prompt

使用指定的模板格式化检索到的文档

func (*RAGRetriever) RetrieveWithContext

func (r *RAGRetriever) RetrieveWithContext(ctx context.Context, query string) (string, error)

RetrieveWithContext 检索并构建上下文

返回格式化的上下文字符串,可直接用于 LLM 提示

func (*RAGRetriever) SetScoreThreshold

func (r *RAGRetriever) SetScoreThreshold(threshold float32)

SetScoreThreshold 设置分数阈值

func (*RAGRetriever) SetTopK

func (r *RAGRetriever) SetTopK(topK int)

SetTopK 设置 TopK

type RAGRetrieverConfig

type RAGRetrieverConfig struct {
	VectorStore      interfaces.VectorStore
	Embedder         Embedder
	TopK             int
	ScoreThreshold   float32
	IncludeMetadata  bool
	MaxContentLength int
}

RAGRetrieverConfig RAG 检索器配置

type RankFusion

type RankFusion struct {
	// Method 融合方法
	Method string // "rrf", "borda", "comb_sum"

	// K RRF 参数
	K float64
}

RankFusion 排名融合

func NewRankFusion

func NewRankFusion(method string) *RankFusion

NewRankFusion 创建排名融合

func (*RankFusion) Fuse

func (rf *RankFusion) Fuse(rankings [][]*interfaces.Document) []*interfaces.Document

Fuse 融合多个排名结果

type Reranker

type Reranker interface {
	// Rerank 重新排序文档
	Rerank(ctx context.Context, query string, docs []*interfaces.Document) ([]*interfaces.Document, error)
}

Reranker 重排序器接口

对检索到的文档进行重新排序,提高结果质量

type RerankingRetriever

type RerankingRetriever struct {
	*BaseRetriever

	// BaseRetriever 基础检索器
	Retriever Retriever

	// Reranker 重排序器
	Reranker Reranker

	// FetchK 初始检索的文档数量
	FetchK int
}

RerankingRetriever 带重排序的检索器

在基础检索器之上应用重排序

func NewRerankingRetriever

func NewRerankingRetriever(
	baseRetriever Retriever,
	reranker Reranker,
	fetchK int,
	config RetrieverConfig,
) *RerankingRetriever

NewRerankingRetriever 创建带重排序的检索器

func (*RerankingRetriever) GetRelevantDocuments

func (r *RerankingRetriever) GetRelevantDocuments(ctx context.Context, query string) ([]*interfaces.Document, error)

GetRelevantDocuments 检索并重排序文档

type Retriever

type Retriever interface {
	core.Runnable[string, []*interfaces.Document]

	// GetRelevantDocuments 检索相关文档
	//
	// 参数:
	//   - ctx: 上下文
	//   - query: 查询字符串
	//
	// 返回:
	//   - []*interfaces.Document: 相关文档列表
	//   - error: 错误信息
	GetRelevantDocuments(ctx context.Context, query string) ([]*interfaces.Document, error)
}

Retriever 定义检索器接口

借鉴 LangChain 的 Retriever 设计,提供统一的文档检索接口 继承自 Runnable[string, []*interfaces.Document],支持管道操作和回调

type RetrieverConfig

type RetrieverConfig struct {
	TopK     int     // 返回的最大文档数
	MinScore float64 // 最小分数阈值
	Name     string  // 检索器名称
}

RetrieverConfig 检索器配置

func DefaultRetrieverConfig

func DefaultRetrieverConfig() RetrieverConfig

DefaultRetrieverConfig 返回默认配置

type SearchType

type SearchType string

SearchType 搜索类型

const (
	// SearchTypeSimilarity 相似度搜索
	SearchTypeSimilarity SearchType = "similarity"

	// SearchTypeSimilarityScoreThreshold 基于相似度阈值的搜索
	SearchTypeSimilarityScoreThreshold SearchType = "similarity_score_threshold"

	// SearchTypeMMR 最大边际相关性搜索
	SearchTypeMMR SearchType = "mmr"
)

type SimpleEmbedder

type SimpleEmbedder struct {
	*BaseEmbedder
	// contains filtered or unexported fields
}

SimpleEmbedder 简单的 TF-IDF 风格嵌入器(用于测试和开发)

使用简单的词频向量表示,不依赖外部模型

func NewSimpleEmbedder

func NewSimpleEmbedder(dimensions int) *SimpleEmbedder

NewSimpleEmbedder 创建简单嵌入器

func (*SimpleEmbedder) Embed

func (e *SimpleEmbedder) Embed(ctx context.Context, texts []string) ([][]float32, error)

Embed 批量嵌入文本

func (*SimpleEmbedder) EmbedQuery

func (e *SimpleEmbedder) EmbedQuery(ctx context.Context, query string) ([]float32, error)

EmbedQuery 嵌入单个查询文本

type VectorStoreRetriever

type VectorStoreRetriever struct {
	*BaseRetriever

	// VectorStore 向量存储实例
	VectorStore interfaces.VectorStore

	// SearchType 搜索类型
	SearchType SearchType

	// SearchKwargs 搜索参数
	SearchKwargs map[string]interface{}
}

VectorStoreRetriever 向量存储检索器

使用向量相似度进行文档检索

func NewVectorStoreRetriever

func NewVectorStoreRetriever(vectorStore interfaces.VectorStore, config RetrieverConfig) *VectorStoreRetriever

NewVectorStoreRetriever 创建向量存储检索器

func (*VectorStoreRetriever) GetRelevantDocuments

func (v *VectorStoreRetriever) GetRelevantDocuments(ctx context.Context, query string) ([]*interfaces.Document, error)

GetRelevantDocuments 检索相关文档

func (*VectorStoreRetriever) WithSearchKwargs

func (v *VectorStoreRetriever) WithSearchKwargs(kwargs map[string]interface{}) *VectorStoreRetriever

WithSearchKwargs 设置搜索参数

func (*VectorStoreRetriever) WithSearchType

func (v *VectorStoreRetriever) WithSearchType(searchType SearchType) *VectorStoreRetriever

WithSearchType 设置搜索类型

Directories

Path Synopsis
examples
advanced command
basic command

Jump to

Keyboard shortcuts

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