AI-translated from English; not yet reviewed by a fluent editor.

# फक्त वाचन करणाऱ्या साधनांसह स्थानिक Realtime आवाज एजंट तयार करा

> OpenAI Realtime आणि दोन काल्पनिक फक्त-वाचन साधनांनी ब्राउझरमध्ये थेट आवाज संभाषण तयार करा. सर्व्हर, ब्राउझर आणि नियंत्रकाचा पूर्ण कोड कॉल ID जुळवणे, सुरक्षित पुढील प्रतिसाद, व्यत्यय आणि मायक्रोफोन मुक्त करणे दाखवतो.

By BIG CHANGE Editorial

Published: 2026-10-19T23:39:53.236Z
Updated: 2026-10-19T23:39:53.236Z
Canonical: https://bigchange.ai/blog/openai-realtime-voice-read-only-tool-calls-guide

![Conceptual charcoal illustration of a person speaking into a tabletop microphone while wearing headphones, with a compact computer and two separate unmarked modules nearby.](https://bigchange.ai/api/media/file/realtime-voice-tool-calls-hero-v1.png)
AI-generated conceptual illustration by BIG CHANGE; no actual OpenAI interface, API session, device test or heard answer is depicted.

बोलून उत्तर देण्यासाठी अनेक शोध लागतात तेव्हा ब्राउझरमधील आवाज संभाषण अधिक गुंतागुंतीचे होते. मॉडेल एका पूर्ण प्रतिसादात अनेक फंक्शन कॉल परत करू शकते. प्रत्येक निकाल मूळ `call_id` सोबत परत पाठवला पाहिजे आणि सर्व निकाल पाठवल्यानंतरच नवीन प्रतिसाद सुरू झाला पाहिजे. मार्गदर्शक विकसकांना पूर्ण localhost उदाहरण देतो: थेट मायक्रोफोन इनपुट, WebRTC प्रवाही प्लेबॅक, दोन काल्पनिक फक्त-वाचन साधने, पुन्हा संवाद आणि व्यत्ययावेळी साफसफाई. तो आमच्या [मूलभूत ब्राउझर आवाज मार्गदर्शकाचा](https://bigchange.ai/blog/openai-realtime-browser-voice-webrtc-guide) विस्तार आहे; त्यात बाह्य साधनांशिवाय बोललेले उत्तर मिळते.

## मोठा बदल

- **काय बदलले:** OpenAI चे [Realtime API](https://developers.openai.com/api/docs/guides/realtime-conversations) थेट आवाज सत्रात फंक्शन कॉल परत करू शकते. उदाहरण `call_id` द्वारे पूर्ण कॉल स्थानिक निकालांशी जोडते आणि मग मॉडेलला पुढे जाण्यास सांगते.
- **हे महत्त्वाचे का:** विकसक अनेक फक्त-वाचन शोधांवर अवलंबून बोललेले उत्तर तपासू शकतो. मायक्रोफोन ध्वनी संकलन व प्लेबॅक ब्राउझरमध्ये आणि सामान्य API किल्ली स्थानिक सर्व्हरवर राहते.
- **कशाकडे लक्ष द्यावे:** स्थानिक तपासण्या कृत्रिम घटनांनी घटनाक्रम व साफसफाई तपासतात. तुमचे खाते, ब्राउझर, उपकरणे आणि नेटवर्क ऐकू येणारी अचूक उत्तरे व अपेक्षित बिल देतात का, हे स्वतःच्या सशुल्क सत्रातून ठरवावे लागेल.

उदाहरण OpenAI चा सामान्य Realtime WebRTC एंडपॉइंट `/v1/realtime/calls` आणि `gpt-realtime-2.1` वापरते. ते वेगळे GPT-Live सत्र प्रोटोकॉल वापरत नाही. खालील दोन “ग्रंथालय” मूल्ये काल्पनिक सॉफ्टवेअर चाचणी डेटा आहेत, खऱ्या ठिकाणाची माहिती नाही. BIG CHANGE ने 20 ऑक्टोबर 2026 रोजी सध्याची [WebRTC](https://developers.openai.com/api/docs/guides/voice-webrtc), [संभाषण](https://developers.openai.com/api/docs/guides/realtime-conversations), [साधने](https://developers.openai.com/api/docs/guides/realtime-mcp) आणि [घटना](https://developers.openai.com/api/reference/resources/realtime/client-events) दस्तऐवज तपासले. आम्ही स्थानिक कृत्रिम नियंत्रक आणि ब्राउझर तपासण्या चालवल्या; सशुल्क API सत्र उघडले नाही किंवा खरा मायक्रोफोन व आवाज तपासला नाही.

## 1. प्रवेश तपासा आणि पाच फाइल तयार करा

Node.js 22.6 किंवा नवे, मायक्रोफोन व स्पीकर असलेला सध्याचा ब्राउझर आणि `gpt-realtime-2.1` चा प्रवेश असलेला OpenAI API प्रकल्प आवश्यक आहे. त्याचे [मॉडेल पान](https://developers.openai.com/api/docs/models/gpt-realtime-2.1) Free स्तर समर्थित नसल्याचे सांगते. आधी API बिलिंग व प्रकल्पाच्या विनंतीदर आणि खर्च मर्यादा तपासा; ChatGPT सदस्यत्वात API वापर समाविष्ट नाही. नेहमीच्या स्थानिक गुपित साठवण्याच्या पद्धतीने `OPENAI_API_KEY` ला **सर्व्हर प्रक्रियेच्या वातावरणात** ठेवा. या फाइल, ब्राउझर कोड किंवा प्रतिलेखात लिहू नका. OpenAI ला पाठवण्याची परवानगी असलेलेच बोलणे वापरा.

नवी निर्देशिका तयार करा आणि खालील पाच पूर्ण कोड ब्लॉक प्रत्येकाच्या वरच्या फाइलनावाने जतन करा. `.mjs` विस्तार कायम ठेवा आणि सर्व फाइल एकाच निर्देशिकेत ठेवा. सर्व्हर `127.0.0.1:3000` वर ऐकतो. स्थानिक पानाची SDP offer स्वीकारतो, सर्व्हरवरील किल्लीने OpenAI ला पाठवतो आणि SDP answer परत करतो. ब्राउझरला सामान्य API किल्ली मिळत नाही. स्थानिक Host व Origin तपासण्या प्रात्यक्षिक localhost पर्यंत मर्यादित ठेवण्यास मदत करतात; त्या सामायिक सेवेतील वापरकर्त्यांची ओळख प्रमाणित करत नाहीत.

**server.mjs**

```javascript
import express from "express";

const app = express();
// This demo accepts only the local page, including protection against DNS rebinding.
app.use((req, res, next) => {
  const hosts = ["localhost:3000", "127.0.0.1:3000"];
  if (!hosts.includes(req.get("host"))) return res.status(403).send("Local host required");
  if (req.method === "POST" && req.get("origin") !== `http://${req.get("host")}`) {
    return res.status(403).send("Same-origin local page required");
  }
  next();
});
app.use(express.text({ type: "application/sdp", limit: "64kb" }));

app.get("/", (_req, res) => res.sendFile("index.html", { root: process.cwd() }));
app.get("/controller.mjs", (_req, res) => res.sendFile("controller.mjs", { root: process.cwd() }));

app.post("/session", async (req, res) => {
  if (!process.env.OPENAI_API_KEY) return res.status(500).send("Server API key missing");
  if (typeof req.body !== "string" || !req.body.startsWith("v=")) {
    return res.status(400).send("Expected an SDP offer");
  }

  const form = new FormData();
  form.set("sdp", req.body);
  form.set("session", JSON.stringify({
    type: "realtime",
    model: "gpt-realtime-2.1",
    output_modalities: ["audio"],
    audio: { output: { voice: "marin" } },
    instructions: "Answer questions about the fictional demo library only using its read-only tools. State clearly that the data is synthetic software test data, not real venue information. For a lookup that may take noticeable time, give one short spoken progress preamble when useful, then call the tools. A preamble is never a result. Do not invent missing information. If a tool result is an error, say that lookup failed. Respond concisely in speech.",
    tools: [
      { type: "function", name: "get_demo_hours", description: "Read synthetic demo-library opening hours; no external account or network.", parameters: { type: "object", properties: {}, additionalProperties: false } },
      { type: "function", name: "get_demo_address", description: "Read synthetic demo-library address; no external account or network.", parameters: { type: "object", properties: {}, additionalProperties: false } }
    ],
    tool_choice: "auto"
  }));

  try {
    const upstream = await fetch("https://api.openai.com/v1/realtime/calls", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
      body: form,
      signal: AbortSignal.timeout(25000)
    });
    const answer = await upstream.text();
    if (!upstream.ok) {
      console.error("Realtime session rejected", upstream.status);
      return res.status(502).send(`OpenAI session request failed (${upstream.status})`);
    }
    res.type("application/sdp").send(answer);
  } catch (error) {
    console.error("Realtime session network failure", error.name);
    res.status(502).send("Could not reach the Realtime API");
  }
});

app.listen(3000, "127.0.0.1", () => console.log("Open http://localhost:3000"));
```

**index.html**

```html
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Local Realtime voice and read-only tool check</title>
<h1>Local voice and tool check</h1>
<p>The library data in this demo is synthetic software test data.</p>
<button id="start">Start voice</button>
<button id="stop" disabled>Stop and release microphone</button>
<p id="status" role="status">Idle</p>
<audio id="reply" autoplay controls></audio>
<pre id="events" aria-label="Event status"></pre>
<script type="module">
import { ToolController } from "/controller.mjs";

const start = document.querySelector("#start");
const stop = document.querySelector("#stop");
const status = document.querySelector("#status");
const events = document.querySelector("#events");
const reply = document.querySelector("#reply");
let current;

function note(line) {
  events.textContent = `${line}\n${events.textContent}`.slice(0, 3000);
}

// These values are synthetic test fixtures, never real business records.
async function runDemoTool(call, signal) {
  if (signal.aborted) throw Error("interrupted");
  let args;
  try { args = JSON.parse(call.arguments); } catch { return { ok: false, error: "Invalid arguments" }; }
  if (!args || Array.isArray(args) || typeof args !== "object" || Object.keys(args).length) {
    return { ok: false, error: "Expected an empty object" };
  }
  if (call.name === "get_demo_hours") return { ok: true, value: "Synthetic demo library hours: Monday-Friday 09:00-17:00." };
  if (call.name === "get_demo_address") return { ok: true, value: "Synthetic demo library address: 1 Example Lane. This is not a real venue." };
  return { ok: false, error: "Tool is not allowed" };
}

function closeSession(session = current, message = "Stopped") {
  if (!session || session.closed) return;
  session.closed = true;
  clearTimeout(session.setupTimer);
  clearTimeout(session.sessionTimer);
  session.controller?.close();
  session.abort.abort();
  session.mic?.getTracks().forEach(track => track.stop());
  if (session.pc) session.pc.onconnectionstatechange = null;
  session.dc?.close();
  session.pc?.close();
  reply.pause();
  if (current === session) {
    current = null;
    reply.srcObject = null;
    start.disabled = false;
    stop.disabled = true;
    status.textContent = message;
    note(message);
  }
}

start.onclick = async () => {
  const session = { abort: new AbortController(), closed: false };
  current = session;
  start.disabled = true;
  stop.disabled = false;
  status.textContent = "Requesting microphone";
  events.textContent = "";
  session.setupTimer = setTimeout(() => closeSession(session, "Setup timed out; microphone stopped"), 30000);
  try {
    const mic = await navigator.mediaDevices.getUserMedia({ audio: true });
    if (session.closed) { mic.getTracks().forEach(track => track.stop()); return; }
    session.mic = mic;
    const pc = session.pc = new RTCPeerConnection();
    pc.ontrack = event => {
      if (session.closed) return;
      reply.srcObject = event.streams[0];
      reply.play().catch(() => note("Playback blocked; press Play on the audio control"));
    };
    pc.onconnectionstatechange = () => {
      if (session.closed) return;
      note(`Peer: ${pc.connectionState}`);
      if (pc.connectionState === "connected") {
        clearTimeout(session.setupTimer);
        clearTimeout(session.sessionTimer);
        session.sessionTimer = setTimeout(() => closeSession(session, "Local session limit reached; microphone stopped"), 55 * 60000);
        status.textContent = "Connected; ask about the synthetic demo library";
      }
      if (["failed", "closed", "disconnected"].includes(pc.connectionState)) closeSession(session, "Connection ended; microphone stopped");
    };
    pc.addTrack(mic.getAudioTracks()[0], mic);
    const dc = session.dc = pc.createDataChannel("oai-events");
    const send = event => {
      if (session.closed || dc.readyState !== "open") throw Error("Event channel is not open");
      dc.send(JSON.stringify(event));
    };
    session.controller = new ToolController({
      send, runTool: runDemoTool,
      status: note,
      fatal: message => closeSession(session, `${message}; microphone stopped`)
    });
    dc.onmessage = message => {
      if (session.closed) return;
      let event;
      try { event = JSON.parse(message.data); } catch { closeSession(session, "Invalid event; microphone stopped"); return; }
      if (event.type === "session.created") note("Realtime session created");
      if (event.type === "output_audio_buffer.cleared") note("Server cleared unplayed speech after interruption");
      session.controller.handle(event).catch(() => closeSession(session, "Controller failed; microphone stopped"));
    };
    dc.onclose = () => { if (!session.closed) closeSession(session, "Event channel closed; microphone stopped"); };
    dc.onerror = () => closeSession(session, "Event channel failed; microphone stopped");
    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer);
    if (session.closed) return;
    const response = await fetch("/session", {
      method: "POST", headers: { "Content-Type": "application/sdp" },
      body: offer.sdp, signal: session.abort.signal
    });
    if (!response.ok) throw Error(`Session request failed (${response.status})`);
    const answer = await response.text();
    if (session.closed) return;
    await pc.setRemoteDescription({ type: "answer", sdp: answer });
    if (!session.closed) status.textContent = "Signaling complete; waiting for connection";
  } catch (error) {
    if (!session.closed) closeSession(session, `Start failed: ${error.message}`);
  }
};
stop.onclick = () => closeSession();
window.addEventListener("pagehide", () => closeSession());
</script>
</html>
```

**controller.mjs**

```javascript
// The same controller runs in the browser and in the synthetic local checks.
export class ToolController {
  constructor({ send, runTool, status, fatal, setTimer = setTimeout, clearTimer = clearTimeout }) {
    Object.assign(this, { send, runTool, status, fatal, setTimer, clearTimer });
    this.epoch = 0;
    this.rounds = 0;
    this.counter = 0;
    this.responses = new Map();
    this.pending = null;
    this.closed = false;
  }

