TS TypeSafe 文档中文版 原文 ↗

并行问题

在 GDPR 维基百科文章上运行一份包含 13 个问题的监管简报,展示把每个问题批量合并进一次 TypeSafe 调用后便宜 12.2 倍、快 10.0 倍,而答案没有任何变化。

你有一份文档,以及关于它的 N 个问题。你可以用一条请求发送全部 N 个问题,也可以用 N 条请求各发送一个问题。在 TypeSafe 中,两种方式得到的答案完全相同:每个问题都独立地 针对文档评分,因此它的答案不取决于请求里还有别的什么内容。

为了验证这一点,本实践手册用两种方式把每个问题各问若干次——全部 N 个问题放在一条请求 里,以及每条请求只放一个问题——并比较逐次运行之间的标准差:即答案从一次重复到下一次 重复移动了多远。一个问题无论带有什么噪声,在两种批处理策略下都带有同样的噪声。批处理 本身不增加噪声。多数答案在两种方式下、全部 5 次重复中都完全一致,每次调用都返回同一个 值,标准差恰好为 0.0。

成本与速度确实会变。文档在每条请求中都占主导。N 次单问题调用要为它付 N 次费用,经历 N 个往返;批量调用只付一次。文档越大,这种节省就越接近完整的 N 倍。

这里的场景是一份监管简报。文档是维基百科上关于 GDPR 的文章(~54,000 个字符,属于 文档主导型工作负载,文档占了每条请求的大部分),一个合规团队想核查 13 件事:8 个 Noul 问题、2 个 Choice 问题和 3 个 Score 问题。

环境准备

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

然后设置 TYPESAFE_API_KEY。

python
import json
import os
import urllib.request
from pathlib import Path
from statistics import mean, stdev
from time import perf_counter
 
from cooksafe import JsonCache, make_playground_link
from IPython.display import Markdown, display
from typesafe_sdk import Choice, ChoiceAnswer, Noul, NoulAnswer, Score, TypeSafeClient
 
TYPESAFE_MODEL = "jev-1.12"
PRICE = (
    0.042,
    0.00,
)  # $ per 1M tokens (input, output); TypeSafe jev-1.12 as of 2026-09, see README
RUNS = 5  # repeats per batching strategy, to estimate each answer's run-to-run std dev
client = TypeSafeClient(api_key=os.environ["TYPESAFE_API_KEY"], timeout=120.0)
json_cache = JsonCache(Path("json_cache.json"))
 

文档:维基百科上关于 GDPR 的文章

以纯文本形式从文章的某个固定修订版本抓取,并连同 API 调用一起缓存到旁边的 json_cache.json 中,因此即使线上文章被编辑,文档及其数字也保持不变。

python
WIKIPEDIA_REVISION = 1363040264  # "General Data Protection Regulation", as of 2026-07
 
 
@json_cache
def fetch_article(revision_id: int) -> str:
    url = (
        "https://en.wikipedia.org/w/api.php?action=query&format=json"
        f"&prop=extracts&explaintext=1&revids={revision_id}"
    )
    request = urllib.request.Request(
        url, headers={"User-Agent": "typesafe-cookbook/1.0"}
    )
    with urllib.request.urlopen(request) as response:
        pages = json.loads(response.read())["query"]["pages"]
    return next(iter(pages.values()))["extract"]
 
 
DOCUMENT = {
    "source": f"https://en.wikipedia.org/?oldid={WIKIPEDIA_REVISION}",
    "text": fetch_article(WIKIPEDIA_REVISION),
}
print(f"{len(DOCUMENT['text']):,} characters")
display(Markdown(f"📄 [Read the pinned Wikipedia revision]({DOCUMENT['source']})"))
 
text
53,777 characters
 

📄 阅读该固定修订版的维基百科页面

问题:8 个 noul + 2 个 choice + 3 个 score

每个答案按类型跟踪一个数字:

  • Noul:为「是」的概率。
  • Choice:最大概率,即被选中标签上的概率。criteria 把每个标签映射到它的含义。
  • Score:归一化到 0-1 的分数,即分数除以最高等级。 criteria 从等级 0 开始向上列出各等级的描述。
