How-to逐行搜索

你手上是 GitHub 的服务条款和一个关于它的自然语言问题。你需要找到回答该问题的那些行,也需要一种检测“文档没有答案”的办法。附带的查询会把带有直接答案的行排在前面,exists 阈值把其余情况归类为“缺失”或“部分”。最终你将得到 find(),它返回 exists 概率以及每行一个相关性分数。

A query scans a document and reveals an answer attached to the matching
line

检索后端由三部分组成:

  1. 给每一行打上一个 ID,让 TypeSafe 能够指向它。
  2. 用一个 Choice 问题按这些行 ID 对查询的回答程度排序。Choice 问题的概率总和恒为 1,因此即使没有任何一行回答该查询,也总有一行排名第一。
  3. 在同一请求中,用一个 Noul 问题检查文档究竟是否包含答案。

准备工作

获取 TypeSafe API 密钥

在 TypeSafe 控制台中创建一个密钥并导出:

bash
export TYPESAFE_API_KEY="your-key-here"

安装依赖

bash
pip install "typesafe-sdk>=0.5.7" cooksafe \
  --extra-index-url https://pypi.typesafe.ai/

JsonCache 会重放随文附带的 API 响应,因此下面的步骤无需 API 密钥、也不会产生任何花费。若想让请求改为实时发出,请设置 TYPESAFE_API_KEY 并删除 json_cache.json。

创建脚本

从导入和客户端开始编写 semantic_search.py:

python
import os
import urllib.request
from pathlib import Path

from cooksafe import JsonCache
from typesafe_sdk import Choice, Noul, NoulCriteria, TypeSafeClient

TYPESAFE_MODEL = "jev-1.12"

client = TypeSafeClient(
    api_key=os.environ.get("TYPESAFE_API_KEY", "cache-only"), timeout=120.0
)
json_cache = JsonCache(Path("json_cache.json"))

第 1 步:给每一行打上 ID

测试文档是 GitHub 的服务条款,被拆分为 218 个条款,因此每个搜索结果都指向一条可引用的行。

向 semantic_search.py 添加:

python
GIST = (
    "https://gist.githubusercontent.com/eugene-shvarts/900632789a24983d5678ffd508dd01f6"
    "/raw/cf9c2ab422d568deade949ef0a06bed6896964b9/github-tos.txt"
)


@json_cache
def fetch_document(url: str) -> str:
    request = urllib.request.Request(
        url, headers={"User-Agent": "typesafe-cookbook/1.0"}
    )
    with urllib.request.urlopen(request) as response:
        return response.read().decode()


LINES = fetch_document(GIST).splitlines()

缓存避免了重复下载,splitlines() 会留下一个包含 218 个字符串的列表。

现在给每一行加上一个短 ID 前缀,再把这些行重新连接成一份文档。模型就用这些 ID 来指向它的答案。

python
def line_id(i: int) -> str:
    return f"L{i:03d}"


DOCUMENT = "\n".join(f"{line_id(i)}| {line}" for i, line in enumerate(LINES))

DOCUMENT 现在看起来是这样:

L052| You own Your Content. If you post Content you did not create, you are responsible for...
L053| You grant us and other Users the licenses in Sections D.4–D.8. These licenses apply...
L054| 4. License Grant to Us

第 2 步:询问答案在哪里

Choice 问题为每个选项返回一个概率。把行 ID 用作选项,“选择一个选项”就变成了“指向某一行”。

python
def where_question(query: str) -> Choice:
    return Choice(
        instructions=f'Which line of the document contains the answer to: "{query}"?',
        criteria={line_id(i): None for i in range(len(LINES))},
    )

选项描述为 None,因为文档本身已经包含每个 ID 对应的文本。查询放在 instructions 中;状态在多次搜索之间保持不变。

一个 Choice 问题最多接受 255 个选项,因此本方案单次请求可搜索最多 255 行的文档。超过这个规模,就分两遍搜索:先用一个 Choice 问题选出一个行窗口,再用第二个问题对窗口内的行排序。

第 3 步:检查答案是否存在

Choice 概率的总和恒为 1,因此即使文档没有回答问题,也总有某一行排名第一。仅凭排序无法区分真正的答案和最接近的无关行。

所以在同一请求中再问第二个问题:

python
def exists_question(query: str) -> Noul:
    return Noul(
        instructions=f'Does any line of the document address or answer: "{query}"?',
        criteria=NoulCriteria(
            true="At least one line of the document states or directly implies the answer",
            false="No line of the document addresses this",
        ),
    )