  abortPending() {
    if (!this.pending) return;
    this.pending.abort.abort();
    if (this.pending.timer) this.clearTimer(this.pending.timer);
    this.pending = null;
  }

  close() {
    this.closed = true;
    this.epoch++;
    this.abortPending();
    this.responses.clear();
  }

  fail(message) {
    if (this.closed) return;
    this.status(message);
    this.close();
    this.fatal(message);
  }

  interrupt() {
    if (this.closed) return;
    this.epoch++;
    this.rounds = 0;
    this.abortPending();
    this.status("Speech detected; interrupted result discarded");
  }

  async handle(event) {
    if (this.closed) return;
    if (event.type === "error") {
      this.fail(`Realtime error: ${event.error?.code || event.error?.message || "unknown"}`);
      return;
    }
    if (event.type === "input_audio_buffer.speech_started") { this.interrupt(); return; }
    if (event.type === "response.created") {
      if (event.response?.id) this.responses.set(event.response.id, this.epoch);
      return;
    }
    if (event.type === "conversation.item.done") {
      const p = this.pending;
      const id = event.item?.id;
      if (!p || p.epoch !== this.epoch || !p.acks.has(id)) return;
      p.acks.delete(id);
      if (p.acks.size === 0) {
        if (p.timer) this.clearTimer(p.timer);
        this.pending = null;
        if (!p.abort.signal.aborted && !this.closed && p.epoch === this.epoch) {
          this.status("All tool outputs acknowledged; resuming response");
          this.send({ type: "response.create" });
        }
      }
      return;
    }
    if (event.type !== "response.done") return;
    const response = event.response;
    const id = response?.id;
    const responseEpoch = this.responses.get(id);
    this.responses.delete(id);
    if (responseEpoch === undefined || responseEpoch !== this.epoch) return;
    this.status(`Response ${id}: ${response.status || "unknown"}`);
    if (response.status !== "completed") return; // Never execute partial/cancelled calls.
    const calls = (response.output || []).filter(item => item.type === "function_call");
    if (!calls.length) return;
    if (this.pending) { this.fail("Overlapping tool batches in one turn"); return; }
    if (calls.length > 8 || ++this.rounds > 3) { this.fail("Tool call or round bound reached"); return; }
    const ids = new Set();
    for (const call of calls) {
      if (call.status !== "completed" || !call.call_id || ids.has(call.call_id)) {
        this.fail("Incomplete or repeated function call ID"); return;
      }
      ids.add(call.call_id);
    }
    const p = { epoch: this.epoch, abort: new AbortController(), acks: new Set(), timer: null };
    this.pending = p;
    this.status(`Executing ${calls.length} read-only local call(s) from ${id}`);
    const outputs = await Promise.all(calls.map(async call => {
      try { return { call, result: await this.runTool(call, p.abort.signal) }; }
      catch { return { call, result: { ok: false, error: "Local lookup failed" } }; }
    }));
    if (this.closed || this.pending !== p || p.epoch !== this.epoch || p.abort.signal.aborted) return;
    try {
      for (const { call, result } of outputs) {
        const itemId = `tool_output_${++this.counter}`;
        p.acks.add(itemId);
        this.send({
          type: "conversation.item.create",
          event_id: `tool_event_${this.counter}`,
          item: { id: itemId, type: "function_call_output", call_id: call.call_id, output: JSON.stringify(result) }
        });
        this.status(`Sent result for ${call.call_id}`);
      }
      p.timer = this.setTimer(() => this.fail("Tool output acknowledgement timed out"), 8000);
    } catch { this.fail("Could not send tool outputs"); }
  }
}
```

**protocol-check.mjs**

```javascript
import assert from "node:assert/strict";
import { ToolController } from "./controller.mjs";

