# 可选：从离线请求到真实候选 / Optional: from an offline request to a live candidate

默认实验仍离线运行。下面先在应用 ZIP 解压目录准备请求，再由读者自行选择支持 Responses 与 Structured Outputs 的模型调用一次只读政策问答，最后复用现有响应分类与 grader。这里不执行订单工具、退款、发货或其他业务写操作，也不宣称任何真实模型成绩。本站没有在线执行接口。

The default lab remains offline. Prepare a request in the extracted application ZIP, optionally make one policy-question request with a reader-selected model that supports Responses and Structured Outputs, then reuse the response classifier and grader. This guide performs no order-tool execution, refunds, shipments, or other business writes. It claims no measured live-model result; the website provides no online execution endpoint.

需已有本地模型凭据时才执行第 2 步；无需为默认实验配置密钥。本指南不提供密钥设置流程。命令适用于 macOS/Linux shell；Windows 可在 WSL 中运行。每次实验使用新目录，避免混用旧回答。

Run step 2 only if you already have local model credentials. The default lab needs none; this guide does not set up keys. Commands use a macOS/Linux shell (or WSL on Windows). Use a fresh directory for every run to avoid mixing old answers.

## 1. 准备实际检索请求 / Prepare the retrieved request

在包含 `application_project.py` 的目录执行。将模型占位符改为自己账号可用且支持上述能力的确切模型标识；准备请求本身不会联网。默认选择电池问题，可将 `case_id` 改为 `ordinary` 或 `unknown`，比较普通、例外与无证据行为。

Run this beside `application_project.py`. Replace the model placeholder with an exact model ID available to your account that supports the required capabilities. Preparation makes no network request. The default battery case can be changed to `ordinary` or `unknown` to compare ordinary, exception, and missing-evidence behavior.

```sh
python3 - <<'PY'
import hashlib, json
from pathlib import Path
from rag_pipeline import run_pipeline
case_id = 'battery'
model = 'reader-selected-model'
directory = Path('model-run')
directory.mkdir(exist_ok=False)
retrieval = run_pipeline()
row = next(r for r in retrieval['rows'] if r['case'] == case_id)
schema = {'type': 'object', 'properties': {
    'decision': {'type': 'string', 'enum': ['eligible', 'manual_review', 'unknown']},
    'returnWindowDays': {'type': ['integer', 'null']},
    'answer': {'type': 'string'},
    'citations': {'type': 'array', 'items': {'type': 'string'}}},
    'required': ['decision', 'returnWindowDays', 'answer', 'citations'],
    'additionalProperties': False}
request = {'model': model, **row['request'], 'max_output_tokens': 1500,
    'store': False, 'text': {'format': {'type': 'json_schema',
    'name': 'policy_answer', 'strict': True, 'schema': schema}}}
request_text = json.dumps(request, ensure_ascii=False, indent=2) + '\n'
(directory / 'request.json').write_text(request_text, encoding='utf-8')
record = {'case': case_id, 'promptVersion': 'v2', 'topK': 3,
    'contextIds': row['contextIds'], 'corpusSha256': retrieval['snapshot']['corpusSha256'],
    'requestSha256': hashlib.sha256(request_text.encode()).hexdigest(),
    'embeddingModel': retrieval['snapshot']['model'], 'source': 'request_prepared_only'}
(directory / 'run.json').write_text(json.dumps(record, indent=2) + '\n', encoding='utf-8')
print('Prepared model-run/request.json; no model request sent.')
PY
```

`request.json` 只有 `build_prompt` 生成的问题与实际检索正文，不包含 `expectedDecision`、`requiredEvidence` 或人工候选。`run.json` 记录上下文、提示版本与数据摘要；不要把它当作模型输出。

`request.json` contains the question and retrieved text produced by `build_prompt`, without expected labels, required-evidence labels, or authored candidates. `run.json` records context, prompt version, and data digests; it is not a model response.

## 2. 可选调用一次 / Optionally make one request

