본문으로 건너뛰기
문서 탐색: 의사결정 모델 / 스트리밍

스트리밍

RightNow AI의사결정 모델스트리밍 업데이트

이 페이지의 내용

스트림은 서버에서 바뀌는 상태를 보내고 WebSocket 연결로 구조화된 결정을 돌려줍니다. 새 텍스트나 배열 항목을 추가하고, 상태를 바꾸고, 수락된 변경을 다루는 결정을 읽습니다.

HTTP로 이벤트 형태의 결정 하나를 받으려면 이벤트 스트림 응답을 읽으세요.

연결하기

스트리밍은 서버 간에만 쓸 수 있습니다. Node 22 이상 또는 Python 3.10 이상을 사용하세요. 브라우저는 WebSocket 업그레이드에서 Authorization 헤더를 설정할 수 없습니다. 키는 서버 프로세스 안에 두세요. 스트림은 rnsk_로 시작하는 키나 API 키 페이지의 키를 사용합니다. SDK의 스트림 클라이언트는 rnsk_로 시작하는 키를 사용합니다.

API 오리진에서 WSS와 /v1/system-zero/stream를 사용하세요. 업그레이드에서 Authorization: Bearer <key>로 인증합니다. Sec-WebSocket-Protocol에는 system-zero.stream.v1만 요청하세요.

텍스트 JSON 메시지를 사용하세요. 브라우저 Origin, URL 자격 증명, 쿠키 인증, 압축, 바이너리 데이터, 쿼리, 끝의 슬래시는 보내지 마세요.

SDK 사용하기

SDK를 설치한 뒤 서버 환경에서 키를 읽습니다. 두 언어 모두 RightNowStreamClient를 내보냅니다.

TypeScript에는 업그레이드 헤더가 필요합니다. 네이티브 지원이 없으면 WebSocket로 서버용 생성자를 넘기세요.

stream.ts
import { RightNowStreamClient } from '@rightnowai/rightnow';

const stream = new RightNowStreamClient();
stream.on('decision', event => console.log(event.reply, event.request_id));
stream.on('error', event => console.error(event.envelope));
try {
  await stream.connect();
  await stream.start({
    model: 'rightnow-decision', state: 'Order received.',
    questions: { ready: { type: 'boolean', instructions: 'Is the order ready?' } },
  }, { decisionMode: 'on_request' });
  const ack = await stream.appendText(' Payment received.');
  await stream.decide();
  const measured = await stream.waitForDecision(ack);
  console.log(measured.decision.reply);
} finally {
  await stream.close();
}

각 변경의 확인 응답을 기다리세요. 응답과 요청 ID는 decision에서, 오류 봉투는 error에서 읽습니다. 클라이언트는 하트비트에 응답하고 알려진 제한에 맞춰 변경 속도를 조절합니다.

다시 연결하면 수락된 상태가 멱등 키와 함께 복원됩니다. 지속되는 스트림을 이어서 재개하지는 않습니다. 연결이 끊겨 결과를 알 수 없으면 possibly_decided를 확인하세요. 다시 연결했다고 해서 그 작업이 계산되지 않았다는 뜻은 아닙니다.

메시지 흐름

스트림 흐름
Text
예시 주고받기 그림입니다.

RightNow가 hello를 보냅니다. 여러분은 hello 후 10초 안에 start를 보냅니다. RightNow가 ack를 보냅니다. 여러분은 append_text를 보냅니다. RightNow가 ack를 보냅니다. 여러분은 decide를 보냅니다. RightNow가 scheduled를 보냅니다. RightNow가 ping을 보냅니다. 여러분은 ping 후 10초 안에 pong을 보냅니다. RightNow가 decision을 보냅니다. RightNow가 goodbye를 보냅니다. ping은 30초마다 옵니다. 유휴 스트림은 120초 후에 닫힙니다. 스트림은 60분 동안 유지됩니다.

hello와 그 제한을 읽은 뒤 마감 전에 start를 보내세요. 질문, 라우팅, 일정, 캐시 키는 연결 동안 고정됩니다. 스트림에서는 hello, ack, decision, error 메시지로 결정 전체를 읽습니다. 스트림은 토큰을 하나씩 보내지 않습니다.

문자열 상태에는 append_text, 배열 요소 전체에는 append_items, 새 상태 전체에는 replace를 사용하세요. 객체는 통째로 바뀌며, 필드 단위의 부분 수정은 지원되지 않습니다. append_attachments는 인라인 첨부 목록만 바꿉니다. 수락된 변경마다 ack를 받고 state_version이 올라갑니다.