const deferred = () => { let resolve, reject; const promise = new Promise((a, b) => { resolve = a; reject = b; }); return { promise, resolve, reject }; };
const tick = () => new Promise(resolve => setImmediate(resolve));
const call = (id, name = "get_demo_hours") => ({ type: "function_call", status: "completed", call_id: id, name, arguments: "{}" });
const created = id => ({ type: "response.created", response: { id } });
const done = (id, status, output = []) => ({ type: "response.done", response: { id, status, output } });

function harness(runTool = async x => ({ ok: true, value: x.name })) {
  const sent = [], statuses = [], failures = [];
  const timers = new Map(); let nextTimer = 0;
  const controller = new ToolController({
    send: e => sent.push(e), runTool,
    status: s => statuses.push(s), fatal: e => failures.push(e),
    setTimer: callback => { const id = ++nextTimer; timers.set(id, callback); return id; },
    clearTimer: id => timers.delete(id)
  });
  return { controller, sent, statuses, failures, timers };
}

// Mixed audio/message output, two asynchronous calls resolved in reverse order.
{
  const a = deferred(), b = deferred();
  const h = harness(x => x.call_id === "call_A" ? a.promise : b.promise);
  await h.controller.handle(created("resp_1"));
  const work = h.controller.handle(done("resp_1", "completed", [
    { type: "message", status: "completed", content: [{ type: "output_audio", transcript: "Checking." }] },
    call("call_A"), call("call_B", "get_demo_address")
  ]));
  b.resolve({ ok: true, value: "address" }); await tick();
  assert.equal(h.sent.length, 0, "first finished lookup must not send or resume early");
  a.resolve({ ok: true, value: "hours" }); await work;
  assert.deepEqual(h.sent.map(x => x.item?.call_id), ["call_A", "call_B"]);
  assert.equal(h.sent.filter(x => x.type === "response.create").length, 0);
  await h.controller.handle({ type: "conversation.item.done", item: { id: h.sent[1].item.id } });
  assert.equal(h.sent.filter(x => x.type === "response.create").length, 0);
  await h.controller.handle({ type: "conversation.item.done", item: { id: h.sent[0].item.id } });
  assert.equal(h.sent.filter(x => x.type === "response.create").length, 1, "one resume after both item acknowledgements");
}

