Skip to content

Guides

Sessions and call setup

The session lifecycle, idempotent creation, languages, branding and instructions, and submitting the transcript.

A session is one intake interview or one documented visit. You create it from your server, the call runs in your interface, and the transcript you submit turns it into a result. This guide covers intake sessions; see Ambient documentation for the differences in ambient mode.

The session object

The session object
{
  "id": "ses_01JDK8Z3Q4",
  "object": "session",
  "external_ref": "visit-000481",
  "status": "completed",
  "mode": "intake",
  "language": "en",
  "device_type": "kiosk",
  "tags": {
    "site": "clinic-03"
  },
  "created_at": "2027-01-12T13:02:11Z",
  "upload_expires_at": "2027-01-13T13:02:11Z",
  "accepted_at": "2027-01-12T13:09:02Z",
  "completed_at": "2027-01-12T13:09:40Z",
  "updated_at": "2027-01-12T13:09:40Z",
  "purge_at": "2027-02-11T13:09:02Z",
  "end_reason": "normal_completion",
  "error": null,
  "deleted": null
}

The session contains no transcript or result text. It tells you where the session is in its lifecycle; the transcript and results live behind GET /sessions/{id}/result. It does carry end_reason, and a value such as emergency says something about the person, so protect session data as well. Every attribute is described in the API reference.

Lifecycle

Session statuses
StatusMeaningWhat happens next
createdThe session exists and call credentials have been issued. No transcript yet.A transcript moves it to processing. Without one it becomes expired at upload_expires_at.
processingThe transcript was accepted and results are being produced.Ends in completed or failed.
completedThe result is available.Final until deletion. A session.completed event is sent.
failedProcessing failed for good. error.code says why.Final. A session.failed event is sent. Create a new session to try again.
expiredNo transcript arrived in time.Final. No usage is recorded.
deletedThe clinical data is gone, by your request or at the end of retention. deleted.reason says which.A tombstone stays listed, and readable with GET /sessions/{id}, for 90 days. After that the id returns 404 not_found.

completed, failed and expired are terminal: a session never leaves them except to become deleted. updated_at advances on every transition, which is what makes incremental sync work.

Creating a session

POST/v1/sessions

Create a session
curl https://api.aimedintake.com/v1/sessions \
  -H "Authorization: Bearer $AIMEDINTAKE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "external_ref": "visit-000481",
    "language": "en",
    "mode": "intake",
    "device_type": "kiosk",
    "tags": {
      "site": "clinic-03"
    }
  }'
Create parameters
FieldRequiredRules
external_refYesYour opaque reference for the encounter, 1 to 128 characters of A-Z a-z 0-9 . _ : -. No personal data.
languageYesOne of the languages enabled for your organization.
modeNointake (default) or ambient.
device_typeNokiosk, web, mobile or other (default).
tagsNoUp to 10 pairs for your own reporting, such as a site or a department. Keys are lowercase letters, digits and underscores, up to 32 characters; values are strings up to 64 characters. No personal data.

Idempotency

external_ref is the idempotency key. There is no separate idempotency header. Repeating a create request never produces a second session:

Repeated create requests
Existing sessionResponseCredentials
None201, created: trueIssued
Status created200, created: falseReissued: a fresh voice secret and upload token. The previous upload token is revoked.
Status processing or later200, created: falseNone
Same reference, different language or mode409 external_ref_conflictNone

This makes creation safe to retry after a timeout, and gives you a way to recover when the response was lost or the voice secret expired before the patient started. A deleted session is still recognised by its reference while its tombstone is listed, so re-creating it returns the deleted session instead of starting a new one. Use a new reference for a new encounter.

Branding and instructions

The assistant speaks under your name and follows your guidance. These settings belong to your organization and apply to every session, so they are not parameters of the create request. Ask your AI Medical Intake contact to set or change them.

Organization settings
SettingEffect
Assistant nameThe name the assistant uses in its greeting and throughout the interview.
Additional instructionsText appended to the interview instructions, for example topics to cover for your specialty or wording your organization prefers.
Enabled languagesThe subset of the nine languages your sessions may use.
Decision supportOn or off. When off, decision_support is null in every result.
Retention periodDays until clinical data is purged after the transcript is accepted. 30 by default.
Upload windowHours a session waits for its transcript. 24 by default.
Webhook endpointThe HTTPS URL that receives events.