on_change에서는 수락된 업데이트가 하나의 결정으로 합쳐질 수 있습니다. on_request에서는 현재 수락된 버전에 대해 decide(state_version)를 보내고 scheduled를 읽습니다. 결정에는 일반 HTTP 응답이 들어 있습니다. 각 결정은 해당 스냅샷의 state_version과 covered_event_ids를 알려 줍니다. 더 새로운 상태가 이미 도착했을 수 있으니 답을 쓰기 전에 state_version을 확인하세요. 상태가 바뀔 때마다 답이 필요하면 on_change를 사용하세요. 이벤트가 수락되는 순간 결정이 시작됩니다. on_request는 이벤트의 확인 응답 후 요청할 때만 결정을 시작하므로, 결정마다 클라이언트에서 네트워크 왕복이 한 번 늘어납니다. on_request 모드에서 결정은 이벤트가 수락된 뒤 80에서 150 ms 후에 시작되며, 그 사이 서버 자체의 처리에는 2에서 5 ms가 걸립니다.

JSON ping마다 ping 쓰기가 끝난 뒤 10000밀리초 안에 같은 nonce를 담은 pong으로 응답하세요. WebSocket 네이티브 제어는 별개입니다. pong을 놓치면 1013과 이유 slow_reader로 닫힙니다.

유휴란 클라이언트 애플리케이션 메시지도 없고 진행 중인 decide도 없는 상태가 120초 이어지는 것입니다. decide가 끝나면 시간 측정이 다시 시작되며, 하트비트는 세지 않습니다. 클라이언트는 WebSocket 종료 코드 1000으로 정상 종료합니다. 클라이언트용 goodbye나 ping JSON 메시지는 없습니다.

서버가 닫을 때 먼저 goodbye를 보낼 수 있습니다. 지속되는 스트림의 재개는 지원되지 않습니다. 다시 연결하고, 상태마다 같은 멱등 키와 바이트 단위로 같은 요청으로 원하는 상태 전체를 다시 보내세요. 성공한 키에는 24시간의 답변 기간이 있으며, 그 기간이 끝난 뒤 30일 동안 요청이나 답변 내용이 없는 식별 기록을 보관합니다. 답변이 만료된 뒤에는 같은 본문에는 409 idempotency_replay_unavailable 응답이, 바뀐 본문에는 400 idempotency_key_reuse 응답이 반환됩니다.

새 연결에서 본문이 같은 것은 start에 직접 정한 prompt_cache_key를 넣었을 때뿐입니다. 넣지 않으면 서버는 새 stream_id를 사용하고, 키는 400 idempotency_key_reuse를 반환합니다. HTTP 요청과 스트림 사이, 두 스트림 사이에서도 마찬가지입니다. 키는 같은 prompt_cache_key일 때만 다시 쓰세요. 어느 경우든 두 번 청구되지 않습니다. 연결이 닫히기 전에 결정이 도착하지 않았다면, 같은 키와 본문으로 완료된 답을 받을 수 있습니다. 재전송을 쓸 수 있다는 보장은 없습니다. 멱등성을 읽으세요. 키가 없으면 전송 중에 잃어버린 결정을 되찾을 수 없습니다. 상태를 다시 보내면 새 작업이 시작됩니다.

재연결 흐름
Text
종료 코드별 재연결 그림입니다.

1002, 1003, 1007, 1008, 1009 이후에는 다시 연결하지 마세요. 1001 이후에는 바로 다시 연결하세요. 1012 이후에는 500밀리초 기다리세요. 1013 이후에는 힌트만큼, 유지 보수라면 300초, 느린 읽기라면 1초 기다리고, 그 밖에는 간격을 늘려 가며 재시도하세요. 1011 이후에는 간격을 늘려 가며 재시도하세요. 1000 이후에는 스트림이 필요할 때 다시 연결하세요. 그런 다음 같은 키로 상태 전체를 다시 보내고 possibly_decided를 확인하세요.

이미지 업데이트하기

준비한 PNG 파일을 shelf-before.png와 shelf-after.png로 저장하세요. 이 Python 예시는 클라이언트 메시지 네 개를 출력합니다. hello 이후 인증된 서버 연결로 하나씩 보내세요.

image-messages.py
Python
import base64
import json
from pathlib import Path

messages = [
    {
        "type": "start",
        "event_id": "evt_1",
        "decision_mode": "on_request",
        "request": {
            "model": "rightnow-decision",
            "state": "Check the current shelf image.",
            "attachments": [
                {
                    "name": "shelf",
                    "type": "image",
                    "data": "shelf-before.png"
                }
            ],
            "questions": {
                "stock": {
                    "type": "choice",
                    "instructions": "Are items visible on shelf?",
                    "criteria": {
                        "present": "Items are visible.",
                        "empty": "The shelf is empty.",
                        "unreadable": "The shelf cannot be assessed."
                    }
                }
            }
        }
    },
    {
        "type": "decide",
        "state_version": 1
    },
    {
        "type": "replace",
        "event_id": "evt_2",
        "state": "Check the current shelf image.",
        "attachments": [
            {
                "name": "shelf",
                "type": "image",
                "data": "shelf-after.png"
            }
        ]
    },
    {
        "type": "decide",
        "state_version": 2
    }
]
for message in messages:
    request = message.get("request", message)
    for attachment in request.get("attachments", []):
        path = Path(attachment["data"])
        encoded = base64.b64encode(path.read_bytes()).decode("ascii")
        attachment["data"] = f"data:image/png;base64,{encoded}"
    print(json.dumps(message))