// One local lookup error does not erase the other result.
{
  const h = harness(async x => { if (x.call_id === "bad") throw Error("synthetic failure"); return { ok: true, value: "fixture" }; });
  await h.controller.handle(created("resp_2"));
  await h.controller.handle(done("resp_2", "completed", [call("bad"), call("good")]));
  assert.equal(JSON.parse(h.sent[0].item.output).ok, false);
  assert.equal(JSON.parse(h.sent[1].item.output).ok, true);
  for (const e of h.sent.slice()) await h.controller.handle({ type: "conversation.item.done", item: { id: e.item.id } });
  assert.equal(h.sent.filter(x => x.type === "response.create").length, 1);
}

// Partial/cancelled responses never dispatch a call.
for (const status of ["failed", "incomplete", "cancelled"]) {
  const h = harness();
  await h.controller.handle(created(`resp_${status}`));
  await h.controller.handle(done(`resp_${status}`, status, [call("ignored")]));
  assert.equal(h.sent.length, 0);
}

// Distinct rounds are bounded, and missing/duplicate IDs are rejected.
{
  const h = harness();
  for (let i = 1; i <= 3; i++) {
    await h.controller.handle(created(`round_${i}`));
    await h.controller.handle(done(`round_${i}`, "completed", [call(`call_${i}`)]));
    const last = h.sent.at(-1);
    await h.controller.handle({ type: "conversation.item.done", item: { id: last.item.id } });
  }
  await h.controller.handle(created("round_4"));
  await h.controller.handle(done("round_4", "completed", [call("too_many")]));
  assert.match(h.failures[0], /bound/);
  assert.equal(h.sent.filter(x => x.type === "response.create").length, 3);
}
{
  const h = harness();
  await h.controller.handle(created("dup"));
  await h.controller.handle(done("dup", "completed", [call("same"), call("same")]));
  assert.match(h.failures[0], /repeated/);
}