此步会由读者的账号发起可能计费的生成请求。使用本地已有的 `OPENAI_API_KEY` 环境变量；不要把凭据写入文件、终端记录或交付物。先核对 `request.json` 的模型标识。命令保存 HTTP 状态、响应头和完整响应，关闭重试；不要因拒答、截断或网络失败把人工样本充作真实响应。

This step makes a potentially billable generation request using the reader's account and an existing local `OPENAI_API_KEY` environment variable. Keep credentials out of files, terminal recordings, and deliverables. Check the model ID in `request.json` first. The command saves HTTP status, headers, and the full response, without retries. Do not replace a refusal, truncation, or network failure with an authored fixture and call it a live result.

```sh
curl --silent --show-error --max-time 60 \
  https://api.openai.com/v1/responses \
  -H "Authorization: Bearer ${OPENAI_API_KEY:?use existing local credentials}" \
  -H 'Content-Type: application/json' \
  --data-binary @model-run/request.json \
  --dump-header model-run/headers.txt \
  --output model-run/response.json \
  --write-out '%{http_code}\n' > model-run/http-status.txt
```

curl 非零退出代表传输失败，先保存失败记录，不执行下一步。HTTP 非 200、拒答和生成不完整由下一步分类，均不算候选通过。模型兼容性和能力以官方文档为准。

A nonzero curl exit indicates transport failure: record it and stop before step 3. Step 3 classifies non-200 HTTP responses, refusals, and incomplete generation; none counts as a passing candidate. Check model compatibility against official documentation.

## 3. 保存候选并复用 grader / Save the candidate and reuse the grader

在同一目录执行。此命令不联网，仅处理保存的文件；检查请求和当前数据未变，按原请求中的同一上下文评分，并保留实际模型、响应 ID、usage、请求 ID 和失败原因。退出码 0 表示机械契约通过，1 表示契约失败，2 表示无法取得完整 JSON 候选或输入不匹配。自由文本仍未评分。

Run in the same directory. This command is offline: it verifies the request and data are unchanged, grades against the context used in the request, and records actual model, response ID, usage, request ID, and failure reasons. Exit 0 means mechanical contract pass, 1 contract failure, and 2 no complete JSON candidate or mismatched inputs. Free-text quality remains unscored.

