Skip to content

Guides

Ambient documentation

Capture a clinician-patient visit, stream live transcription and receive a drafted clinical note with evidence links.

Ambient documentation listens to a visit and drafts the clinical note. The session, webhook and result work exactly as they do for intake; what differs is how audio is captured and what the result contains.

How it works

  1. Your server creates a session with mode: "ambient".
  2. The clinician’s device streams the room audio to the stream_url and receives the live transcript on the same connection.
  3. Your interface labels the speakers and, when the visit ends, submits the transcript.
  4. You receive session.completed and fetch the note from the result endpoint.

Create an ambient session

Create an ambient session
curl https://api.aimedintake.com/v1/sessions \
  -H "Authorization: Bearer $AIMEDINTAKE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "external_ref": "visit-000482",
    "language": "en",
    "mode": "ambient",
    "device_type": "web"
  }'

Instead of voice, the response carries ambient:

Response · 201
{
  "id": "ses_01JDKB7M2X",
  "object": "session",
  "external_ref": "visit-000482",
  "status": "created",
  "mode": "ambient",
  "language": "en",
  "device_type": "web",
  "tags": {},
  "created_at": "2027-01-12T14:00:05Z",
  "upload_expires_at": "2027-01-13T14:00:05Z",
  "accepted_at": null,
  "completed_at": null,
  "updated_at": "2027-01-12T14:00:05Z",
  "purge_at": null,
  "end_reason": null,
  "error": null,
  "deleted": null,
  "created": true,
  "ambient": {
    "stream_url": "wss://api.aimedintake.com/api/ambient/stream?session_id=ambient-01JDKB7M2X&language=en&ticket=EXAMPLE_TICKET",
    "expires_at": "2027-01-12T14:01:05Z"
  },
  "upload_token": "upl_9bWc2HsY6dQ4tGf1EXAMPLE"
}

stream_url carries a ticket in its query string that is bound to this session and expires within 60 seconds. Treat the whole URL as a secret: pass it to the clinician’s device, do not log it, and open the connection before ambient.expires_at. If the ticket expires first, create the session again with the same external_ref to receive a fresh URL. If ambient documentation is not enabled for your organization, the request fails with 422 mode_not_available.

Stream the visit audio

Open a WebSocket to stream_url and send the microphone audio as binary frames: 16-bit PCM, mono, 16,000 Hz, in frames of about 100 ms. Transcription events arrive as JSON text frames.

Browser
import { connectCapture, openAmbientStream } from './ambient-stream';

// ambient is the object your backend passed on from the create response.
const stream = openAmbientStream(ambient.stream_url, {
  onUpdate: showLiveTranscript,
  // Called at once when the stream fails or closes early, not only when the visit ends.
  onFailure: (error) => {
    microphone.getTracks().forEach((track) => track.stop());
    // The transcript may be incomplete: the clinician reviews it before anything is submitted.
    reviewIncompleteTranscript(error.partial);
  },
});

// Start capture only once the stream is open, so the first words are not lost.
await stream.ready;
// The worklet posts 16-bit PCM, mono, 16 kHz, as ArrayBuffer frames of about 100 ms.
const capture = connectCapture(stream, captureNode.port);

async function endVisit() {
  // Drains the worklet first, so the last words are sent, then finishes the stream.
  // Resolves only after the server has transcribed them and closed cleanly.
  // If it rejects, onFailure has already shown the partial transcript.
  try {
    return await capture.finish();
  } finally {
    microphone.getTracks().forEach((track) => track.stop());
  }
}

A capture worklet holds a little audio that it has not posted yet, and frames it has posted can still be on their way when the clinician ends the visit. Finishing the stream at that moment would cut off the last words. So the worklet answers a flush message with its remaining samples followed by flushed, and connectCapture sends the stream’s finish message only after that confirmation has arrived.