// User speech or Stop invalidates in-flight lookups and ignores their late results.
for (const mode of ["speech", "stop"]) {
  const d = deferred(), h = harness(() => d.promise);
  await h.controller.handle(created(`resp_${mode}`));
  const work = h.controller.handle(done(`resp_${mode}`, "completed", [call("late")]));
  if (mode === "speech") await h.controller.handle({ type: "input_audio_buffer.speech_started" });
  else h.controller.close();
  d.resolve({ ok: true, value: "late fixture" }); await work;
  assert.equal(h.sent.length, 0);
}

// A late response completion or acknowledgement from the interrupted turn cannot resume it.
{
  const h = harness();
  await h.controller.handle(created("old"));
  await h.controller.handle({ type: "input_audio_buffer.speech_started" });
  await h.controller.handle(done("old", "completed", [call("late_call")]));
  assert.equal(h.sent.length, 0);
  await h.controller.handle(created("new"));
  await h.controller.handle(done("new", "completed", [call("fresh_call")]));
  const output = h.sent[0];
  await h.controller.handle({ type: "input_audio_buffer.speech_started" });
  await h.controller.handle({ type: "conversation.item.done", item: { id: output.item.id } });
  assert.equal(h.sent.filter(x => x.type === "response.create").length, 0);
}

// Missing server acknowledgement closes instead of speculatively resuming.
{
  const h = harness();
  await h.controller.handle(created("no_ack"));
  await h.controller.handle(done("no_ack", "completed", [call("one")]));
  assert.equal(h.timers.size, 1);
  [...h.timers.values()][0]();
  assert.match(h.failures[0], /timed out/);
  assert.equal(h.sent.filter(x => x.type === "response.create").length, 0);
}

console.log("Synthetic controller checks passed: ordering, single resume, error isolation, bounds and interruption.");
```

**browser-check.mjs**

```javascript
import assert from "node:assert/strict";
import fs from "node:fs";
import vm from "node:vm";
import { ToolController } from "./controller.mjs";

const html = fs.readFileSync(new URL("./index.html", import.meta.url), "utf8");
const script = html.match(/<script type="module">([\s\S]*?)<\/script>/)?.[1]
  .replace('import { ToolController } from "/controller.mjs";', "");
assert.ok(script, "inline browser module found");

function fakePage(mediaPromise) {
  const nodes = Object.fromEntries(["#start", "#stop", "#status", "#events", "#reply"].map(k => [k, {
    disabled: k === "#stop", textContent: "", srcObject: null,
    pause() { this.paused = true; }, play() { return Promise.resolve(); }
  }]));
  let fetches = 0, peer;
  class FakePeer {
    constructor() { peer = this; this.connectionState = "new"; }
    addTrack() {}
    createDataChannel() { return this.dc = { readyState: "open", close() { this.closed = true; }, send() {} }; }
    async createOffer() { return { sdp: "v=0" }; }
    async setLocalDescription() {}
    async setRemoteDescription() {}
    close() { this.closed = true; }
  }
  vm.runInNewContext(script, {
    ToolController, document: { querySelector: k => nodes[k] },
    navigator: { mediaDevices: { getUserMedia: () => mediaPromise } },
    RTCPeerConnection: FakePeer,
    fetch: async () => { fetches++; return { ok: true, text: async () => "answer" }; },
    window: { addEventListener() {} },
    AbortController, setTimeout, clearTimeout, console
  });
  return { nodes, peer: () => peer, fetches: () => fetches };
}

// Stop while permission is pending; any late track is released without a session request.
{
  let allowMic;
  const page = fakePage(new Promise(resolve => { allowMic = resolve; }));
  const starting = page.nodes["#start"].onclick();
  page.nodes["#stop"].onclick();
  const track = { stopped: false, stop() { this.stopped = true; } };
  allowMic({ getTracks: () => [track], getAudioTracks: () => [track] });
  await starting;
  assert.equal(track.stopped, true);
  assert.equal(page.fetches(), 0);
  assert.equal(page.nodes["#start"].disabled, false);
}