start를 보내고, 버전 1의 ack를 기다린 뒤 decide를 보내세요. replace를 보내기 전에 그 결정을 읽으세요. 버전 2의 ack를 기다린 뒤 두 번째 결정을 요청하세요. 하트비트에 계속 응답하고 알려진 제한을 지키세요.

교체에서는 이미지 목록 전체를 넘깁니다. 생략하면 이전 목록이 유지됩니다. 기존 이미지를 유지하면서 더 추가하려는 경우에만 append_attachments를 사용하세요. 유지되는 파일은 모두 일반적인 개수 제한과 공통 바이트 제한 안에 들어가야 합니다.

답변된 새 스냅샷마다, 유지된 이미지를 포함해 그 안의 모든 이미지에 요금이 붙습니다. 이미지당 USD 0.003, 답변된 질문당 USD 0.0001, 답변된 호출당 USD 0.00001이며, 나머지 텍스트는 따로 청구됩니다. 이 두 스냅샷은 답변되면 각각 이미지 요금 하나를 포함합니다.

확인 응답은 청구되는 답변이 아닙니다. 미디어 토큰 캐시 적중이 있어도 파일 요금은 없어지지 않습니다. 지속되는 미디어 캐시는 없습니다. 이 예시는 스냅샷을 따로 요청하지만, 자동 결정에서는 업데이트가 합쳐질 수 있습니다.

클라이언트 메시지

start

idempotency_key
선택. string. 최소 길이: 1.
type
필수. "start"
event_id
필수. "evt_1"
request
필수. Start request. 추가 필드는 허용되지 않습니다.
decision_mode
필수. "on_change" or "on_request"
min_interval_ms
선택. integer. 최솟값: 0. 최댓값: 60000. 기본값: 0.

append_text

idempotency_key
선택. string. 최소 길이: 1.
type
필수. "append_text"
event_id
필수. string
text
필수. string. 최소 길이: 1.

append_items

idempotency_key
선택. string. 최소 길이: 1.
type
필수. "append_items"
event_id
필수. string
items
필수. array of JSON value. 최소 항목 수: 1. 최대 항목 수: 4096.

append_attachments

idempotency_key
선택. string. 최소 길이: 1.
type
필수. "append_attachments"
event_id
필수. string
attachments
필수. Inline attachment array. 최소 항목 수: 1.

replace

idempotency_key
선택. string. 최소 길이: 1.
type
필수. "replace"
event_id
필수. string
state
필수. string, object or array
attachments
선택. Inline attachment array. 최대 항목 수: 16.

decide

type
필수. "decide"
state_version
필수. integer. 최솟값: 1. 최댓값: 100000.

pong

type
필수. "pong"
nonce
필수. integer. 최솟값: 1. 최댓값: 9007199254740991.

서버 메시지

hello

type
필수. "hello"
stream_id
필수. string
seq
필수. integer. 최솟값: 1. 최댓값: 9007199254740991.
protocol
필수. "system-zero.stream.v1"
request_id
필수. string. 최소 길이: 1. 최대 길이: 128.
limits
필수. Advertised limits. 추가 필드는 허용되지 않습니다.
rate_limit
필수. Rate limit snapshot or null

ack

type
필수. "ack"
stream_id
필수. string
seq
필수. integer. 최솟값: 1. 최댓값: 9007199254740991.
event_id
필수. string
state_version
필수. integer. 최솟값: 1. 최댓값: 100000.
state_bytes
필수. integer. 최솟값: 0.
synthesized_body_bytes
필수. integer. 최솟값: 0. 최댓값: 3665920.
scheduled
필수. boolean

scheduled

type
필수. "scheduled"
stream_id
필수. string
seq
필수. integer. 최솟값: 1. 최댓값: 9007199254740991.
state_version
필수. integer. 최솟값: 1. 최댓값: 100000.
in_flight
필수. boolean

ping

type
필수. "ping"
stream_id
필수. string
seq
필수. integer. 최솟값: 1. 최댓값: 9007199254740991.
nonce
필수. integer. 최솟값: 1. 최댓값: 9007199254740991.

decision

