跳转到正文
文档导航: 决策模型 / 快速开始

快速开始

RightNow AI决策模型快速开始 更新于

本页内容

用你的密钥通过普通 HTTP 调用模型,或安装 SDK 并发送带命名问题的文本状态。

用你的密钥调用

API keys 页面上创建的密钥,与所有开放模型使用同一基础 URL 调用 RightNow 决策模型。

一个密钥,所有模型
Text
一个密钥调用所有模型的示意图。

一个密钥通过一个基础 URL 调用所有模型:/v1/chat/completions 到达开放模型,/v1/decisions 到达 RightNow 决策模型。用量从一个余额支付,图中用条形表示。

TypeScript
const response = await fetch("https://api.rightnowai.co/v1/decisions", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.RIGHTNOW_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "rightnow-decision",
    state: "Order 1234: the customer asks for a refund 45 days after delivery. The policy allows 30 days.",
    questions: {
      refund_allowed: { type: "noul", instructions: "Is the refund allowed under the policy?" },
      next_step: { type: "choice", instructions: "What should support do next?",
        options: ["approve", "deny", "escalate"] },
    },
  }),
});
console.log(await response.json());
decisions reply shape
Text
id: string
model: string
provider: string
answers:
  refund_allowed:
    type: "noul"
    noul: number
  next_step:
    type: "choice"
    choice: string
    confidence: number
    probabilities:
      approve: number
      deny: number
      escalate: number
usage:
  input_tokens: integer
  output_tokens: integer
  input_tokens_details:
    cached_tokens: integer
  cost: number
回答的结构。每个类型代表一个值。
answers
每个问题有一个回答,放在该问题的名称下。
noul
一个从 0 到 1 的是或否概率。
choice
选中的选项及其从 0 到 1 的 confidence,以及 probabilities 中每个选项的概率。
usage.cost
这次调用的费用。请参阅 价格。

请求

model
必填。发送 rightnow-decision。
state
必填。文本、JSON 对象或 JSON 数组。
questions
必填。从每个问题的名称到该问题的映射,有 1 到 32 个条目。
type
问题的类型。noul 是是或否的概率。在文本调用中,choice 接受 2 到 10 个 options,score 接受 2 到 4 个 levels。
user
可选。一个最多 256 个字符的字符串。
Idempotency-Key
可选请求头。在你可能重试的每次调用上都发送它:用相同的值和正文重新发送,会返回第一个回答,并且不会再次收费。第一次调用仍在运行时,重新发送会收到 409:请等待后再发送。没有这个请求头的重试是一次新的调用,被回答就会收费。相同的值配不同的正文会以 400 拒绝,且不收取任何费用。

响应头

X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
你的密钥自己的每分钟限额。同样的三个还会带 -Requests 后缀返回。
x-request-id
请求 id。
X-RightNow-Request-Id
RightNow 决策模型自己的请求 id。
Retry-After
在 429 和 503 上返回。冷启动会替你等待;如果等待结束,调用会返回 503:在这些秒数之后重新发送同样的调用,如果之前发过,请带上同样的 Idempotency-Key。

发送文件

文件作为 state 内的一个条目发送。

种类条目类型形式
图片image_urlimage_url.url:PNG 或 JPEG 的数据 URL。
文档filefile.filename 和 file.file_data:一个名称,以及一个 PDF 的数据 URL。
视频video_urlvideo_url.url:MP4 的数据 URL。
音频input_audioinput_audio.data 和 input_audio.format:base64 数据,以及格式 wav。

限制就是输入中的那些。使用这个密钥时,音频只能是 WAV,一次调用最多包含 32 个问题。

带文件的调用按文本价格收费,并加上价格表中每个文件的费用。请参阅 价格。

回答中的 usage 显示费用:media_fee_nanocents 是文件的费用,media_parts 按正文顺序列出每个文件及其 kind、unit、units 和 fee_nanocents。

此密钥暂不可用

attachments
400 unsupported_parameter。不收取任何费用。请把文件作为 state 内的条目发送。
作为问题类型的 boolean
400 unsupported_question_type。这里的是或否问题是 noul。
stream 或 session_id
400 decision_session_not_supported
provider
400 invalid_request
一次调用中超过 32 个问题
400 invalid_request,其中 param 为 questions。
上传与会话
此密钥不提供。
长上下文选项
无法用此密钥选择。

较早的 decide 路径、决策查询和 webhook 对此密钥返回 401 invalid_api_key 和消息 This path takes a key that starts with rnsk_. With this key, call POST /v1/decisions.

获取密钥