python
QUESTIONS = {
    "breach_72h": Noul(
        instructions="Must a personal data breach be reported to the supervisory authority within 72 hours?"
    ),
    "applies_non_eu": Noul(
        instructions="Does the regulation apply to organisations established outside the EU that offer goods or services to people in the EU?"
    ),
    "dpo_all_orgs": Noul(
        instructions="Must every organisation appoint a Data Protection Officer, regardless of what data it processes?"
    ),
    "pre_ticked_consent": Noul(
        instructions="Can valid consent be obtained through pre-ticked boxes or inactivity?"
    ),
    "right_erasure": Noul(
        instructions="Does the regulation grant individuals a right to erasure of their personal data?"
    ),
    "data_portability": Noul(
        instructions="Does the regulation include a right to data portability?"
    ),
    "us_federal_law": Noul(instructions="Is the GDPR a United States federal law?"),
    "criminal_penalties": Noul(
        instructions="Does the GDPR itself impose criminal penalties such as imprisonment?"
    ),
    "instrument_type": Choice(
        instructions="What kind of EU legal instrument is the GDPR?",
        criteria={
            "Regulation": "Directly binding law in all member states, no national implementation needed.",
            "Directive": "Sets goals that member states implement through national law.",
            "Treaty": "An international treaty between states.",
            "Recommendation": "Non-binding guidance.",
        },
    ),
    "max_fine": Choice(
        instructions="What is the maximum administrative fine for the most serious infringements?",
        criteria={
            "TwentyM_or_4pct": "Up to EUR 20 million or 4% of annual worldwide turnover, whichever is greater.",
            "TenM_or_2pct": "Up to EUR 10 million or 2% of annual worldwide turnover, whichever is greater.",
            "FixedCap": "A fixed amount not tied to turnover.",
            "NoFines": "The GDPR provides no administrative fines.",
        },
    ),
    "individual_rights": Score(
        instructions="How strong are the rights the GDPR grants to individuals over their data?",
        criteria=[
            "None: individuals get no rights over their data.",
            "Weak: a right to be informed, but little control.",
            "Moderate: access and correction rights, but limited means to act on them.",
            "Strong: access, erasure, portability, and objection rights, with enforcement behind them.",
        ],
    ),
    "penalty_severity": Score(
        instructions="How severe are the penalties the GDPR provides for non-compliance?",
        criteria=[
            "None: no penalties of any kind.",
            "Symbolic: small fixed fines unlikely to change behavior.",
            "Substantial: fines large enough to matter to most companies.",
            "Severe: fines scaled to global revenue, material even to the largest companies.",
        ],
    ),
    "compliance_burden": Score(
        instructions="How heavy is the compliance burden the GDPR places on organisations?",
        criteria=[
            "Negligible: no meaningful obligations.",
            "Light: a few notices and disclosures.",
            "Moderate: documented processes and some dedicated roles for larger processors.",
            "Heavy: records, impact assessments, officers, and breach procedures for many organisations.",
            "Extreme: obligations so demanding that ordinary organisations cannot fully comply.",
        ],
    ),
}
N = len(QUESTIONS)
METRIC = {  # question type -> the one number we track per answer
    Noul: "p(yes)",
    Choice: "max prob",
    Score: "normalized score",
}
 

用两种方式各问 5 次

ask() 把问题的任意子集连同文档一起发送,并把每个答案归约为它那一个被跟踪的数字。文档在 每次调用中都逐字节相同。

两种批处理策略各运行 RUNS = 5 次,让每个问题在每种策略下都得到 5 个答案,足以比较均值 (两者是否一致?)和标准差(批处理是否增加了噪声?)。调用结果缓存在 json_cache.json 中, 该文件随实践手册一起提供,因此重新渲染是免费的;删掉它即可实时重跑。

python
@json_cache
def ask(keys: tuple[str, ...], run: int):
    """One TypeSafe call -> ({key: tracked metric}, input_tokens, output_tokens, latency_s);
    ``run`` only forces a distinct live call per repeat."""
    started = perf_counter()
    response = client.system_one(
        state={"article": DOCUMENT},
        questions={key: QUESTIONS[key] for key in keys},
        model=TYPESAFE_MODEL,
    )
    values = {}
    for key in keys:
        answer = response.answers[key]
        if isinstance(answer, NoulAnswer):
            values[key] = answer.noul
        elif isinstance(answer, ChoiceAnswer):
            values[key] = max(answer.probabilities.values())
        else:
            values[key] = answer.score / (len(QUESTIONS[key].criteria) - 1)
    return (
        values,
        response.usage.input_tokens,
        response.usage.output_tokens,
        perf_counter() - started,
    )
 
 
def priced(result):
    """({key: metric}, in_tokens, out_tokens, latency) -> ({key: metric}, cost_usd, latency)."""
    values, input_tokens, output_tokens, latency = result
    return values, input_tokens / 1e6 * PRICE[0] + output_tokens / 1e6 * PRICE[1], latency
 
 
# Price after cache retrieval, so a price change needs no new calls.
batched = [
    priced(ask(tuple(QUESTIONS), run)) for run in range(RUNS)
]  # all N in one call, x RUNS
singles = [
    {key: priced(ask((key,), run)) for key in QUESTIONS} for run in range(RUNS)
]  # N x 1, x RUNS
 

批处理不改变答案

每个问题:在 5 次运行中,它的被跟踪数字在每种批处理策略下的均值和标准差。如果批处理改变了 答案,批量列就会与单条列不同。均值发生偏移就是偏差。标准差更大就是噪声。