type
필수. "decision"
stream_id
필수. string
seq
필수. integer. 최솟값: 1. 최댓값: 9007199254740991.
state_version
필수. integer. 최솟값: 1. 최댓값: 100000.
covered_event_ids
필수. array of string. 최대 항목 수: 4096. 항목은 서로 달라야 합니다.
reply
필수. HTTP decision reply. 추가 필드는 허용되지 않습니다.
request_id
필수. string. 최소 길이: 1. 최대 길이: 128.
http_status
필수. 200
server_timing
필수. string or null
latency_ms
필수. number or null. 최솟값: 0.
rate_limit
필수. Rate limit snapshot or null
queue_ms
필수. number. 최솟값: 0.
decide_ms
필수. number. 최솟값: 0.

error

type
필수. "error"
stream_id
필수. string
seq
필수. integer. 최솟값: 1. 최댓값: 9007199254740991.
phase
필수. "protocol" or "decide" or "lifecycle"
state_version
필수. integer. 최솟값: 0. 최댓값: 100000.
event_id
필수. string or null
covered_event_ids
필수. array of string. 최대 항목 수: 4096. 항목은 서로 달라야 합니다.
http_status
필수. integer. 최솟값: 400. 최댓값: 599.
envelope
필수. HTTP error envelope. 추가 필드는 허용되지 않습니다.
retry
필수. Retry fields. 추가 필드는 허용되지 않습니다.
rate_limit
필수. Rate limit snapshot or null
server_timing
필수. string or null
fatal
필수. boolean

goodbye

type
필수. "goodbye"
stream_id
필수. string
seq
필수. integer. 최솟값: 1. 최댓값: 9007199254740991.
reason
필수. "idle" or "max_lifetime" or "auth" or "policy" or "shutdown" or "maintenance" or "overload" or "slow_reader" or "lease_lost" or "store_unavailable" or null
state_version
필수. integer. 최솟값: 0. 최댓값: 100000.
last_decision_state_version
필수. integer. 최솟값: 0. 최댓값: 100000.
resume
필수. object. 추가 필드는 허용되지 않습니다.

공통 필드

상태는 JSON 객체, 배열, 문자열 중 하나입니다. 중첩된 숫자, 불리언, null은 JSON 그대로 유지됩니다. 짧은 키를 사용하고, 정밀도가 중요하면 큰 정수나 정확한 소수를 숫자 문자열로 보내세요. 단위, 좌표계, 데이터의 최신성 정보는 직접 제공하세요.

각 결정은 일반 결정 API의 검증, 제공 여부, 청구, 제한을 따릅니다. 선택지와 점수 단계는 모델 목록의 제한 안에 두세요. 스키마의 상한이 더 크다고 해서 제공을 약속하는 것은 아닙니다. ack는 상태를 연결 메모리에 받아들일 뿐, 입력 제공을 허락하지 않으며 결정, 청구, 지속 저장도 확정하지 않습니다.

질문 이름은 ASCII 영문자, 숫자, 밑줄로 최대 64자이며 영문자나 밑줄로 시작합니다. 첨부 이름은 ASCII 영문자, 숫자, 밑줄, 하이픈으로 최대 64자이며 영문자로 시작합니다. 첨부 이름은 서로 달라야 합니다.

start에서 prompt_cache_key를 생략하면 서버는 stream_id를 사용합니다. 연결을 넘어 바이트 단위로 같은 재전송을 하려면 안정적인 prompt_cache_key를 명시해 보내세요.

요청 정책은 start.request에 넣습니다.

replace.attachments를 생략하면 현재 목록이 유지됩니다. 빈 목록은 모든 첨부를 없앱니다. 텍스트나 배열을 추가해도 첨부는 바뀌지 않습니다. 인라인 데이터에는 별도의 MIME 필드가 없습니다. 문서 파일은 인라인 PDF 데이터여야 합니다. PDF와 동영상(미리 보기)에는 HTTP와 같은 제한이 적용됩니다. 입력을 읽으세요. 스트림은 업로드 참조를 받지 않습니다.

Start request

model
필수. string. 최소 길이: 1. 최대 길이: 200.
state
필수. string, object or array
questions
필수. Named questions. 최소 필드 수: 1. 최대 필드 수: 1024.
attachments
선택. Inline attachment array. 최대 항목 수: 16.
prompt_cache_key
선택. string. 최소 길이: 1. 최대 길이: 256.
route
선택. "standard" or "committee". 보류 중인 기능입니다. "committee"는 404 committee_not_available로 거부되며 청구되지 않습니다
mode
선택. "standard" or "deliberate". 보류 중인 기능입니다. "deliberate"는 404 deliberate_not_available로 거부되며 청구되지 않습니다
policy
선택. Request policy object. 요청 정책을 참고하세요.

Boolean question

type
필수. "boolean"
instructions
필수. nonempty string, object or array
criteria
선택. object. 추가 필드는 허용되지 않습니다.