The visual experience is entirely yours: the API has no hosted page. Your interface decides what the patient sees while the call runs.

Choosing the language

language sets the language the assistant speaks and the speech recognition hint. The summary and decision support are written in English for clinical use; see Languages. Choose it before the call, for example from the patient’s selection on your first screen. A language that is not enabled for your organization returns 422 language_not_enabled.

Call credentials

While an intake session is created, the create response carries two credentials for the device:

  • voice: where to connect, a short-lived client_secret, and the session_config to send. See Browser voice connection.
  • upload_token: a single-use token for submitting the transcript. See Upload tokens.

upload_expires_at is fixed when the session is created. Reissuing credentials gives you a fresh secret and token but does not move that deadline.

client_secret_expires_at gives the secret’s expiry in Unix seconds. Open the connection before then. If a patient starts late, create the session again with the same reference to get a fresh secret.

If the voice provider cannot issue a secret, the create request fails with 502 voice_provider_unavailable. Retry the same request.

Submitting the transcript

POST/v1/sessions/{id}/transcript

When the call ends, send the conversation in spoken order. Authenticate with the upload token from the device, or with a secret key from your server.

Submit the transcript
curl "https://api.aimedintake.com/v1/sessions/$SESSION_ID/transcript" \
  -H "Authorization: Bearer $AIMEDINTAKE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "utterances": [
      {
        "speaker": "assistant",
        "text": "Hello, I am Ana, an AI assistant with your care team. I would like to ask a few questions before your visit. Is that okay?",
        "start_ms": 0,
        "end_ms": 6200
      },
      {
        "speaker": "patient",
        "text": "Yes, that is fine.",
        "start_ms": 6900,
        "end_ms": 8100
      },
      {
        "speaker": "assistant",
        "text": "Thank you. What brings you in today?",
        "start_ms": 8600,
        "end_ms": 10900
      },
      {
        "speaker": "patient",
        "text": "I have had a tight feeling in my chest since yesterday evening, mostly when I climb stairs.",
        "start_ms": 11800,
        "end_ms": 17400
      }
    ],
    "ended_at": "2027-01-12T13:08:55Z",
    "end_reason": "normal_completion"
  }'
Transcript rules
FieldRules
utterances1 to 2,000 items, in spoken order.
utterances[].speakerassistant or patient.
utterances[].text1 to 4,000 characters, not blank.
start_ms, end_msOptional. Milliseconds from the start of the call, with end_ms not before start_ms.
ended_atOptional. When the call ended.
end_reasonOptional, defaults to other. See End reason.

The transcript as a whole must be between 10 and 50,000 characters; otherwise the request fails with transcript_too_short or transcript_too_long.

Response · 202
{
  "id": "ses_01JDK8Z3Q4",
  "status": "processing",
  "transcript_digest": "sha256:e94ada0c075c47abfa26f36d58e4b2bbf6e6c0fa225991e3d273fe744359ecdf",
  "accepted_at": "2027-01-12T13:09:02Z"
}

Only 202 means the transcript was accepted. A 422 or 429 means it was not, so check the status before you tell the patient the interview has been sent.

When an upload is uncertain

transcript_digest is a SHA-256 over the canonical form (RFC 8785) of the request body. A session processes exactly one transcript, and what a repeated request returns depends on the credential:

Repeated transcript uploads
Repeat sent withSame bodyDifferent body
Secret keyThe original 202, even after upload_expires_at. No second job starts.409 transcript_already_accepted
Upload token401 invalid_upload_token: the token was consumed when the transcript was accepted.401 invalid_upload_token

The one exception is a deleted session, by your request or at the end of retention. A valid secret-key replay then returns 409 session_closed, the accepted body included, while the tombstone exists (90 days); after that it returns 404 not_found. A consumed upload token still returns 401 invalid_upload_token, because authentication comes first. After authentication the API checks, in this order: deletion; then, for a session that already has a transcript, the digest; then, for a first upload only, upload_expires_at.

So a device that lost the response cannot find out by itself whether its upload arrived, and it must not retry with the token. Have it hand the exact body it sent, byte for byte and including ended_at, to your backend, which then decides:

  1. Pick the endpoint from the session’s mode, which your backend stored when it created the session: /transcript for intake, /ambient-note for ambient. No read is needed, so a key with only sessions:write can do this.
  2. If the device was answered 429, wait for its Retry-After first. Then send the same bytes to that endpoint. The API compares digests, so this is safe whatever happened to the device upload and whatever the session’s status; only a deleted session answers otherwise.
  3. Act on the answer, and on nothing else:
Outcome of the replay
AnswerMeaningTell the device
202This exact body is the session’s transcript, whether it was accepted now or by the earlier attempt.Accepted.
409 transcript_already_acceptedA different transcript was accepted before. This one was not, and will not be.Not accepted. Staff must look at it.
409 session_closedThe session accepts no further upload: it was deleted, or its upload deadline passed before any transcript was accepted. This says nothing about an earlier upload: a deleted session may already have had its transcript accepted and processed.No further upload is possible. Prior receipt is unknown. Do not resubmit automatically; staff decide.
Any other 409, one whose code cannot be read, or 404 not_found (the tombstone is gone)Final, but it says nothing about an earlier upload.Staff review. Keep the body, treat prior receipt as unknown, and do not retry automatically.
400, 413, 415, 422The body itself is invalid, for example too short. Sending it again cannot succeed.Rejected, with the problem code. Do not retry.
429Wait for Retry-After seconds, then send the same bytes again. Being rate limited never ends recovery.Submission unconfirmed.
Timeout or 5xxStill unknown. Keep the session id and the body, and send the same bytes again.Submission unconfirmed.

The device puts the session id and the serialized body into its UI state before it sends anything, and keeps them until the outcome is definitive. Until then it shows “submission unconfirmed” and tries again with the same bytes; an answer that cannot be read counts as no answer. Only one recovery runs per session: a manual “Try again” joins the one in progress, and nothing changes the screen after a definitive outcome. Branch on the problem code, not on the status: both a different transcript and a closed session answer 409, and a 409 whose code cannot be read or is not recognized goes to staff review, with the body kept and no automatic retry. The upload is registered as one operation before the UI holds it, so a “Try again” pressed while the device request is still outstanding joins that request, and only the caller that started it reports the outcome. A different body for the same session gets its own replay and its own answer.

Browser · submit-transcript.ts
// Browser side: submit a transcript with the single-use upload token, and keep it until it is settled.

const API = 'https://api.aimedintake.com/v1';

/**
 * accepted:    this exact body is the session's transcript.
 * conflict:    a different transcript was accepted earlier. Tell staff.
 * closed:      no further upload is possible. Whether an earlier upload was received is unknown.
 * review:      a 409 whose problem code could not be read or is not one of the above, or a session that
 *              no longer exists (404 to your backend's replay). Final: never
 *              resubmit automatically. Prior receipt is unknown. Keep the pending upload for staff.
 * rejected:    the body itself is invalid; `code` says why. Sending it again cannot succeed.
 * unconfirmed: still unknown after every retry. Keep the pending upload and try again later.
 */
export type UploadResult =
  | { outcome: 'accepted' | 'conflict' | 'closed' | 'review' | 'unconfirmed' }
  | { outcome: 'rejected'; code: string };

/** What must be kept, unchanged, until the outcome is definitive. */
export interface PendingUpload {
  sessionId: string;
  /** The serialized JSON body. Build it once: every retry must send the same bytes. */
  body: string;
  endpoint: 'transcript' | 'ambient-note';
}

export interface SubmitOptions {
  /** Called each time the outcome is still unknown, so the UI can show "submission unconfirmed". */
  onUnconfirmed?: (pending: PendingUpload) => void;
  /** Recovery attempts before giving up with "unconfirmed". */
  attempts?: number;
  /** Seconds between recovery attempts when no delay is named. */
  retrySeconds?: number;
}

const OUTCOMES = ['accepted', 'conflict', 'closed', 'review', 'rejected'];
const wait = (seconds: number) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

/**
 * Seconds to wait: the Retry-After value when it is a number of seconds, otherwise the default.
 * (An HTTP date, or a header the browser may not read, falls back to the default.
 * The API exposes Retry-After to registered origins on the two upload routes.)
 */
function retryAfter(response: Response | undefined, otherwise: number): number {
  const seconds = Number(response?.headers.get('Retry-After') ?? NaN);
  return Number.isFinite(seconds) && seconds >= 0 ? seconds : otherwise;
}

