semantic

package
v2.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package semantic 是「可选语义检索」(#266 步骤 2b)的核心:切块、凭据隐去、向量量化、内存索引、后台嵌入流水线与查询。

隐私与资源不变量(设计文档 V1–V9,每一条都有对应测试与变异对照):

  • V1 关闭 = 零协程、零出站、零内存缓存:工作协程只在「总开关开 + 未暂停 + 密钥可用 + 至少勾了一个项目」时才存在;
  • V2 同意范围:只有「已勾选项目 ∩ 允许的内容类型」内、未归档的内容才会被切块外发;外发前再按真实归属核对一次;
  • V3 凭据隐去:外发的、哈希的、给用户看的片段都是隐去之后的文本(TitleAndLines 是唯一入口);
  • V4 逐条回源校验:查询命中要重读最新原文、核对范围与归档、重算 text_hash,对不上就丢弃;
  • V5 出站只经 embedding.Service.Embed:本包不引入 net/http(有测试盯着);
  • V6 资源有界:块数上限、嵌入限速(块 / 分钟)、查询限速(次 / 分钟)、不在持有数据库连接时出站;
  • V7 向量只在同一签名(model|dims)内比较;签名变了旧向量作废,重建要用户确认;
  • V8 取消勾选的项目,向量立刻删除(同步),不等下一轮对账;
  • V9 只给网页登录用户(由 API 层保证)。

Package semantic 是可选语义检索的第二部分(#266 步骤 2b):切块、向量量化、凭据隐去、内存向量索引、 后台嵌入流水线与语义查询。

它站在 internal/embedding(配置、密钥、外呼、预算)与 internal/store(条目与向量的持久化)之上: 所有出站请求只走 embedding.Service.Embed,所有数据库读写只走 store 的导出方法。

不变量(设计稿 .cursor/planning/2026-10-26-266-step2b-vector-pipeline-design.md 第 0 节):

V1 关闭 = 零:没有后台协程、没有出站、没有内存缓存。
V2 同意范围:只有「已勾选项目 ∩ 允许类型」的内容会出站。
V3 凭据隐去:出站文本里的凭据特征先替换成 Redacted。
V4 回源校验:语义命中要重新读源行、重算文本哈希,对不上就丢弃。
V5 预算:出站只走 Service.Embed。
V6 资源有界:块数上限、单条最多 MaxChunks 块、出站期间不占数据库连接。
V7 签名一致:向量只和同一个 model|dims 签名的向量比较。
V8 撤回即删:取消勾选项目,该项目的向量立即删除。

Index

Constants

View Source
const (
	DefaultChunksPerMinute          = 1000                      // 嵌入限速:每分钟最多外发多少块
	DefaultQueriesPerMinute         = 30                        // 查询限速:每分钟最多外发多少次查询向量
	DefaultMaxChunks                = 200_000                   // 向量块数上限(内存索引约 200 MB @1024 维)
	DefaultMinScore         float32 = embedding.DefaultMinScore // 默认相似度下限:低于它的语义命中不展示(设置页「相似度下限」可调,默认值的来由见 embedding.DefaultMinScore)

)

默认参数(Options 里没给的取这里)。

View Source
const (
	// ReasonTruncated:内容超过单条上限,只嵌入了前面一部分。
	ReasonTruncated = "truncated"
	// ReasonTailRejected:补后半部分时被嵌入服务拒绝(比如内容安全拦截),保留了前面已经嵌好的部分。
	ReasonTailRejected = "tail_rejected"
	// ReasonRejected:整条被嵌入服务拒绝(比如内容安全拦截),没有向量。
	ReasonRejected = "rejected"
	// ReasonTooShort:去掉空白与隐去内容之后太短(少于 MinRunes 个字符),不嵌入。
	ReasonTooShort = "too_short"
)

没有被完整嵌入的原因(界面按它给出人话)。

View Source
const EntryMaxChunks = 600

EntryMaxChunks 是一个条目最多嵌入多少块(单条上限):600 块 ≈ 21 万 token ≈ 25 万个汉字, 覆盖绝大多数长文档与长对话段;超出的部分不嵌入(关键词检索不受影响,它走全文索引,单条上限是 1 MiB)。

提高这个上限**不改** chunkerVersion:文本哈希(含 chunkerVersion)只取决于清洗后的文本,与块数上限无关, 查询时的回源校验(V4)比的就是它;改了版本号会让库里的每一个命中都被当成「内容变了」丢掉。 切块是顺序的(第 i 块只取决于它前面的内容),所以上限变高时前面的块与块哈希一字不变,向量照旧复用, 只有新增的后半部分要发出去嵌入。

View Source
const IncompleteListMax = 200

IncompleteListMax 是一次最多列出多少条(总数另给,界面写明「只列出前 N 条」)。

View Source
const LegacyEntryMaxChunks = 200

LegacyEntryMaxChunks 是单条上限提高之前写入的条目所用的上限;库里 chunk_cap = 0 的条目按它算。

View Source
const Redacted = "[已隐去]"

Redacted 是被隐去内容的替换文字。

Variables

View Source
var DefaultParams = Params{TargetTokens: 350, OverlapTokens: 50, MaxChunks: EntryMaxChunks, MinRunes: 20, TitleMaxRunes: 200}

DefaultParams 是线上用的参数。运行期间只读:嵌入流水线与查询时的回源校验共用它(V4),测试要改上限时 必须在创建控制器之前改、停掉控制器之后再还原。

View Source
var ErrBadVector = errors.New("向量不可用(空、含非数字或全零)")

ErrBadVector 表示服务返回的向量不能用(空、含 NaN / Inf、全零)。

View Source
var ErrDimMismatch = errors.New("语义索引:向量维度与索引不一致")

ErrDimMismatch 表示向量维度与索引不一致(换了模型 / 维度,或提供商悄悄变了):不写入、不比较。

Functions

func Clean

func Clean(s string) string

Clean 是出站文本的唯一清洗入口:归一化 → 隐去凭据 → 再归一化。嵌入与回源校验都用它。幂等。

func CleanLine

func CleanLine(s string) string

CleanLine 把一段文字清洗成单行(行内换行折成空格),用于标题与群消息。

func Dequantize

func Dequantize(q []int8, scale float32) []float32

Dequantize 把量化向量还原成(近似的单位)浮点向量,测试与诊断用。

func Dot

func Dot(a, b []int8) int32

Dot 是两个 int8 向量的点积(长度必须相同,调用方保证)。int32 够用:127·127·维度 < 2^31,维度 ≤ 4096。

func EstimateTokens

func EstimateTokens(s string) int

EstimateTokens 估算一段文字的 token 数:汉字假名约 0.7、ASCII 约 0.3、其他约 0.5,向上取整。 只用来决定块的大小;预算入账用的是服务回报的真实用量。

func EstimateTokensFor

func EstimateTokensFor(chars int64) int64

EstimateTokensFor 把字符数估成 token 数(上限)。

func Normalize

func Normalize(s string) string

Normalize:换行统一、去控制字符与零宽字符、行尾空白、连续空行折成一个、首尾空白。纯函数、幂等。

func PackInt8

func PackInt8(q []int8) []byte

PackInt8 / UnpackInt8 在 []int8 与数据库里存的 []byte 之间转换(同一份内存的两种看法,这里直接拷贝,简单可靠)。

func Quantize

func Quantize(v []float32) (q []int8, scale float32, err error)

Quantize 把一个浮点向量变成「int8 + scale」。输入不会被修改。

func Redact

func Redact(s string) string

Redact 把凭据特征替换成 Redacted。纯函数、确定性、幂等:嵌入时与回源校验时用的是同一个, 所以隐去不会让文本哈希对不上。

func Score

func Score(dot int32, sa, sb float32) float32

Score 由点积与两个 scale 还原出余弦相似度的近似值。

func SigOf

func SigOf(cfg embedding.Config) string

SigOf 是向量库的签名:只有同一签名的向量才能互相比较(V7)。

func UnpackInt8

func UnpackInt8(b []byte) []int8

Types

type Built

type Built struct {
	Chunks    []Chunk
	Truncated bool   // 超过 MaxChunks,后面的内容没有嵌入
	Skipped   bool   // 内容太短或几乎全是隐去内容:不嵌入、不外发
	TextHash  string // 归一化并隐去凭据后的「标题 + 正文」的哈希(含切块规则版本)
}

Built 是一个条目切块的结果。

func Build

func Build(title string, lines []string, p Params) Built

Build 把「标题 + 若干源行」切成块。lines 是已经清洗过的单行文字(文档正文的每一行,或群消息的每条一行); 空行会被忽略。确定性纯函数:嵌入与回源校验用同一个,同样的输入永远得到同样的块。

func BuildText

func BuildText(title, body string, p Params) Built

BuildText 清洗标题与正文,再按行切块。title 取单行;正文里的空行被忽略。

type Chunk

type Chunk struct {
	Seq    int
	Text   string // 要嵌入的文本:标题行 + 块正文
	Hash   string // Text 的哈希(32 个十六进制字符)
	Tokens int    // 估算 token 数(含标题)
	// First / Last 是这一块覆盖的源行下标(含)。群消息段里一行就是一条消息,靠它把块映射回消息。
	First, Last int
}

Chunk 是一块要嵌入的文本。

type ClearResult

type ClearResult struct {
	Entries int64 `json:"entries"`
	Chunks  int64 `json:"chunks"`
}

ClearResult 是清除向量的结果。

type Controller

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

Controller 管理语义检索的后台嵌入流水线、内存索引与查询。可并发使用。

func NewController

func NewController(o Options) *Controller

NewController 创建控制器:不启动任何协程,不做任何外呼。

func (*Controller) Clear

func (c *Controller) Clear(ctx context.Context) (*ClearResult, error)

Clear 删除全部向量并暂停(否则后台会立刻把它们重新嵌回来)。勾选的项目与设置保留。

func (*Controller) Close

func (c *Controller) Close()

Close 停止工作协程并释放全部内存;之后 Notify 不再起任何协程。可重复调用。

func (*Controller) Incomplete

func (c *Controller) Incomplete(ctx context.Context) (*IncompleteList, error)

Incomplete 列出没有被完整嵌入的条目(及原因)。

func (*Controller) IndexLoaded

func (c *Controller) IndexLoaded() (loaded bool, entries, chunks int, bytes int64)

IndexLoaded 报告内存索引是否在内存里,以及它的条目数 / 块数 / 向量字节数。

func (*Controller) Notify

func (c *Controller) Notify()

Notify 通知控制器「设置变了」,按最新设置对齐工作协程,可以放心在任何改动设置的地方调用(总开关、范围、暂停、密钥、嵌入配置):

  • 现在不该跑(关闭 / 暂停 / 没有项目 / 没有密钥……)→ 立刻叫停工作协程(取消进行中的外呼、叫醒睡眠)并等它退出,再释放内存缓存; 返回时不会再有这条流水线发出的新请求(已经在路上的那个请求被取消,结果丢弃);
  • 该跑、已有工作协程 → 唤醒它立即对账;
  • 该跑、没有工作协程 → 启动。

启动时调用一次即可恢复上次的运行。不能在工作协程里调用(它会等工作协程退出)。

func (*Controller) Pause

func (c *Controller) Pause(ctx context.Context) error

Pause 暂停:后台嵌入与语义查询都停止,内存缓存释放;向量保留。

func (*Controller) QueriesPerMinute

func (c *Controller) QueriesPerMinute() int

QueriesPerMinute 是「查询向量外发」当前每分钟的上限。

func (*Controller) Query

func (c *Controller) Query(ctx context.Context, p QueryParams) (*QueryResult, error)

Query 做一次语义查询:任何一步失败都返回 State != ok 的回执(不是错误),让调用方退回词法; 只有范围本身不合法(项目不存在、参数冲突)才返回 error。

func (*Controller) Rebuild

func (c *Controller) Rebuild(ctx context.Context) (*RebuildResult, error)

Rebuild 在模型 / 维度变了之后,由用户确认:删掉签名不符的旧向量(以及上次被服务拒绝的条目,让它们重试), 然后按新签名重新嵌入。没有可重建的内容返回 invalid-input 错误。

func (*Controller) Rescan

func (c *Controller) Rescan()

Rescan 立即对账一次(没有工作协程且应当运行时会启动它)。

func (*Controller) Resume

func (c *Controller) Resume(ctx context.Context) error

Resume 继续(同时清掉自动暂停留下的原因)。

func (*Controller) Running

func (c *Controller) Running() bool

Running 报告工作协程是否存在(V1 的测试用)。

func (*Controller) SetEnabled

func (c *Controller) SetEnabled(ctx context.Context, on bool) (store.SemanticRun, error)

SetEnabled 打开 / 关闭总开关。打开前要求密钥可用且维度已填;打开会清除暂停状态;关闭立刻释放内存缓存(向量保留、不再使用)。

func (*Controller) SetQueriesPerMinute

func (c *Controller) SetQueriesPerMinute(n int)

SetQueriesPerMinute 改「查询向量外发」每分钟最多多少次,立即生效。设置页「智能体检索额度」里的「语义合计」保存时调用, 进程启动时也按存下的值调用一次,所以这个限速(网页搜索框与智能体共用)跟着用户设的合计走;缓存命中的查询不占次数。

func (*Controller) SetScope

func (c *Controller) SetScope(ctx context.Context, kinds *[]string, projects *[]uint) (*ScopeResult, error)

SetScope 修改勾选的项目与允许外发的内容类型(nil = 不改)。范围缩小时,范围外的向量在返回之前就已同步删除(V8), 并让进行中的流水线作废它手里的落库(scopeGen 前进),所以取消勾选的内容不会被复活。

func (*Controller) Status

func (c *Controller) Status(ctx context.Context, detail bool) (*Status, error)

Status 返回整体状态;detail 为 true 时额外现算各项目的范围、覆盖率与 token 预估(查询较重,设置页打开时才用)。

type Hit

type Hit struct {
	Meta  Meta
	Score float32
	Seq   int // 最匹配的那一块的序号
}

Hit 是一个条目的最近邻结果:条目分数取它所有块里最高的。

type IncompleteItem

type IncompleteItem struct {
	Kind     string   `json:"kind"`
	Ref      string   `json:"ref"`
	Title    string   `json:"title"`
	Projects []string `json:"projects"` // 条目所属的、已勾选的项目名
	Reason   string   `json:"reason"`
	Chunks   int      `json:"chunks"`              // 已嵌入的块数
	ChunkCap int      `json:"chunk_cap,omitempty"` // 嵌入时的单条上限(truncated / tail_rejected)
	Redo     bool     `json:"redo,omitempty"`      // truncated:单条上限已经提高,后半部分正在或即将补上
}

IncompleteItem 是一个没有被完整嵌入的条目。

type IncompleteList

type IncompleteList struct {
	Total          int              `json:"total"`
	Counts         map[string]int   `json:"counts"` // 四种原因各有多少条(都在,没有的是 0)
	Items          []IncompleteItem `json:"items"`  // 最多 IncompleteListMax 条:先按原因(截断在前、太短在后),再按内容类型、已嵌入块数(多的在前)
	More           bool             `json:"more"`   // 还有没列出来的(Total > len(Items))
	EntryMaxChunks int              `json:"entry_max_chunks"`
	MinRunes       int              `json:"min_runes"`
}

IncompleteList 是明细的响应。

type Index

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

Index 是向量库在内存里的副本,只用来做「扫一遍」的最近邻查询(几十万块以内,纯 Go 点积,不引入任何依赖)。 所有方法并发安全;查询持读锁,写入(Apply / Remove)持写锁——一次全量扫描是几十到一两百毫秒,写入最多等这么久。

func NewIndex

func NewIndex(sig string, dims int) *Index

NewIndex 创建一个空索引;sig 是 model|dims 签名,dims 是向量维度。

func (*Index) Apply

func (ix *Index) Apply(meta Meta, chunks []Vec) error

Apply 用 chunks 整体替换一个条目(没有则新增);chunks 为空等于删除。

func (*Index) Bytes

func (ix *Index) Bytes() int64

Bytes 估算向量数据占用的内存(不含元数据与切片头的开销)。

func (*Index) Clear

func (ix *Index) Clear()

Clear 清空索引。

func (*Index) Dims

func (ix *Index) Dims() int

Dims 返回向量维度。

func (*Index) Has

func (ix *Index) Has(kind, ref string) (Meta, bool)

Has 判断条目是否在索引里,并返回它的快照。

func (*Index) Keys

func (ix *Index) Keys() []Key

Keys 返回索引里全部条目的键(用于和库里对账)。

func (*Index) Len

func (ix *Index) Len() (entries, chunks int)

Len 返回条目数与块数。

func (*Index) Remove

func (ix *Index) Remove(keys ...Key) int

Remove 删除若干条目;不存在的忽略。返回实际删掉的条目数。

func (*Index) Search

func (ix *Index) Search(query []float32, k int, minScore float32, allow func(Meta) bool) ([]Hit, error)

Search 找与查询向量最相近的前 k 个条目(每个条目取最高分的块)。 allow 为空表示不筛;非空时对每个条目的快照调用一次,返回 false 的条目不参与(范围过滤,V2 / V4 的第一道)。 minScore 以下的不返回。结果按分数降序,同分按 (类型, ref) 升序,完全确定。

func (*Index) SetMeta

func (ix *Index) SetMeta(meta Meta) bool

SetMeta 只更新一个已有条目的快照(归属变了、向量没变);条目不在索引里返回 false。

func (*Index) Sig

func (ix *Index) Sig() string

Sig 返回索引对应的签名。

type Key

type Key struct{ Kind, Ref string }

Key 是一个条目的标识(类型 + ref)。

type KindStat

type KindStat struct {
	Count int   `json:"count"`
	Chars int64 `json:"chars"`
}

KindStat 是某个项目里一种内容类型的体量(与「当前是否允许外发这种类型」无关:设置页据此估算「勾上之后会多发多少」)。

type Meta

type Meta struct {
	Kind, Ref      string
	WorkflowID     string
	ProjectID      uint
	ConversationID string
	TextHash       string
}

Meta 是一个条目在内存里保留的归属快照:查询时先按它筛范围(便宜),命中后仍会回源按真实归属再核一遍(V4)。

type NotReadyError

type NotReadyError struct{ Reason string }

NotReadyError 表示现在还不能打开语义检索(密钥不可用 / 维度没填);Reason 面向用户。

func IsNotReady

func IsNotReady(err error) (*NotReadyError, bool)

IsNotReady 判断错误是不是「现在还不能打开」。

func (*NotReadyError) Error

func (e *NotReadyError) Error() string

type Options

type Options struct {
	Store *store.Store
	Embed *embedding.Service

	ChunksPerMinute  int
	QueriesPerMinute int
	MaxChunks        int
	GroupSize        int
	ReconcileEvery   time.Duration
	BatchPause       time.Duration
	BackoffMin       time.Duration
	BackoffMax       time.Duration
	IdleRelease      time.Duration
	// MinScore 大于 0 时是对相似度下限的强制覆盖(测试 / 运维用);0 = 跟随设置页里的「相似度下限」。
	MinScore       float32
	QueryCacheSize int
	QueryCacheTTL  time.Duration

	Now  func() time.Time
	Logf func(format string, args ...any)
}

Options 创建控制器的参数。

type Params

type Params struct {
	TargetTokens  int // 每块正文的目标估算 token 数(约 350 ≈ 500 个汉字)
	OverlapTokens int // 相邻块重叠的估算 token 数(约 15%)
	MaxChunks     int // 一个条目最多切多少块;超出的部分不嵌入(Truncated)
	MinRunes      int // 去掉空白与隐去标记后,标题 + 正文少于这么多个字符的条目不嵌入(Skipped)
	TitleMaxRunes int // 标题行最长字符数
}

Params 是切块参数。

type Prepared

type Prepared struct {
	Built   Built
	Title   string
	Lines   []string
	LineSeq []int64 // 群消息段:每一行对应的消息 seq;其它类型为 nil
}

Prepared 是一条原文清洗、切块后的结果:嵌入流水线与查询时的回源校验共用 Prepare, 所以两边切出的块与 text_hash 永远一致(V3 / V4)。凭据隐去也发生在这里:外发的、哈希的、给用户看的片段,都是隐去之后的文本。

func Prepare

func Prepare(t *store.SemanticText) Prepared

Prepare 对回源读到的最新原文做「清洗 → 切块」。

func (Prepared) Chunk

func (p Prepared) Chunk(seq int) (Chunk, bool)

Chunk 取序号为 seq 的块;找不到时取第一块;没有块返回 false。

func (Prepared) MessageSeq

func (p Prepared) MessageSeq(c Chunk) int64

MessageSeq 返回一个块第一行对应的群消息 seq(用来跳到群里的那条消息);不是群消息段返回 0。

func (Prepared) Snippet

func (p Prepared) Snippet(c Chunk, maxRunes int) string

Snippet 取一个块覆盖的源行拼成片段(单行、按字符数截断)。

type ProjectStatus

type ProjectStatus struct {
	ID       uint   `json:"id"`
	Name     string `json:"name"`
	Slug     string `json:"slug"`
	Archived bool   `json:"archived,omitempty"`
	Enabled  bool   `json:"enabled"`

	// 以下按「当前允许的内容类型」统计。
	Eligible      int   `json:"eligible"`       // 范围内(允许类型)的条目数
	Covered       int   `json:"covered"`        // 其中已追平的(已嵌入,或判定为不嵌入)
	Chars         int64 `json:"chars"`          // 全部内容的字符数
	EstTokens     int64 `json:"est_tokens"`     // 全部嵌入需要的 token(上限估算)
	PendingTokens int64 `json:"pending_tokens"` // 还没追平的部分需要的 token(上限估算)

	// 各类内容(SearchKinds 里的每一类)各自的体量(不论当前是否允许)。
	Kinds map[string]KindStat `json:"kinds"`
}

ProjectStatus 是一个项目的语义检索情况(设置页的项目列表用)。

type QueryHit

type QueryHit struct {
	store.SearchHit
	Score float32 `json:"score"`
}

QueryHit 是一条语义命中:与词法命中同形状,外加相似度分数。

type QueryParams

type QueryParams struct {
	Q          string
	ProjectID  uint
	WorkflowID string
	Kinds      []string // 空 = 全部允许的类型
	Limit      int
	// MinScore 非 nil 时覆盖这一次查询的相似度下限(-1~1,余弦相似度的取值范围)。只给评测与阈值校准用:降到 -1 就是不设下限,
	// 才看得到完整的分数分布;只改「展示哪些命中」,同意范围、回源核对与限速都不受影响。
	MinScore *float32
}

QueryParams 是一次语义查询。范围字段与词法检索同义(project_id 与 workflow_id 互斥)。

type QueryResult

type QueryResult struct {
	State   State      `json:"state"`
	Reason  string     `json:"reason,omitempty"`
	Hits    []QueryHit `json:"hits"`
	Covered int        `json:"covered"` // 范围内已追平的条目数
	Total   int        `json:"total"`   // 范围内的条目总数
}

QueryResult 是一次语义查询的回执。State != ok 时 Hits 为空,Reason 说明原因(调用方退回词法结果并给一句话说明)。

type RebuildResult

type RebuildResult struct {
	Dropped int `json:"dropped_entries"`
}

RebuildResult 是重建的结果。

type ScopeResult

type ScopeResult struct {
	Added   []uint `json:"added"`
	Removed []uint `json:"removed"`
	Deleted int    `json:"deleted_entries"` // 因为不在范围内而被立即删除向量的条目数
}

ScopeResult 是修改勾选范围的结果。

type State

type State string

State 是语义检索的状态(界面徽标与查询回执共用)。

const (
	StateOff          State = "off"           // 总开关关
	StateNoProject    State = "no_project"    // 开了,但一个项目都没勾
	StateNoKinds      State = "no_kinds"      // 开了,但没有允许外发的内容类型
	StatePaused       State = "paused"        // 用户暂停
	StateAttention    State = "attention"     // 自动暂停:需要处理(原因见 Reason)
	StateNoKey        State = "no_key"        // API Key 不可用
	StateNeedsDims    State = "needs_dims"    // 向量维度为 0,无法确定签名
	StateNeedsRebuild State = "needs_rebuild" // 模型 / 维度变了,旧向量已停用,等用户确认重建
	StateIdle         State = "idle"          // 已追平
	StateRunning      State = "running"       // 正在嵌入
	StateRetry        State = "retry"         // 外呼失败,等待重试
	StateBudget       State = "budget"        // 今日 token 额度用完
	StateFull         State = "full"          // 向量块数到达上限

	// 以下只出现在查询回执里。
	StateOK         State = "ok"
	StateProjectOff State = "project_off" // 查询限定的项目没有开启语义检索
	StateThrottled  State = "throttled"   // 查询过于频繁
	StateDegraded   State = "degraded"    // 查询失败,已退回词法
	StateEmpty      State = "empty"       // 还没有任何向量
)

type Status

type Status struct {
	State  State  `json:"state"`
	Reason string `json:"reason,omitempty"`

	Enabled    bool     `json:"enabled"`
	Paused     bool     `json:"paused"`
	Kinds      []string `json:"kinds"`
	ProjectIDs []uint   `json:"project_ids"`
	Sig        string   `json:"sig"`

	Entries      int64 `json:"entries"`       // 向量库里已嵌入的条目(含旧签名的)
	Skipped      int64 `json:"skipped"`       // 内容太短而不嵌入的条目
	Failed       int64 `json:"failed"`        // 服务拒绝嵌入的条目
	StaleEntries int64 `json:"stale_entries"` // 签名与当前不同、需要重建的条目
	Truncated    int64 `json:"truncated"`     // 因超长只嵌入了前面部分的条目
	Chunks       int64 `json:"chunks"`
	VecBytes     int64 `json:"vec_bytes"`
	MaxChunks    int   `json:"max_chunks"`

	// 范围内条目数 / 已追平 / 待嵌入:不带 detail 时是工作协程上一次对账的快照(snapshot_at 是它的时间);
	// 关闭、暂停、没有勾选项目等不运行的状态下没有快照(全为 0、没有 snapshot_at),要看现算的数字请加 detail。
	Eligible      int        `json:"eligible"`
	Covered       int        `json:"covered"`
	Pending       int        `json:"pending"`
	PendingTokens int64      `json:"pending_tokens"`
	SnapshotAt    *time.Time `json:"snapshot_at,omitempty"`
	ProgressDone  int        `json:"progress_done"`
	ProgressTotal int        `json:"progress_total"`

	RetryAt     *time.Time `json:"retry_at,omitempty"`
	LastError   string     `json:"last_error,omitempty"`
	LastErrorAt *time.Time `json:"last_error_at,omitempty"`

	IndexLoaded  bool  `json:"index_loaded"`
	IndexEntries int   `json:"index_entries"`
	IndexChunks  int   `json:"index_chunks"`
	IndexBytes   int64 `json:"index_bytes"`

	ChunksPerMinute  int     `json:"chunks_per_minute"`
	QueriesPerMinute int     `json:"queries_per_minute"`
	MinScore         float32 `json:"min_score"`

	Projects []ProjectStatus `json:"projects,omitempty"`
}

Status 是语义检索的整体状态。

type Vec

type Vec struct {
	Seq   int
	Scale float32
	Q     []int8
}

Vec 是一个向量块(已量化)。

Directories

Path Synopsis
Package fakeembed 是测试用的「假嵌入服务」:一个本机的 OpenAI 兼容 /embeddings 端点, 用确定性的「概念词典 + 字符 n-gram 哈希」造向量,使近义词在向量上相近、而词法完全不命中—— 这样才能验证「语义检索」真的比词法多找到了东西。
Package fakeembed 是测试用的「假嵌入服务」:一个本机的 OpenAI 兼容 /embeddings 端点, 用确定性的「概念词典 + 字符 n-gram 哈希」造向量,使近义词在向量上相近、而词法完全不命中—— 这样才能验证「语义检索」真的比词法多找到了东西。

Jump to

Keyboard shortcuts

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