Get started
Quickstart
Create a session, run the call in your interface, receive the webhook and fetch the result, end to end.
This guide takes one voice intake interview from start to finish: your server creates a session, your interface runs the call, and your server receives a webhook and reads the result. Allow about thirty minutes.
1. Get your keys
Keys are issued to your organization when you are onboarded. Request access if you do not have them yet. You receive:
| Credential | Looks like | Use |
|---|---|---|
| Test secret key | sk_test_… | Development, with synthetic data only. Never billed. |
| Live secret key | sk_live_… | Production. |
| Webhook signing secret | whsec_… | Verifying that events come from us. One per environment. |
Start with the test key. Keep both values on your server, in environment variables, and replace the placeholders below with the real values: the webhook receiver in step 5 refuses to start with a placeholder secret.
export AIMEDINTAKE_API_KEY="sk_test_..."
export AIMEDINTAKE_WEBHOOK_SECRET="whsec_..."2. Create a session
From your server, create a session with your own reference for the encounter and the interview language. The reference makes the call idempotent: sending the same request again returns the same 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 };The response is the session plus everything the interface needs: voice to open the call and upload_token to submit the transcript afterwards.
{
"id": "ses_01JDK8Z3Q4",
"object": "session",
"external_ref": "visit-000481",
"status": "created",
"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": null,
"completed_at": null,
"updated_at": "2027-01-12T13:02:11Z",
"purge_at": null,
"end_reason": null,
"error": null,
"deleted": null,
"created": true,
"voice": {
"provider": "xai",
"ws_url": "wss://api.x.ai/v1/realtime?model=grok-voice-3.0",
"client_secret": "xai-realtime-client-secret-EXAMPLE",
"client_secret_expires_at": 1799759231,
"session_config": {
"model": "grok-voice-3.0",
"instructions": "You are Ana, an AI intake assistant for your care team. Ask one question at a time…",
"voice": "eve",
"sample_rate": 24000,
"turn_detection": {
"type": "server_vad",
"idle_timeout_ms": null,
"silence_duration_ms": 500
},
"transcription": {
"model": "grok-transcribe",
"language_hint": "en",
"keyterms": [
"hypertension",
"metformin",
"shortness of breath"
]
},
"greeting_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?",
"tools": [
{
"type": "function",
"name": "hangUp",
"description": "End the interview after the final spoken statement.",
"parameters": {
"type": "object",
"properties": {
"reason": {
"type": "string",
"enum": [
"initial_refusal",
"normal_completion",
"patient_stop",
"emergency"
]
}
},
"required": [
"reason"
],
"additionalProperties": false
}
}
]
}
},
"upload_token": "upl_3kTq8ZxV1mN0pLr7EXAMPLE"
}3. Start the call in your UI
Pass voice and upload_token to your interface. The browser opens a WebSocket directly to the realtime voice provider with the short-lived client_secret, sends the configuration it was given, and streams microphone audio. The assistant speaks first, discloses that it is an AI and asks for consent before any medical question. Give the patient a Stop button as well.
Your backend stores the session’s mode for later and passes on the session status too. If the session already existed and is past created, there are no credentials and no call to start: show where the session stands instead.
The Browser voice connection guide contains a complete clientrunIntakeCall, that you can copy. With it, the interface code is short:
// Browser side: one intake interview from the Start button to a settled upload.
import { runIntakeCall, VoiceCallError, type CallResult, type LateTranscription, type Utterance } from './voice-call';
import { recoverPending, submitTranscript, type PendingUpload, type UploadResult } from './submit-transcript';
/** The screens of your interface. Replace these with your own. */
export interface InterviewUi {
/** The session already exists and is past "created": show where it stands, start no call. */
showSessionStatus(sessionId: string, status: string): void;
/** The call failed. `partial` is for staff; it is not a finished interview. */
showCallFailed(partial: Utterance[]): void;
/**
* A patient transcription arrived after the deadline. Flag this session and item for staff review.
* For late_gap, text is the last nonblank wording before the empty final.
*/
flagForReview(late: LateTranscription): void | Promise<void>;
/**
* Review records whose delivery through flagForReview failed or had not settled when the call ended.
* Keep them in a queue you own and retry later. Must not throw. A record with `pending: true` may still
* arrive through flagForReview too: both paths must upsert under the same (sessionId, itemId) key.
*/
queueForReview(records: LateTranscription[]): void;
/** Called before anything is sent: keep `pending` in your UI state until an outcome is shown. */
holdPending(pending: PendingUpload): void;
/** The outcome is still unknown. Show "submission unconfirmed" and offer `retryUpload(pending, ui)`. */
showUnconfirmed(pending: PendingUpload): void;
/** This interview was received. The only success. */
showThanks(): void;
/** A different transcript was already accepted for this session. Staff must look at it. */
showConflict(): void;
/** No further upload is possible. Prior receipt is unknown. Never resubmit automatically. */
showClosed(): void;
/** The transcript itself was refused, for example as too short. Staff see the code. */
showRejected(code: string): void;
/**
* The API answered 409 with a reason that could not be read, or the session no longer exists.
* Final: never resubmit automatically.
* Prior receipt is unknown: keep `pending` for staff to review.
*/
showReview(pending: PendingUpload): void;
}
function report(result: UploadResult, pending: PendingUpload, ui: InterviewUi): void {
switch (result.outcome) {
case 'accepted': return ui.showThanks();
case 'conflict': return ui.showConflict();
case 'closed': return ui.showClosed();
case 'rejected': return ui.showRejected(result.code);
case 'review': return ui.showReview(pending);
default: return ui.showUnconfirmed(pending);
}
}
// Each upload operation is reported once, however many callers wait for it.
const reported = new WeakSet<Promise<UploadResult>>();
async function reportOnce(operation: Promise<UploadResult>, pending: PendingUpload, ui: InterviewUi): Promise<void> {
let result: UploadResult;
try {
result = await operation;
} catch {
result = { outcome: 'unconfirmed' }; // whatever went wrong, the interview is still held
}
if (reported.has(operation)) return; // a "Try again" that joined it: the first caller reports
reported.add(operation);
report(result, pending, ui);
}
/**
* Retry a pending upload later, with the same bytes, for example from a "Try again" button.
* If the upload or a recovery of these bytes is still running, this joins it, starts nothing
* new, and leaves reporting the outcome to the caller that started it.
*/
export function retryUpload(pending: PendingUpload, ui: InterviewUi): Promise<void> {
return reportOnce(recoverPending(pending, { onUnconfirmed: (held) => ui.showUnconfirmed(held) }), pending, ui);
}
export async function runInterview(stopButton: HTMLButtonElement, ui: InterviewUi): Promise<void> {
// Stop must work from the first moment: bind it before anything is awaited.
const stop = new AbortController();
stopButton.onclick = () => stop.abort();
// 1. Ask your own backend to create the session (step 2).
let session: { session_id: string; status: string; voice?: Parameters<typeof runIntakeCall>[0]; upload_token?: string };
try {
const created = await fetch('/api/intake-sessions', { method: 'POST', signal: stop.signal });
if (!created.ok) throw new Error('Could not start the interview');
session = await created.json();
} catch (error) {
if (stop.signal.aborted) return; // stopped while the session was being created
throw error;
}
if (stop.signal.aborted) return; // never ask for the microphone after Stop
// The session already has its transcript: do not start another call.
if (session.status !== 'created' || !session.voice || !session.upload_token) {
return ui.showSessionStatus(session.session_id, session.status);
}
// 2. Run the interview. It ends when the assistant closes it, or when the patient presses Stop.
let call: CallResult;
try {
call = await runIntakeCall(session.voice, {
signal: stop.signal,
sessionId: session.session_id,
onLateTranscription: (late) => ui.flagForReview(late),
});
} catch (error) {
// The call failed, or part of it could not be transcribed: nothing is uploaded, no success is shown.
if (error instanceof VoiceCallError && error.undelivered.length) ui.queueForReview([...error.undelivered]);
return ui.showCallFailed(error instanceof VoiceCallError ? error.utterances : []);
}
if (call.undelivered?.length) ui.queueForReview([...call.undelivered]); // before any other outcome
// Nothing was said: there is no transcript to submit. The session expires by itself.
if (call.utterances.length === 0) return;
// 3. Build the body once and register its upload, then put it in UI state before it is sent.
// Registering first means a "Try again" pressed while the device request is outstanding
// joins that request. The body stays in UI state, unchanged, until the outcome is definitive.
const pending: PendingUpload = {
sessionId: session.session_id,
endpoint: 'transcript',
body: JSON.stringify({
utterances: call.utterances,
ended_at: new Date().toISOString(),
end_reason: call.endReason,
}),
};
const upload = submitTranscript(pending, session.upload_token, {
onUnconfirmed: (held) => ui.showUnconfirmed(held),
});
ui.holdPending(pending); // the request starts only after this returns
await reportOnce(upload, pending, ui);
}Three things in this flow matter for patients. The Stop button is bound before anything is awaited, so pressing it while the session is still being created means the microphone is never requested. A call that fails, including one that ran to its end but where part of the patient’s speech could not be transcribed, is shown to staff and never uploaded as a finished interview. And the transcript is put into pending state before it is sent and stays there, unchanged, until the upload has a definitive outcome; until then the screen says the submission is unconfirmed. If a patient transcription arrives after the deadline while the connection is still open, flagForReview receives the session ID, item ID, and text for staff review. Records whose delivery failed or had not settled go to queueForReview, a queue you own, before any outcome is shown, so none is lost. A record marked pending: true may still arrive through flagForReview as well: both paths must upsert under the same (sessionId, itemId) key.
4. Submit the transcript
The sample above already submits the transcript from the browser with the upload token, through submitTranscript from When an upload is uncertain. You can equally send it from your server with your secret key, which is the easiest way to try the API before you build the interface. Use the id returned by the create request; for curl, put it in SESSION_ID.
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)}`);The API answers 202 and starts processing. Only 202 means accepted. For every other answer, follow the outcome rules in When an upload is uncertain: 409 is decided by its problem code, and one that cannot be read goes to staff review; 400, 413, 415 and 422 reject the body; 401, 429, a timeout or a 5xx leave the outcome unknown, so your server replays the same bytes.
{
"id": "ses_01JDK8Z3Q4",
"status": "processing",
"transcript_digest": "sha256:e94ada0c075c47abfa26f36d58e4b2bbf6e6c0fa225991e3d273fe744359ecdf",
"accepted_at": "2027-01-12T13:09:02Z"
}5. Receive the webhook
When processing finishes, we send a signed session.completed event to the HTTPS endpoint registered for your organization. Processing typically finishes within a minute and can take a few minutes for long conversations. The event carries the event and session ids, the time and the mode, and no transcript or result text:
{
"id": "evt_01JDKD0V8N",
"type": "session.completed",
"created_at": "2027-01-12T13:09:41Z",
"session": "ses_01JDK8Z3Q4",
"data": {
"status": "completed",
"mode": "intake"
}
}Verify the signature against the raw request body, queue the event, and answer with a 2xx status. The verification function is in the Webhooks guide.
import os
from flask import Flask, request
from verify_webhook import verify_webhook, webhook_key # see the Webhooks guide
SECRET = os.environ.get("AIMEDINTAKE_WEBHOOK_SECRET")
webhook_key(SECRET) # refuse to start with a missing or malformed secret
app = Flask(__name__)
@app.post("/webhooks/aimedintake")
def receive():
ok = verify_webhook(
SECRET,
request.headers.get("webhook-id", ""),
request.headers.get("webhook-timestamp", ""),
request.headers.get("webhook-signature", ""),
request.get_data(), # the raw bytes, not the parsed JSON
)
if not ok:
return "", 400
event = request.get_json()
# One atomic insert keyed by the event id: a duplicate delivery changes nothing.
queue.insert_if_absent(event["id"], event)
return "", 204import { createServer } from 'node:http';
import { verifyWebhook, webhookKey } from './verify-webhook'; // see the Webhooks guide
const secret = process.env.AIMEDINTAKE_WEBHOOK_SECRET;
webhookKey(secret); // refuse to start with a missing or malformed secret
createServer(async (request, response) => {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(chunk as Buffer);
const rawBody = Buffer.concat(chunks); // the raw bytes, not the parsed JSON
const ok = verifyWebhook(
secret,
{
id: String(request.headers['webhook-id'] ?? ''),
timestamp: String(request.headers['webhook-timestamp'] ?? ''),
signature: String(request.headers['webhook-signature'] ?? ''),
},
rawBody,
);
if (!ok) {
response.writeHead(400).end();
return;
}
const event = JSON.parse(rawBody.toString('utf8'));
// One atomic insert keyed by the event id: a duplicate delivery changes nothing.
await queue.insertIfAbsent(event.id, event);
response.writeHead(204).end();
}).listen(8080);6. Fetch the result
Use the session id from the verified event to read the result from your server, and write it to your own record store. Do not print or log clinical output.
curl "https://api.aimedintake.com/v1/sessions/$SESSION_ID/result" \
-H "Authorization: Bearer $AIMEDINTAKE_API_KEY"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 store_result(session_id):
"""Call with the session id from a verified session.completed event."""
response = requests.get(f"{API}/sessions/{session_id}/result", headers=HEADERS, timeout=30)
if response.status_code == 410:
return # deleted or purged before it was fetched: there is nothing to store
if not response.ok:
raise RuntimeError(f"No result: {problem_code(response)}")
result = response.json()
# Write to your protected record store. Never print or log clinical output.
if result["mode"] == "ambient":
records.save_note(session_id, result["ambient_note"], result["transcript"])
else:
records.save_intake(
session_id,
summary=result["summary"]["text"],
decision_support=(result["decision_support"] or {}).get("text"),
code_suggestions=result["code_suggestions"],
transcript=result["transcript"],
)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}`;
}
}
/** Call with the session id from a verified session.completed event. */
async function storeResult(sessionId: string): Promise<void> {
const response = await fetch(`${API}/sessions/${sessionId}/result`, { headers });
if (response.status === 410) return; // deleted or purged before it was fetched: nothing to store
if (!response.ok) throw new Error(`No result: ${await problemCode(response)}`);
const result = await response.json();
// Write to your protected record store. Never print or log clinical output.
if (result.mode === 'ambient') {
await records.saveNote(sessionId, result.ambient_note, result.transcript);
} else {
await records.saveIntake(sessionId, {
summary: result.summary.text,
decisionSupport: result.decision_support?.text ?? null,
codeSuggestions: result.code_suggestions,
transcript: result.transcript,
});
}
}{
"session": "ses_01JDK8Z3Q4",
"status": "completed",
"mode": "intake",
"language": "en",
"generated_at": "2027-01-12T13:09:40Z",
"transcript_source": "client",
"transcript": [
{
"id": "utt_0001",
"seq": 1,
"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
},
{
"id": "utt_0002",
"seq": 2,
"speaker": "patient",
"text": "Yes, that is fine.",
"start_ms": 6900,
"end_ms": 8100
},
{
"id": "utt_0003",
"seq": 3,
"speaker": "assistant",
"text": "Thank you. What brings you in today?",
"start_ms": 8600,
"end_ms": 10900
},
{
"id": "utt_0004",
"seq": 4,
"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
}
],
"summary": {
"text": "**Chief complaint:** Chest tightness since yesterday evening.\n\n**History:** Exertional, mostly on climbing stairs. No further history was collected."
},
"decision_support": {
"text": "**Considerations for the clinician:** Exertional chest tightness of recent onset warrants prompt assessment, including an ECG."
},
"code_suggestions": [
{
"system": "icd10cm",
"code": "R07.89",
"display": "Other chest pain",
"score": 0.84
},
{
"system": "icd10cm",
"code": "R07.9",
"display": "Chest pain, unspecified",
"score": 0.82
}
],
"ambient_note": null,
"model_ids": {
"summary": "summary-2026-10",
"analysis": "analysis-2026-10"
},
"pipeline_version": "2026.11.2"
}Store what you need in your own system. We delete the clinical data automatically at purge_at, and you can delete it earlier with DELETE /sessions/{id}.
Go live
- Swap the test key and webhook secret for the live ones. Nothing else changes.
- Check that your webhook endpoint validates its secret at startup, verifies signatures, de-duplicates on
webhook-idand answers within 10 seconds. - Handle
session.failedas well assession.completed, and reconcile with listing in case an event is missed. - Give each key the narrowest scopes that its service needs.
- Confirm that
external_refandtagscarry no personal data. - Allow the voice provider’s WebSocket origin in your content security policy.