// Stop after signaling: microphone, data channel, peer and playback all close.
{
  const track = { stopped: false, stop() { this.stopped = true; } };
  const page = fakePage(Promise.resolve({ getTracks: () => [track], getAudioTracks: () => [track] }));
  await page.nodes["#start"].onclick();
  page.nodes["#stop"].onclick();
  assert.equal(page.fetches(), 1);
  assert.equal(track.stopped, true);
  assert.equal(page.peer().closed, true);
  assert.equal(page.peer().dc.closed, true);
  assert.equal(page.nodes["#reply"].paused, true);
  assert.equal(page.nodes["#reply"].srcObject, null);
}

console.log("Synthetic browser lifecycle checks passed: late microphone and full Stop cleanup.");
```

त्या निर्देशिकेत सर्व्हरची एकमेव अवलंबिता स्थापित करा आणि सर्व्हर सुरू करा:

```bash
npm init -y
npm install express
node server.mjs
```

उघडा `http://localhost:3000`. पानावर **Start voice**, **Stop and release microphone**, ध्वनी प्लेयर आणि घटनांची स्थिती दिसली पाहिजे. फक्त ब्राउझर पान आणि नियंत्रक मॉड्यूल दिले जातात; दोन्ही चाचणी फंक्शन ब्राउझरमध्ये चालतात, खरे ठिकाण, दिनदर्शिका, CRM किंवा व्यावसायिक खाते वापरत नाहीत.

## 2. सुरू करा, ऐका आणि निकाल तपासा

क्लिक करा **Start voice**, मायक्रोफोनला परवानगी द्या आणि **Connected** ची वाट पाहा. काल्पनिक प्रात्यक्षिक ग्रंथालयाची वेळ व पत्ता विचारा. ब्राउझर मायक्रोफोनचा आवाज WebRTC माध्यम ट्रॅकवर पाठवतो आणि दूरचा ध्वनी ट्रॅक येताच प्लेयरला जोडतो. आपोआप प्लेबॅक अडल्यास दिसणाऱ्या नियंत्रणावर **Play** दाबा. उपयोगी असेल तेव्हा आधी छोटी प्रगती सूचना बोलण्यास सर्व्हरचे निर्देश सांगतात. मॉडेल ती वगळू शकते; ती ऐकू आली तरी शोध यशस्वी झाल्याचा पुरावा नाही.

घटना पटल किल्ली, कच्चा ध्वनी किंवा प्रतिलेख न छापता प्रतिसाद स्थिती, कॉल ID आणि आउटपुट पुष्टी दाखवते. मॉडेल कोणतेही साधन न वापरता, एक किंवा अनेक साधने निवडू शकते. जेव्हा `response.done` मध्ये `status: completed` असते, नियंत्रक **सर्व** आउटपुट आयटममधील पूर्ण `function_call` आयटम शोधतो आणि प्रत्येक `call_id` उपस्थित व वेगळा आहे का तपासतो. तो परवानगीतील शोध अनेक एकाच वेळीही चालवतो, मग प्रत्येक मूळ ID साठी एक `function_call_output` पाठवतो. अयशस्वी शोध त्या कॉलचा त्रुटी निकाल बनतो, इतर निकाल टिकतात. नियंत्रक प्रत्येक ठरवलेल्या आउटपुट आयटम ID साठी `conversation.item.done` येण्याची वाट पाहतो आणि मग एकच `response.create` पाठवतो. सर्व पुष्ट्यांची प्रतीक्षा हा या उदाहरणाचा सावध स्थानिक क्रम आहे, API ची अट नाही. एका प्रतिसादात जास्तीत जास्त आठ कॉल आणि न थांबलेल्या संवाद पाळीत तीन साधन फेऱ्या आहेत; या स्थानिक मर्यादा आहेत.

पाहा **Realtime session created**, जोडलेला समकक्ष, कॉल झाले असल्यास त्यांचे ID, आउटपुट पुष्टी आणि पूर्ण पुढील प्रतिसाद. उत्तर ऐकून वेळ व पत्ता `index.html` मधील काल्पनिक मजकुराशी तुलना करा. फक्त प्रतिसाद पूर्ण झाल्याची घटना ऐकू येणारा प्लेबॅक किंवा उत्तराची अचूकता सिद्ध करत नाही. यासाठी स्वतःचा शुल्क लागणारा ब्राउझर रन आवश्यक आहे; BIG CHANGE ने तो केलेला नाही.

## 3. संवाद पुन्हा करा, व्यत्यय द्या आणि मायक्रोफोन मुक्त करा

पुन्हा सुरू न करता दुसरा प्रश्न विचारा. व्यत्यय तपासण्यासाठी मॉडेल बोलताना किंवा शोध प्रलंबित असताना बोला. WebRTC व आवाज क्रियाशीलता ओळखीसाठी OpenAI रद्द करणे आणि अजून न वाजलेल्या ध्वनीचे सर्व्हरमार्फत छाटणे नोंदवते. `input_audio_buffer.speech_started` आल्यावर स्थानिक नियंत्रक प्रलंबित शोधही अमान्य करतो, म्हणजे उशिराचा निकाल थांबवलेला प्रतिसाद पुन्हा सुरू करू शकत नाही. हा कोड WebSocket ध्वनी प्लेयरला लागणारा वेगळा प्लेबॅक कर्सर आणि छाटण्याच्या घटना लागू करत नाही.