async function definitive(response: Response): Promise<UploadResult> {
  const code: unknown = await response.json().then((problem) => problem?.code, () => undefined);
  if (response.status === 409) {
    if (code === 'transcript_already_accepted') return { outcome: 'conflict' };
    if (code === 'session_closed') return { outcome: 'closed' };
    // A 409 we cannot read is still final, but it could mean a deleted session that had
    // this transcript: it is not proof that the body was invalid.
    return { outcome: 'review' };
  }
  return { outcome: 'rejected', code: typeof code === 'string' ? code : `http_${response.status}` };
}

// One operation per pending upload: the device request and any recovery after it.
// A second call with the same session, endpoint and bytes joins the operation in flight.
const operations = new Map<string, Promise<UploadResult>>();
// The latest operation of each session. A different body for the same session waits for it.
const latest = new Map<string, Promise<UploadResult>>();

function once(pending: PendingUpload, run: () => Promise<UploadResult>): Promise<UploadResult> {
  const key = JSON.stringify([pending.sessionId, pending.endpoint, pending.body]);
  const running = operations.get(key);
  if (running) return running;
  // Starts after the session's previous operation, and never in the same tick: the caller can
  // put `pending` into UI state after registering and before anything is sent.
  const previous = latest.get(pending.sessionId) ?? Promise.resolve();
  const operation: Promise<UploadResult> = previous.then(run, run).finally(() => {
    if (operations.get(key) === operation) operations.delete(key);
    if (latest.get(pending.sessionId) === operation) latest.delete(pending.sessionId);
  });
  operations.set(key, operation);
  latest.set(pending.sessionId, operation);
  return operation;
}

async function recover(pending: PendingUpload, options: SubmitOptions, delaySeconds: number): Promise<UploadResult> {
  const { attempts = 5, retrySeconds = 5 } = options;
  if (delaySeconds > 0) await wait(delaySeconds); // a delay the API asked for comes first
  for (let attempt = 0; attempt < attempts; attempt += 1) {
    let response: Response | undefined;
    try {
      response = await fetch(`/api/intake-sessions/${pending.sessionId}/${pending.endpoint}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: pending.body,
      });
      if (response.ok) {
        // Reading the answer can fail too. Only a well-formed outcome counts.
        const result = await response.json();
        if (OUTCOMES.includes(result?.outcome)) return result;
      }
    } catch {
      // Network failure, timeout, or an answer that broke off: still unknown.
    }
    // Not settled. Say so, wait, and send the same bytes again.
    options.onUnconfirmed?.(pending);
    if (attempt < attempts - 1) await wait(retryAfter(response, retrySeconds));
  }
  return { outcome: 'unconfirmed' };
}

/**
 * Asks your backend to replay the pending bytes with its secret key; it answers { outcome }.
 * While an upload or recovery of these same bytes is running, this returns that operation:
 * it starts no second request and cannot overtake the first. A different body for the
 * same session is replayed after it, and gets its own answer.
 */
export function recoverPending(pending: PendingUpload, options: SubmitOptions = {}): Promise<UploadResult> {
  return once(pending, () => recover(pending, options, 0));
}

/**
 * Registers the upload as the one operation for these bytes, then sends it once the caller's
 * current code has run. A recoverPending() for the same bytes, such as a "Try again" pressed
 * while the device request is outstanding, joins this operation.
 */
export function submitTranscript(
  pending: PendingUpload,
  uploadToken: string,
  options: SubmitOptions = {},
): Promise<UploadResult> {
  return once(pending, () => upload(pending, uploadToken, options));
}

async function upload(pending: PendingUpload, uploadToken: string, options: SubmitOptions): Promise<UploadResult> {
  let response: Response | undefined;
  try {
    response = await fetch(`${API}/sessions/${pending.sessionId}/${pending.endpoint}`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${uploadToken}`, 'Content-Type': 'application/json' },
      body: pending.body,
    });
  } catch {
    // Network failure: the transcript may or may not have been accepted.
  }

  // Definitive answers are reported at once, and never retried.
  if (response?.status === 202) return { outcome: 'accepted' };
  if (response && [400, 409, 413, 415, 422].includes(response.status)) return definitive(response);

  // Anything else is uncertain: no response, 401 after a lost response, 429 or 5xx.
  // The token is single use, so never retry with it. Respect the delay the API asked for,
  // then hand the same bytes to your backend.
  return recover(pending, options, response?.status === 429 ? retryAfter(response, 1) : 0);
}
Server · settle an uncertain upload
import time

import os
import requests

API = "https://api.aimedintake.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['AIMEDINTAKE_API_KEY']}"}