Choice question

type
필수. "choice"
instructions
필수. nonempty string, object or array
criteria
필수. object with named entries of string or null. 최소 필드 수: 1. 최대 필드 수: 255. 키 최대 길이: 256.

Score question

type
필수. "score"
instructions
필수. nonempty string, object or array
criteria
필수. array of string. 최소 항목 수: 2. 최대 항목 수: 10. 항목: 최소 길이 1. 항목은 비어 있지 않은 문자열이어야 합니다.

Inline data

name
필수. string
type
필수. "document" or "image" or "audio" or "video"
data
필수. string. data:로 시작해야 합니다.

Advertised limits

max_duration_ms
필수. 3600000
idle_timeout_ms
필수. 120000
start_timeout_ms
필수. 10000
heartbeat_interval_ms
필수. 30000
native_heartbeat_interval_ms
선택. 10000
receipt_timeout_ms
선택. 240000
max_control_queue_frames
선택. 2
pong_timeout_ms
필수. 10000
max_message_bytes
필수. 4194304
max_decide_body_bytes
필수. 3665920
max_pending_events
필수. 4096
max_events
필수. 100000
max_events_per_second
필수. 5
max_send_queue_bytes
필수. 4194304
max_send_queue_frames
필수. 64
min_interval_ms
필수. 0
event_burst
필수. 10
max_messages_per_second
필수. 40
message_burst
필수. 80
max_streams_per_process
필수. 16
max_native_control_frames_per_second
필수. 8
native_control_frame_burst
필수. 16
max_native_control_bytes_per_second
필수. 512
native_control_byte_burst
필수. 1024

Rate limit snapshot

limit
필수. integer. 최솟값: 0.
remaining
필수. integer. 최솟값: 0.
reset_epoch_seconds
필수. integer. 최솟값: 0.

HTTP decision reply

id
필수. string
model
필수. string
served_by
필수. string
created
필수. integer. 최솟값: 0. 최댓값: 9007199254740991.
context
필수. object. 추가 필드는 허용되지 않습니다.
answers
필수. object
usage
필수. object. 추가 필드는 허용되지 않습니다.

HTTP error envelope

error
필수. HTTP error. 추가 필드는 허용되지 않습니다.
request_id
필수. string

HTTP error

message
필수. string
type
필수. "invalid_request_error" or "authentication_error" or "permission_error" or "not_found_error" or "rate_limit_error" or "overloaded_error" or "api_error" or "server_error"
param
필수. string or null
code
필수. string or null
retryable
필수. boolean
limit_cents
선택. integer. 최솟값: 0.
spent_cents
선택. integer. 최솟값: 0.
resets_at
선택. string
details
선택. object with named entries of JSON value

Retry fields

should_retry
필수. boolean
retry_after_ms
필수. number or null. 최솟값: 0.
retry_after
필수. string or null

Named questions

<question name>
필수. Boolean question, choice question or score question. 최소 필드 수: 1. 최대 필드 수: 1024.

Inline attachment array

<item>
선택. Inline data. 최대 항목 수: 16.

goodbye.resume fields

supported
필수. false
action
필수. "reconnect_and_replay"
retry_after_ms
필수. integer. 최솟값: 0.

Boolean question.criteria fields

true
선택. string
false
선택. string

HTTP decision reply.context fields

route
필수. "direct" or "long"
tokens
필수. integer. 최솟값: 0. 최댓값: 9007199254740991.

HTTP decision reply.usage fields

input_tokens
필수. integer. 최솟값: 0. 최댓값: 9007199254740991.
cached_input_tokens
필수. integer. 최솟값: 0. 최댓값: 9007199254740991.
media_tokens
필수. integer. 최솟값: 0. 최댓값: 9007199254740991.
long_input_tokens
필수. integer. 최솟값: 0. 최댓값: 9007199254740991.
media_items
필수. integer. 최솟값: 0. 최댓값: 9007199254740991.
thought_tokens
필수. integer. 최솟값: 0. 최댓값: 9007199254740991.

순서와 시퀀스

수락된 변경마다 ack를 받고 state_version이 한 번 올라갑니다.

ID는 정확히 evt_1, evt_2처럼 이어집니다. 거부된 업데이트는 수정한 재시도를 위해 다음 ID를 비워 둡니다.

텍스트 추가는 그대로 이어 붙이고, 배열 추가는 완전한 값을 더하며, replace는 문자열, 배열, 객체 상태 전체를 바꿉니다.

객체 상태를 바꾸려면 replace를 사용하세요. 첨부는 따로 바꿀 수 있습니다.

ack는 상태가 게이트웨이 메모리에 수락되었다는 뜻이며, 결정, 청구, 지속 저장을 뜻하지 않습니다.

