TypeScript 가이드

TypeScript에서의 OpenAI Decisions API

OpenAI는 Decisions API용 SDK를 공개하지 않았습니다 — 복사할 client.decisions.create가 없습니다. 이 페이지는 이 사이트의 엔드포인트(decisions-1을 제공하는, 호출 가능한 OpenAI Decisions API 대안)를 위한 완전히 타입이 지정된 TypeScript 코드를 보여줍니다. 같은 제한적 의사결정 패턴을 따릅니다.

업데이트

계약 정의하기

요청을 한 번만 타입화하면 어디서든 재사용할 수 있습니다. model은 리터럴 유니온이라 고정 ID가 오타로 변하지 않습니다. questions는 질문 ID를 키로 하는 record이며 각각 noul, choice, score 타입입니다.

answers는 type으로 판별되는 유니온으로 타입화하세요 — 이것이 응답 처리를 안전하게 만드는 부분입니다: noul 답변에는 noul이, choice 답변에는 choice와 probabilities가 있습니다. type으로 좁히면 올바른 필드를 얻습니다.

TypeScript

interface DecisionQuestion {
  type: 'noul' | 'choice' | 'score'
  instructions: string
  criteria?: Record<string, string> | string[]
}

interface DecisionRequest {
  model: 'decisions-1' | 'decisions-latest'
  state: string | Record<string, unknown> | unknown[]
  questions: Record<string, DecisionQuestion>
}

interface DecisionAnswers {
  [questionId: string]:
    | { type: 'noul'; noul: number }
    | { type: 'choice'; choice: string; probabilities: Record<string, number>; confidence: number }
    | { type: 'score'; score: number; legend: string[]; probabilities: Record<string, number>; confidence: number }
}

호출하기

Bearer 키로 POST 한 번. satisfies DecisionRequest가 본문을 컴파일 타임에 검사하고 AbortSignal.timeout이 멈춘 호출이 파이프라인을 막는 것을 방지합니다. answers를 읽기 전에 type 필드로 좁히세요.

TypeScript

const res = await fetch('https://decisions-api.net/api/v1/decisions', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.DECISIONS_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(request satisfies DecisionRequest),
  signal: AbortSignal.timeout(30000),
})
const { answers } = (await res.json()) as { answers: DecisionAnswers }

const team = answers.team
if (team.type === 'choice' && team.confidence >= 0.7) {
  routeTo(team.choice)
}

타임아웃과 재시도

429와 502는 짧은 백오프 재시도 가치가 있습니다 — 실패 호출은 과금되지 않습니다. 402는 잔액 부족입니다: 충전하세요, 재시도는 소용없습니다. 422는 검증 오류이며 메시지가 필드를 명시하니 본문을 고치세요.

TypeScript

async function decide(body: DecisionRequest, attempts = 3): Promise<DecisionAnswers> {
  for (let i = 0; i < attempts; i++) {
    const res = await fetch('https://decisions-api.net/api/v1/decisions', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.DECISIONS_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(30000),
    })
    if (res.status === 429 || res.status === 502) {
      await new Promise(r => setTimeout(r, 2 ** i * 1000))
      continue
    }
    if (res.status === 402) throw new Error('out of credits')
    if (!res.ok) throw new Error(`decision call failed: ${res.status}`)
    return (await res.json() as { answers: DecisionAnswers }).answers
  }
  throw new Error('decision call failed')
}

프로바이더를 한 함수 뒤에 두기

호출자는 텍스트를 받아 라벨을 반환하는 타입화된 함수만 봐야 합니다 — HTTP 세부사항이 아니라. OpenAI가 Decisions API를 열면 decide() 내부만 교체하고 모든 호출 지점은 그대로 둡니다. 질문 텍스트, 옵션, 임계값은 그대로 유지됩니다.

TypeScript

// Keep the decision behind one typed function. Swap the HTTP
// layer when OpenAI publishes its schema — callers never change.
export async function routeTicket(text: string): Promise<string> {
  const answers = await decide({
    model: 'decisions-1',
    state: text,
    questions: {
      team: {
        type: 'choice',
        instructions: 'Which team should own this ticket?',
        criteria: {
          payments: 'Checkout or billing.',
          frontend: 'Rendering or browser behavior.',
          account: 'Login or permissions.',
        },
      },
    },
  })
  const team = answers.team
  return team.type === 'choice' && team.confidence >= 0.7 ? team.choice : 'triage'
}

자주 묻는 질문

Decisions API용 공식 OpenAI SDK 예제가 있나요?

없습니다. OpenAI는 Decisions API의 SDK 메서드나 요청 스키마를 공개하지 않았습니다 — client.decisions.create를 보여주는 코드는 전부 지어낸 것입니다. 이 페이지는 평범한 HTTP를 쓰며, 어떤 프로바이더 SDK도 내부적으로 그렇게 합니다.

타입에 코드 생성기가 필요한가요?

아니요 — 이 페이지의 인터페이스가 계약 전체를 커버합니다. 프로젝트에 그대로 복사하세요. 감사할 수 있을 만큼 작고 프로바이더 간에 안정적입니다.

구조화된 컨텍스트는 어떻게내나요?

state는 문자열뿐 아니라 JSON 객체나 배열도 받습니다 — json 본문에 dict를 그대로 전달하면 모델이 컨텍스트로 읽습니다.

브라우저에서 의사결정 실행

설정 없이 — 신규 방문자 무료 크레딧 1개로 플레이그라운드에서 실제 호출을 실행하세요.