본문으로 건너뛰기
문서 탐색: 의사결정 모델 / 빠른 시작

빠른 시작

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 경로, 결정 조회와 웹훅은 이 키에 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퍼센트 이상 작아질 때 압축해서 보냅니다. 끄려면 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().