क्लिक करा **Stop and release microphone** आणि ब्राउझरचा मायक्रोफोन निर्देशक बंद झाल्याची खात्री करा. परवानगीची विनंती प्रलंबित असतानाही थांबवता येते; उशिरा परवानगी मिळाल्यास मिळालेला ट्रॅक लगेच थांबतो. तीच साफसफाई ट्रॅक थांबवते, सुरू सत्र विनंती रद्द करते, डेटा चॅनल व समकक्ष बंद करते, प्लेबॅक थांबवून वेगळा करते, साधनांचे काम रद्द करते आणि पान सोडताना, मांडणी किंवा स्थानिक सत्राचा वेळ संपताना किंवा कनेक्शन बिघडताना टाइमर काढते. उदाहरणात मांडणीसाठी 30 सेकंद, स्थानिक सत्रासाठी 55 मिनिटे आहेत; OpenAI Realtime चे कमाल 60 मिनिटे सांगते.

## 4. स्थानिक तपासण्या चालवा आणि चुका सुधारा

त्याच निर्देशिकेत चालवा:

```bash
node --check server.mjs
node --check controller.mjs
node protocol-check.mjs
node browser-check.mjs
```

दोन्ही स्क्रिप्ट कृत्रिम घटना आणि ब्राउझर अनुकरण वापरतात. त्या मिश्र संदेश/फंक्शन प्रतिसाद, उलट क्रमाने पूर्ण होणारे दोन कॉल, एका पुढील प्रतिसादापूर्वी सर्व आउटपुट व पुष्टी, कॉलनिहाय त्रुटी अलग ठेवणे, फक्त पूर्ण कॉल चालवणे, फेऱ्यांच्या मर्यादा, बोलून व्यत्यय, उशिराच्या परवानगीचे मुक्तीकरण आणि Stop साफसफाई तपासतात. API विनंती करत नाहीत. उत्तीर्ण होणे नेटवर्क वेळ, खरे उपकरण, आवाज गुणवत्ता किंवा उत्पादन विश्वासार्हता मोजत नाही.

जर **Start** अयशस्वी झाले, तर दिसणारी स्थिती व स्थानिक सर्व्हरला मिळालेला बाह्य HTTP स्टेटस वाचा. परवानगी, `localhost:3000`, सर्व्हर वातावरण किल्ली, मॉडेल प्रवेश, बिलिंग, मर्यादा व नेटवर्क तपासा. 502 बाह्य नकार, नेटवर्क बिघाड किंवा उदाहरणातील 25 सेकंद विनंतीमर्यादा दर्शवू शकतो; OpenAI ला विनंती मिळालीच नाही असे सिद्ध होत नाही. जोडणी असून ध्वनी नसेल तर इनपुट व आउटपुट उपकरण तपासून **Play** दाबा. अयशस्वी, अपूर्ण किंवा रद्द प्रतिसाद अर्धवट कॉल चालवू शकत नाही. आउटपुट पुष्टीचा वेळ संपल्यास नियंत्रक अनिश्चित दुहेरी पुढील विनंती पाठवण्याऐवजी सत्र बंद करतो. सुरू होण्याचा किंवा नेटवर्कचा निकाल अज्ञात असल्यास सत्र थांबवा, मायक्रोफोन मुक्त झाल्याची खात्री करा आणि पुन्हा प्रयत्नापूर्वी प्रकल्प वापर तपासा; रद्द विनंतीनेही खर्च झाला असू शकतो.

## खर्च आणि मर्यादा