Capture worklet
// In your capture worklet: answer a flush with the samples still buffered, then confirm.
this.port.onmessage = (event) => {
  if (event.data?.type !== 'flush') return;
  if (this.filled > 0) {
    const rest = this.out.slice(0, this.filled).buffer;
    this.port.postMessage(rest, [rest]);
    this.filled = 0;
  }
  this.port.postMessage({ type: 'flushed' });
};
ambient-stream.ts
// Browser client for the ambient visit audio stream.
// Input: `ambient.stream_url` from POST /v1/sessions (mode "ambient").
// Output: the final utterances to label and send to POST /v1/sessions/{id}/ambient-note.

export interface StreamUtterance {
  id: string;
  speaker_index: number;
  text: string;
  start_ms: number;
  end_ms: number;
  is_final: boolean;
}

/**
 * The stream did not open, failed, or did not finish cleanly, so the transcript may be incomplete.
 * `partial` holds the final utterances received so far: show them to the clinician
 * for review, and do not submit them as the complete visit without that review.
 */
export class AmbientStreamError extends Error {
  constructor(message: string, public readonly partial: StreamUtterance[]) {
    super(message);
    this.name = 'AmbientStreamError';
  }
}

export interface AmbientStreamHandlers {
  /** The live transcript changed. */
  onUpdate?: (utterances: StreamUtterance[]) => void;
  /** The stream failed or closed early. Called once, at once: stop the microphone and show `error.partial`. */
  onFailure?: (error: AmbientStreamError) => void;
}

export interface AmbientStream {
  /** Resolves when the stream is open. Start capturing audio only after this. */
  ready: Promise<void>;
  /** Send one frame of 16-bit PCM, mono, 16 kHz (about 100 ms). Throws before `ready`. */
  sendAudio(frame: ArrayBuffer): void;
  /** End the visit. Resolves with the final utterances only after the server has closed the stream cleanly. */
  finish(): Promise<StreamUtterance[]>;
  /** Report a failure on your side, such as a microphone that stopped. Ends the stream as failed. */
  fail(message: string): void;
}

export function openAmbientStream(streamUrl: string, handlers: AmbientStreamHandlers = {}): AmbientStream {
  const utterances = new Map<string, StreamUtterance>(); // id -> latest version
  const finals = () => [...utterances.values()].filter((item) => item.is_final);

  let failure: AmbientStreamError | undefined;
  let finishSent = false;
  let finished: Promise<StreamUtterance[]> | undefined;
  let resolveFinish: ((result: StreamUtterance[]) => void) | undefined;
  let rejectFinish: ((error: AmbientStreamError) => void) | undefined;
  let markReady!: () => void;
  let markNotReady!: (error: AmbientStreamError) => void;

  const ready = new Promise<void>((resolve, reject) => {
    markReady = resolve;
    markNotReady = reject;
  });
  ready.catch(() => undefined); // the failure is also reported through onFailure and finish()

  const socket = new WebSocket(streamUrl);
  socket.binaryType = 'arraybuffer';

  // Every failure goes through here, from the moment the socket exists: once, and immediately.
  const fail = (message: string) => {
    if (failure) return;
    failure = new AmbientStreamError(message, finals());
    markNotReady(failure);
    rejectFinish?.(failure);
    handlers.onFailure?.(failure);
  };

  socket.onopen = () => markReady();
  socket.onmessage = (message: MessageEvent<string>) => {
    let event: { type?: string; message?: unknown; id?: string; text?: unknown };
    try {
      event = JSON.parse(message.data);
    } catch {
      return fail('The stream sent a message that could not be read');
    }
    if (event.type === 'error') return fail(String(event.message));
    if (event.type !== 'utterance' || typeof event.id !== 'string') return;
    // A final event with empty text withdraws an interim guess: remove it.
    if (String(event.text).trim() === '') utterances.delete(event.id);
    else utterances.set(event.id, event as StreamUtterance);
    handlers.onUpdate?.([...utterances.values()]);
  };
  socket.onerror = () => fail('The stream connection failed');
  socket.onclose = (event: CloseEvent) => {
    // Complete only when we asked to finish, nothing failed, and the server closed cleanly with 1000.
    if (finishSent && !failure && event.code === 1000 && event.wasClean) resolveFinish?.(finals());
    else fail(`The stream closed early (code ${event.code})`);
  };

  return {
    ready,
    sendAudio(frame) {
      if (failure || finishSent) return; // the visit is over: no more audio is sent
      if (socket.readyState !== WebSocket.OPEN) throw new Error('The stream is not open yet: wait for ready');
      socket.send(frame);
    },
    finish() {
      // One promise, however often this is called, and one finish message.
      finished ??= new Promise<StreamUtterance[]>((resolve, reject) => {
        resolveFinish = resolve;
        rejectFinish = reject;
        if (failure) return reject(failure);
        if (socket.readyState !== WebSocket.OPEN) {
          socket.close(); // still connecting, or already closing: there is no complete visit to return
          return fail('The visit was ended before the stream was open');
        }
        finishSent = true;
        socket.send(JSON.stringify({ type: 'finish' }));
      });
      return finished;
    },
    fail(message) {
      fail(message);
      if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) socket.close();
    },
  };
}