本页的调用使用 API keys 页面上的密钥。最后一节针对较早的决策模型密钥。

在活跃的工作区中,于 API keys 下创建一个有名称的密钥。 完整密钥只在创建时显示。

在发起调用的进程中设置 RIGHTNOW_API_KEY。把密钥留在你的服务器上,并通过 HTTPS 调用。

macOS or Linux
Shell
export RIGHTNOW_API_KEY="<your key>"
Windows PowerShell
PowerShell
$env:RIGHTNOW_API_KEY = "<your key>"

Get an API key

  1. 获取密钥

    在你的服务器上设置 RIGHTNOW_API_KEY。

  2. 安装 SDK

    运行 npm install @rightnowai/rightnow@0.5.1 或 python -m pip install rightnow-sdk==0.5.1。

  3. 第一次调用

    复制 decide.ts 或 decide.py 并运行。

  4. 读取回答

    读取 answers.damaged.decision。它的值是 true 或 false。

你的第一次调用,按步骤展示。

安装 SDK

使用 API keys 页面上的密钥时,SDK 只调用 POST /v1/decisions:它的模型列表、决策查询和流需要以 rnsk_ 开头的密钥,并且它会在发送请求之前拒绝 attachments。SDK 没有调用开放模型的方法:请用同一个密钥通过 HTTP 调用它们。

Node 22 或更高版本,ES 模块,仅限服务器端。Python 3.10 或更高版本,仅限服务器端。

TypeScript 软件包 README (opens in a new tab) 和 Python 软件包 README (opens in a new tab)。

install.sh
npm install @rightnowai/rightnow@0.5.1

从 0.5.0 起,软件包为 @rightnowai/rightnow 和 rightnow-sdk;旧的软件包名称仍然可用。

工具选择:RightNow 决策模型从你的工具中选出下一步要调用的工具,或者一个都不选,并为每个工具给出概率。它不编写参数或消息,也不运行工具。

文本、PDF 和视频允许 9 个工具和“不选”,必须使用工具时允许 10 个;图像或音频允许 25 个工具和“不选”,必须使用工具时允许 26 个。

使用 toolQuestions / tool_questions 和 selectTool / select_tool。见工具选择 (opens in a new tab)。

第一次调用

发送一个状态和一个命名的问题,然后读取答案。

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.

32 KB 或以上的请求体,如果 gzip 压缩能让它至少缩小百分之 10,就会以 gzip 压缩发送;传入 compressRequests: false / compress_requests=False 可关闭此功能。

读取回答

在你的回答中读取 answers.damaged。answers.damaged.probability 为真的可能性。decision 在真至少和假一样可能时选择真;confidence 是它的概率。alternatives 包含另一个结果及其置信度。在此版本中 calibrated 为 false。

reply shape
Text
id: string
model: string
served_by: string
created: integer
context:
  route: string
  tokens: integer
answers:
  damaged:
    type: "boolean"
    probability: number
    confidence: number
    calibration_version: string
    decision: boolean
    alternatives:
      decision: boolean
      confidence: number
    calibrated: boolean
usage:
  input_tokens: integer
  cached_input_tokens: integer
  media_tokens: integer
  long_input_tokens: integer
  media_items: integer
  thought_tokens: integer
回答的结构。每个类型代表一个值。

SDK 重试

规则行为
上限默认重试 5 次,这也是上限;每次尝试 150 秒,重试总预算为 60 秒。单次等待超过 60 秒时,会抛出最后一个错误。
重试标志已标记表示 error.retryable 为 true,或 x-should-retry 响应头为 true。任一标志明确为 false 时,不会重试。
429capacity_exhausted、rate_limit_exceeded、concurrency_limit_exceeded 或 workspace_limit_exceeded。
5xx504 和维护除外,包括 service_unavailable 和 model_unavailable。
409idempotency_conflict。
传输带键的 POST 或 GET 在收到任何响应字节之前,也可以重试符合条件的连接失败或超时,即使请求已经发出。收到响应字节之后的失败从不重试。身份验证和权限类型的错误从不重试。
等待使用 Retry-After-Ms;没有毫秒值时使用 Retry-After。等待时间从不短于一个随机退避下限:0.5 秒的一个随机比例,每次尝试翻倍,上限为 8 秒。
冷启动冷池会返回已标记的 503 model_unavailable,并在 Retry-After 中给出等待时间。SDK 会用同一个幂等密钥重试同一个请求体。重试标志明确为 false 时,会停止重试。

处理拒绝

SDK 遵循上面的重试规则。

在决策的重试中保持相同的 Idempotency-Key 和 JSON 正文。新的决策需要新的密钥。请参阅 幂等性 和 错误。

