文件導航

並行提問

在 GDPR 維基百科文章上做一次 13 個問題的合規簡報,證明把所有問題合併進一次 TypeSafe 呼叫要便宜 12.2 倍、快 10.0 倍,而答案不變。

你有一份文件,還有關於它的 N 個問題。你可以發一個包含全部 N 個問題的請求,也可以發 N 個各含一個問題的請求。用 TypeSafe,兩種方式得到的答案一樣:每個問題都是獨立針對文件打分的,所以它的答案不取決於請求裡還有什麼別的東西。

為了驗證這一點,這份 cookbook 把每個問題用兩種方式各問好幾次 —— 全部 N 個放一個請求,以及每次請求只放一個問題 —— 然後比較逐次執行的標準差:一個答案從一次重複到下一次會波動多遠。一個問題有什麼噪聲,在兩種分批策略下都有,分批本身不增添噪聲。多數答案在兩種方式下、全部 5 次重複裡都完全一致,每次呼叫的值都一樣,標準差恰好為 0.0。

成本和速度確實會變。文件在每次請求裡都佔大頭。N 次單問題呼叫要為它付 N 次費,走 N 次往返;合批的呼叫只付一次。文件越大,這個節省就越接近整整 N 倍。

這裡的案例是一份合規簡報。文件是維基百科上的 GDPR 條目(約 54,000 字元,屬於文件主導型負載 —— 文件佔每次請求的大部分),一個合規團隊想核查 13 件事:8 個 Noul 問題、2 個 Choice 問題,以及 3 個 Score 問題。

準備

pip install ipython 'cooksafe>=0.2.0,<0.3.0'

然後設定 TYPESAFE_API_KEY。

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,所以即便線上條目被編輯,文件和它的數字也保持不變。

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']})"))
53,777 characters

📄 閱讀這個固定的維基百科修訂版

問題:8 個 noul + 2 個 choice + 3 個 score

按型別,每個答案追蹤一個數字:

  • Noul:答案為「是」的機率。
  • Choice:最大機率,即落在所選中標籤上的機率。criteria 把每個標籤對映到它的含義。
  • Score:歸一化到 0-1 的分數,即分數除以最高檔位。criteria 從檔位 0 往上列出各檔描述。
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,它隨 cookbook 一起釋出,所以重新渲染不花錢;把它刪掉就能重跑即時呼叫。

@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 次執行中的均值和標準差。如果分批改變了答案,合批那幾列就會和單問那幾列不同。均值偏移是偏差,標準差變大是噪聲。

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}"
    )
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,以及 8 個 noul 裡的 6 個,在全部 5 次重複中都完全一致:兩種分批策略下標準差都恰好為 0.0,每次合批呼叫和單問呼叫返回的數字都一樣。一次包含 N 個問題的呼叫,和 N 次各含一個問題的呼叫,給出相同答案。
  • breach_72h 和 criminal_penalties 帶一點逐次執行的取樣噪聲,而且在兩種分批策略下大小相同,均值也在這個噪聲範圍內一致。這個噪聲是問題本身的屬性,而不是你如何分批的屬性:分批既不偏移答案,也不增加方差。

無論哪種方式,都不存在分批效應:沒有任何問題的答案取決於和它共享請求的那另外 12 個問題。

唯一的區別:成本和速度

答案相同,賬單不同。約 54,000 字元的條目在每次請求裡都佔大頭,所以:

  • 成本:13 次單問題呼叫會把條目重發 13 次;合批呼叫只發一次。這個節省不管你怎樣發起呼叫都成立。
  • 速度:該數字是把 13 次單問呼叫的延遲加總,所以它假設這些呼叫一個接一個地跑。併發發起會縮小差距,但 13 倍的 token 成本依然在。

token 數和延遲和答案一起被快取;成本是在之後套上去的,兩者都對 5 次執行取平均。

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"
)
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 個問題,打包成一個分享連結。開啟它就能即時重跑這份簡報;返回同樣的數字。

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 裡開啟這篇文章和這些問題 →