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
{
"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
| Status | Meaning | What happens next |
|---|---|---|
created | The 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. |
processing | The transcript was accepted and results are being produced. | Ends in completed or failed. |
completed | The result is available. | Final until deletion. A session.completed event is sent. |
failed | Processing failed for good. error.code says why. | Final. A session.failed event is sent. Create a new session to try again. |
expired | No transcript arrived in time. | Final. No usage is recorded. |
deleted | The 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
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"
}
}'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}"
response = requests.post(f"{API}/sessions", headers=HEADERS, timeout=30, json={
"external_ref": "visit-000481",
"language": "en",
"mode": "intake",
"device_type": "kiosk",
"tags": {
"site": "clinic-03",
},
})
if not response.ok:
raise RuntimeError(f"Create failed: {problem_code(response)}")
session = response.json()
# Hand the device only what it needs. The secret key stays on your server.
# Credentials are present only while the session is waiting for its call.
device_payload = {"session_id": session["id"], "status": session["status"]}
if session["status"] == "created":
device_payload["voice"] = session["voice"]
device_payload["upload_token"] = session["upload_token"]const API = 'https://api.aimedintake.com/v1';
const headers = {
Authorization: `Bearer ${process.env.AIMEDINTAKE_API_KEY}`,
'Content-Type': 'application/json',
};
/** The problem code, or the HTTP status when the body is not a problem document. */
async function problemCode(response: Response): Promise<string> {
try {
return (await response.json()).code ?? `http_${response.status}`;
} catch {
return `http_${response.status}`;
}
}
const response = await fetch(`${API}/sessions`, {
method: 'POST',
headers,
body: JSON.stringify({
external_ref: "visit-000481",
language: "en",
mode: "intake",
device_type: "kiosk",
tags: {
site: "clinic-03"
}
}),
});
if (!response.ok) throw new Error(`Create failed: ${await problemCode(response)}`);
const session = await response.json();
// Hand the device only what it needs. The secret key stays on your server.
// Credentials are present only while the session is waiting for its call.
const devicePayload =
session.status === 'created'
? { session_id: session.id, status: session.status, voice: session.voice, upload_token: session.upload_token }
: { session_id: session.id, status: session.status };| Field | Required | Rules |
|---|---|---|
external_ref | Yes | Your opaque reference for the encounter, 1 to 128 characters of A-Z a-z 0-9 . _ : -. No personal data. |
language | Yes | One of the languages enabled for your organization. |
mode | No | intake (default) or ambient. |
device_type | No | kiosk, web, mobile or other (default). |
tags | No | Up 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:
| Existing session | Response | Credentials |
|---|---|---|
| None | 201, created: true | Issued |
Status created | 200, created: false | Reissued: a fresh voice secret and upload token. The previous upload token is revoked. |
Status processing or later | 200, created: false | None |
Same reference, different language or mode | 409 external_ref_conflict | None |
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.
| Setting | Effect |
|---|---|
| Assistant name | The name the assistant uses in its greeting and throughout the interview. |
| Additional instructions | Text appended to the interview instructions, for example topics to cover for your specialty or wording your organization prefers. |
| Enabled languages | The subset of the nine languages your sessions may use. |
| Decision support | On or off. When off, decision_support is null in every result. |
| Retention period | Days until clinical data is purged after the transcript is accepted. 30 by default. |
| Upload window | Hours a session waits for its transcript. 24 by default. |
| Webhook endpoint | The 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-livedclient_secret, and thesession_configto 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.
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"
}'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}"
session_id = session["id"] # from the create response
response = requests.post(f"{API}/sessions/{session_id}/transcript", headers=HEADERS, timeout=30, json={
"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",
})
if response.status_code != 202:
raise RuntimeError(f"Upload failed: {problem_code(response)}")const API = 'https://api.aimedintake.com/v1';
const headers = {
Authorization: `Bearer ${process.env.AIMEDINTAKE_API_KEY}`,
'Content-Type': 'application/json',
};
/** The problem code, or the HTTP status when the body is not a problem document. */
async function problemCode(response: Response): Promise<string> {
try {
return (await response.json()).code ?? `http_${response.status}`;
} catch {
return `http_${response.status}`;
}
}
const sessionId = session.id; // from the create response
const response = await fetch(`${API}/sessions/${sessionId}/transcript`, {
method: 'POST',
headers,
body: JSON.stringify({
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"
}),
});
if (response.status !== 202) throw new Error(`Upload failed: ${await problemCode(response)}`);| Field | Rules |
|---|---|
utterances | 1 to 2,000 items, in spoken order. |
utterances[].speaker | assistant or patient. |
utterances[].text | 1 to 4,000 characters, not blank. |
start_ms, end_ms | Optional. Milliseconds from the start of the call, with end_ms not before start_ms. |
ended_at | Optional. When the call ended. |
end_reason | Optional, 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.
{
"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:
| Repeat sent with | Same body | Different body |
|---|---|---|
| Secret key | The original 202, even after upload_expires_at. No second job starts. | 409 transcript_already_accepted |
| Upload token | 401 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:
- Pick the endpoint from the session’s mode, which your backend stored when it created the session:
/transcriptfor intake,/ambient-notefor ambient. No read is needed, so a key with onlysessions:writecan do this. - If the device was answered
429, wait for itsRetry-Afterfirst. 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. - Act on the answer, and on nothing else:
| Answer | Meaning | Tell the device |
|---|---|---|
202 | This exact body is the session’s transcript, whether it was accepted now or by the earlier attempt. | Accepted. |
409 transcript_already_accepted | A different transcript was accepted before. This one was not, and will not be. | Not accepted. Staff must look at it. |
409 session_closed | The 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, 422 | The body itself is invalid, for example too short. Sending it again cannot succeed. | Rejected, with the problem code. Do not retry. |
429 | Wait for Retry-After seconds, then send the same bytes again. Being rate limited never ends recovery. | Submission unconfirmed. |
| Timeout or 5xx | Still 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 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);
}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")// Server side (Node 18+): settle a transcript upload whose outcome the device could not confirm.
const API = 'https://api.aimedintake.com/v1';
/**
* accepted: this exact body is the session's transcript.
* conflict: a different transcript was accepted earlier (transcript_already_accepted). Tell staff.
* closed: no further upload is possible (session_closed: expired or deleted). Whether an earlier
* upload was received is unknown. Do not resubmit.
* review: a 409 whose problem code could not be read or is not one of the above, or a 404: the
* session no longer exists (its tombstone is removed 90 days after deletion). Final: do not
* resubmit. Prior receipt is unknown. Staff decide.
* rejected: the body itself is invalid; `code` says why. Sending it again cannot succeed.
*/
export type RecoveryResult =
| { outcome: 'accepted' | 'conflict' | 'closed' | 'review' }
| { outcome: 'rejected'; code: string };
async function problemCode(response: Response): Promise<string> {
try {
return (await response.json()).code ?? `http_${response.status}`;
} catch {
return `http_${response.status}`;
}
}
/** Seconds to wait: the Retry-After value when it is a number of seconds, otherwise a default. */
function retryAfter(response: Response, otherwise = 1): number {
const seconds = Number(response.headers.get('Retry-After') ?? NaN);
return Number.isFinite(seconds) && seconds >= 0 ? seconds : otherwise;
}
const wait = (seconds: number) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
/**
* `rawBody` is the exact JSON string the device tried to upload, unchanged.
* `mode` is the session's mode, which your backend stored when it created the session,
* so this needs no read access: a key with only the sessions:write scope is enough.
*
* Have your route answer 200 with the returned object, and 503 when this throws
* (not settled yet: the device keeps its bytes and asks again).
*/
export async function recoverUpload(
sessionId: string,
rawBody: string,
mode: 'intake' | 'ambient',
apiKey: string | undefined = process.env.AIMEDINTAKE_API_KEY,
): Promise<RecoveryResult> {
const headers = { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' };
const endpoint = mode === 'ambient' ? 'ambient-note' : '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.
// The session's status is never consulted: "processing" would not say which transcript arrived.
for (let attempt = 0; attempt < 5; attempt += 1) {
const response = await fetch(`${API}/sessions/${sessionId}/${endpoint}`, { method: 'POST', headers, body: rawBody });
if (response.status === 202) return { outcome: 'accepted' };
if (response.status === 429) {
await wait(retryAfter(response)); // rate limited: wait, then send the same bytes
continue;
}
const code = await problemCode(response);
if (code === 'transcript_already_accepted') return { outcome: 'conflict' };
if (code === 'session_closed') return { outcome: 'closed' };
// Any other 409, or one whose body could not be read: final, but prior receipt is unknown.
if (response.status === 409) return { outcome: 'review' };
// Authenticated, yet the session is unknown: its tombstone is gone. Final; prior receipt is unknown.
if (response.status === 404) return { outcome: 'review' };
// The request itself is wrong (too short, too long, malformed...): definitive, never retried.
if ([400, 413, 415, 422].includes(response.status)) return { outcome: 'rejected', code };
throw new Error(`Upload not settled: ${code}`);
}
// Still rate limited. Not an outcome: answer 503 so the device keeps the body and asks again.
throw new Error('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.
| Value | Meaning | Billable |
|---|---|---|
normal_completion | The patient confirmed the summary and the assistant closed the interview. | Yes |
initial_refusal | The patient declined at the opening consent question. No medical questions were asked. | No |
patient_stop | The patient asked to stop after consenting. | Yes, unless the transcript has fewer than 3 patient utterances |
emergency | The assistant recognised a possible emergency, told the patient to seek urgent help and ended the interview. | No |
disconnected | The call dropped without the assistant ending it. | Yes |
other | Anything 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.