跳转到正文
文档导航: 决策模型 / 幂等性

幂等性

RightNow AI决策模型幂等性 更新于

本页内容

使用 Idempotency-Key,可以在已存储的答案可用期间重放同一个决策。

decide.ts
import { RightNowClient } from '@rightnowai/rightnow';

const client = new RightNowClient({
  apiKey: process.env.RIGHTNOW_API_KEY,
  baseURL: "https://api.rightnowai.co/v1",
});
const reply = await client.decide({
  "model": "rightnow-decision",
  "state": "The blender I ordered arrived with a cracked jar.",
  "questions": {
    "damaged": {
      "type": "boolean",
      "instructions": "Did the item arrive damaged?"
    }
  }
});
console.log(JSON.stringify(reply, null, 2));

// Set RIGHTNOW_API_KEY to your API key before running this example.
// Run this example on your server.
// SDK defaults: The default is 5 retries, also the maximum, with 150 seconds
// per attempt and a 60-second total retry budget. A single wait longer than 60
// seconds raises the last error.
// Use Retry-After-Ms, or Retry-After when milliseconds are absent. The wait is
// never shorter than a random backoff floor: a random fraction of 0.5 seconds
// doubled for each attempt, capped at 8 seconds.

以 rnsk_ 开头的密钥通过普通 HTTP 调用决策路径。

保持密钥和正文不变

为新的决策生成一个新密钥。重试时保持该密钥和相同的 JSON 正文,并使用相同的工作区和 API 密钥。

API 会把规范化的 JSON 正文连同方法和路由一起比较。保持密钥不变而更改正文,会返回 400 idempotency_key_reuse。

请求策略也属于这项比较,因此在同一个密钥下更改策略,会返回同样的拒绝。

这个请求头是可选的。没有它,重复调用无法取回在传输中丢失的答案。

读取重放

成功的密钥有 24 小时的答案窗口,并在该窗口结束后的 30 天内保留一条不含请求或答案内容的身份记录;答案过期后,相同的正文会返回 409 idempotency_replay_unavailable,更改过的正文会返回 400 idempotency_key_reuse。

相同的密钥和正文可以返回已完成的答案,并带有 X-RightNow-Idempotent-Replay: true。重放带有新的请求追踪和当前的速率限制响应头。

重放的可用性不受保证。如果无法读取已确定的答案,响应会使用 X-RightNow-Idempotent-Replay: unavailable 和 409 idempotency_replay_unavailable。

如果已存储的答案暂时无法读取,在存储恢复之后、答案过期或被清除之前,相同的密钥和正文可能会重放它。恢复不受保证。此拒绝带有 error.retryable: false;请停止自动重试。新密钥会开始新的工作,并可能得到不同的答案。

处理重放拒绝

代码怎么做
idempotency_conflict同一工作仍在运行。等待 Retry-After 指定的时间后,用相同的 Idempotency-Key 和正文重试。
idempotency_key_reuse对这个 Idempotency-Key 使用原来的正文,或为更改过的工作使用新密钥。
idempotency_replay_unavailable检查 error.details.original_status。新密钥会开始新的工作,而不是取回旧答案。
invalid_idempotency_key修正空白或格式错误的密钥。密钥由 1 到 255 个可打印的 ASCII 字符组成。
idempotency_unavailable等待 Retry-After 指定的时间后,用相同的 Idempotency-Key 重试。
相同请求
Text
带密钥重试示意图。

参数已更改则失败;运行中的工作需等待。已存储的回复会重放;缺失的回复会停止自动重试。

用 error.retryable 和 x-should-retry 判断是否重试。遵循响应中给出的等待时间;见错误。