使用早期的决策模型密钥

以 rnsk_ 开头的密钥通过普通 HTTP 调用 decide 路径。使用示例中打印的策略。

decide.sh
# Set RIGHTNOW_API_KEY to your API key before running this example.
# Generate once per logical decision; reuse this key when retrying.
idempotency_key="$(uuidgen 2>/dev/null \
  || cat /proc/sys/kernel/random/uuid 2>/dev/null \
  || openssl rand -hex 16 2>/dev/null \
  || python3 -c 'from uuid import uuid4; print(uuid4())' 2>/dev/null)"
cat > request.json <<'EOF'
{
  "model": "rightnow-decision",
  "state": "The blender I ordered arrived with a cracked jar.",
  "questions": {
    "damaged": {
      "type": "boolean",
      "instructions": "Did the item arrive damaged?"
    }
  }
}
EOF
# Headerless error responses require Python 3 to read error.code.
# Manual example policy: 130 seconds per attempt, a 600-second resend window
# with no retry-count cap. If x-should-retry is present, resend only when
# x-should-retry is true. If the header is absent, resend on 429, or on 409 and
# 5xx only with a retryable error.code. No answer also retries. Wait Retry-After
# plus up to 10 %, otherwise a random wait doubling from 1 s to 30 s. Stop if
# Retry-After is over 60 s. Also stop when a 429 has no Retry-After, or a 5xx
# has x-should-retry but no Retry-After.
# 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.
random() { od -An -N4 -tu4 /dev/urandom | tr -d ' '; }
# Stop resending after 10 minutes.
start=$(date +%s) attempt=0
while :; do
  : "${RIGHTNOW_API_KEY:?set it first}"
  : "${idempotency_key:?could not make one}"
  rm -f reply.json
  out=$(curl https://api.rightnowai.co/v1/decision-model/decide \
    --max-time 130 -sS -o reply.json -D - -w '%{http_code}' \
    -H "Authorization: Bearer $RIGHTNOW_API_KEY" \
    -H "Content-Type: application/json" \
    -H "Idempotency-Key: $idempotency_key" \
    -d @request.json)
  code=$(printf '%s' "$out" | tail -c 3)
  retry_header=$(printf '%s\n' "$out" \
    | grep -i '^x-should-retry:' | tail -n 1)
  retry=$(printf '%s\n' "$retry_header" \
    | sed 's/^[^:]*:[[:space:]]*//;s/[[:space:]]*$//')
  after=$(printf '%s\n' "$out" | grep -i '^retry-after:' \
    | tail -n 1 | sed 's/^[^:]*:[[:space:]]*//;s/[[:space:]]*$//')
  case $after in *[!0-9]*|'') after= ;; esac
  if [ -z "$retry_header" ]; then
    case $code in
      000|429) ;;
      409|5??)
        error_code=$(python3 -c 'import json, sys
try:
    print(json.load(sys.stdin).get("error", {}).get("code", ""))
except (ValueError, AttributeError):
    pass' < reply.json 2>/dev/null) || break
        case $code:$error_code in
          409:idempotency_conflict) ;;
          5??:service_unavailable) ;;
          5??:model_unavailable) ;;
          5??:billing_settlement_error) ;;
          5??:idempotency_unavailable) ;;
          5??:limiter_unavailable) ;;
          5??:internal_error) ;;
          5??:maintenance) ;;
          *) break ;;
        esac ;;
      *) break ;;
    esac
  else
    [ "$retry" = true ] || break
    case $code in 4??|5??) ;; *) break ;; esac
  fi
  if [ -n "$after" ]; then
    after=$(printf '%s' "$after" | sed 's/^0*//')
    after=${after:-0}
    [ "$after" -le 60 ] || break
    ms=$(( after * 1000 + $(random) % (after * 100 + 1) ))
  else
    [ "$code" != 429 ] || break
    if [ -n "$retry_header" ]; then
      case $code in 5??) break ;; esac
    fi
    cap=$(( attempt < 5 ? 1000 << attempt : 30000 ))
    ms=$(( $(random) % (cap + 1) ))
  fi
  [ $(( $(date +%s) - start + ms / 1000 )) -lt 600 ] || break
  sleep "$(( ms / 1000 )).$(printf '%03d' $(( ms % 1000 )))"
  [ $(( $(date +%s) - start )) -lt 600 ] || break
  attempt=$(( attempt + 1 ))
done
echo "HTTP $code"
cat reply.json 2>/dev/null

使用此密钥时,SDK 还会列出模型:client.models.list()。