zleap-sag2
中文
SAG2 原文检索引擎:统一词法召回、多轮 JEV 证据评分和本地多样性排序。
支持 SQLite、MySQL、PostgreSQL 和 OceanBase。连接已有 SAG1 库时,自动从
source_chunk 读取现有段落;空库使用 SAG2 自有存储。
0.2.0.post1 补齐 PyPI 页面使用的中英双语说明,功能与 0.2.0 相同。
0.2.0:减少 JEV 输入 token
JEV 默认使用 stateful 请求格式,在同一批请求内共享候选上下文,减少重复输入。
MuSiQue、HotpotQA、2WikiMultihopQA 各前 1,000 题的在线对照中,服务端返回的
JEV 输入 token 分别减少 19.14%、18.65%、18.32%,合计减少 18.70%。
实验使用 302ai 的 typesafe/jev-1.13,收益取决于模型、服务商和候选内容;
本次未观察到稳定提速,检索召回率有小幅波动。
兼容或排障时仍可设置 DECISION_PAYLOAD_STYLE=inline。完整口径和结果见
实验说明,
版本变更见 CHANGELOG。
安装
可按包名从 PyPI 安装:
pip install zleap-sag2
# MySQL / OceanBase
pip install 'zleap-sag2[mysql]'
# PostgreSQL
pip install 'zleap-sag2[postgres]'
# 电子表格转换
pip install 'zleap-sag2[tables]'
从源码安装时,先进入包含本文件和 pyproject.toml 的包目录,再执行
pip install .;可选依赖使用 pip install '.[tables]' 等形式。
也可通过 pip install 指定已下载 wheel 文件的实际路径。
独立开发
可以直接在 IDE 或 Codex 中打开包目录:仓库中的 packages/sag2,或解压后的
源码包根目录。以下命令均在该目录执行。源码、测试、脚本、文档和环境变量模板
均在本目录内;使用仓库检出时,Git 提交仍属于 zleap 根仓库。
make install # 本目录 .venv,只安装 SAG2 和开发/表格依赖
make verify # lint、离线测试、构建、产物元数据检查
cp .env.example .env # 需要连接模型服务时再填写
也可在根目录运行 make -C packages/sag2 verify。根目录的 make verify 仍检查 SAG。
本包独立版本为 src/zleap/sag2/__about__.py,发布 tag 为 zleap-sag2/vX.Y.Z;
发布配置见仓库的 RELEASING.md。zleap 元包暂不依赖 SAG2,
使用者需单独安装 zleap-sag2。
import asyncio
from zleap.sag2 import DataEngine, EngineConfig
from zleap.sag2 import TextSource, SourceDescriptor, SearchScope, SearchRequest
async def main():
config = EngineConfig.from_env(".env")
async with DataEngine(config, data_source_id="demo") as engine:
await engine.ingest(
TextSource(
text="# 示例\nAlice 出生在北京。",
descriptor=SourceDescriptor(
data_source_id="demo",
source_id="alice",
source_type="text",
),
)
)
result = await engine.search(
SearchRequest(query="Alice 出生在哪里?", scope=SearchScope(data_source_ids=("demo",)))
)
for hit in result.chunks:
print(hit.score, hit.content)
asyncio.run(main())
parse 和 chunk 可在启动数据库前使用。index(ChunkSet) 直接保存已有分块。
配置
关系库环境变量与 SAG1 一致,使用 EngineConfig.from_env(".env") 显式读取文件;
EngineConfig.from_env() 只读取进程环境,不自动寻找 .env。最小配置:
SAG_RELATIONAL_PROVIDER=sqlite
SAG_DATA_DIR=./.zleap
DECISION_ENDPOINT=https://api.typesafe.ai/v1/systemone
DECISION_MODEL=jev-latest
DECISION_API_KEY=your-key
推荐使用 JEV(TypeSafe) 或
D1-ultra(Liquid AI) 作为决策模型。
使用 D1-ultra 时,将接口改为 https://api.liquid.ai/decisions/v1/systemone、
模型改为 d1-ultra,并填写 Liquid AI 的 API Key。使用其他服务商时,
模型 ID 与接口地址以该服务商为准,三项配置需对应同一服务。
决策请求的 token 预算使用随包提供的 o200k_base 编码资源;首次启动无需下载
tokenizer 或预置缓存。实际用量仍取决策服务返回的 usage。
SQLite 使用 <SAG_DATA_DIR>/sag.db,默认 .zleap/sag.db。服务库使用
SAG_RELATIONAL_HOST / PORT / USER / PASSWORD / DATABASE,连接池、超时及
PostgreSQL TLS 参数同样沿用 SAG_RELATIONAL_*。默认端口为 MySQL 3306、
PostgreSQL 5432、OceanBase 2881。
RELATIONAL_PROVIDER、DATA_DIR、DB_HOST / DB_PORT / DB_USER /
DB_PASSWORD / DB_NAME、DB_POOL_* / DB_MAX_OVERFLOW / DB_CONNECT_TIMEOUT /
DB_COMMAND_TIMEOUT、DB_TLS_* 也与 SAG1 一致。同名进程变量覆盖文件值;
同时设置等价名称时,SAG_* 优先,空值视为未设置。
SAG1 的配置文件可以直接复用,SAG2 不使用其中的 LLM、Embedding、向量库和
事件配置;搜索需补充 DECISION_*。未配置任何决策模型参数时仍可解析、切块、读取与续页,
部分配置决策模型参数会在加载时明确报错。也可以直接构造 EngineConfig 和
RelationalConfig,显式配置不读取环境变量。
直接搜索 SAG1 已有数据
用 EngineConfig.from_env(".env") 读取 SAG1 的连接配置,补充决策模型配置后直接调用
search() 或 search_page(),无需先调用 index()。
引擎启动时识别 source_chunk,沿用原段落 ID,读取 article / chat_conversation
补充来源信息,并遵守活动 generation、来源删除和数据源停用状态。normal / lite
的文本关系表均可读取,不需要安装 zleap-sag 或访问原向量库、事件表。
此模式支持搜索、分页、read_chunk()、read_outline() 和 source_state()。
原 SAG1 业务表保持只读,写入、删除和持久处理任务继续由 SAG1 管理;这些调用
在 SAG2 中会明确报 sag.read_only_storage,capabilities() 返回实际可用能力。
启动只补建 sag2_state / sag2_search_sessions 两张辅助表,需要相应建表权限;
翻页仍会写会话状态,SAG1/SAG2 的分页结果不会混用。
SAG1 的后续写入会使缓存刷新、旧游标过期,包括没有更新 manifest 的普通
index() 写入。为此,当前每次读取与游标校验都会扫描请求数据源的段落并计算
可见文本指纹,成本随范围内数据量增长。不提供旧 SAG2 数据向 SAG1 的迁移。
会话和录音转写支持按完整单元重叠切块。对 parse() 返回的会话或录音结果使用:
from zleap.sag2 import ChunkOptions
chunk_set = await engine.chunk(
parsed,
ChunkOptions(strategy="overlap", max_tokens=800, overlap_tokens=100),
)
下一块会尽可能携带上一块末尾连续的完整消息或转写单元。重叠部分的 token 数
不超过 overlap_tokens,同时为新单元预留 max_tokens 内的空间;计算包含说话人
标签和换行。单元放不下时减少或取消重叠,不截断消息。单条超长单元仍完整保留,
因此可能单独超过 max_tokens。重叠单元保留原始文本、引用及时间范围。
overlap_tokens 默认是 0,表示不重叠;会话默认的时间窗口和录音默认的 token
窗口不受影响。
SearchOptions 配置 SAG2 候选数、扩展词数、追加轮数和输出数量;默认 100/20/2/10。
搜索失败会抛出异常,JEV 可重试错误最多尝试四次。
分页搜索沿用 zleap-sag 的调用方式:
from zleap.sag2 import SearchPageRequest
# request 是包含 query、scope、options 的 SearchRequest。
page = await engine.search_page(SearchPageRequest(request=request, page_size=20))
for hit in page.result.chunks:
print(hit.score, hit.content)
if page.next_cursor is not None:
page = await engine.search_page(
SearchPageRequest(cursor=page.next_cursor, cursor_request=request)
)
首次执行 SAG2 并持久化结果,后续翻页不再调用 JEV,可跨进程与重启使用。
总数受搜索的 top_k 限制;默认每页 50 项、有效期 300 秒。
问题或范围不匹配、游标篡改会报 CursorInvalidError;到期或相关数据源变更会报
CursorExpiredError,调用方应重新搜索。过期会话通过 maintain() 有界清理。
指定数据库时,向 EngineConfig(relational=RelationalConfig(...)) 传入提供方与
对应的异步连接地址。sqlite 使用 sqlite+aiosqlite:///...,mysql 与
oceanbase 使用 mysql+aiomysql://...,postgres 使用
postgresql+asyncpg://...;凭据由应用配置提供。
详细说明见仓库中的架构文档、
开发与验证和
接口兼容说明。
这些文档也包含在源码包的 docs/ 目录中。
JEV 默认使用 stateful 请求格式共享批内候选上下文。兼容或排障时可设置
DECISION_PAYLOAD_STYLE=inline,或显式传入 JevConfig(payload_style="inline", ...)。
English
SAG2 is a passage retrieval engine that combines lexical retrieval, multiple rounds
of JEV evidence scoring, and local diversity ranking. It supports SQLite, MySQL,
PostgreSQL, and OceanBase. When connected to an existing SAG1 database, it reads
passages from source_chunk; empty databases use SAG2's own storage.
0.2.0.post1 adds the complete Chinese and English description used by PyPI.
Its functionality is the same as 0.2.0.
0.2.0: reduced JEV input tokens
JEV uses the stateful payload format by default, sharing candidate context within
each request batch to reduce repeated input. Online comparisons on the first
1,000 questions from each of MuSiQue, HotpotQA, and 2WikiMultihopQA reduced
server-reported JEV input tokens by 19.14%, 18.65%, and 18.32%, respectively,
or 18.70% combined. The experiment used typesafe/jev-1.13 via 302ai.
Savings depend on the model, provider, and candidate content. The experiment did
not demonstrate a consistent speedup, and retrieval recall varied slightly.
Set DECISION_PAYLOAD_STYLE=inline for compatibility or troubleshooting. See the
experiment report
for the methodology and results, and the
CHANGELOG
for release notes.
Installation
Install the package from PyPI:
pip install zleap-sag2
# MySQL / OceanBase
pip install 'zleap-sag2[mysql]'
# PostgreSQL
pip install 'zleap-sag2[postgres]'
# Spreadsheet conversion
pip install 'zleap-sag2[tables]'
To install from source, enter the package directory containing this file and
pyproject.toml, then run pip install .. Use pip install '.[tables]' to include
optional dependencies. You can also pass a downloaded wheel's path to pip install.
Independent development
Open packages/sag2 in the repository, or the root of an extracted source
distribution, directly in your IDE or Codex. Run the following commands in that
directory. Source code, tests, scripts, documentation, and the environment template
are all contained there. In a repository checkout, commits belong to the root
zleap repository.
make install # Local .venv with SAG2, development and table dependencies
make verify # Lint, offline tests, build and artifact metadata checks
cp .env.example .env # Fill in credentials when connecting to a model service
You can also run make -C packages/sag2 verify from the repository root. The root
make verify checks SAG. SAG2 maintains its own version in
src/zleap/sag2/__about__.py and uses release tags named zleap-sag2/vX.Y.Z.
See RELEASING.md for the
release configuration. The zleap umbrella package does not currently depend on
SAG2; install zleap-sag2 separately.
import asyncio
from zleap.sag2 import DataEngine, EngineConfig
from zleap.sag2 import TextSource, SourceDescriptor, SearchScope, SearchRequest
async def main():
config = EngineConfig.from_env(".env")
async with DataEngine(config, data_source_id="demo") as engine:
await engine.ingest(
TextSource(
text="# Example\nAlice was born in Beijing.",
descriptor=SourceDescriptor(
data_source_id="demo",
source_id="alice",
source_type="text",
),
)
)
result = await engine.search(
SearchRequest(
query="Where was Alice born?", scope=SearchScope(data_source_ids=("demo",))
)
)
for hit in result.chunks:
print(hit.score, hit.content)
asyncio.run(main())
parse and chunk can be used before starting the database. Use index(ChunkSet)
to store chunks that have already been prepared.
Configuration
Relational database environment variables are compatible with SAG1. Use
EngineConfig.from_env(".env") to explicitly load a file; EngineConfig.from_env()
reads only the process environment and does not search for .env. Minimal settings:
SAG_RELATIONAL_PROVIDER=sqlite
SAG_DATA_DIR=./.zleap
DECISION_ENDPOINT=https://api.typesafe.ai/v1/systemone
DECISION_MODEL=jev-latest
DECISION_API_KEY=your-key
JEV (TypeSafe) and
D1-ultra (Liquid AI) are recommended decision
models. For D1-ultra, set the endpoint to https://api.liquid.ai/decisions/v1/systemone,
the model to d1-ultra, and use your Liquid AI API key. For other providers, use
their documented model ID and endpoint. The endpoint, model, and key must all
refer to the same service.
Decision request token budgets use the bundled o200k_base encoding resource.
The first startup does not require a tokenizer download or a prepopulated cache.
Actual usage comes from the decision service's returned usage.
SQLite uses <SAG_DATA_DIR>/sag.db, defaulting to .zleap/sag.db. Server databases
use SAG_RELATIONAL_HOST, PORT, USER, PASSWORD, and DATABASE.
Connection pool, timeout, and PostgreSQL TLS settings also use SAG_RELATIONAL_*.
Default ports are 3306 for MySQL, 5432 for PostgreSQL, and 2881 for OceanBase.
The aliases RELATIONAL_PROVIDER, DATA_DIR, DB_HOST, DB_PORT, DB_USER,
DB_PASSWORD, DB_NAME, DB_POOL_*, DB_MAX_OVERFLOW, DB_CONNECT_TIMEOUT,
DB_COMMAND_TIMEOUT, and DB_TLS_* are compatible with SAG1 as well. A process
variable overrides the same name in the file. When equivalent names are both set,
SAG_* takes precedence; empty values are treated as unset.
You can reuse a SAG1 configuration file. SAG2 does not use its LLM, embedding,
vector database, or event settings; add DECISION_* settings for search. Without
any decision model configuration, parsing, chunking, reading, and pagination remain
available. Partial decision model configuration raises an explicit error during
configuration loading. You can also construct EngineConfig and
RelationalConfig directly; explicit configuration does not read environment variables.
Searching existing SAG1 data
Load SAG1 connection settings with EngineConfig.from_env(".env"), add decision
model settings, and call search() or search_page() directly without first
calling index(). On startup, the engine detects source_chunk, preserves the
existing passage IDs, and reads article and chat_conversation for source
metadata. It respects active generations, deleted sources, and disabled data
sources. Both normal and lite relational text tables are supported, without
installing zleap-sag or accessing the original vector database or event tables.
This mode supports search, pagination, read_chunk(), read_outline(), and
source_state(). Existing SAG1 business tables are read-only. SAG1 continues to
manage writes, deletion, and durable processing tasks; these operations raise
sag.read_only_storage in SAG2, and capabilities() reports the available
operations. Startup creates only the auxiliary sag2_state and
sag2_search_sessions tables, requiring the corresponding table-creation
permissions. Pagination writes session state; SAG1 and SAG2 pagination results
are not interchangeable.
Subsequent SAG1 writes refresh caches and expire old cursors, including ordinary
index() writes that do not update a manifest. To support this, every read and
cursor validation currently scans passages within the requested data sources and
computes a fingerprint of the visible text. This cost grows with the data in
scope. Migration from old SAG2 data to SAG1 is not provided.
Conversations and recording transcripts support chunk overlap using complete
units. For conversation or transcript output returned by parse(), use:
from zleap.sag2 import ChunkOptions
chunk_set = await engine.chunk(
parsed,
ChunkOptions(strategy="overlap", max_tokens=800, overlap_tokens=100),
)
Each new chunk carries as many consecutive, complete trailing messages or
transcript units from the previous chunk as fit. Overlap does not exceed
overlap_tokens and leaves room for a new unit within max_tokens; counting
includes speaker labels and newlines. If a unit does not fit, overlap is reduced
or omitted rather than truncating the message. A single oversized unit remains
intact and may exceed max_tokens. Overlapping units preserve the original text,
references, and time ranges. overlap_tokens defaults to 0, meaning no overlap.
The default conversation time window and recording token window are unaffected.
SearchOptions controls candidate count, expansion terms, additional rounds, and
output count, with defaults of 100/20/2/10. Search failures raise exceptions;
retryable JEV errors allow at most four attempts.
Paginated search follows the zleap-sag calling pattern:
from zleap.sag2 import SearchPageRequest
# request is a SearchRequest containing query, scope, and options.
page = await engine.search_page(SearchPageRequest(request=request, page_size=20))
for hit in page.result.chunks:
print(hit.score, hit.content)
if page.next_cursor is not None:
page = await engine.search_page(
SearchPageRequest(cursor=page.next_cursor, cursor_request=request)
)
The first call runs SAG2 and persists the results. Later pages do not call JEV
again and work across processes and restarts. The total result count is limited
by search top_k; the default page size is 50 and sessions expire after 300
seconds. A mismatched question or scope, or a tampered cursor, raises
CursorInvalidError. Expiration or changes to the relevant data sources raise
CursorExpiredError, requiring a new search. maintain() cleans up expired
sessions in bounded batches.
To specify a database explicitly, pass its provider and asynchronous connection
URL to EngineConfig(relational=RelationalConfig(...)). SQLite uses
sqlite+aiosqlite:///...; MySQL and OceanBase use mysql+aiomysql://...;
PostgreSQL uses postgresql+asyncpg://.... Supply credentials through your
application configuration.
Further details are available in the repository's
architecture,
development and validation,
and API compatibility
documents. These are also included in the source distribution's docs/ directory.
JEV defaults to the stateful payload format to share candidate context within
each batch. For compatibility or troubleshooting, set
DECISION_PAYLOAD_STYLE=inline or pass JevConfig(payload_style="inline", ...).
Metadata
Release files for zleap-sag2 0.2.0.post1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| zleap_sag2-0.2.0.post1.tar.gz | 4.0 MB | With provenance | Details for zleap_sag2-0.2.0.post1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| zleap_sag2-0.2.0.post1-py3-none-any.whl | Python 3 | none | any | Details for zleap_sag2-0.2.0.post1-py3-none-any.whl |
Total release size: 7.9 MB
Release files / zleap_sag2-0.2.0.post1.tar.gz
| Download URL | zleap_sag2-0.2.0.post1.tar.gz |
|---|---|
| Size | 4.0 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c8633f0c580eafd4045204a30d44eec7be6e55eb9f872acbe245880ce7299531
|
|
BLAKE2b-256 checksum How to use checksums |
dfc25562c2bbf89ea4532ac9c713a7fa370e434ad4e76d2e5e023115e3777666
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.
Transparency logRelease files / zleap_sag2-0.2.0.post1-py3-none-any.whl
| Download URL | zleap_sag2-0.2.0.post1-py3-none-any.whl |
|---|---|
| Size | 4.0 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6e65b819d44e32158acbdfbb5b5143e1c009a6bc8f373b64891e0df3be599a7e
|
|
BLAKE2b-256 checksum How to use checksums |
6022d99a2ba4dd5fac1e91e65a77509548a7fed765917980ede83d9927271914
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.
Transparency logSecurity for zleap-sag2 0.2.0.post1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for zleap_sag2-0.2.0.post1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.