embedding

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: 29 Imported by: 0

Documentation

Overview

Package embedding 是「可选语义检索」(#266 第 2 步)与在线嵌入服务之间的那一层。

它只做三件事,并且彼此隔离:

  • config.go 配置的形状、默认值、校验(不含密钥);
  • vault.go API Key 的密封保管:数据目录里自动生成的主密钥文件(0600)+ AES-256-GCM,密文绑定到服务主机;
  • guard.go / client.go 对外的一次 HTTP 调用:只允许 https、拨号时检查实际 IP(防 SSRF)、不跟随重定向、错误先打码;
  • service.go 把上面几块与持久化、用量预算拼起来,给 API 层与后续的向量流水线用。

本包是叶子包(只依赖标准库与 internal/secure),持久化通过 Persistence 接口由 store 实现。

Index

Constants

View Source
const (
	// DefaultBaseURL 是阿里云百炼的 OpenAI 兼容接口(填到 /v1 为止,请求时再拼 /embeddings)。
	DefaultBaseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
	// DefaultModel 取自用户 bailian.env 里的默认配置;备选 text-embedding-v4。
	DefaultModel = "qwen3.7-text-embedding"
	// DefaultDimensions 是默认向量维度;最终取值由评测集决定(步骤 3),这里只是起步值。
	DefaultDimensions = 1024
	// DefaultBatchSize 是一次请求带几条文本;百炼 text-embedding-v4 的上限是 10。
	DefaultBatchSize = 10
	// DefaultTimeoutSeconds 是单次请求的总超时。
	DefaultTimeoutSeconds = 60
	// DefaultDailyTokenCap 是每天最多花多少 token(Hub 本地日期);0 = 不限。
	DefaultDailyTokenCap int64 = 1_000_000
	// DefaultMinScore 是语义命中的默认相似度下限(余弦相似度):低于它的命中不展示。
	// 0.35 → 0.50:2026-10-27 在生产上用 15 道自拟问题扫过一遍——0.35 时没有答案的问题会凑出一组不相关的结果(误报 2/4),
	// 0.50 起零误报,而期望命中的分数最小 0.63。样本很小,所以设置页里可以调(用户确认项 Q152 选 a)。
	DefaultMinScore = 0.50
)
View Source
const (
	MinDimensions      = 16
	MaxDimensions      = 4096
	MaxBatchSize       = 25
	MinTimeoutSeconds  = 5
	MaxTimeoutSeconds  = 300
	MinDailyTokenCap   = 1000
	MaxDailyTokenCap   = 10_000_000_000
	MinMinScore        = 0.20
	MaxMinScore        = 0.90
	MaxPricePerMillion = 1_000_000.0
	MaxCurrencyLen     = 8 // 币种标记最多几个字符(按字,不按字节)

	MinKeyLen = 8
	MaxKeyLen = 512
)

各字段的合法范围(界面从服务端的 Limits 里读,不另存一份)。

View Source
const CredentialName = "embedding"

CredentialName 是库里保存的唯一一份密钥的名字(表按名字做主键,将来要存别的密钥也不必改表)。

View Source
const TestSentence = "RelayMesh embedding connection test"

TestSentence 是「测试连接」发出的唯一内容:一句固定的英文,不含任何用户数据。

Variables

View Source
var (
	// ErrVaultUnavailable 表示当前运行方式没有持久的数据目录(例如内存数据库),无法安放主密钥文件。
	ErrVaultUnavailable = errors.New("当前运行方式没有持久数据目录,无法保存密钥")
	// ErrNoMasterKey 表示主密钥文件不存在:只有 Seal(用户保存密钥)才会创建它,Open 永远不会。
	ErrNoMasterKey = errors.New("主密钥文件不存在")
	// ErrBadMasterKey 表示主密钥文件存在但内容无效。绝不覆盖它:覆盖会让库里已有的密文永久解不开。
	ErrBadMasterKey = errors.New("主密钥文件内容无效")
)
View Source
var ErrBudgetExceeded = errors.New("今日 token 预算已用完")

ErrBudgetExceeded 表示今日 token 预算不够这一次调用(调用没有发出)。

View Source
var ErrInvalidConfig = errors.New("语义检索配置不合法")

ErrInvalidConfig 表示配置取值不合法;错误信息面向用户,可以直接展示。

View Source
var ErrKeyNotReady = errors.New("API Key 不可用")

ErrKeyNotReady 表示密钥不可用(没设置、主机变了或主密钥文件有问题);具体原因见包装后的说明。

View Source
var ErrThrottled = errors.New("测试过于频繁,请稍等几秒再试")

ErrThrottled 表示测试太频繁(或上一次还没结束)。

Functions

func BoundHost

func BoundHost(u *url.URL) string

BoundHost 是密钥绑定的主机标识:小写主机名 + 端口(缺省按协议补 443 / 80)。 同一个服务换路径(/v1 → /v2)不算换主机;换了主机或端口,已保存的密钥就不再可用,要重新粘贴。

func EstimateTokens

func EstimateTokens(inputs []string) int

EstimateTokens 是发出请求之前的保守估计:一个字符按一个 token 算(中文约 1–1.5 字 / token,英文约 4 字符 / token, 所以这个估计对英文偏高,对预算检查是安全的一侧)。

func LastFour

func LastFour(key string) string

LastFour 返回给界面看的末四位;密钥不够长(< 16)时一个字符都不露。

func ParseBaseURL

func ParseBaseURL(raw string, allowPrivate bool) (*url.URL, error)

ParseBaseURL 解析并校验服务地址,返回规整后的 URL(无末尾斜杠)。 默认只收 https;allowPrivate 时也收 http。无论哪种,地址里都不许有用户信息、查询串、片段, 也不许以 /embeddings 结尾(请求时由客户端拼)。主机是字面 IP 或 localhost 时,在这里就按「内网」拦下(早报错,拨号时还会再查一次)。

func ValidateAPIKey

func ValidateAPIKey(raw string) (string, error)

ValidateAPIKey 整理并检查用户粘贴的密钥:去首尾空白;长度 8–512;只能是可见 ASCII,中间不许有空白。 错误信息不含密钥本身。

Types

type CallError

type CallError struct {
	Kind       ErrKind
	Status     int
	Message    string
	RetryAfter time.Duration // 仅 429 / 503:服务建议的等待时间(已限幅)
}

CallError 是一次外呼的失败。Message 面向用户、已打码(不含密钥),可以直接展示与写入审计。

func (*CallError) Error

func (e *CallError) Error() string

func (*CallError) Retryable

func (e *CallError) Retryable() bool

Retryable 报告这类失败是否值得稍后重试(流水线用)。

type Client

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

Client 只服务一个固定配置与一把密钥;用完即弃(连接池很小,空闲 30 秒回收)。

func NewClient

func NewClient(cfg Config, key, userAgent string) (*Client, error)

NewClient 校验配置并创建客户端。key 只存在这个对象里,不会被日志或错误信息带出。

func (*Client) Embed

func (c *Client) Embed(ctx context.Context, inputs []string) (*EmbedResult, error)

Embed 为 inputs 里的每条文本取一个向量。失败时返回 *CallError。不重试:重试与退避由调用方(流水线)决定。

type Config

type Config struct {
	// BaseURL 是嵌入服务的地址,填到 /v1 为止,不带末尾斜杠,不含 /embeddings。
	BaseURL string `json:"base_url"`
	// Model 是模型名,原样放进请求。
	Model string `json:"model"`
	// Dimensions 是向量维度;0 表示不传,用服务的默认维度。
	Dimensions int `json:"dimensions"`
	// BatchSize 是一次请求最多带几条文本。
	BatchSize int `json:"batch_size"`
	// TimeoutSeconds 是单次请求的总超时。
	TimeoutSeconds int `json:"timeout_seconds"`
	// DailyTokenCap 是每天的 token 上限(Hub 本地日期);0 = 不限。
	DailyTokenCap int64 `json:"daily_token_cap"`
	// AllowPrivate 打开后允许 http 与回环 / 内网地址,并按环境变量走代理——用于自建服务;
	// 代价是密钥可能以明文经过链路,也失去了拨号时的地址检查。默认关。
	AllowPrivate bool `json:"allow_private"`
	// MinScore 是语义命中的相似度下限(余弦相似度,MinMinScore–MaxMinScore):低于它的命中不展示;改完立刻生效,不影响已嵌入的向量。
	// 库里没有这个字段的旧配置读出来是 DefaultMinScore(见 store 的 decode:在默认值之上解码)。
	MinScore float64 `json:"min_score"`
	// PricePerMillion 是用户按供应商官方定价自己填的单价(每百万 token 多少钱,币种见 PriceCurrency);0 = 没填,界面不估算费用。
	// 只用于界面展示估算费用:不参与每日额度、限速与外发,Hub 也不预置任何价格(价格会变,各家不同)。
	PricePerMillion float64 `json:"price_per_million"`
	// PriceCurrency 是单价的币种标记(如 ¥ / $ / CNY),只用于展示;填了单价就必须填。
	PriceCurrency string `json:"price_currency"`
}

Config 是持久化的完整配置(不含密钥,密钥在 Vault 里)。

func DefaultConfig

func DefaultConfig() Config

DefaultConfig 是从未配置过时的取值。

func (Config) Normalize

func (c Config) Normalize() Config

Normalize 只做无损整理(去空白、去末尾斜杠、数字取整到合理小数位),不改变含义。 MinScore 为 0 视为「没设」,取默认值(手写的 Config{} 与旧数据都因此仍然合法)。

func (Config) Validate

func (c Config) Validate() error

Validate 检查整张配置。错误是 ErrInvalidConfig 的包装,信息可直接展示。

type Credential

type Credential struct {
	Name      string
	Sealed    string
	Last4     string
	BoundHost string
	UpdatedAt time.Time
}

Credential 是库里保存的一份密封密钥;不含明文。

type EmbedResult

type EmbedResult struct {
	Vectors    [][]float32   // 与输入一一对应、已按 index 排好序
	Dimensions int           // 实际维度
	Tokens     int           // 服务报告的 token 数;服务没报时是保守估计
	Reported   bool          // Tokens 是否来自服务
	Model      string        // 服务回报的模型名(可能为空)
	Status     int           // HTTP 状态码
	Latency    time.Duration // 从发出请求到解析完响应
}

EmbedResult 是一次成功的 /embeddings 调用。

type ErrKind

type ErrKind string

ErrKind 是一次外呼失败的分类;界面按它给出可操作的提示,流水线按它决定重试还是停下。

const (
	KindBlocked     ErrKind = "blocked"      // 拨号检查拒绝了目标地址(内网 / 本机 / 保留段)
	KindNetwork     ErrKind = "network"      // 域名解析失败、连接被拒、连接中断
	KindTimeout     ErrKind = "timeout"      // 超时
	KindTLS         ErrKind = "tls"          // 证书校验失败
	KindAuth        ErrKind = "auth"         // 401 / 403:服务拒绝了这把 key
	KindNotFound    ErrKind = "not_found"    // 404:地址或模型不对
	KindRateLimited ErrKind = "rate_limited" // 429
	KindBadRequest  ErrKind = "bad_request"  // 400 / 422 等:请求本身有问题(维度不被支持、文本太长……)
	KindServer      ErrKind = "server"       // 5xx
	KindRedirect    ErrKind = "redirect"     // 3xx:不跟随
	KindBadResponse ErrKind = "bad_response" // 响应格式不对 / 向量不合法
	KindCanceled    ErrKind = "canceled"     // 调用方取消
)

type GuardView

type GuardView struct {
	Mode string `json:"mode"` // strict | relaxed
}

GuardView 说明出站防护当前的模式。

type KeyState

type KeyState string

KeyState 是已保存密钥的状态。

const (
	KeyNone         KeyState = "none"          // 没有保存过
	KeyOK           KeyState = "ok"            // 可用
	KeyHostMismatch KeyState = "host_mismatch" // 服务地址的主机换了,旧密钥只认原主机
	KeyUnreadable   KeyState = "unreadable"    // 主密钥文件缺失 / 无效,或密文被改动
)

type KeyView

type KeyView struct {
	State          KeyState   `json:"state"`
	HasKey         bool       `json:"has_key"`
	Last4          string     `json:"last4,omitempty"`
	BoundHost      string     `json:"bound_host,omitempty"`
	UpdatedAt      *time.Time `json:"updated_at,omitempty"`
	VaultAvailable bool       `json:"vault_available"`
	// Reason 在 unreadable 时说明原因:no_master_key | bad_master_key | cannot_open。
	Reason string `json:"reason,omitempty"`
}

KeyView 是给界面的密钥状态:永远不含明文,只有「有没有」「末四位」「绑定的主机」。

type Limits

type Limits struct {
	MinDimensions      int     `json:"min_dimensions"`
	MaxDimensions      int     `json:"max_dimensions"`
	MaxBatchSize       int     `json:"max_batch_size"`
	MinTimeoutSeconds  int     `json:"min_timeout_seconds"`
	MaxTimeoutSeconds  int     `json:"max_timeout_seconds"`
	MinDailyTokenCap   int64   `json:"min_daily_token_cap"`
	MaxDailyTokenCap   int64   `json:"max_daily_token_cap"`
	MinKeyLen          int     `json:"min_key_len"`
	MaxKeyLen          int     `json:"max_key_len"`
	MinMinScore        float64 `json:"min_min_score"`
	MaxMinScore        float64 `json:"max_min_score"`
	MaxPricePerMillion float64 `json:"max_price_per_million"`
	MaxCurrencyLen     int     `json:"max_currency_len"`
}

Limits 是各数字字段的合法范围,随 GET 一起给界面。

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits 返回当前版本的范围。

type Options

type Options struct {
	Persistence Persistence
	// DataDir 是主密钥文件所在目录;空串 = 保管库不可用(不能保存密钥)。
	DataDir   string
	UserAgent string
	// Now 与 TestInterval 供测试替换。
	Now          func() time.Time
	TestInterval time.Duration
}

Options 创建 Service 的参数。

type Persistence

type Persistence interface {
	// GetEmbeddingConfig 读配置;从未保存过返回 DefaultConfig。
	GetEmbeddingConfig(ctx context.Context) (Config, error)
	// UpdateEmbeddingConfig 在一个事务里「读—改—写」;validate 不通过就不写。
	UpdateEmbeddingConfig(ctx context.Context, mutate func(Config) Config, validate func(Config) error) (Config, error)

	GetEmbeddingCredential(ctx context.Context) (Credential, bool, error)
	PutEmbeddingCredential(ctx context.Context, c Credential) error
	DeleteEmbeddingCredential(ctx context.Context) error

	// ReserveEmbeddingTokens 原子地检查并预留今天的预算:cap > 0 且 已用 + estimate 超过 cap 时返回 false(不改动任何东西);
	// 否则 tokens += estimate、requests += 1 并返回 true。cap == 0 表示不检查(仍然记账)。
	ReserveEmbeddingTokens(ctx context.Context, day string, estimate, cap int64) (bool, error)
	// SettleEmbeddingTokens 用真实用量替换预留:tokens += actual - estimate(不低于 0);failed 时 errors += 1。
	SettleEmbeddingTokens(ctx context.Context, day string, estimate, actual int64, failed bool) error
	EmbeddingUsageDays(ctx context.Context, fromDay, toDay string) ([]UsageDay, error)
	EmbeddingUsageTotals(ctx context.Context) (UsageTotals, error)
}

Persistence 是持久化的需求,由 *store.Store 实现。

type Service

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

Service 把配置、密钥保管、外呼、用量预算拼在一起。可并发使用。

func NewService

func NewService(o Options) *Service

NewService 创建服务。它不启动任何协程,不做任何外呼。

func (*Service) ClearKey

func (s *Service) ClearKey(ctx context.Context) (View, error)

ClearKey 删除已保存的密钥。主密钥文件保留(里面没有任何用户数据,删掉没有收益)。

func (*Service) Embed

func (s *Service) Embed(ctx context.Context, inputs []string) (*EmbedResult, error)

Embed 给一批文本取向量,受每日 token 预算约束(先预留、后按真实用量结算)。供向量流水线与检索使用(2b)。 返回的错误:*CallError(外呼失败)、ErrBudgetExceeded(没有发出)、ErrKeyNotReady(没有发出)、数据库错误。

func (*Service) SetKey

func (s *Service) SetKey(ctx context.Context, raw string) (View, error)

SetKey 校验、密封并保存密钥(替换已有的)。密钥绑定到当前配置的服务主机。

func (*Service) Status

func (s *Service) Status(ctx context.Context) (View, error)

Status 返回当前配置、密钥状态与用量。

func (*Service) Test

func (s *Service) Test(ctx context.Context, draft *Update) (TestResult, error)

Test 用已保存的密钥与(草稿叠加后的)配置向服务发一句固定英文,核对地址、鉴权、模型与维度。 draft 只含非机密字段,只对这一次测试有效,不保存。测试不受每日上限拦截,但计入用量。 返回 error 的情形只有:草稿不合法(ErrInvalidConfig)、太频繁(ErrThrottled)、数据库故障;服务端的各种失败都在 TestResult 里。

func (*Service) UpdateConfig

func (s *Service) UpdateConfig(ctx context.Context, upd Update) (View, error)

UpdateConfig 保存非机密配置(部分更新)。校验不过返回 ErrInvalidConfig 的包装。

func (*Service) Usage

func (s *Service) Usage(ctx context.Context, days int) ([]UsageDay, error)

Usage 返回 [from, to](含)区间内每天的用量,没有记录的日子不出现。

type TestResult

type TestResult struct {
	OK         bool   `json:"ok"`
	Kind       string `json:"kind"` // ok | 外呼失败的分类(ErrKind)| no_key | host_mismatch | unreadable | vault_unavailable
	Message    string `json:"message"`
	Warning    string `json:"warning,omitempty"`
	HTTPStatus int    `json:"http_status,omitempty"`
	LatencyMS  int64  `json:"latency_ms,omitempty"`
	Dimensions int    `json:"dimensions,omitempty"`
	Tokens     int    `json:"tokens,omitempty"`
	Model      string `json:"model,omitempty"`
	Host       string `json:"host,omitempty"`
}

TestResult 是「测试连接」的结果;不论成败都不含密钥。

type Update

type Update struct {
	BaseURL         *string  `json:"base_url"`
	Model           *string  `json:"model"`
	Dimensions      *int     `json:"dimensions"`
	BatchSize       *int     `json:"batch_size"`
	TimeoutSeconds  *int     `json:"timeout_seconds"`
	DailyTokenCap   *int64   `json:"daily_token_cap"`
	AllowPrivate    *bool    `json:"allow_private"`
	MinScore        *float64 `json:"min_score"`
	PricePerMillion *float64 `json:"price_per_million"`
	PriceCurrency   *string  `json:"price_currency"`
}

Update 是部分更新:没给的字段保持原值。

func (Update) ApplyTo

func (u Update) ApplyTo(cur Config) Config

ApplyTo 把更新叠加在 cur 上,返回已整理的新配置(不校验)。

type UsageDay

type UsageDay struct {
	Day      string `json:"day"`
	Requests int64  `json:"requests"`
	Tokens   int64  `json:"tokens"`
	Errors   int64  `json:"errors"`
}

UsageDay 是一天的用量(按 Hub 本地日期)。次数包含失败的尝试。

type UsageTotals

type UsageTotals struct {
	Requests int64 `json:"requests"`
	Tokens   int64 `json:"tokens"`
	Errors   int64 `json:"errors"`
}

UsageTotals 是全部历史(保留期内)的累计。

type UsageView

type UsageView struct {
	Day       string      `json:"day"`
	Today     UsageDay    `json:"today"`
	Cap       int64       `json:"cap"`
	Remaining *int64      `json:"remaining"` // nil = 不限
	Totals    UsageTotals `json:"totals"`
}

UsageView 是用量概况。

type Vault

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

Vault 管理主密钥文件并密封 / 解封 API Key。零值不可用,用 NewVault 创建;可并发使用。

func NewVault

func NewVault(dir string) *Vault

NewVault 创建保管库;dir 是主密钥文件所在目录(通常是数据库所在目录),空串表示不可用。

func (*Vault) Available

func (v *Vault) Available() bool

Available 报告是否有可用的数据目录。

func (*Vault) Open

func (v *Vault) Open(sealed, boundHost string) (string, error)

Open 解开 Seal 的输出。主密钥文件不存在返回 ErrNoMasterKey(不会创建);密文被篡改、主密钥不对、 主机不一致都返回 secure.ErrSealOpen(故意不区分原因)。

func (*Vault) Seal

func (v *Vault) Seal(plain, boundHost string) (string, error)

Seal 把密钥密封,绑定到 boundHost。主密钥文件不存在时在这里创建(0600,O_EXCL)。

type View

type View struct {
	Config   Config    `json:"config"`
	Key      KeyView   `json:"key"`
	Usage    UsageView `json:"usage"`
	Defaults Config    `json:"defaults"`
	Limits   Limits    `json:"limits"`
	Guard    GuardView `json:"guard"`
}

View 是 GET 的完整响应。

Jump to

Keyboard shortcuts

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