与 Choice 概率不同,Noul 概率不依赖于其他选项,因此当文档没有答案时,它可以降到接近零。

第 4 步:在一次请求中发送两个问题

system_one 方法一次运行即可回答两个问题。状态只发送一次,因此添加存在性检查只需要少量额外输出。

A tagged document and user question enter one TypeSafe request. A Choice question scores
every line while a Noul question checks whether an answer exists. Local code then ranks the
lines and applies the document verdict.
python
@json_cache
def _find(
    model: str,
    state: str,
    where: Choice,
    exists: Noul,
) -> dict:
    response = client.system_one(
        state=state,
        questions={"where": where, "exists": exists},
        model=model,
    )
    probabilities = response.answers["where"].probabilities
    return {
        "exists": response.answers["exists"].noul,
        "relevance": [probabilities.get(line_id(i), 0.0) for i in range(len(LINES))],
    }


def find(query: str) -> dict:
    return _find(
        TYPESAFE_MODEL,
        DOCUMENT,
        where_question(query),
        exists_question(query),
    )

relevance 列表按文档顺序为每一行保留一个分数。

第 5 步:读取结果

两段本地代码完成收尾:verdict() 把原始的 exists 概率转换为三种状态,中间那种对应部分回答;show() 把 relevance 渲染成条形图,让排序结果在终端里可读。

python
FOUND, ABSENT = 0.7, 0.35  # present answers typically read >=0.9, absent <=0.05


def verdict(exists: float) -> str:
    if exists >= FOUND:
        return "answered in this document"
    return "not in this document" if exists < ABSENT else "partially addressed"


def show(query: str, top: int = 4) -> dict:
    result = find(query)
    print(f'"{query}"')
    print(f"  exists {result['exists']:.2f} -> {verdict(result['exists'])}")
    ranked = sorted(
        range(len(LINES)), key=lambda i: result["relevance"][i], reverse=True
    )
    for i in ranked[:top]:
        bar = "#" * max(1, round(result["relevance"][i] * 12))
        preview = LINES[i][:58].rstrip()
        print(f"  {line_id(i)}  {result['relevance'][i]:.2f}  {bar:<12}  {preview}")
    return result

这些阈值可以区分下面这些示例,但在生产环境使用之前,请针对你自己的文档加以调校。

第 6 步:运行搜索

提问四个问题:两个有直接答案、一个没有答案、一个是部分回答。

python
print(f"{len(LINES)} lines, {len(DOCUMENT):,} characters\n")
show("who owns the code I upload?")
print()
show("can GitHub kick me off the platform without warning?")
print()
show("do I have to take disputes to arbitration?", top=2)
print()
show("can minors use GitHub with parental permission?", top=2)
218 lines, 43,980 characters

"who owns the code I upload?"
  exists 0.98 -> answered in this document
  L052  0.95  ###########   You own Your Content. If you post Content you did not crea
  L046  0.02  #             Short version: You own content you create, but you allow u
  L051  0.02  #             3. Ownership and License Grants
  L217  0.01  #             Questions about the Terms of Service? Contact us through t

"can GitHub kick me off the platform without warning?"
  exists 0.97 -> answered in this document
  L168  0.97  ############  GitHub has the right to suspend or terminate your access t
  L167  0.03  #             3. GitHub May Terminate
  L000  0.00  #             Effective date: April 27, 2026 · A. Definitions
  L001  0.00  #             Short version: We use these basic terms throughout the agr

"do I have to take disputes to arbitration?"
  exists 0.14 -> not in this document
  L205  0.86  ##########    Except to the extent applicable law provides otherwise, th
  L168  0.02  #             GitHub has the right to suspend or terminate your access t

"can minors use GitHub with parental permission?"
  exists 0.46 -> partially addressed
  L029  0.90  ###########   You must be age 13 or older. While we are thrilled to see
  L012  0.07  #             “User,” “You,” and “Your” refer to the individual person,

这些分数意味着什么

前两个查询返回直接答案,以及验证答案所需的源行。

另外两个查询则说明存在性检查为什么重要:

  • 仲裁:排序给最接近的行打出 0.86 的分数,但 exists 只有 0.14。答案不在文档中。
  • 家长许可:年龄规则排名第一,但它没有回答家长许可是否会改变这条规则。结果是部分涵盖。

排序告诉你该去哪里找;exists 分数告诉你结果是否回答了问题。

在你自己的文档上试试

在 TypeSafe Playground 中打开打好标签的合同,在同一段文本上编辑这些问题。要搜索你自己的文档,请更换 fetch_document() 中的 URL;脚本其余的每一行都基于 LINES 工作。