첨부 추가나 교체를 포함해 수락된 변경마다 직접 정한 키를 가진 새 버전이 만들어집니다. 바뀌지 않은 버전은 그 키를 유지합니다.

거부된 변경은 이전 키를 그대로 둡니다. 키가 없는 변경은 키를 지웁니다.

게이트웨이는 진행 중인 decide 하나와 대기 중인 요청 하나만 유지합니다.

이어서 들어온 변경은 최신 상태로 합쳐집니다.

on_request 모드에서 decide는 현재 수락된 버전을 지정해야 합니다. 그 스냅샷은 전송할 수 있게 될 때 선택됩니다.

state_version은 누적된 도달 지점입니다. covered_event_ids는 그 전송에서 새로 확정된 변경 묶음만 가리킵니다.

ack는 그것을 다루는 어떤 결정보다 먼저 도착합니다.

이벤트에서 결정까지의 관찰을 끝내는 것은 성공한 결정뿐이며, ack나 오류는 끝내지 않습니다.

종료 중에는 유효한 변경이 적용되고 scheduled: false로 확인되지만, 이 연결에서 다른 decide를 시작하지는 않습니다.

서버 seq는 1에서 시작해 서버 메시지마다 늘어납니다.

멱등 키는 앞뒤의 ASCII 공백을 없앤 뒤 1자에서 255자의 출력 가능한 ASCII 문자입니다. 키가 없는 변경은 이전 키를 지웁니다.

다시 연결하면 새 이벤트 번호를 가진 새 스트림이 만들어집니다.

start에서 원하는 상태 전체를 다시 보낸 뒤, 그 재전송에 없는 변경만 추가하세요.

재연결에는 완전히 무작위한 간격을 쓰고, 서버가 더 긴 재시도 대기를 알리면 그것을 따르세요.

하트비트는 추론 요금을 발생시키지 않으며 유휴 시간이나 수명을 늘리지도 않습니다.

제한

hello에서 알려 주는 제한을 읽으세요. 스트림 제한은 일반 HTTP 제한을 늘리지 않습니다. 유휴 시간에는 하트비트와 결정을 기다리는 시간이 들어가지 않습니다. 계정의 스트림 용량은 모든 머신을 합쳐 스트림 소켓 하나이며, 무료, 크레딧 전용, 유료 계정 모두 같습니다입니다.

receipt_timeout_ms는 호환을 위해 남은 전송 힌트이며, 완전한 수신 기한이 아닙니다. 상대가 살아 있는지와 수신이 멈췄는지를 계속 확인하세요. 두 클라이언트 모두 명령을 보낸 때부터 3,818,000 ms의 수신 기한을 사용합니다. 확인된 응답으로 비활성 타이머는 갱신할 수 있지만 이 기한은 늘릴 수 없습니다. JSON 전용 EventTarget 전송은 수신 기한을 늘리지 않고 3,848,000 ms의 예비 하트비트를 사용합니다.

max_duration_ms
3600000 밀리초
idle_timeout_ms
120000 밀리초
start_timeout_ms
10000 밀리초
heartbeat_interval_ms
30000 밀리초
native_heartbeat_interval_ms
10000 밀리초
receipt_timeout_ms
240000 밀리초
max_control_queue_frames
2 프레임
pong_timeout_ms
10000 밀리초
max_message_bytes
4194304 UTF-8 바이트
max_decide_body_bytes
3665920 UTF-8 바이트
max_pending_events
4096 이벤트
max_events
100000 이벤트
max_events_per_second
5 이벤트/초
max_send_queue_bytes
4194304 바이트
max_send_queue_frames
64 프레임
min_interval_ms
0 밀리초
event_burst
10 이벤트
max_messages_per_second
40 메시지/초
message_burst
80 메시지
max_streams_per_process
16 스트림
max_native_control_frames_per_second
8 프레임/초
native_control_frame_burst
16 프레임
max_native_control_bytes_per_second
512 바이트/초
native_control_byte_burst
1024 바이트
maximum_decision_interval
60000 밀리초
mutation_burst
10 이벤트
application_message_rate
40 메시지/초
application_message_burst
80 메시지
max_pending_probes
2 프로브
write_progress_timeout
5000 밀리초
decision_settlement_timeout
5000 밀리초
close_handshake_timeout
5000 밀리초
consecutive_retryable_failures
3 회 실패/상태 버전
protocol_refusal_limit
3 회 거부/기간
protocol_refusal_window
60000 밀리초
account_decision_burst
5 회 시작
account_decision_ceiling
60 회 시작/분

오류와 종료 코드

error.envelope와 error.retry를 읽으세요. 결정 실패에는 일반 HTTP 상태와 오류 봉투가 그대로 유지됩니다. 거부된 변경은 상태, 버전, 다음 이벤트 ID를 바꾸지 않습니다. 치명적인 오류 뒤에는 반드시 연결이 닫힙니다.