/** The side of the capture worklet's port that your page holds. */
export interface CapturePort {
  onmessage: ((event: MessageEvent) => void) | null;
  postMessage(message: unknown): void;
}

/**
 * Connects the capture worklet to the stream so that no captured audio is lost at the end.
 *
 * The worklet posts each PCM frame as an ArrayBuffer. When it receives { type: 'flush' } it
 * posts whatever samples it still holds as a last frame, and then { type: 'flushed' }.
 * Messages on a port arrive in order, so once 'flushed' is here every frame has been sent.
 */
export function connectCapture(stream: AmbientStream, port: CapturePort) {
  let flushed: (() => void) | undefined;
  let ending: Promise<StreamUtterance[]> | undefined;
  port.onmessage = (event) => {
    if (event.data?.type === 'flushed') flushed?.();
    else stream.sendAudio(event.data); // every other message is a PCM frame
  };
  const drainAndFinish = async (): Promise<StreamUtterance[]> => {
    const drained = await new Promise<boolean>((resolve) => {
      const timer = setTimeout(() => resolve(false), 2000); // a worklet that never answers must not hang the visit
      flushed = () => {
        clearTimeout(timer);
        resolve(true);
      };
      port.postMessage({ type: 'flush' });
    });
    if (!drained) stream.fail('The microphone capture did not drain: the last words may be missing');
    return stream.finish();
  };
  return {
    /**
     * End the visit: drain the capture worklet first, then finish the stream.
     * One operation, however often this is called (End Visit pressed twice): one flush, one finish.
     */
    finish(): Promise<StreamUtterance[]> {
      ending ??= drainAndFinish();
      return ending;
    },
  };
}

Wait for ready before you send audio: frames sent while the connection is still opening would be lost. A visit transcript is complete only when you asked the stream to finish, no error was reported, and the server closed the connection cleanly with code 1000. Any other close, such as 1011 when transcription fails, means words may be missing. The client reports that through onFailure the moment it happens, with the utterances it has, so that you can stop the microphone and a clinician can review them before anything is submitted. finish() can be called more than once; it sends one finish message and always returns the same result.

Utterance event
{
  "type": "utterance",
  "id": "u2",
  "speaker_index": 1,
  "text": "My throat has been sore for three days and I had a fever last night.",
  "start_ms": 2300,
  "end_ms": 6900,
  "is_final": true
}
Stream messages
DirectionMessageMeaning
SendBinary framePCM16 audio.
Send{"type":"finish"}No more audio. The remaining speech is transcribed, then the connection closes.
ReceiveutteranceA stretch of speech. Events with the same id replace each other until is_final is true. A final event with empty text withdraws the utterance: remove it.
ReceiveerrorThe stream failed; message is safe to show. The transcript so far may be incomplete.

speaker_index distinguishes the voices in the room (0, 1, …) but does not know who is the clinician. Let the clinician confirm which voice is theirs, once, and map the indexes to clinician and patient; use unknown for anyone else.

The audio is transcribed as it streams. It is not stored by AI Medical Intake, and our speech-to-text provider is instructed not to retain it for model training.

Submit the transcript

POST/v1/sessions/{id}/ambient-note