python
print(
    f"{'question':<22}{'metric':<18}{'batched mean':>13}{'single mean':>12}"
    f"{'batched std':>13}{'single std':>12}"
)
for key, question in QUESTIONS.items():
    batched_values = [values[key] for values, _cost, _latency in batched]
    single_values = [singles[run][key][0][key] for run in range(RUNS)]
    print(
        f"{key:<22}{METRIC[type(question)]:<18}{mean(batched_values):>13.3f}"
        f"{mean(single_values):>12.3f}{stdev(batched_values):>13.4f}{stdev(single_values):>12.4f}"
    )
 
text
question              metric             batched mean single mean  batched std  single std
breach_72h            p(yes)                    0.804       0.814       0.0055      0.0055
applies_non_eu        p(yes)                    0.990       0.990       0.0000      0.0000
dpo_all_orgs          p(yes)                    0.030       0.030       0.0000      0.0000
pre_ticked_consent    p(yes)                    0.040       0.040       0.0000      0.0000
right_erasure         p(yes)                    0.990       0.990       0.0000      0.0000
data_portability      p(yes)                    0.990       0.990       0.0000      0.0000
us_federal_law        p(yes)                    0.010       0.010       0.0000      0.0000
criminal_penalties    p(yes)                    0.108       0.108       0.0045      0.0084
instrument_type       max prob                  1.000       1.000       0.0000      0.0000
max_fine              max prob                  1.000       1.000       0.0000      0.0000
individual_rights     normalized score          1.000       1.000       0.0000      0.0000
penalty_severity      normalized score          1.000       1.000       0.0000      0.0000
compliance_burden     normalized score          0.750       0.750       0.0000      0.0000
 

按问题类型解读这张表:

  • Choice、Score 以及八个 noul 中的六个,在 5 次重复中返回完全一致的结果: 在两种批处理策略下标准差都恰好为 0.0,每次批量调用和单条调用都返回同一个数字。 一条包含 N 个问题的调用,给出的答案与 N 条各含一个问题的调用相同。
  • breach_72h 和 criminal_penalties 带有少量逐次运行的采样噪声,而且这种噪声在两种 批处理策略下大小相同,均值在该噪声范围内一致。噪声是问题本身的属性,而不是你如何批处理 的属性:批处理既不移动答案,也不增加方差。

无论哪种方式,都不存在批处理效应:没有任何问题的答案取决于与它共享同一条请求的另外 12 个 问题。

唯一的差别:成本与速度

相同的答案,不同的账单。约 54,000 字符的文章在每条请求中都占主导,因此:

  • 成本:13 次单问题调用把文章重发了 13 次;批量调用只发送一次。 无论你如何发起调用,这种节省都成立。
  • 速度:图中的数字把 13 次单条调用的延迟相加,因此它假设这些调用依次运行。并发发起它们 的话,差距会缩小,但 13 倍的 token 成本仍然存在。

token 数量与延迟同答案一起被缓存;费用在之后套用,两者都对 5 次运行取平均。

python
batched_cost = mean(cost for _values, cost, _latency in batched)
batched_latency = mean(latency for _values, _cost, latency in batched)
singles_cost = mean(
    sum(singles[run][key][1] for key in QUESTIONS) for run in range(RUNS)
)
singles_latency = mean(
    sum(singles[run][key][2] for key in QUESTIONS) for run in range(RUNS)
)
print(f"{'batching':<24}{'calls':>6}{'cost':>12}{'total time':>12}")
print(
    f"{f'one call, all {N}':<24}{1:>6}{'$' + format(batched_cost, '.6f'):>12}{format(batched_latency, '.2f') + 's':>12}"
)
print(
    f"{f'{N} calls, one each':<24}{N:>6}{'$' + format(singles_cost, '.6f'):>12}{format(singles_latency, '.2f') + 's':>12}"
)
print(
    f"\nbatching: {singles_cost / batched_cost:.1f}x cheaper, {singles_latency / batched_latency:.1f}x faster"
)
 
text
batching                 calls        cost  total time
one call, all 13             1   $0.000497       0.27s
13 calls, one each          13   $0.006090       2.71s
 
batching: 12.2x cheaper, 10.0x faster
 

在 TypeSafe playground 中打开

同一篇文章和同样的 13 个问题,打包进一个分享链接。打开它即可实时重跑这份简报;返回的数字 相同。

python
playground_link = make_playground_link(
    {"article": DOCUMENT}, QUESTIONS, models=[TYPESAFE_MODEL]
)
display(
    Markdown(
        f"🔗 [Open this article + questions in the TypeSafe playground]({playground_link})"
    )
)
 

在 TypeSafe playground 中打开这篇文章和这些问题 →