```sh
python3 - <<'PY'
import hashlib, json, sys
from pathlib import Path
from application_data import read_cases
from model_response_contract import classify_response
from prompt_iteration import grade
from rag_pipeline import run_pipeline
def evaluate_saved():
    p = Path('model-run')
    for name in ['candidate.json', 'grade.json']:
        (p / name).unlink(missing_ok=True)
    record = json.loads((p / 'run.json').read_text(encoding='utf-8'))
    record['source'] = record.get('responseOrigin', 'reader_supplied_response')
    if record['source'] not in ['reader_supplied_response', 'authored_fixture_smoke_only']:
        raise ValueError('unsupported response origin')
    def finish(exit_code, reason=None):
        record.update(exitCode=exit_code, failureReason=reason)
        (p / 'run.json').write_text(json.dumps(record, indent=2) + '\n', encoding='utf-8')
        sys.exit(exit_code)
    request_bytes = (p / 'request.json').read_bytes()
    request = json.loads(request_bytes)
    retrieval = run_pipeline(record['topK'])
    row = next(r for r in retrieval['rows'] if r['case'] == record['case'])
    if (hashlib.sha256(request_bytes).hexdigest() != record['requestSha256'] or
        retrieval['snapshot']['corpusSha256'] != record['corpusSha256'] or
        row['contextIds'] != record['contextIds'] or
        request['input'] != row['request']['input'] or
        request['instructions'] != row['request']['instructions']):
        print('Inputs changed; prepare a fresh run (exit 2).')
        finish(2, 'inputs_changed')
    status = int((p / 'http-status.txt').read_text().strip())
    try:
        response = json.loads((p / 'response.json').read_text(encoding='utf-8'))
    except ValueError:
        response = None
    event = classify_response(response, status)
    metadata = response if isinstance(response, dict) else {}
    headers = (p / 'headers.txt').read_text(encoding='utf-8')
    request_id = next((line.split(':', 1)[1].strip() for line in headers.splitlines()
                       if line.lower().startswith('x-request-id:')), None)
    record.update(httpStatus=status,
        responseKind=event['kind'], model=metadata.get('model'),
        responseId=metadata.get('id'), usage=metadata.get('usage'), requestId=request_id)
    (p / 'run.json').write_text(json.dumps(record, indent=2) + '\n', encoding='utf-8')
    if event['kind'] != 'text':
        print(json.dumps({'responseKind': event['kind'], 'semanticQuality': 'not_scored'}))
        finish(2, event['kind'])
    try:
        answer = json.loads(event['text'])
    except ValueError:
        print('Complete text is not JSON; retain the raw response.')
        finish(2, 'invalid_candidate_json')
    (p / 'candidate.json').write_text(json.dumps(answer, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
    chunks = {c['id']: c for c in retrieval['chunks']}
    context = [chunks[cid] for cid in record['contextIds']]
    case = next(c for c in read_cases() if c['id'] == record['case'])
    result = grade(case, answer, context)
    (p / 'grade.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
    print(json.dumps(result))
    record.update(contractPassed=result['contractPassed'], failedChecks=result['failedChecks'],
        semanticQuality=result['semanticQuality'])
    finish(0 if result['contractPassed'] else 1, None if result['contractPassed'] else 'contract_failed')
try:
    evaluate_saved()
except (OSError, ValueError, KeyError, TypeError, StopIteration) as error:
    failure = {'responseKind': 'input_or_file_error',
        'failureReason': type(error).__name__, 'semanticQuality': 'not_scored', 'exitCode': 2}
    try:
        path = Path('model-run/run.json')
        record = json.loads(path.read_text(encoding='utf-8'))
        if isinstance(record, dict):
            record.update(failure)
            path.write_text(json.dumps(record, indent=2) + '\n', encoding='utf-8')
    except (OSError, ValueError):
        pass
    print(json.dumps(failure))
    sys.exit(2)
PY
```

## 4. 人工复核和提交范围 / Human review and reporting scope

逐句对照 `request.json` 的证据，记录自由文本中每个关键主张的支持片段。合法标签和引用仍可能附带“已经退款”之类错误正文，`semanticQuality=not_scored` 必须保留。交付请求、响应、`candidate.json`、`grade.json` 和 `run.json`，注明模型/提示/数据版本、HTTP 与进程退出码及未验证项。只分享脱敏材料，不附凭据。比较 v1/v2 时每版用新目录、同样本、同检索与明确参数；三个问题的通过数不能代表生产准确率。

Compare every important free-text claim with evidence in `request.json` and record its supporting passage. Valid labels and citations can accompany false prose such as an executed refund; retain `semanticQuality=not_scored`. Deliver the request, response, candidate, grade, and run record, with model/prompt/data versions, HTTP and process exit codes, and unverified scope. Share only sanitized material, without credentials. For v1/v2 comparisons, use fresh directories and the same samples, retrieval, and explicit parameters. Three cases do not establish production accuracy.

可不执行第 2 步，用作者 `text_response` 与 `CANDIDATES` 做文件处理冒烟验证；须在 `run.json` 加上 `"responseOrigin": "authored_fixture_smoke_only"`，第 3 步会保留该来源标记。本网站本轮验证只运行这类离线检查，没有消耗生成模型 API。

You can skip step 2 and smoke-test file handling with authored `text_response` and `CANDIDATES`; add `"responseOrigin": "authored_fixture_smoke_only"` to `run.json` so step 3 preserves the source marker. This site's validation used only offline checks and consumed no generation API.

请求形状、拒答与不完整处理核对日期 / Request-shape, refusal, and incomplete-response documentation checked: 2026-10-05.

- [OpenAI Responses reference](https://developers.openai.com/api/reference/resources/responses/methods/create)
- [OpenAI Structured Outputs guide](https://developers.openai.com/api/docs/guides/structured-outputs?api-mode=responses)