def problem_code(response):
    """The problem code, or the HTTP status when the body is not a problem document."""
    try:
        return response.json()["code"]
    except (ValueError, KeyError, TypeError):
        return f"http_{response.status_code}"


def recover_upload(session_id, raw_body, mode):
    """Settle an upload the device could not confirm.

    raw_body is the exact JSON the device tried to upload, unchanged. mode is the
    session's mode, stored by your backend when it created the session, so a key
    with only the sessions:write scope is enough.

    Returns {"outcome": ...}: "accepted" (this exact body is the transcript), "conflict"
    (a different transcript was accepted earlier: tell staff), "closed" (no further upload
    is possible; prior receipt is unknown; do not resubmit), "review" (a 409 whose code could
    not be read or is not one of these, or a 404 because the session's tombstone is gone: final,
    prior receipt unknown, staff decide) or "rejected" with the problem
    "code" (the body itself is invalid: never retry). Answer 200 with this object, and 503
    when this raises, so that the device keeps its bytes and asks again.
    """
    endpoint = "ambient-note" if mode == "ambient" else "transcript"

    # Replay the same bytes. The API compares digests: once a transcript was accepted, the
    # same body returns the original 202, whatever the session's status, and a different body
    # returns 409 transcript_already_accepted. A deleted session returns 409 session_closed while
    # its tombstone exists and 404 not_found after removal.
    for _ in range(5):
        # stream=True: the status is known before the body is read, so a body that breaks
        # off can still be told apart by status.
        with requests.post(
            f"{API}/sessions/{session_id}/{endpoint}",
            headers={**HEADERS, "Content-Type": "application/json"},
            data=raw_body,
            timeout=30,
            stream=True,
        ) as response:
            if response.status_code == 202:
                return {"outcome": "accepted"}
            if response.status_code == 429:
                delay = response.headers.get("Retry-After", "")
                time.sleep(int(delay) if delay.isascii() and delay.isdigit() else 1)  # then the same bytes
                continue
            try:
                code = problem_code(response)
            except requests.RequestException:
                code = None  # the problem body broke off
            if code == "transcript_already_accepted":
                return {"outcome": "conflict"}
            if code == "session_closed":
                return {"outcome": "closed"}
            if response.status_code == 409:
                return {"outcome": "review"}  # unreadable or unknown 409: final, prior receipt unknown
            if response.status_code == 404:
                return {"outcome": "review"}  # the session's tombstone is gone: final, prior receipt unknown
            code = code or f"http_{response.status_code}"
            if response.status_code in (400, 413, 415, 422):
                return {"outcome": "rejected", "code": code}  # definitive: the body is invalid
            raise RuntimeError(f"Upload not settled: {code}")
    # Still rate limited. Not an outcome: answer 503 so the device keeps the body and asks again.
    raise RuntimeError("Upload not settled: rate_limited")

Creating the session again returns a fresh upload token only while the session is created, which is useful when the device never managed to send anything. The same rules apply to POST /sessions/{id}/ambient-note.

End reason

end_reason records why the conversation ended. When the assistant ends an interview it states one of four reasons, which your client reports with the transcript. The value is stored on the session, and it decides whether the session is billable. Usage records carry the billing outcome, not the reason. Ambient sessions have no end reason.

End reasons
ValueMeaningBillable
normal_completionThe patient confirmed the summary and the assistant closed the interview.Yes
initial_refusalThe patient declined at the opening consent question. No medical questions were asked.No
patient_stopThe patient asked to stop after consenting.Yes, unless the transcript has fewer than 3 patient utterances
emergencyThe assistant recognised a possible emergency, told the patient to seek urgent help and ended the interview.No
disconnectedThe call dropped without the assistant ending it.Yes
otherAnything else. The default when the field is omitted.Yes

When your own interface ends the call, for example from a Stop button, the assistant gives no reason and your client chooses one. The sample client reports patient_stop when the patient has spoken fewer than three times, and other after that.

The value is reported by your client and recorded as stated; the API does not verify it. Sessions of test organizations are never billable. See Usage records. Because a value such as emergency is information about the person, it is cleared when the session is deleted.

Expiry

A session with no accepted transcript by upload_expires_at becomes expired. The window is 24 hours from creation by default. An expired session produces no result and no usage record, its upload token stops working, and further uploads fail with 409 session_closed. Abandoned calls therefore need no cleanup on your side.