SPB Git forge

spb/doc-api

Public
2commits 1branches 0releases
15.7 MBsize
maindefault branch
13 days agolast push
Python 88.3% TypeScript 7.6% Shell 4.1%
1.8 KB · 28 lines typescript
Raw Blame History
1// STATUS: UNVERIFIED (not executed; mirrors the LIVE_VERIFIED Python example). Costs < $0.001 per run.2// Node ≥ 22: global WebSocket cannot set headers, so we authenticate with the documented browser-style3// subprotocols using an ephemeral client secret minted first with the standard key.4// Run: node --env-file=.env --experimental-strip-types examples/openai/realtime/websocket_text_only.ts5const key = process.env.OPENAI_API_KEY!;6const model = "gpt-realtime-mini";78const secret = await fetch("https://api.openai.com/v1/realtime/client_secrets", {9  method: "POST", headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },10  body: JSON.stringify({ session: { type: "realtime", model, output_modalities: ["text"] } }),11}).then((r) => r.json());1213const ws = new WebSocket(`wss://api.openai.com/v1/realtime?model=${model}`, ["realtime", `openai-insecure-api-key.${secret.value}`]);14const seen: string[] = [];15ws.addEventListener("open", () => {16  ws.send(JSON.stringify({ type: "session.update", session: { type: "realtime", output_modalities: ["text"], instructions: "Reply with OK only." } }));17  ws.send(JSON.stringify({ type: "conversation.item.create", item: { type: "message", role: "user", content: [{ type: "input_text", text: "Reply with OK." }] } }));18  ws.send(JSON.stringify({ type: "response.create", response: { output_modalities: ["text"], max_output_tokens: 16 } }));19});20ws.addEventListener("message", (m) => {21  const ev = JSON.parse(String(m.data));22  seen.push(ev.type);23  if (ev.type === "response.output_text.delta") console.log("delta:", ev.delta);24  if (ev.type === "error") { console.error(ev.error); ws.close(); }25  if (ev.type === "response.done") { console.log("usage:", ev.response.usage); console.log(seen.join(" → ")); ws.close(); }26});27ws.addEventListener("error", (e) => console.error("ws error", e));28