After the stream has closed, submit the final, non-blank utterances with their speaker labels. Authenticate with the upload token or a secret key, as for an intake transcript.

Submit the visit transcript
curl "https://api.aimedintake.com/v1/sessions/$SESSION_ID/ambient-note" \
  -H "Authorization: Bearer $AIMEDINTAKE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "utterances": [
      {
        "id": "u1",
        "speaker": "clinician",
        "text": "What brings you in today?",
        "start_ms": 0,
        "end_ms": 1800
      },
      {
        "id": "u2",
        "speaker": "patient",
        "text": "My throat has been sore for three days and I had a fever last night.",
        "start_ms": 2300,
        "end_ms": 6900
      },
      {
        "id": "u3",
        "speaker": "clinician",
        "text": "Your temperature is 38.1 and your throat is red with swollen tonsils. I would like to do a rapid strep test.",
        "start_ms": 41000,
        "end_ms": 48600
      }
    ]
  }'
Ambient utterance rules
FieldRules
utterances1 to 2,000 items, in spoken order.
idRequired and unique within the request. Letters, digits, _ and -, up to 64 characters. You can reuse the ids from the stream.
speakerclinician, patient or unknown.
text1 to 4,000 characters, not blank.
start_ms, end_msRequired. Milliseconds from the start of the visit.

The API answers 202 with the session in processing; check for that status before you tell the clinician the note is on its way. Uncertain uploads are handled as they are for intake: see When an upload is uncertain. The clinician may correct the transcript in your interface before you submit it; the note is drafted from what you send.

Response · 202
{
  "id": "ses_01JDKB7M2X",
  "status": "processing",
  "transcript_digest": "sha256:666f51d50214a51436bbc54ff82be74a4917edb45990c4605f2b11f445dbc81a",
  "accepted_at": "2027-01-12T14:21:30Z"
}

Ambient sessions have no end_reason: the field stays null. A completed ambient session is charged only in a live organization; in a test organization it is recorded with billable: false.

The clinical note

After session.completed, the result carries the note in ambient_note. For ambient sessions summary and decision_support are null and the top-level code_suggestions is empty; the note has its own.

ambient_note
{
  "subjective": [
    {
      "text": "Sore throat for three days with fever last night.",
      "evidence": [
        "u2"
      ]
    }
  ],
  "objective": [
    {
      "text": "Temperature 38.1 °C. Pharynx erythematous with swollen tonsils.",
      "evidence": [
        "u3"
      ]
    }
  ],
  "assessment": [
    {
      "text": "Acute pharyngitis; streptococcal infection to be excluded.",
      "evidence": [
        "u2",
        "u3"
      ]
    }
  ],
  "plan": [
    {
      "text": "Rapid strep test.",
      "evidence": [
        "u3"
      ]
    }
  ],
  "patient_summary": "You came in with a sore throat and fever. Your clinician examined your throat and discussed doing a rapid strep test.",
  "code_suggestions": [
    {
      "system": "icd10cm",
      "code": "J02.9",
      "display": "Acute pharyngitis, unspecified",
      "score": 0.86
    }
  ],
  "dropped_lines": 0
}
Note fields
FieldDescription
subjective, objective, assessment, planThe four sections of the note, written in English. Each is a list of statements with text and evidence. A section that was not discussed is an empty list.
evidenceThe ids of the utterances the statement cites, never empty. Use them to link each line of the note to the place in the transcript it refers to.
patient_summaryA plain-language summary of the visit, written in the session language, that can be given to the patient after the clinician has reviewed it.
code_suggestionsDiagnosis code suggestions for the visit, in the same shape as intake suggestions.
dropped_linesHow many drafted statements were removed by the checks below.

What the citations guarantee

Before a note is returned, each drafted statement is checked, and removed if it fails:

  • it must cite at least one utterance that exists in the transcript you submitted;
  • a number in an objective finding must appear in the cited utterances;
  • a medication dose must appear in the cited utterances.

These checks keep invented citations, measurements and doses out of the note. They do not prove that a cited utterance supports the statement made about it: that judgement belongs to the clinician. Show each statement next to the speech it cites, and have the clinician review, edit and sign the note in your system.