코드상태의미
stream_invalid_message400스트림 메시지가 올바르지 않습니다.
stream_state_type400스트림 상태가 이 변경을 지원하지 않습니다.
stream_event_order409스트림 이벤트가 다음 상태 버전을 지정하지 않습니다.
stream_version_mismatch409요청한 스트림 버전이 현재 버전이 아닙니다.
stream_not_started400스트림이 시작되지 않았습니다.
stream_already_started409스트림이 이미 시작되었습니다.
stream_upgrade_required426이 엔드포인트는 WebSocket 연결만 받습니다.
stream_limit_exceeded429스트림 제한에 도달했습니다.
stream_view_bound409이 스트림은 하나의 모델 버전에 묶여 있습니다. start에 첨부를 넣어 새 스트림을 여세요.
invalid_request400첨부 목록, 항목 또는 반복된 이름이 올바르지 않습니다.
media_unsupported400첨부 개수가 해당 종류의 제한을 넘었습니다.
payload_too_large413결정 요청 전체가 바이트 제한을 넘었습니다.
limiter_unavailable503속도 제한 상태를 읽을 수 없습니다. 재시도 대기 시간을 따르세요.
service_unavailable503새 연결 용량이 가득 찼거나 서버가 멈추는 중입니다. 재시도 대기 시간을 따르세요.

on_change 모드에서는 유지 보수가 아닌 429나 503, 또는 HTTP 409 idempotency_conflict이고 HTTP 응답이 재시도를 허용하면, Retry-After 대기 뒤에 최신 상태가 다시 예약됩니다.

게이트웨이는 실패마다 error 메시지를 보내고, 같은 버전에서 재시도할 수 있는 실패가 세 번 이어지면 자동 재시도를 멈춥니다.

세 번째 오류에는 fatal: true가 있고 HTTP 재시도 필드가 유지됩니다.

그 뒤에 이유 overload의 goodbye, resume.retry_after_ms의 Retry-After 대기, 종료 1013이 이어지며, 클라이언트는 다시 연결하고 다시 보냅니다.

다음 자동 재시도가 스트림의 남은 수명에 닿거나 넘는다면, 같은 치명적인 결과가 바로 적용됩니다.

On_request는 스스로 재시도하지 않습니다.

키를 유지해도 연결이 끊긴 뒤 원래 응답을 되찾을 수 있다는 보장은 없습니다.

Retry-After-Ms가 Retry-After보다 우선합니다.

코드조건이유재연결
1000클라이언트의 정상 종료 또는 애플리케이션이 120초 동안 유휴idlelazy
1001최대 수명 1시간max_lifetimeimmediate
1002RFC 6455 프레임 프로토콜 오류nullnever
1003바이너리 데이터 프레임nullnever
1007잘못된 UTF-8 또는 형식이 잘못된 JSONnullnever
1008거부된 키나 계정 또는 404 unknown_endpoint, start 시간 초과, 메시지나 이벤트 빈도, 네이티브 제어 프레임이나 바이트 한도 또는 전체 이벤트 제한, 60초 안의 프로토콜 거부 3회(종료 처리 중 제외), 또는 WebSocket 조각이나 청크 정책auth, policynever
1009WebSocket 데이터 프레임이나 메시지 크기, 대기 중인 수신 바이트 또는 대기 이벤트 수 한도 초과nullnever
1011예상하지 못한 내부 실패nullbackoff
1012서버 재시작shutdownafter hint. 재시도 대기 ms: 500밀리초
1013유지 보수, 과부하, 느린 읽기(네이티브나 JSON pong을 놓친 경우 포함), 잃었거나 갱신할 수 없는 임대, 또는 사용할 수 없는 저장소maintenance, overload, slow_reader, lease_lost, store_unavailableafter hint or backoff. 유지 보수 재시도 대기 ms: 300000밀리초. 느린 읽기 재시도 대기 ms: 1000밀리초

goodbye.resume.retry_after_ms와 서버가 알리는 더 긴 재시도 대기를 따르세요. 재연결에는 간격을 늘려 가며 시도하세요. goodbye는 최선을 다해 보낼 뿐이며, 전송 종료가 그것 없이 도착할 수도 있습니다.

서버는 1006을 보내지 않습니다. 갑작스럽게 연결이 끊긴 뒤 클라이언트가 1006을 볼 수 있으며, 그때는 간격을 늘려 가며 다시 연결하면 됩니다.

수동 WebSocket

서버 실행 환경에서 보내는 JSON 메시지 예시입니다. MODEL_ID과 SERVED_BY는 인증된 조회에서 얻은 값으로 바꾸세요. 시간, 개수, 확률은 응답 형태를 보여 주기 위한 것입니다. 이 주고받기에서 서버는 결정 뒤에 다시 시작하고, goodbye를 보낸 다음 코드 1012로 닫습니다. 다시 연결하기 전에 최소 500밀리초 기다리세요.