OpenAI चे [मॉडेल पान](https://developers.openai.com/api/docs/models/gpt-realtime-2.1) आणि [किंमतपत्रक](https://developers.openai.com/api/docs/pricing), 20 ऑक्टोबर 2026 रोजी तपासलेले, कॅश नसलेल्या मजकूर इनपुट/आउटपुटसाठी प्रति दहा लाख टोकन 4/24 अमेरिकी डॉलर आणि ध्वनी इनपुट/आउटपुटसाठी 32/64 डॉलर दर्शवतात. खरा खर्च टोकन, ध्वनी आणि पुन्हा येणाऱ्या संवाद संदर्भावर अवलंबून असतो. आम्ही बिल, विलंब, थेट साधनवर्तन किंवा सुरुवातीची सूचना मोजली नाही. मायक्रोफोन ध्वनी OpenAI ला जातो. ठरावीक काल्पनिक फंक्शन खरे व्यावसायिक एकत्रीकरण किंवा लेखनाची परवानगी देत नाहीत. सामायिक उपयोजनाला स्वतःची वापरकर्ता ओळख, मर्यादा, साधन अधिकृतता, देखरेख व समीक्षा लागेल.

### स्रोत आणि अधिक वाचन

- [OpenAI WebRTC मार्गदर्शक](https://developers.openai.com/api/docs/guides/voice-webrtc): ब्राउझर माध्यम ट्रॅक, दूरचा प्लेबॅक, डेटा चॅनल व विश्वासू सर्व्हरमधून SDP देवाणघेवाण. या विशिष्ट ब्राउझरची किंवा खात्याची चाचणी नाही.
- [Realtime संभाषणे](https://developers.openai.com/api/docs/guides/realtime-conversations): पूर्ण प्रतिसादाचा संपूर्ण आउटपुट, फंक्शन निकालक्रम, व्यत्यय आणि 60 मिनिटांची सत्रमर्यादा. विशिष्ट मॉडेल साधन वापरेल याचे वचन नाही.
- [Realtime साधने](https://developers.openai.com/api/docs/guides/realtime-mcp): अनुप्रयोगाच्या नियंत्रणातील फंक्शन कॉल आणि `function_call_output`. या स्थानिक चाचणी डेटाचे यश सिद्ध होत नाही.
- [क्लायंट](https://developers.openai.com/api/reference/resources/realtime/client-events) आणि [सर्व्हर घटना](https://developers.openai.com/api/reference/resources/realtime/server-events) संदर्भ: आयटम ID, पुष्टी आणि प्रतिसाद घटना रचना. सर्व पुष्ट्यांची वाट पाहणे हा उदाहरणाचा स्थानिक पर्याय आहे.
- [Realtime निर्देश लेखन](https://developers.openai.com/api/docs/guides/voice-prompting): अटीनुसार छोटी बोलकी प्रगती सूचना; ऐकू येणाऱ्या आउटपुटची हमी नाही.
- [मॉडेल प्रवेश](https://developers.openai.com/api/docs/models/gpt-realtime-2.1) आणि [API किंमती](https://developers.openai.com/api/docs/pricing): सध्याचे प्रवेशस्तर व टोकन दर. खऱ्या बिलासाठी स्वतःचा प्रकल्प वापर तपासा.

## Sources

- [OpenAI WebRTC मार्गदर्शक](https://developers.openai.com/api/docs/guides/voice-webrtc) — ब्राउझर मायक्रोफोन व दूरचे ध्वनी ट्रॅक, oai-events डेटा चॅनल व /v1/realtime/calls मधून सामान्य API किल्लीने विश्वासू सर्व्हर SDP देवाणघेवाण नोंदवतो. या उदाहरणाचे खरे उपकरण किंवा नेटवर्क वर्तन सिद्ध करत नाही.
- [OpenAI Realtime संभाषणे](https://developers.openai.com/api/docs/guides/realtime-conversations) — response.done पूर्ण आउटपुट, फंक्शन निकालानंतर पुढे जाणे, न वाजलेल्या ध्वनीचे सर्व्हरछाटणेसह WebRTC VAD व्यत्यय आणि 60 मिनिटांची मर्यादा नोंदवतो. वाचक रनमध्ये साधनवापर किंवा अचूक बोलण्याची हमी नाही.
- [साधनांसह OpenAI Realtime](https://developers.openai.com/api/docs/guides/realtime-mcp) — अनुप्रयोग फंक्शन साधने, मूळ call_id असलेले function_call_output आयटम आणि response.create ने पुढे जाणे नोंदवतो. प्रत्येक आउटपुट पुष्टीची प्रतीक्षा हा अतिरिक्त स्थानिक क्रम आहे.
- [OpenAI Realtime क्लायंट घटना](https://developers.openai.com/api/reference/resources/realtime/client-events) — उदाहरणातील conversation.item.create, आयटम ID, function_call_output व response.create रचना ठरवतो; संदर्भ एकत्रीकरण चाचणी नाही.
- [OpenAI Realtime सर्व्हर घटना](https://developers.openai.com/api/reference/resources/realtime/server-events) — उदाहरणातील पूर्ण प्रतिसाद, अंतिम संवाद आयटम पुष्टी आणि त्रुटी घटना रचना ठरवतो. सर्व पुष्ट्यांची प्रतीक्षा स्थानिक पर्याय आहे, API अट किंवा एकत्रीकरण चाचणी नाही.
- [OpenAI आवाज क्रियाशीलता ओळख](https://developers.openai.com/api/docs/guides/realtime-vad) — स्थानिक काम अमान्य करण्यासाठी speech_started व speech_stopped संकेत नोंदवतो; येथे खरा व्यत्यय तपासलेला नाही.
- [OpenAI Realtime निर्देश लेखन](https://developers.openai.com/api/docs/guides/voice-prompting) — अटीनुसार छोटी प्रगती सूचना मागण्यास आधार देतो. सशुल्क सत्रात सूचना पाहिलेली नाही.
- [OpenAI gpt-realtime-2.1 मॉडेल](https://developers.openai.com/api/docs/models/gpt-realtime-2.1) — मॉडेल ID, असमर्थित Free स्तर आणि प्रति दहा लाख टोकन कॅशरहित दर देतो: मजकूर इनपुट/आउटपुट 4/24 अमेरिकी डॉलर, ध्वनी 32/64. प्रवेश व बिलिंगसाठी वाचकाने खाते तपासावे.
- [OpenAI API किंमती](https://developers.openai.com/api/docs/pricing) — gpt-realtime-2.1 चे प्रकाशित मजकूर व ध्वनी टोकन दर पुष्ट करतो; या गाइडच्या सत्राची निश्चित किंमत नाही.
- [OpenAI API आणि ChatGPT बिलिंग](https://help.openai.com/en/articles/9039756-managing-billing-for-chatgpt-and-the-api-platform) — OpenAI सांगते की API वापराचे बिल ChatGPT सदस्यत्वापेक्षा वेगळे असते. याने वाचकाची सध्याची शिल्लक किंवा प्रकल्प मर्यादा ठरत नाही.
