<!-- Generated from the zh/docs page by the site build (site/integrations/md-twins.mjs); never edit by hand. -->

# 快速入门

输入 OpenQASM 3，输出正准 counts。完整的顺利路径；每个字段都在[API 参考](https://pauli.xyz/reference)中，原始规范见 [`/openapi.json`](https://pauli.xyz/openapi.json)。

## 0 · 获取密钥

[创建工作区](https://pauli.xyz/zh/signup)，取得管理员密钥；下面的每个客户端都从环境变量读取密钥：

```
export PAULI_API_KEY=pauli_sk_…   # shown once at creation; rotate any time
```

## 1 · Qiskit

注册表中的每台设备都是一个 Qiskit `BackendV2`：选一台、运行、按 Qiskit 自己的键序读取 counts。运行固定在您选定的后端上，绝不静默回退：

```
pip install qiskit-pauli   # Python ≥ 3.10
```

```
from qiskit import QuantumCircuit
from qiskit_pauli import PauliProvider

qc = QuantumCircuit(3, 3)                 # GHZ
qc.h(0); qc.cx(0, 1); qc.cx(0, 2)
qc.measure(range(3), range(3))

provider = PauliProvider()                # reads PAULI_API_KEY
backend = provider.least_busy(simulator=True)  # drop simulator=True for hardware
counts = backend.run(qc, shots=1000).result().get_counts()
print(counts)                             # {'000': 489, '111': 511}
```

本页其余部分都通过 `provider.client` 完成，它是每个后端之下完整的带类型客户端：金额是精确的 `Decimal`（传 float 会抛异常），每次提交自动携带幂等键，异常与下方的稳定错误码一一对应。

## 2 · 为整个设备群估价（免费）

一次调用即可在每台符合条件的设备上为*您的*电路估价，并给出预计队列、保真度与带理由的排除项：

```
from qiskit import qasm3

client = provider.client                  # the full pauli-sdk client
fleet = client.jobs.estimate(qasm3.dumps(qc), shots=1000)
for e in fleet.estimates:                 # cheapest first
    print(e.device, e.amount, e.predicted_queue_seconds, e.fidelity_score)
for x in fleet.excluded:                  # reasoned exclusions, complete
    print(x.device, x.reasons[0].code)
```

```
ionq.simulator 0.000000 1.0 1.0
ionq.qpu.forte-enterprise-1 2.700000 6871.0 0.953
```

## 3 · 按策略提交

从 `cheapest`、`fastest`、`highest_fidelity`、`balanced` 中选择；可钉住某台设备，也可按提供商、价格、队列或区域加约束。作业会立即返回路由决定与精确成本；每次提交都带有幂等键（不传则自动生成），因此重试绝不会重复提交：

```
job = client.jobs.submit(qasm3.dumps(qc), shots=1000,
                         policy="highest_fidelity", only=["ionq"],
                         allow_simulator_fallback=True, max_spend_usd="10.00",
                         idempotency_key="exp-042-run-7",
                         webhook_url="https://example.com/hooks/pauli")
print(job.routing_decision.selected_device, job.cost_estimate.amount)
```

执行前的失败会回退到下一台最优设备（设 `allow_fallback=False` 可禁用）；每一跳都有记录，您只为真正执行的那台设备付费。

## 4 · 轮询，或使用 Webhook

```
job.wait()   # jittered backoff to a terminal state; timeout=… to bound it
# created → validating → estimating → queued → transpiling → submitted → running → completed
```

指定 `webhook_url`（仅限 https）后，每次状态变更都会 POST 一次，并用提交密钥的 Webhook 密文（创建密钥时显示）签名；请按 `X-Pauli-Event-Id` 去重：

```
import hashlib, hmac, time

def verify(secret: str, body: bytes, header: str, tolerance: int = 300) -> bool:
    pairs = [p.split("=", 1) for p in header.split(",")]  # header: X-Pauli-Signature
    t = next(v for k, v in pairs if k == "t")
    if abs(time.time() - int(t)) > tolerance:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, v) for k, v in pairs if k == "v1")
```

SDK 已内置此验签流程：`pauli_sdk.webhooks.unwrap(body, headers, secret=…)`。

## 5 · 结果：统一的比特顺序

```
{
  "counts": {"000": 489, "111": 511},
  "bit_ordering": "cbit0_left",
  "register_map": {"c": ["q[0]", "q[1]", "q[2]"]},
  "metadata": {"provider_job_id": "…", "calibration_snapshot_id": "…"},
  "insights": {"shape": "cat_pair", "confidence": "high", "headline": "GHZ-like cat state: …"},
  "billing": {"billed_usd": "2.470000"}
}
```

**counts 约定**：每个键最左边的字符是最先声明的寄存器的经典比特 0；多个寄存器按声明顺序展平。所有提供商都归一到这一约定；分析代码永远不用分支。

**Insights**：直方图形态的参考分类（猫态、均匀分布、周期梳、Porter-Thomas 斑纹……），带通俗标题和考虑 shots 数的置信度，只由 counts 推导。仅作阅读辅助，绝非评分依据。

## 6 · 您自己的凭证（BYOK）

注册凭证（/console/credentials 或 `PUT /v1/credentials/{provider}`）后，该提供商上的作业将在您的账户下运行：提供商直接向您收费；您的钱包只支付平台服务费（[定价](https://pauli.xyz/zh/pricing)）。估价、状态与结果都会显示 `byok`；回退绝不跨越计费模式。

## 7 · 智能体（MCP）

Model Context Protocol 位于 `https://pauli.xyz/mcp`（Streamable HTTP），使用同一个 bearer 密钥。工具与本页流程一一对应。

```
claude mcp add --transport http pauli https://pauli.xyz/mcp \
  --header "Authorization: Bearer $PAULI_API_KEY"
```

## 8 · 在智能体中付款

付费提交超出余额时返回 `402` `billing.insufficient_credits`；其 `detail` 是一份付款挑战，写明缺口金额、充值端点以及如何确认到账。充值（充值返回托管的 `checkout_url`，由人来完成），然后用同一个 `Idempotency-Key` 重新提交。自动充值（`PATCH /v1/billing/settings`）会在作业遇到 402 之前从已保存的卡补足。MCP 工具结果原样携带同一份挑战。

另外两个 402，`billing.monthly_cap_exceeded` 与 `billing.key_cap_exceeded`，是您自设的上限，不带挑战。若支出符合预期，请调高上限。

---

## 错误

每个错误都是 `{"error": {"code", "message", "detail?", "request_id"}}`，错误码稳定；完整注册表见 [`/public/errors`](https://pauli.xyz/public/errors)。联系支持时请附上 `request_id`。最先遇到的几个：

| 错误码 | 含义 |
| --- | --- |
| program.invalid | OpenQASM 3 解析失败；detail 给出行与列。 |
| routing.no_feasible_device | 在您的约束下没有设备能运行该程序；detail 列出每台设备的原因。 |
| billing.insufficient_credits | 402：补足缺口后重新提交（第 8 节）。 |