서버
JSON
{
  "type": "hello",
  "stream_id": "szws_0123456789abcdef0123456789abcdef",
  "seq": 1,
  "protocol": "system-zero.stream.v1",
  "request_id": "example-opening",
  "limits": {
    "max_duration_ms": 3600000,
    "idle_timeout_ms": 120000,
    "start_timeout_ms": 10000,
    "heartbeat_interval_ms": 30000,
    "native_heartbeat_interval_ms": 10000,
    "receipt_timeout_ms": 240000,
    "max_control_queue_frames": 2,
    "pong_timeout_ms": 10000,
    "max_message_bytes": 4194304,
    "max_decide_body_bytes": 3665920,
    "max_pending_events": 4096,
    "max_events": 100000,
    "max_events_per_second": 5,
    "max_send_queue_bytes": 4194304,
    "max_send_queue_frames": 64,
    "min_interval_ms": 0,
    "event_burst": 10,
    "max_messages_per_second": 40,
    "message_burst": 80,
    "max_streams_per_process": 16,
    "max_native_control_frames_per_second": 8,
    "native_control_frame_burst": 16,
    "max_native_control_bytes_per_second": 512,
    "native_control_byte_burst": 1024
  },
  "rate_limit": null
}
클라이언트
JSON
{
  "type": "start",
  "event_id": "evt_1",
  "request": {
    "model": "MODEL_ID",
    "state": "Initial log\n",
    "questions": {
      "ready": {
        "type": "boolean",
        "instructions": "Is the job ready?"
      }
    },
    "prompt_cache_key": "example-affinity"
  },
  "decision_mode": "on_request",
  "min_interval_ms": 0,
  "idempotency_key": "example-state-1"
}
서버
JSON
{
  "type": "ack",
  "stream_id": "szws_0123456789abcdef0123456789abcdef",
  "seq": 2,
  "event_id": "evt_1",
  "state_version": 1,
  "state_bytes": 15,
  "synthesized_body_bytes": 158,
  "scheduled": false
}
클라이언트
JSON
{
  "type": "append_text",
  "event_id": "evt_2",
  "text": "Job is ready.\n",
  "idempotency_key": "example-state-2"
}
서버
JSON
{
  "type": "ack",
  "stream_id": "szws_0123456789abcdef0123456789abcdef",
  "seq": 3,
  "event_id": "evt_2",
  "state_version": 2,
  "state_bytes": 30,
  "synthesized_body_bytes": 173,
  "scheduled": false
}
클라이언트
JSON
{
  "type": "decide",
  "state_version": 2
}
서버
JSON
{
  "type": "scheduled",
  "stream_id": "szws_0123456789abcdef0123456789abcdef",
  "seq": 4,
  "state_version": 2,
  "in_flight": false
}
서버
JSON
{
  "type": "ping",
  "stream_id": "szws_0123456789abcdef0123456789abcdef",
  "seq": 5,
  "nonce": 1
}
클라이언트
JSON
{
  "type": "pong",
  "nonce": 1
}
서버
JSON
{
  "type": "decision",
  "stream_id": "szws_0123456789abcdef0123456789abcdef",
  "seq": 6,
  "state_version": 2,
  "covered_event_ids": [
    "evt_1",
    "evt_2"
  ],
  "reply": {
    "id": "szd_0123456789abcdef0123456789abcdef",
    "model": "MODEL_ID",
    "served_by": "SERVED_BY",
    "created": 1790000000,
    "context": {
      "route": "direct",
      "tokens": 32
    },
    "answers": {
      "ready": {
        "type": "boolean",
        "probability": 0.9,
        "confidence": 0.9,
        "calibration_version": "unpublished",
        "decision": true,
        "alternatives": [
          {
            "decision": false,
            "confidence": 0.1
          }
        ],
        "calibrated": false
      }
    },
    "usage": {
      "input_tokens": 32,
      "cached_input_tokens": 0,
      "media_tokens": 0,
      "long_input_tokens": 0,
      "media_items": 0,
      "thought_tokens": 0
    }
  },
  "request_id": "example-decision",
  "http_status": 200,
  "server_timing": null,
  "latency_ms": null,
  "rate_limit": null,
  "queue_ms": 0,
  "decide_ms": 40000
}
서버
JSON
{
  "type": "goodbye",
  "stream_id": "szws_0123456789abcdef0123456789abcdef",
  "seq": 7,
  "reason": "shutdown",
  "state_version": 2,
  "last_decision_state_version": 2,
  "resume": {
    "supported": false,
    "action": "reconnect_and_replay",
    "retry_after_ms": 500
  }
}