# cancel avatar video Source: https://anam.ai/docs/api-reference/avatar-videos/cancel-an-avatar-video https://api.anam.ai/swagger.json post /v1/avatar-videos/{id}/cancel Requests a clean worker/session shutdown. Terminal cancellation is idempotent and any replay that finalizes later remains accessible. # create avatar video Source: https://anam.ai/docs/api-reference/avatar-videos/create-an-avatar-video https://api.anam.ai/swagger.json post /v1/avatar-videos Creates an asynchronous avatar-video render backed by a normal recorded Anam session. A saved persona contributes only its snapshotted avatar, voice, language, model and director notes; its greeting, brain, prompt and tools never run. The request is rejected rather than queued when either concurrency limit is full. # get avatar video Source: https://anam.ai/docs/api-reference/avatar-videos/get-an-avatar-video https://api.anam.ai/swagger.json get /v1/avatar-videos/{id} Returns authoritative job state and a fresh one-hour recording URL when the canonical replay is ready. A read also reconciles late recordings. # list avatar videos Source: https://anam.ai/docs/api-reference/avatar-videos/list-avatar-videos https://api.anam.ai/swagger.json get /v1/avatar-videos # retry avatar video Source: https://anam.ai/docs/api-reference/avatar-videos/retry-an-avatar-video https://api.anam.ai/swagger.json post /v1/avatar-videos/{id}/retry Creates a new job from the original immutable snapshot and links it through retryOf. Only terminal jobs can be retried. # create avatar Source: https://anam.ai/docs/api-reference/avatars/create-avatar https://api.anam.ai/swagger.json post /v1/avatars Create a new one-shot avatar from an image file or image URL. You can use either multipart/form-data with an image file, or JSON with an image URL. Every plan includes unlimited saved custom avatars. Image moderation quotas and creation capacity limits still apply. # delete avatar Source: https://anam.ai/docs/api-reference/avatars/delete-avatar https://api.anam.ai/swagger.json delete /v1/avatars/{id} Delete an avatar by ID. By default this is a soft delete: the avatar disappears from Lab and the API, which can't restore it, and its stored assets are kept. Pass `hard=true` to permanently purge the avatar and its stored assets (source image and generated versions). A hard delete cannot be undone and is intended for data-erasure requests; it also purges avatars that were previously soft-deleted. Stored assets are kept while another avatar still uses them, such as a copy Anam made for another organization. Deleting the last avatar that uses them starts the purge, which runs after the response and is best effort. A hard delete never deletes personas: when active personas (or their drafts) still use the avatar the request fails with `409 Conflict` and the impacted persona IDs. Move those personas to another avatar (e.g. `PUT /v1/personas/{id}` with a new `avatarId`) and retry. # get avatar Source: https://anam.ai/docs/api-reference/avatars/get-avatar https://api.anam.ai/swagger.json get /v1/avatars/{id} Returns an avatar by ID # list avatars Source: https://anam.ai/docs/api-reference/avatars/list-avatars https://api.anam.ai/swagger.json get /v1/avatars Returns a list of all avatars. A search or filter that matches none answers 200 with an empty `data` list. # update avatar Source: https://anam.ai/docs/api-reference/avatars/update-avatar https://api.anam.ai/swagger.json put /v1/avatars/{id} Update an avatar by ID (only display name can be updated) # create engine session Source: https://anam.ai/docs/api-reference/engine/create-engine-session https://api.anam.ai/swagger.json post /v1/engine/session Start a live persona session. Two authentication modes are supported via the `Authorization: Bearer` header: - **Session token** (browser clients): pass a session token minted by `POST /v1/auth/session-token`. The session configuration was bound to the token when it was created, so the body only carries optional `clientMetadata`. This is the flow the client-side SDKs use; you normally don't call this endpoint yourself. - **API key** (server-side SDKs): pass your API key directly and supply the session configuration in the request body — the same shape as the `/v1/auth/session-token` body (`personaConfig`, `environment`, `sessionOptions`, plus optional `clientLabel` and `clientMetadata`; `expiresInSeconds`, `maxSessions` and `widgetConfig` do not apply). This skips the session-token exchange. Only use this from a secure server-side context — never expose an API key in a browser. # create knowledge group Source: https://anam.ai/docs/api-reference/knowledge/create-knowledge-group https://api.anam.ai/swagger.json post /v1/knowledge/groups Create a new knowledge group # delete knowledge document Source: https://anam.ai/docs/api-reference/knowledge/delete-knowledge-document https://api.anam.ai/swagger.json delete /v1/knowledge/documents/{id} Delete a document from a knowledge folder # delete knowledge group Source: https://anam.ai/docs/api-reference/knowledge/delete-knowledge-group https://api.anam.ai/swagger.json delete /v1/knowledge/groups/{id} Delete a knowledge folder # get knowledge document Source: https://anam.ai/docs/api-reference/knowledge/get-knowledge-document https://api.anam.ai/swagger.json get /v1/knowledge/documents/{id} Get a single document by ID # get knowledge document download Source: https://anam.ai/docs/api-reference/knowledge/get-knowledge-document-download https://api.anam.ai/swagger.json get /v1/knowledge/documents/{id}/download Get a presigned download URL for a knowledge document # get knowledge group Source: https://anam.ai/docs/api-reference/knowledge/get-knowledge-group https://api.anam.ai/swagger.json get /v1/knowledge/groups/{id} Get a single knowledge folder by ID # list knowledge group documents Source: https://anam.ai/docs/api-reference/knowledge/list-knowledge-group-documents https://api.anam.ai/swagger.json get /v1/knowledge/groups/{id}/documents Get all documents in a knowledge folder # list knowledge groups Source: https://anam.ai/docs/api-reference/knowledge/list-knowledge-groups https://api.anam.ai/swagger.json get /v1/knowledge/groups Returns a list of all knowledge groups for the organization # search knowledge group Source: https://anam.ai/docs/api-reference/knowledge/search-knowledge-group https://api.anam.ai/swagger.json post /v1/knowledge/groups/{id}/search Search for similar content in a knowledge folder using vector similarity. Limited to 60 valid search requests per UTC minute per organization, shared across API keys and groups. Requests are allowed if the rate-limit store is unavailable. # update knowledge document Source: https://anam.ai/docs/api-reference/knowledge/update-knowledge-document https://api.anam.ai/swagger.json put /v1/knowledge/documents/{id} Update a document (rename) # update knowledge group Source: https://anam.ai/docs/api-reference/knowledge/update-knowledge-group https://api.anam.ai/swagger.json put /v1/knowledge/groups/{id} Update a knowledge folder # upload knowledge group document Source: https://anam.ai/docs/api-reference/knowledge/upload-knowledge-group-document https://api.anam.ai/swagger.json post /v1/knowledge/groups/{id}/documents Upload a document to a knowledge folder (Supports PDF, TXT, MD, DOCX, CSV, JSON up to 50MB). Authentication can be via API key (Bearer token) OR upload token (X-Upload-Token header). # create llm Source: https://anam.ai/docs/api-reference/llms/create-llm https://api.anam.ai/swagger.json post /v1/llms Create a new LLM configuration # delete llm Source: https://anam.ai/docs/api-reference/llms/delete-llm https://api.anam.ai/swagger.json delete /v1/llms/{id} Delete an LLM configuration. When active personas (or their working drafts) still use the LLM, the request is refused with 409 because deleting it would make those personas' sessions fail. Move the impacted personas to another LLM (PUT /v1/personas/{id}), then retry. # get llm Source: https://anam.ai/docs/api-reference/llms/get-llm https://api.anam.ai/swagger.json get /v1/llms/{id} Get a specific LLM by ID # list llms Source: https://anam.ai/docs/api-reference/llms/list-llms https://api.anam.ai/swagger.json get /v1/llms Returns a list of all LLMs available to the organization # update llm Source: https://anam.ai/docs/api-reference/llms/update-llm https://api.anam.ai/swagger.json put /v1/llms/{id} Update an LLM configuration # cancel meeting invite Source: https://anam.ai/docs/api-reference/meetings/cancel-meeting-invite https://api.anam.ai/swagger.json delete /v1/meetings/invites/{id} Cancel a pending meeting invite by ID for the authenticated organization. Cancellation is idempotent for invites that are already `cancelled`, `ended`, or `failed`. A successful cancellation returns no response body. # create meeting invite Source: https://anam.ai/docs/api-reference/meetings/create-meeting-invite https://api.anam.ai/swagger.json post /v1/meetings/invites Invite a persona to join a Google Meet, Zoom, or Microsoft Teams meeting. Provide exactly one of `personaId` for a saved persona, or `personaConfig` for a runtime persona configuration. The runtime persona configuration is used to start the meeting session but is not stored on the meeting invite. The invite is created in `pending` status. `displayName` is normalized to include an AI disclosure suffix before the persona joins the meeting, and the persona's video shows an AI label. Organizations that handle AI disclosure themselves can ask Anam to allow `aiDisclosure: false`, which removes both. By default the persona joins immediately. Provide `joinAt` to schedule the join for a future time; scheduling at least 10 minutes ahead reserves the persona a guaranteed place on the call, which is the most reliable way to join meetings that are planned in advance. # get meeting invite Source: https://anam.ai/docs/api-reference/meetings/get-meeting-invite https://api.anam.ai/swagger.json get /v1/meetings/invites/{id} Get a meeting invite by ID for the authenticated organization. # list meeting invites Source: https://anam.ai/docs/api-reference/meetings/list-meeting-invites https://api.anam.ai/swagger.json get /v1/meetings/invites List meeting invites for the authenticated organization, most recent first. Filter by `status` to find invites in a particular lifecycle state — for example `pending` invites that have not joined yet, or `active` invites currently in a call. # Anam REST API Source: https://anam.ai/docs/api-reference/overview Call the Anam REST API directly, authenticate server-side requests, and find the endpoints for personas, sessions, voices, tools, and knowledge. All endpoints are served under: ``` https://api.anam.ai/v1 ``` ## Get an API key Create a key from the [API keys page](https://lab.anam.ai/api-keys) in the Lab. See [Get your API key](https://anam.ai/docs/javascript-sdk/api-key) for the full walkthrough. Keep the key on your server. Never ship it to a browser or mobile app. ## Authenticate requests Every request takes a bearer token in the `Authorization` header: ```bash theme={"system"} curl https://api.anam.ai/v1/personas \ -H "Authorization: Bearer $ANAM_API_KEY" ``` ## Connecting clients Clients don't use your API key. Your backend creates a short-lived session token with [`POST /v1/auth/session-token`](/docs/api-reference/sessions/create-session-token) and hands it to the client, which uses it to open a WebRTC stream. See [Authentication](https://anam.ai/docs/javascript-sdk/authentication) for a worked server example. ## Conventions * Request and response bodies are JSON. Field names are `camelCase`. * List endpoints accept `page` and `perPage` query parameters and return `{ data: [...], meta: { total, currentPage, perPage, lastPage, prev, next } }`. # create persona Source: https://anam.ai/docs/api-reference/personas/create-persona https://api.anam.ai/swagger.json post /v1/personas Create a new persona # delete persona Source: https://anam.ai/docs/api-reference/personas/delete-persona https://api.anam.ai/swagger.json delete /v1/personas/{id} Soft-delete a persona owned by the authenticated organization. Missing, already deleted, and other organizations' personas return 404 # get persona Source: https://anam.ai/docs/api-reference/personas/get-persona https://api.anam.ai/swagger.json get /v1/personas/{id} Returns a persona by id # list personas Source: https://anam.ai/docs/api-reference/personas/list-personas https://api.anam.ai/swagger.json get /v1/personas Returns a list of all personas # update persona Source: https://anam.ai/docs/api-reference/personas/update-persona https://api.anam.ai/swagger.json put /v1/personas/{id} Update a persona by id # create pronunciation dictionary Source: https://anam.ai/docs/api-reference/pronunciation-dictionaries/create-pronunciation-dictionary https://api.anam.ai/swagger.json post /v1/pronunciation-dictionaries Creates a pronunciation dictionary. Select it for a session with `voiceGenerationOptions.pronunciationDictionaryId`. Entries are validated as a whole: if any entry is invalid, nothing is saved and the response lists every error by one-based row. # delete pronunciation dictionary Source: https://anam.ai/docs/api-reference/pronunciation-dictionaries/delete-pronunciation-dictionary https://api.anam.ai/swagger.json delete /v1/pronunciation-dictionaries/{id} Archives a pronunciation dictionary. It disappears from the API and Lab, and sessions can no longer select it. Archiving is permanent: there is no way to unarchive a dictionary. Its entries and history are kept until your organization is deleted. A dictionary that a persona uses can't be archived: the response is 409 `DICTIONARY_ATTACHED` with the persona IDs. Remove the dictionary from those personas in Lab first. # get pronunciation dictionary Source: https://anam.ai/docs/api-reference/pronunciation-dictionaries/get-pronunciation-dictionary https://api.anam.ai/swagger.json get /v1/pronunciation-dictionaries/{id} Returns a pronunciation dictionary with its entries and current revision. # import pronunciation dictionary Source: https://anam.ai/docs/api-reference/pronunciation-dictionaries/import-pronunciation-dictionary https://api.anam.ai/swagger.json post /v1/pronunciation-dictionaries/import Creates a pronunciation dictionary from a Cartesia pronunciation dictionary file: an array of `{ text, pronunciation, case_sensitive? }` rows, with an optional Anam `sounds_like` fallback. A pronunciation containing `<<` or `>>` is imported as an IPA entry; anything else is a sounds-like entry. The file is validated as a whole: it must hold 1 to 500 rows and at most 1 MiB of UTF-8 JSON. When `json` is an array, the limit applies to the array serialized without whitespace. If any row is invalid, nothing is saved and the response lists every error by one-based row and file field name. # list pronunciation dictionaries Source: https://anam.ai/docs/api-reference/pronunciation-dictionaries/list-pronunciation-dictionaries https://api.anam.ai/swagger.json get /v1/pronunciation-dictionaries Lists your organization's pronunciation dictionaries, newest first. Archived dictionaries are not listed. Entries are omitted; read a dictionary to get them. # update pronunciation dictionary Source: https://anam.ai/docs/api-reference/pronunciation-dictionaries/update-pronunciation-dictionary https://api.anam.ai/swagger.json put /v1/pronunciation-dictionaries/{id} Updates a pronunciation dictionary's name, entries or both. `entries` replaces the whole list. The save is live: sessions that start afterwards use the new entries, and running sessions keep the entries they started with. Without `expectedRevision`, the update applies to the current revision and the last write wins. With it, the update is rejected with 409 `REVISION_CONFLICT` if the dictionary has been saved since that revision. Entries are validated as a whole: if any entry is invalid, nothing is saved and the response lists every error by one-based row. # create session token Source: https://anam.ai/docs/api-reference/sessions/create-session-token https://api.anam.ai/swagger.json post /v1/auth/session-token Create a new session token used to initialise Anam client side SDKs # delete session Source: https://anam.ai/docs/api-reference/sessions/delete-session https://api.anam.ai/swagger.json delete /v1/sessions/{id} Permanently deletes all customer information captured for a session: the session report (transcript, per-turn analytics, tool call details), generated insights, conversation summary, the video recording, the requester IP and location, the client label and client metadata, and the persona configuration recorded with the session (system prompt, personality, initial message, persona name, tool definitions and custom style prompts). The session record itself and its usage records are retained for billing and aggregate statistics, with the session's identifiers, timestamps, duration and settings that hold no content, such as the avatar, voice and model IDs. The session must have ended. This action is irreversible. Idempotent: deleting already-deleted session data succeeds. # delete session recording Source: https://anam.ai/docs/api-reference/sessions/delete-session-recording https://api.anam.ai/swagger.json delete /v1/sessions/{id}/recording Permanently deletes the session's video recording from storage. This removes customer information only — the session record itself and its usage records are retained. The session must have ended. This action is irreversible. Idempotent: deleting an already-deleted recording succeeds. # delete session report Source: https://anam.ai/docs/api-reference/sessions/delete-session-report https://api.anam.ai/swagger.json delete /v1/sessions/{id}/report Permanently deletes the conversation data captured for a session: the session report (transcript, per-turn analytics, tool call details), generated insights, and conversation summary. This removes customer information only — the session record itself and its usage records are retained. The session must have ended. This action is irreversible. Idempotent: deleting an already-deleted report succeeds. # get aggregated session analytics Source: https://anam.ai/docs/api-reference/sessions/get-aggregated-session-analytics https://api.anam.ai/swagger.json get /v1/sessions/analytics Returns aggregated latency analytics across sessions — percentile distributions (p50/p90/p95/p99/max/avg) for each stage of the transcription → LLM → TTS → first-audio path, interruption and error rates, tool call outcomes, and a sample of the slowest turns. Only sessions where Anam runs the conversational pipeline (turnkey, custom LLM and ElevenLabs agent sessions) produce analytics reports; LiveKit and audio-passthrough sessions count toward `sessionCount` but never carry analytics. Defaults to the last 24 hours; the maximum range is 31 days. Reports are aggregated from the 1000 most recent report-capable sessions matching the filters — session types that never produce reports don't consume that window — and the `truncated` field reports when more report-capable sessions matched. Narrow the time range or filters to analyse busier periods exhaustively. # get session concurrency status Source: https://anam.ai/docs/api-reference/sessions/get-current-concurrency-status https://api.anam.ai/swagger.json get /v1/sessions/concurrency Returns the organization's concurrent-session limit, an approximate count of sessions currently in use, whether a new session can likely be started, and an estimated wait time until a slot frees. Intended as an advisory pre-check before starting a session (e.g. to gate a "Start" button or show a wait estimate). The count is the Lab's optimistic view and can briefly over-report; the authoritative limit is enforced when a session is actually created, which may still return 429. # get session Source: https://anam.ai/docs/api-reference/sessions/get-session https://api.anam.ai/swagger.json get /v1/sessions/{id} Returns a session by ID, including the tool calls made during the session once it has ended and the engine has delivered its session report (`toolCalls` is empty until then, and always empty for LiveKit and audio-passthrough sessions, which never produce a report). Tool call names, timing and status are always included, and error messages are too unless transcripts were disabled for the session. Call arguments, results and accessed-document names are only included when transcripts were enabled for the session and the session is not zero-data-retention, since they embed conversation content. HTTP headers and credential-like keys are never returned. Anam-internal admin API keys may fetch sessions of any organization. # get session analytics Source: https://anam.ai/docs/api-reference/sessions/get-session-analytics https://api.anam.ai/swagger.json get /v1/sessions/{id}/analytics Returns per-turn latency analytics for a session — where time was spent in the transcription → LLM → TTS → first-audio path for each conversational turn, plus session-level summary metrics. Analytics become available once the session has ended and the engine has delivered its session report; until then this endpoint returns 404. Analytics exist only for sessions where Anam runs the conversational pipeline (turnkey, custom LLM and ElevenLabs agent sessions) — LiveKit and audio-passthrough sessions never produce them. Message text is omitted unless `includeMessages=true` is passed and transcripts were enabled for the session. Anam-internal admin API keys may fetch analytics for sessions of any organization. # get session recording Source: https://anam.ai/docs/api-reference/sessions/get-session-recording https://api.anam.ai/swagger.json get /v1/sessions/{id}/recording Returns a presigned URL to download the session recording. Recordings are never returned for zero-data-retention sessions, including to Anam-internal admin API keys. Admin keys may fetch recordings for non-ZDR sessions of any organization. # get session transcript Source: https://anam.ai/docs/api-reference/sessions/get-session-transcript https://api.anam.ai/swagger.json get /v1/sessions/{id}/transcript Returns the conversation transcript for a session. Transcripts are never returned for zero-data-retention sessions, including to Anam-internal admin API keys. Admin keys may fetch transcripts for non-ZDR sessions of any organization. # list sessions Source: https://anam.ai/docs/api-reference/sessions/list-sessions https://api.anam.ai/swagger.json get /v1/sessions Returns a list of all sessions for the organization # stop session Source: https://anam.ai/docs/api-reference/sessions/stop-session https://api.anam.ai/swagger.json post /v1/sessions/{id}/stop Force-terminates a running session. The engine hosting the session disconnects the client and shuts the session down immediately. Termination is asynchronous on the engine side: the session's `endTime`, exit status and session report are delivered through the normal end-of-session flow shortly after the stop, so the session may briefly still appear active on `GET /v1/sessions/{id}`. Stopping a session that has already ended returns `200` without contacting the engine, so repeating a stop is safe. That includes a session whose end reaches Lab while the stop is in flight. Running sessions that never reached an engine, or that run over the LiveKit or Agora integrations, have no engine host to terminate and return `404`. If the engine does not confirm the stop of a running session, the request fails with `502`. # create share link Source: https://anam.ai/docs/api-reference/share-links/create-share-link https://api.anam.ai/swagger.json post /v1/share-links Create a new share link # delete share link Source: https://anam.ai/docs/api-reference/share-links/delete-share-link https://api.anam.ai/swagger.json delete /v1/share-links/{id} Delete a share link by ID # get share link Source: https://anam.ai/docs/api-reference/share-links/get-share-link https://api.anam.ai/swagger.json get /v1/share-links/{id} Returns a share link by ID # list share links Source: https://anam.ai/docs/api-reference/share-links/list-share-links https://api.anam.ai/swagger.json get /v1/share-links Returns a list of all share links for the organization # update share link Source: https://anam.ai/docs/api-reference/share-links/update-share-link https://api.anam.ai/swagger.json put /v1/share-links/{id} Update a share link by ID # create tool Source: https://anam.ai/docs/api-reference/tools/create-tool https://api.anam.ai/swagger.json post /v1/tools Create a new tool for function calling in persona sessions # delete tool Source: https://anam.ai/docs/api-reference/tools/delete-tool https://api.anam.ai/swagger.json delete /v1/tools/{id} Delete a tool. The tool will be soft-deleted and no longer available. # get tool Source: https://anam.ai/docs/api-reference/tools/get-tool https://api.anam.ai/swagger.json get /v1/tools/{id} Get a tool by ID # list tools Source: https://anam.ai/docs/api-reference/tools/list-tools https://api.anam.ai/swagger.json get /v1/tools Returns a list of all tools for the organization # update tool Source: https://anam.ai/docs/api-reference/tools/update-tool https://api.anam.ai/swagger.json put /v1/tools/{id} Update an existing tool # create voice Source: https://anam.ai/docs/api-reference/voices/create-voice https://api.anam.ai/swagger.json post /v1/voices Create a voice by cloning from audio or importing an existing provider voice. Send clone audio inline as multipart/form-data (the whole request must stay under ~4.5MB), or first upload a larger clip via `POST /v1/voices/presigned-upload` and reference its `audioKey`. Provider imports are checked against Anam's supported model registry. Cartesia, ElevenLabs, and Fish Audio imports must successfully generate a sample before the voice is persisted; the first import of an ElevenLabs Voice Library voice typically takes about a minute while ElevenLabs adds it to Anam's account. New integrations should prefer POST /v1/voice-imports for synchronous validation and preview generation. An import by provider voice ID shares that endpoint's organization limit: 30 voice imports and model changes an hour, at most 3 at once, refused with 429 `rate_limited` and `Retry-After` before any provider work. # create voice presigned upload Source: https://anam.ai/docs/api-reference/voices/create-voice-presigned-upload https://api.anam.ai/swagger.json post /v1/voices/presigned-upload Request a presigned URL for uploading a voice-clone audio clip directly to storage. Use this for clips larger than the ~4.5MB request-body limit of the multipart `POST /v1/voices` endpoint. Flow: (1) call this endpoint to get an `uploadUrl` and `audioKey`; (2) `PUT` the raw audio bytes to `uploadUrl` with the same `Content-Type`; (3) call `POST /v1/voices` with a JSON body referencing the `audioKey` to perform the clone. # delete voice Source: https://anam.ai/docs/api-reference/voices/delete-voice https://api.anam.ai/swagger.json delete /v1/voices/{id} Delete a voice by ID. The voice is soft-deleted locally and then removed at the TTS provider. When active personas (or their working drafts) still use the voice, the request is refused with 409 because deleting the voice would silence those personas' sessions. Move the impacted personas to another voice (PUT /v1/personas/{id}), then retry. # get ElevenLabs API key status Source: https://anam.ai/docs/api-reference/voices/get-the-organizations-elevenlabs-api-key-status https://api.anam.ai/swagger.json get /v1/voices/elevenlabs-key Which ElevenLabs API key the organization saved for importing voices with `useOrganizationKey`. Never returns the key, only its last four characters. # get voice Source: https://anam.ai/docs/api-reference/voices/get-voice https://api.anam.ai/swagger.json get /v1/voices/{id} Returns a voice by ID # list voices Source: https://anam.ai/docs/api-reference/voices/list-voices https://api.anam.ai/swagger.json get /v1/voices Returns a list of all voices. A search or filter that matches none answers 200 with an empty `data` list. # remove ElevenLabs API key Source: https://anam.ai/docs/api-reference/voices/remove-the-organizations-elevenlabs-api-key https://api.anam.ai/swagger.json delete /v1/voices/elevenlabs-key Removes the saved key. Voices that use the key stop speaking, and sessions with them fail to start, until a key is saved again. # save ElevenLabs API key Source: https://anam.ai/docs/api-reference/voices/save-the-organizations-elevenlabs-api-key https://api.anam.ai/swagger.json put /v1/voices/elevenlabs-key Saves or replaces the organization's ElevenLabs API key, for voices that only exist in its own ElevenLabs account: instant clones, Voice Design voices and Professional Voice Clones. Anam checks the key with ElevenLabs on each of its API hosts, including data-residency hosts, and stores it encrypted. Afterwards, `POST /v1/voice-imports` with `useOrganizationKey: true` imports a voice that speaks with it, and ElevenLabs bills that speech to the key's account. The key needs Text to Speech access, which Anam checks without generating speech. # update voice Source: https://anam.ai/docs/api-reference/voices/update-voice https://api.anam.ai/swagger.json put /v1/voices/{id} Update a voice by ID. Its display name, provider model, gender, accent (`country`) and description can be changed. # create voice import Source: https://anam.ai/docs/api-reference/voices/validate-and-import-a-provider-voice https://api.anam.ai/swagger.json post /v1/voice-imports Synchronously validates the provider voice/model and persists the Voice only after a real TTS preview succeeds. A provider validation may take up to 90 seconds, after a best-effort metadata lookup of up to 5 seconds; the first import of an ElevenLabs Voice Library voice typically takes about a minute while ElevenLabs adds it to Anam's account. Only provider and providerVoiceId are required. Omitted displayName and description use provider metadata; supplied values take precedence. If unavailable, the name is Imported and the description is null. This endpoint does not accept voice-clone audio; use POST /v1/voices for cloning. Every successful request by provider voice ID creates a new Voice and generates a new preview, even when the same provider voice ID and model already exist in the organization, so repeating one (a retry after a lost response, say) creates another Voice: list voices (GET /v1/voices) before retrying. Omitted models resolve to the provider default. Each organization can start 30 voice imports and voice model changes an hour, at most 3 at once; more are refused with 429 `rate_limited` and `Retry-After` before any provider work, so nothing is charged. Two ElevenLabs options reach voices Anam's own ElevenLabs account can't. `useOrganizationKey: true` validates and speaks with your organization's saved ElevenLabs API key (PUT /v1/voices/elevenlabs-key), so any voice in your own ElevenLabs account works, including instant clones, Voice Design voices and Professional Voice Clones; these voices have `isZdr: false`. `shareUrl` instead of `provider` and `providerVoiceId` imports a Professional Voice Clone shared with Anyone with the link, which then speaks with Anam's account. A share link for a voice your organization already has on the requested model regenerates its preview, applies any displayName, and returns that Voice with 200 instead of creating another. # Generate avatar videos Source: https://anam.ai/docs/avatar-videos/overview Render a supplied script as an asynchronous avatar video using a saved persona or an avatar and voice. Avatar videos turn a script into a recorded MP4 without opening an interactive conversation. Create a video from your backend, check its status, then download it when it is ready. > [!NOTE] > > Call the avatar-video API from your backend. Keep your Anam API key out of browsers and mobile apps. ## Create a video Provide an `avatarId` and `voiceId` to create an ephemeral persona for the video: ```bash theme={"system"} curl --request POST https://api.anam.ai/v1/avatar-videos \ --header "Authorization: Bearer $ANAM_API_KEY" \ --header "Content-Type: application/json" \ --header "Idempotency-Key: onboarding-welcome-v1" \ --data '{ "script": "Welcome to the product tour.", "avatarId": "YOUR_AVATAR_ID", "voiceId": "YOUR_VOICE_ID", "directorNotes": { "presetStyle": "warm" } }' ``` The API returns `202 Accepted` with an avatar-video resource. Every create request requires an `Idempotency-Key`. If you need to repeat the same request after a network error, reuse the same key to receive the original video job instead of creating another one. Use a new key for a different video. ## Use a saved persona Alternatively, replace the direct avatar and voice fields with a saved `personaId`: ```json theme={"system"} { "script": "Welcome to the product tour.", "personaId": "YOUR_PERSONA_ID" } ``` The saved persona contributes its avatar, voice, language, avatar model, and director notes. Only the submitted script is spoken; its greeting, brain, prompt, and tools do not run. Do not combine `personaId` with direct configuration fields. ## Check the status and download Use the returned `id` to fetch the latest status: ```bash theme={"system"} curl https://api.anam.ai/v1/avatar-videos/AVATAR_VIDEO_ID \ --header "Authorization: Bearer $ANAM_API_KEY" ``` The status moves from `pending` to `running`, `finalizing`, and `completed`. Download the MP4 from `content.url` when `content.available` is `true`. The URL expires after one hour; fetch the resource again to get a fresh URL. See the API reference for all voice, model, director-note, language, video-size, list, cancel, retry, and error options. > [card] [Avatar video API reference](/docs/api-reference/avatar-videos/create-an-avatar-video) > > See every request field, response, operation, and error. # Changelog Source: https://anam.ai/docs/changelog Follow new Anam features, SDK and API improvements, documentation updates, fixes, and other changes that affect applications in production. **November 6th, 2026** The Anam MCP server is now hosted ## Spotlight: the Anam MCP server is now hosted Anam's MCP server now runs at `https://lab.anam.ai/mcp`. Connect Claude, ChatGPT, Cursor, VS Code, Claude Code, Codex or any MCP client to your Anam account with no install. It replaces the `anam-mcp` Python package, which is no longer maintained. [Set it up](https://lab.anam.ai/mcp) or [read the docs](https://anam.ai/docs/resources/mcp). *** ## Moving from anam-mcp **What changes** * **Sign-in:** Sign in with your Anam account over OAuth instead of pasting an API key. Choose one organization and **Full access** or **Read only** on Anam's consent page. * **API keys still work:** Agents without a browser can send an Anam API key as `Authorization: Bearer `. * **No local install:** You no longer need Python, `uv` or `uvx`, and new tools arrive without an update. * **One URL:** Use `https://lab.anam.ai/mcp` everywhere. `/mcp/claude`, `/mcp/chatgpt`, `/mcp/copilot`, `/mcp/gemini`, `/mcp/agentforce` and `/mcp/muse` serve the smaller tool sets made for those platforms' directory listings. * **Meetings without Recall:** Sending a persona to Google Meet, Zoom or Microsoft Teams no longer needs a Recall AI key. **Tool names** Every tool now starts with `anam_` and follows `anam__`, so `list_personas` is `anam_persona_list` and `create_share_link` is `anam_share_link_create`. Personas, avatars, voices, tools, sessions, knowledge folders and documents, LLMs and share links map one to one. The exceptions: * `search_avatars` and `search_voices` → `anam_avatar_list` and `anam_voice_list`, with `search` (and `gender` or `country` for voices). * `create_voice` → `anam_voice_import` for a provider voice ID, or the new `anam_voice_clone` for a recording. * `create_webhook_tool` and `create_knowledge_tool` → `anam_tool_create`. To give a persona knowledge, use `anam_persona_knowledge_add`. * `upload_knowledge_document` → `anam_knowledge_document_create_from_text`, or `anam_knowledge_document_create_from_url` for a web page. * `get_knowledge_group`, `update_knowledge_group`, `delete_knowledge_group` and `search_knowledge_group` → `anam_knowledge_folder_get`, `_update`, `_delete` and `_search`. * `generate_avatar_video` → `anam_avatar_video_create`, then `anam_avatar_video_get` until it's ready. * `add_avatar_to_meeting`, `get_meeting_bot_status`, `list_meeting_bots` and `remove_avatar_from_meeting` → `anam_meeting_invite_create`, `_get`, `_list` and `_cancel`. Cancelling works before the persona joins. **New tools:** a quickstart persona and share link in one call (`anam_quickstart`), a persona from a brief (`anam_persona_from_brief`), session search, transcripts, analytics and insights, stopping and deleting sessions, pronunciation dictionaries, usage and plan limits, integration guides and starter code, and search over these docs. See the [full tool list](https://anam.ai/docs/resources/mcp#tools). **How to switch** Remove the `anam` server that runs `uvx anam-mcp` from your client's config, then add the hosted server: * **Claude (claude.ai and Desktop):** Settings → Connectors → Add custom connector. Paste `https://lab.anam.ai/mcp` and choose Connect. * **ChatGPT:** Plugins → plus button → Add custom MCP server. Paste `https://lab.anam.ai/mcp` and choose OAuth. * **Claude Code:** `claude mcp add --transport http --scope user anam https://lab.anam.ai/mcp`, then `claude mcp login anam`. * **Cursor:** In `mcp.json`, replace the `uvx` entry with `"anam": { "url": "https://lab.anam.ai/mcp" }`. * **VS Code:** `code --add-mcp '{"name":"anam","type":"http","url":"https://lab.anam.ai/mcp"}'` * **Codex:** `codex mcp add anam --url https://lab.anam.ai/mcp`, then `codex mcp login anam`. **November 3rd, 2026** Anam's built-in ElevenLabs voices now use v4 Turbo ## Spotlight: Anam's built-in ElevenLabs voices now use v4 Turbo ![Select Voice panel in Lab filtered to ElevenLabs v4 Turbo and Stock, showing 374 voices including Lucy, Archer and Jessica.](https://framerusercontent.com/images/ObCPY7YhojSqFwrsZZLVEGJbvo.jpg?width=960\&height=880) Anam’s built-in ElevenLabs voices now start speaking sooner with **ElevenLabs v4 Turbo**. On November 3, all 374 built-in voices previously using v3 Conversational moved to v4 Turbo, keeping their existing voice IDs. Personas using these voices switched automatically unless configured with a different model. The voices may sound slightly different. Built-in Flash v2.5 and Multilingual v2 voices haven’t changed. *** ## Lab Changes **Improvements** * **Browse v4 Turbo voices:** Open your persona’s Voice tab and filter by **Model → ElevenLabs v4 Turbo** and **Type → Stock** to explore the updated voices. ## Persona Changes **Improvements** * **Faster speech starts:** Built-in ElevenLabs voices previously on v3 Conversational now use v4 Turbo, reducing the wait before speech begins. * **Existing voice IDs preserved:** Keep using your current voice IDs. IDs for the separate v4 Turbo copies added in October also continue to work and resolve to their original voices. ## SDK/API Changes **Compatibility** * **Check your voice settings:** v4 and v4 Turbo support `stability` and `similarityBoost` in `voiceGenerationOptions`. Remove `speed`, `volume`, `emotion`, `style`, and `useSpeakerBoost` from v4 configurations. Requests containing `speed`, `style`, or `useSpeakerBoost` return `400`. * **Keep a persona on v3:** Set `voiceGenerationOptions.model` to `eleven_v3_conversational` and include only `stability` alongside it. See [voice configuration](https://anam.ai/docs/personas/voices/configuration). * **Voice import defaults unchanged:** New ElevenLabs imports still default to v3 Conversational. You can continue to [import your own voices](https://anam.ai/docs/personas/voices/custom-voices) using that model. **October 22nd, 2026** Cara-4.1 Express, wider framing, and unlimited custom avatars ## Spotlight: Cara-4.1 Express, wider framing, and unlimited custom avatars Meet **Cara-4.1 Express**, our most expressive realtime avatar model yet. Launched on October 20, it brings more expressive animation, improved lip sync, and closer control over how your avatar performs. Available in Anam Lab and through the API. Select Cara-4.1 Express for a compatible avatar, or set `avatarModel: "cara-4.1-express"` in your persona config. [Read the launch announcement](https://anam.ai/blog/cara-4-1-express) or [explore Cara-4.1 Express](https://anam.ai/cara-4-1). * **Wider framing:** Create custom avatars with up to 40% wider framing, showing more of the character and their surroundings. * **Unlimited custom avatars:** Every plan, including Free, can now save unlimited custom avatars. Creation capacity and image-generation quotas still apply. *** ## Lab Changes **Improvements** * **Unlimited saved custom avatars:** Every plan, including Free, can now save unlimited custom avatars. Creation capacity and image-generation quotas still apply. * **Wider avatar framing:** Create custom avatars with up to 40% wider framing, showing more of the character and their surroundings. Preview framing and screen shapes before creating. * **Session review:** Recording, summary, and transcript now sit together, with synchronized playback, expandable tool calls, and clearer issues and performance views. * **Share-link calls:** Refreshed call layouts keep captions clear of the avatar’s face, use portrait video on supported phones, and explain microphone access before requesting it. * **Voice imports:** A guided wizard helps you choose the right import method for your provider and voice type. Provider sign-in, ElevenLabs share-link import, and use of your own ElevenLabs key are in beta and rolling out by organization. ## Persona Changes **Improvements** * **Director Notes:** Now out of beta, with improved prompt adherence and custom performance styles. Set separate custom prompts for speaking and idle behavior. * **Session-length limits:** Set a published persona’s maximum session length in Build → Advanced. The limit can shorten your plan’s allowance. * **English transcription defaults:** Supported English full-pipeline sessions using the Default transcription provider now use Cartesia Ink-2. Explicit provider choices and configured sensitivity values are preserved. ## SDK/API Changes **Improvements** * **Independent retention controls:** Use `sessionOptions.dataRetention` to control recording and transcript storage separately. See [recording and transcript controls](https://anam.ai/docs/personas/session/recordings#turn-recording-and-transcripts-on-or-off) for supported configurations. * **Persona duration:** Set `maxSessionLengthSeconds` when creating or updating a saved persona. Accepts 60–7200 whole seconds, or `null` to remove the persona limit. * **Expanded voice imports:** `POST /v1/voice-imports` supports ElevenLabs share links and voices accessed with your organization’s saved ElevenLabs key, where enabled. Own-key voices require a Cara 4 avatar, use your ElevenLabs billing, and cannot be used with Anam Zero Data Retention. See [custom voices](https://anam.ai/docs/personas/voices/custom-voices). **September 22nd, 2026** Avatar personalization, expressive voices, and more control over your personas ## Spotlight: Avatar personalization, expressive voices, and more control over your personas **Personalize an avatar to match your brand:** Use text prompts to change clothing, backgrounds, or visual style, and attach a reference image to guide the edit; including adding your company logo to apparel or the background. **More expressive voices:** ElevenLabs v3 models are now available in the Anam lab. You can also switch a custom voice’s model without reimporting it, updating every persona that uses that voice. **Control avatar framing:** Preview and adjust zoom-out framing during avatar creation, within your organization’s allowance, or reset to automatic framing. **Experimental English speech recognition:** [Opt into Cartesia Ink-2](https://anam.ai/docs/personas/session/voice-detection) for English transcription and turn detection in Lab and the API. *** ## Lab Changes **Improvements** * **Voice model editing:** Change a custom voice’s model directly from the voice editor without reimporting it. * **Knowledge tool settings:** Configure retrieval controls in the tool editor, with values preserved when switching between form and JSON views. * **Catalog browsing:** Avatar and voice catalogs now support infinite scrolling, smoother search, and improved scroll-position retention. * **Billing notifications:** Organization owners can manage recipients for Lab billing notifications. **Fixes** * **Call startup:** Fixed sessions remaining stuck while connecting. Stalled attempts now time out with retry guidance, and cancelled attempts release their session allocation. * **Call endings:** Fixed normal, inactivity, and duration-limit endings incorrectly displaying server errors. * **Persona saves:** Improved recovery when overlapping edits cause a temporary save conflict. * **Browser translation:** Fixed issues where browser translation could crash interactive Lab screens. * **Subscription cancellation:** Eligible overdue self-service subscriptions can now schedule cancellation at the end of the billing period. Outstanding invoices remain payable. * **Consent synchronization:** Open Lab tabs now recognize analytics-consent withdrawal made on another Anam site without requiring a reload. ## Persona Changes **Improvements** * **Experimental English transcription:** Cartesia Ink-2 is available as an opt-in, English-only transcription and turn-detection provider in Lab and the API. **Integration note** * **Installed widgets:** Upgrade older installed or version-pinned widgets to receive the widget startup-recovery fixes. Updating Lab does not update separately installed widgets. ## SDK/API Changes **Compatibility** * **Avatar creation:** New creation requests must use Cara 4. Legacy `engineKey` creation and older-model creation requests are no longer supported. Supply an image and select `cara-4`, or omit the model. Existing older avatars remain usable in sessions. * **ElevenLabs v3 settings:** Only `stability` is supported in v3 `voiceGenerationOptions`. Remove unsupported options from existing configurations before starting sessions; these fields are not removed automatically. * **Default ElevenLabs model:** Creating an ElevenLabs voice without an explicit model now selects v3 Conversational. Specify your previous model to preserve the earlier behavior. Existing voices are unchanged. **Improvements** * **Knowledge retrieval controls:** Saved and inline knowledge tools now support `topK`, `minScore`, and `maxContextTokens`. Omitted values retain service defaults. **September 9th, 2026** Multi-utterance talk streams, custom speech-to-text provider, and faster voice models ## Spotlight: Multi-utterance talk streams, custom speech-to-text provider, and faster voice models **Multi-utterance talk streams:** Applications can send ordered [utterances within one talk stream](https://anam.ai/docs/javascript-sdk/reference/talk-commands#streaming-multiple-utterances); for example, speaking before a tool call and continuing with its result. **Choose your speech-to-text provider:** Full-pipeline personas can now use Anam or Deepgram for transcription. Select a provider under [Voice Detection](https://anam.ai/docs/personas/session/voice-detection) in the Lab, or set `voiceDetectionOptions.sttProvider` through the API. **Faster Cartesia speech in the US:** Cartesia-backed personas served in the US now benefit from a server-side optimization that reduces text-to-speech startup latency without integration changes. *** ## Lab Changes **Improvements** * **Session diagnostics:** Sessions now show customer-safe termination reasons with guidance for supported LiveKit, Daily, Agora, and Turnkey scenarios. See Session Termination Reasons. * **Session review:** Click a transcript timestamp to jump directly to that moment in the session recording. * **Embed setup:** Disallowed iframe origins now show the referring domain and explain how to update and publish Allowed domains. **Fixes** * **Sessions History:** Fixed date-filtered lists and CSV exports, invalid page states after filtering, and mobile pagination hidden behind navigation. * **Widget previews:** Draft initial messages and greeting settings now apply correctly to the next preview call. * **Public conversations:** Cookie prompts no longer cover iframe, share-link, or meeting conversations. * **Session finalization:** Fixed an issue that could leave very short sessions marked active or later classified as orphaned. * **Avatar videos:** Improved stale-job recovery so failed work does not prevent newer video requests from completing. ## Persona Changes **Improvements** * **Speech-to-text selection:** Full-pipeline personas can now use Anam or Deepgram for transcription. Choose a provider in the Lab or set `voiceDetectionOptions.sttProvider` through the API. See Voice Detection. * **Faster Cartesia speech starts:** Cartesia-backed personas served in the US now benefit from a server-side optimization that shortens text-to-speech startup without integration changes. * **New Cartesia voices:** New voice clones and imported Cartesia voices now use Sonic 3.6. Existing voices keep their current model. **Fixes** * **Transcription reliability:** Deepgram Flux now falls back faster when its primary endpoint is unavailable and recovers turns that do not receive an end-of-turn signal. * **LiveKit reconnects:** Reconnecting now preserves the avatar’s existing camera and microphone tracks instead of creating duplicate publications. ## SDK/API Changes **Improvements** * **Microphone capture:** JavaScript SDK `v4.27.0` requests browser-supported noise suppression, automatic gain control, voice isolation, and mono capture for more consistent input audio. **Fixes** * **Saved-persona attribution:** Sessions started from saved personas now return the correct `personaId`. Filtering `GET /v1/sessions` by persona also includes recoverable historical sessions. **Compatibility** * **Pipecat 1.8:** `pipecat-anam v0.2.0-alpha.6` supports Pipecat 1.8 and requires Python 3.11+. Applications using Pipecat 1.7 or earlier should remain on `v0.2.0-alpha.5`. **August 24th, 2026** Generate avatar videos and faster responses ## Spotlight: Avatar videos, faster responses, and multi-utterance tool calls **Avatar videos:** The new [Avatar Videos API](https://anam.ai/docs/avatar-videos/overview) turns a supplied script into a downloadable MP4 without opening an interactive conversation. Use a saved persona, or choose an avatar and voice directly, then retrieve the video when it is ready. **Faster responses:** Server-side optimizations reduce response latency by around 100–200 ms for supported persona configurations, helping conversations feel quicker without integration changes. **Multi-utterance tool calls:** With [multi-utterance persona turns](https://anam.ai/docs/personas/tools/overview#multi-utterance-persona-turns), compatible LLMs can speak before a tool call and continue after its result arrives within the same logical turn. *** ## Lab Changes **Improvements** * **AI avatar disclosure:** Lab sessions, share links, and meeting experiences now include a persistent [AI avatar disclosure](https://anam.ai/docs/security/ai-avatar-disclosure). * **Deprecated LLM visibility:** Deprecated stock LLMs are clearly labelled and excluded from defaults and recommendations. Existing published personas can keep their current model, while new persona assignments are prevented. **Fixes** * **Iframe embeds:** Fixed an issue where an [embedded persona](https://anam.ai/docs/embed/overview) could be replaced by a 404 when starting a session. ## Persona Changes **Improvements** * **Faster LiveKit connections:** Improved server-side regional routing keeps LiveKit sessions on a nearby media edge, shortening connection setup and reducing slow starts that could briefly show a black avatar tile or low-quality video. See the [LiveKit latency guidance](https://anam.ai/docs/integrations/livekit/configuration#optimize-latency). * **Timed conversation pauses:** The new [`pause_conversation`](https://anam.ai/docs/personas/tools/system-tools#pause-conversation) system tool lets a persona acknowledge a requested pause and remain quiet for up to 10 minutes, resuming early if the user speaks. * **Tool-call safeguards:** A single LLM turn now stops after 10 tool calls or five consecutive identical calls, reducing stalled and runaway loops. See [Tool limitations](https://anam.ai/docs/personas/tools/overview#limitations). **Fixes** * **Repeated responses:** Fixed an issue where duplicate OpenAI Responses API text parts could make a persona repeat itself. ## SDK/API Changes **Improvements** * **Session region controls:** Enterprise organizations can request the `eu` or `us` engine region, choose `preferred` failover or `strict` no-cross-region fallback, and read the region that served the session. See [Session Regions](https://anam.ai/docs/personas/session/regions). * **Multi-utterance messages:** JavaScript SDK `v4.25.0` and Python SDK `v0.11.0` expose optional utterance IDs and ordered utterance arrays while preserving the existing full message content. See the [JavaScript](https://anam.ai/docs/javascript-sdk/reference/events#multi-utterance-persona-turns) and [Python](https://anam.ai/docs/python-sdk/quickstart#multi-utterance-persona-turns) examples. * **Disclosure controls:** JavaScript, Python, and LiveKit integrations can opt into Anam’s persistent disclosure with `showAIAvatarDisclosure` or `show_ai_avatar_disclosure`. See [AI Avatar Disclosure](https://anam.ai/docs/security/ai-avatar-disclosure#enable-anams-disclosure-for-sdk-and-integration-sessions). * **Custom TTS guidance:** Updated [audio-passthrough](https://anam.ai/docs/javascript-sdk/examples/custom-tts) and [LiveKit](https://anam.ai/docs/integrations/livekit/configuration#optimize-latency) documentation covers sequence completion, supported audio chunk types, startup buffering, and latency optimization. **July 10th, 2026** Invite personas to Google Meet, Zoom, and Microsoft Teams calls ## Spotlight: Invite personas to your meetings Personas can now join Google Meet, Zoom, and Microsoft Teams calls as participants. Create an invite with a meeting URL and a persona via the new [Meetings API](https://anam.ai/docs/personas/meetings), and the persona joins the call, either immediately or at a scheduled time up to 7 days ahead. Scheduling at least 10 minutes in advance reserves guaranteed capacity for the join, which is the most reliable way to get a persona into a planned meeting. In group calls the persona joins silently and only responds when addressed by its display name; for 1:1 calls it can greet on join and respond to everything. You choose the region the persona joins from (`eu`, `us-east`, or `us-west`), with a strict mode for data-residency requirements. Once the persona is in the call, the invite links to a regular session, so transcripts and session details work through the existing Sessions API. Meeting participants always see that the persona is an AI: display names carry an "(AI)" suffix and the persona's video includes a persistent AI-disclosure treatment. Read the [Meetings](https://anam.ai/docs/personas/meetings) guide to get started. *** ## Lab Changes **Improvements** * **Invite from the Build page:** Published personas have a new Invite action that adds them to a meeting directly from the Lab. ## SDK/API Changes **Improvements** * **Meetings API:** New `/v1/meetings/invites` endpoints to create, list, get, and cancel meeting invites, gated by a new `meetings` API key permission scope. See the [API reference](/docs/api-reference/meetings/create-meeting-invite). **June 22nd, 2026** Faster persona session connections, clearer billing, team management, and broader API controls ## Spotlight: Faster time to first frame for persona sessions Persona sessions now connect much faster, with major improvements to time to first frame. We reduced work on the session-start path, improved WebRTC/TURN connection handling, warmed connection paths earlier, and made startup more resilient to transient failures. The improvement is already visible in production: US persona sessions are now seeing p50 time to first frame below 1 second, with p95 below 3 seconds. *** ## Lab Changes **Improvements** * **Team management:** Added a dedicated Team page for invites, member lists, roles, removals, and pending invitations. * **Billing visibility:** Billing is now a persistent nav item, with plan/usage status in the Lab and upcoming-invoice previews on the subscription page. * **Build and session performance:** Build page data now loads in parallel, session-token and session-start paths do less blocking work, and connection warmups/regional routing reduce time to playable sessions. **Fixes** * **Knowledge Library downloads:** Restored open and download actions for files in the Knowledge Library modal. * **Microphone controls:** Fixed mic discovery before first session and added microphone selection to public share-link sessions. * **Safari and iOS compatibility:** Fixed Safari voice-clone recording previews, iOS fullscreen errors, and older Safari microphone-permission checks. * **Security hardening:** Tightened server-side URL fetching, resource ownership checks, share-link protections, upload quota validation, pagination limits, anonymous metrics limits, and auth session handling. ## Persona Changes **Improvements** * **Mid-session config updates:** Live sessions can now receive language, voice generation, and voice detection updates over the data channel without reconnecting. * **Connection reliability:** Cloudflare TURN is now the default path with fallback, WebRTC forwarding has safer drain/flow handling, and regional Deepgram URLs improve transcription routing. **Fixes** * **Turn-taking stability:** Fixed rapid-interrupt edge cases, duplicate/missing LiveKit end-of-turn signals, and avatar freezes during interrupt transitions. * **Silence and end-call behavior:** Silence-breaker prompts now stay in the conversation language and no longer accidentally trigger the `end_call` tool. * **Tool-call resilience:** Personas recover more gracefully from malformed model streams or hallucinated tool calls before failing over. * **Session recordings:** Recording now waits for the primary WebRTC connection before starting, reducing missing recordings caused by early recorder connection attempts. ## SDK/API Changes **Improvements** * **RTC configuration control:** JavaScript SDK `v4.15.0` adds `rtcConfiguration`, including support for forcing TURN relay with `iceTransportPolicy: "relay"`. * **Session start retries:** JavaScript SDK `v4.14.0` retries `startSession` on transient failures. * **Direct session start:** `POST /v1/engine/session` can now accept a raw API key with session config in the request body for server-side SDKs and backend integrations. * **Widget config updates:** `PUT /v1/personas/{id}` can update embed widget settings such as call-to-action text and allowed origins. * **Developer guidance:** Docs now cover mid-session updates, `rtcConfiguration`, TURN-relay forcing, and registering event/tool handlers before starting a session. **Fixes** * **LiveKit compatibility:** Restored field-based persona config inference so existing LiveKit plugin payloads continue to create sessions. * **API-managed personas:** API-created and API-updated personas are no longer cleaned up by stale Lab draft cleanup. * **Persona ownership validation:** API create/update and draft/publish paths now enforce organization scoping for referenced avatars, voices, and LLMs. * **Webhook and external URL safety:** Webhook tool URLs, avatar image URLs, custom LLM URLs, and avatar-source fetches now use stricter public-URL validation. **May 27th, 2026** A refreshed Lab experience, better session controls, and cleaner voice/session workflows ## Spotlight: Refreshed Lab and better session controls The Lab has a refreshed interface across Build, Personas, Sessions, Dashboard, and API Keys, with cleaner navigation, updated controls, improved tables, and a more consistent design system throughout the product. Builders also have more predictable control over session behavior. Silence prompts and automatic session endings can now be disabled by setting their timeout values to `0`, and the confirmed end-call flow records clearer end reasons in session reports. *** ## Lab Changes **Improvements** * **Lab refresh:** Updated the main Lab experience across Build, Personas, Sessions, Dashboard, and API Keys with refreshed navigation, controls, tables, and styling. * **Custom LLM editing:** The Build page now supports full custom LLM editing, including URL, format, model/deployment/API version, reasoning settings, description, and safe API key rotation. * **Sessions History:** Added server-side search, API key/date filters, filtered pagination, and more reliable CSV exports. * **Voice discovery:** Voice language filters now reflect supported Cartesia Sonic 3.5 and ElevenLabs Flash v2.5 languages, with improved locale/accent matching and neutral localized sample text. **Fixes** * **Persona autosave:** Added timeouts and retries so personas no longer get stuck in "Saving" and block publishing indefinitely. * **Avatar player layout:** The avatar player now responds better to limited vertical space so video and config controls remain visible. * **Knowledge Library names:** Long folder and file names now truncate more reliably so counts and action buttons stay reachable. ## Persona Changes **Improvements** * **Session controls:** `silenceBeforeSkipTurnSeconds: 0` and `silenceBeforeSessionEndSeconds: 0` now disable silence prompts and automatic session endings. * **End-call flow:** Added a confirmed `end_call` flow with standardized close messages and `end_reason` / `end_message` in session reports. * **Multilingual transcription:** Deepgram Flux now defaults to the multilingual model with supported language hints. * **Conversation context:** Increased the default agentic LLM message history from 8 to 20 messages for more coherent longer conversations. **Fixes** * **End-call reliability:** Added guards against repeated `end_call` loops and incorrect turn-finished events. * **Reasoning text safety:** Leaked `` blocks are scrubbed from spoken output and message history while preserved for reasoning aggregation. * **ElevenLabs transcripts:** Fixed missing spaces when rebuilding assistant transcripts from ElevenLabs alignment chunks. ## SDK/API Changes **Improvements** * **Voice detection options:** API validation and Swagger now document the new `0` disable behavior and expanded timeout ranges for silence controls. * **Avatar API reference:** Clarified avatar media fields, including signed idling preview URLs and the current public avatar model mapping. **Fixes** * **Validation consistency:** Session-token and Lab persona validation now agree on silence timeout ranges and descriptions. * **SDK logging:** JavaScript SDK log wording has been cleaned up for clearer developer diagnostics. **May 12th, 2026** Cara 4 early access, higher-quality voice cloning, and smoother Knowledge/API workflows ## Spotlight: Cara 4 early access Cara 4 is now available in early access for enabled organizations. It brings higher-resolution avatar output, stronger expressivity, and improved custom avatar creation for teams testing the next generation of Anam avatars. Once access is enabled for an organization, builders can select **Cara 4 (Latest)** in the Lab or set `avatarModel: "cara-4-latest"` when creating a persona or session token via the API. *** ## Lab Changes **Improvements** * **Cara 4 early access:** Enabled organizations can now try Cara 4 from the Build page model selector and use the new early-access setup guide. * **Knowledge Library:** Redesigned the Knowledge Library, upload, folder, and batch-upload dialogs with cleaner layouts, clearer file states, and a smoother upload flow. * **Voice cloning quality:** Cartesia voice clones now use Sonic 3.5, improving clone quality and expressiveness for generated voices. * **Configurable first messages:** The Lab now supports custom persona first messages, making it easier to control how a session opens. **Fixes** * **Knowledge deletion:** Knowledge document and folder deletion now returns immediately instead of blocking while vector and file cleanup finishes in the background. * **Knowledge cleanup reliability:** Fixed cleanup deadlocks around large legacy documents so deleted Knowledge files are purged more reliably. * **Long Knowledge names:** Long folder and file names now truncate correctly, keep actions reachable, and validate upload/rename limits before they hit database errors. * **Lab Home templates:** Fixed Lab Home persona templates that could recite their own system prompts instead of staying in character. * **Persona list refresh:** Persona lists now refresh correctly after draft autosave and publish changes, reducing stale Build and Personas page states. * **Tool interruption setting:** Fixed the Tools UI so the interruption-control setting is passed through correctly. ## Persona Changes **Improvements** * **Cara 4 streaming:** Tuned Cara 4 frame buffering and bitrate behavior for smoother high-quality playback during early-access sessions. * **Audio preprocessing:** Updated speech enhancement and VAD handling with newer ai-coustics/Voice Focus support. * **Cartesia pronunciation support:** Enterprise customers can now request custom Cartesia pronunciation rules for specific words or brand terms. **Fixes** * **Interrupted greetings:** Interrupted first messages are now recorded accurately in conversation history, so personas do not retain text they never actually spoke. * **Audio latency:** Fixed an audio pipeline issue that could add latency in some sessions. * **Turkish turn-taking:** Disabled eager end-of-turn behavior for Turkish to reduce premature interruptions. * **Audio passthrough avatars:** Fixed audio passthrough sessions so the selected `avatarModel` is passed through correctly. * **LLM message tracking:** Added safeguards for missing LLM part IDs to reduce message-history edge cases. ## SDK/API Changes **Improvements** * **Cara 4 via API:** Enabled organizations can request Cara 4 with `avatarModel: "cara-4-latest"` when creating session tokens or personas. * **OpenAPI accuracy:** Fixed OpenAPI/Swagger generation issues, including missing fields and tool-update schema coverage. * **Pipecat startup:** Updated `pipecat-anam` alpha releases with a non-blocking startup flow that reduces time to first bot speech, plus improved interrupt handling. **Fixes** * **Clearer ID errors:** Passing an avatar, persona, or voice ID into the wrong field now returns a helpful `400`/`404` response instead of a generic server error. * **Validation status codes:** Session-token validation errors now surface as validation failures instead of misleading capacity errors. * **Persona API state:** Fixed persona API responses that could return draft persona data instead of the latest published persona. * **Deleted Knowledge filtering:** Added an internal safety check so deleted Knowledge documents are filtered out of RAG results while vector cleanup catches up. **April 20th, 2026** More predictable session openings, high-quality starts, and cleaner avatar refinement ## ⚡ More predictable session openings This release gives builders more control over how sessions begin, especially when a tool-driven turn needs to run cleanly without being interrupted partway through. That makes longer or multi-step tool flows feel more predictable for both builders and end users. On the media side, you can now pin a session to start in high video quality using `sessionOptions.videoQuality`, which helps sessions reach their intended bitrate faster. We also tightened one-shot avatar refinement so flat or near-solid backgrounds are preserved more reliably in both the Lab and `/v1` avatar creation flow. *** ## Lab Changes **Improvements** * **Better default model:** New personas and built-in agent templates now default to GPT OSS 120B instead of GPT OSS 20B, improving reasoning quality and tool use out of the box. **Fixes** * **Cleaner avatar refinement:** Fixed a Gemini refinement issue that could replace plain or near-solid avatar backgrounds with invented scenery, textures, or objects during one-shot avatar creation. ## Persona Changes **Improvements** * **Protected tool turns:** Tool-driven turns can now optionally suppress interruptions while your app is still handling the action, making longer or multi-step tool flows more predictable. **Fixes** * **Protected-turn cleanup:** Interrupt protection is now released cleanly when a greeting or tool turn finishes without spoken output, reducing the chance of sessions getting stuck in a protected state. ## SDK/API Changes **Improvements** * **Initial video quality control:** `sessionOptions.videoQuality` now accepts `high` or `auto`, letting you pin a session to start at the maximum video bitrate instead of ramping up from the default profile. **Fixes** * **Avatar API refinement backgrounds:** The same background-preservation fix now applies to the `/v1` avatar creation flow, so refined API-created avatars are less likely to pick up hallucinated scenery. **April 13th, 2026** A major docs overhaul and better tool visibility across session views ## 📚 The Anam docs have been overhauled We redesigned the docs to make it much easier to find the right starting point and drill into the part of the platform you care about. Navigation is now organized around Overview, Embed, JavaScript SDK, Python SDK, Integrations, API Reference, and Changelog, with a rewritten overview page and clearer Learn / Embed / Build entry points. This overhaul also adds dedicated Python SDK and LiveKit documentation, plus more focused guides for avatars, voices, LLMs, tools, session options, and network configuration. *** ## Docs Changes **Improvements** * **New navigation:** The docs now use clearer top-level tabs and reorganized sections so it is faster to jump between concepts, embedding, SDKs, integrations, and API reference. * **New SDK and integration guides:** Added dedicated Python SDK documentation and a full LiveKit integration section, including overview, quickstart, and configuration guides. * **Focused concept pages:** Split key setup topics into dedicated pages for available LLMs, creating custom avatars, session controls, voice configuration, and network requirements. **Fixes** * **Docs redirects:** Added redirects for renamed and legacy docs URLs so older links and indexed API-reference pages are less likely to land on 404s. * **Navigation polish:** Improved overview labeling, changelog labeling, and navbar behavior across the docs experience. ## Lab Changes **Improvements** * **Sessions page:** Tool calls now appear across session Analytics, Overview, Transcript, and export views, including status, arguments, results, errors, and execution time. ## Persona Changes **Improvements** * **Client tool round-trips:** Personas can now continue once your application returns a client tool result, making client-side actions easier to chain into a conversation. * **Webhook tracing:** Webhook tool requests now include session and correlation IDs, making it easier to trace tool calls across your own backend systems. **Fixes** * **Audio preprocessing resilience:** Sessions now fail open if speech-enhancement preprocessing is unavailable, instead of ending unexpectedly. * **Session startup reliability:** Improved startup and media-timeout handling so transient processing issues are less likely to interrupt an active turn. ## SDK/API Changes **Improvements** * **Client tool results:** The JavaScript SDK now sends client tool results and errors back to the engine over the data channel, with session-scoped safeguards. * **Avatar creation API:** `POST /v1/avatars` now accepts an optional `avatarModel` field during avatar creation. **March 30th, 2026** A simpler tool builder and clearer API/runtime error handling ## 🛠️ Tool setup got much easier in the Lab We redesigned the tool editor so webhook tools can be configured with form-based builders for headers, query params, and body params instead of raw JSON. That makes it much easier to set up tools correctly, especially for non-technical builders or teams collaborating across product and engineering. This release also includes a few practical fixes around upload limits, session behavior, and API error handling so the platform behaves more clearly when something goes wrong. *** ## Lab Changes **Improvements** * **Tool editor:** Rebuilt webhook tool configuration with form-based builders for headers, query params, and body params, so you no longer need to edit raw JSON for common setups. **Fixes** * **Connection errors:** Improved LLM URL normalization and connection error messages when custom model endpoints are misconfigured. * **Avatar uploads:** Reduced the avatar image upload limit to match the real platform file limit and avoid failed uploads. * **Session cleanup:** Fixed a bug where active sessions could keep running after the player unmounted during tab switches. ## SDK/API Changes **Improvements** * **Capacity signaling:** When session capacity is exhausted, the API now returns a clearer `429` response instead of a generic failure. **Fixes** * **Knowledge auth:** Fixed knowledge-upload auth and header handling for API callers. **March 23rd, 2026** Context injection, speech detection events & voice cloning for all plans ## 🎯 Client-side context injection You can now inject context into a conversation without triggering a persona response. Call `addContext()` in the JavaScript SDK to silently append information — like CRM data, page navigation events, or real-time application state — to the conversation history. The persona won't respond immediately, but will have that context available the next time the user speaks. This is useful for building context-aware agents that adapt to what the user is doing in your application without interrupting the conversation flow. ## 🎙️ User speech detection events The SDK now emits `userSpeechStarted` and `userSpeechEnded` events the moment voice activity is detected, before any transcription is available. Use these to build responsive "listening" indicators and other UI feedback that reacts instantly when the user begins or stops speaking. *** ## Lab Changes **Improvements** * **Voice cloning for all plans:** Custom voice cloning is available across plans. * **Share and embed redesign:** Share links and embed widgets have been consolidated into a simpler 1-to-1 model with a cleaner management interface. * **Persona tools via API:** The PUT persona endpoint now accepts a `tool` field, allowing you to attach tools to personas programmatically. **Fixes** * Fixed one-shot avatar refinement timing out by making Gemini refinement non-fatal with a 35-second timeout. * Fixed knowledge upload endpoints not accepting Bearer API key authentication. * Fixed end-session race conditions with idempotent endpoint and atomic updates. ## Persona Changes **Improvements** * **Conversation context accuracy:** A new message history system tracks which text was actually spoken versus interrupted, and records tool call arguments and results. The persona now maintains accurate context after interruptions, leading to more coherent multi-turn conversations. * **Audio passthrough stability:** Late-arriving audio in BYO TTS sessions no longer causes unintended interruptions. Audio is buffered and played back in order, improving reliability for Pipecat and other audio passthrough integrations. **Fixes** * Fixed stale video frames occasionally appearing after a response completes. ## SDK/API Changes **Improvements** * **Context injection:** New `addContext()` method lets you inject context into the conversation history without triggering a response ([JS SDK v4.11.0](https://github.com/anam-org/javascript-sdk/releases/tag/v4.11.0)). * **Speech detection events:** `userSpeechStarted` and `userSpeechEnded` events fire at the VAD level for instant speech detection ([JS SDK v4.12.0](https://github.com/anam-org/javascript-sdk/releases/tag/v4.12.0)). **March 9th, 2026** Adaptive bitrate streaming, zero data retention & system tools ## 📡 Adaptive bitrate streaming Anam now dynamically adjusts video quality based on network conditions. When bandwidth drops, the stream adapts in real time to maintain smooth, uninterrupted video rather than freezing or dropping frames. When conditions improve, quality scales back up automatically. This is a significant improvement for users on mobile networks, VPNs, or connections with variable bandwidth. ## 🔒 Zero Data Retention mode Enterprise customers can now enable **Zero Data Retention** on any persona. When enabled, no session data — recordings, transcripts, or conversation logs — is stored after a session ends. This applies across the full pipeline including voice and LLM data. Toggle it on from persona settings in the Lab, or set it via the API. [Learn more](https://anam.ai/docs/security/privacy). *** ## Lab Changes **Improvements** * **System tools:** Personas can now use built-in system tools. `change_language` switches speech recognition to a different language mid-conversation, and `skip_turn` pauses the persona from responding when the user needs a moment to think. Enable them from the Tools tab in Build. * **Tool validation:** Auto-deduplication of tool names with clearer validation error messages. * **Share link management:** Migrated share links to a 1-to-1 primary model with a simpler toggle interface. **Fixes** * Fixed reasoning model responses getting stuck in "thinking..." state. * Fixed soft-deleted knowledge folders not restoring on document upload. * Fixed LiveKit session type classification for snake\_case environment payloads. ## Persona Changes **Improvements** * **Agora AV1 support:** Agora integration now supports the AV1 video codec for better compression and quality at lower bitrates. * **Multi-agent LiveKit:** Audio routing now works correctly in multi-agent LiveKit rooms with multiple Anam avatars. **Fixes** * Fixed tool enum type validation. **February 27th, 2026** Four new integrations, Build page redesign & knowledge base overhaul ## 🔌 New integrations Four new ways to use Anam avatars in your stack: **Pipecat**\ The [`pipecat-anam`](https://pypi.org/project/pipecat-anam/) package brings Anam avatars to [Pipecat](https://github.com/pipecat-ai/pipecat), the open-source framework for voice and multimodal AI agents. `pip install pipecat-anam`, add `AnamVideoService` to your pipeline, and you're streaming. Use audio passthrough for full control over your own orchestration, or let Anam handle the pipeline end-to-end. [GitHub repo](https://github.com/anam-org/pipecat-anam). **ElevenLabs server-side agents**\ Put a face on any agent you've built in ElevenLabs. Pass in your ElevenLabs agent ID and session token when starting a session, and Anam handles the rest, no changes to your existing ElevenLabs setup needed. [Cookbook](https://anam.ai/cookbook/elevenlabs-server-side-agents). **VideoSDK**\ Anam is now officially supported on [VideoSDK](https://www.videosdk.live/), a WebRTC platform similar to LiveKit. Built on top of the Python SDK. **Framer**\ The Anam Avatar plugin is now [on the Framer Marketplace](https://www.framer.com/marketplace/plugins/anam-avatar/). Drop an avatar into any Framer site without writing code. ## 📐 Metaxy: sample-level versioning for ML pipelines We wrote up a deep dive on [Metaxy](https://anam.ai/blog/metaxy), our open-source metadata versioning framework for multimodal data pipelines. It tracks partial data updates at the field level so teams only reprocess what actually changed. Works with orchestrators like Dagster, agnostic to compute (Ray, DuckDB, etc.). [GitHub](https://github.com/anam-org/metaxy). *** ## Lab Changes **Improvements** * **Build page redesign:** Everything lives in Build now. Avatars, Voices, LLMs, Tools, and Knowledge are tabs within a single page. Create custom avatars, clone voices, add LLMs, and upload knowledge files without leaving the page. Knowledge is a file drop on the Prompt tab: upload a document and it's automatically turned into a RAG tool. * **Smart voice matching:** One-shot avatars now auto-select a voice matching the avatar's detected gender. * **Mobile improvements:** Tables replaced with cards and lists. Bottom tab bar instead of hamburger menu. Long-press context menus on persona tiles. Touch-friendly tooltips. * **Knowledge base improvements:** Non-blocking document deletion with pending state and rollback on error. PDF uploads restored. Stuck documents are auto-detected with retry from the UI. **Fixes** * Fixed typo in thinking duration display. * Fixed sticky hover states on touch devices. ## Persona Changes **Improvements** * **Video stability:** New TWCC-based frame-drop pacer with GCC congestion control. Smoother video on constrained or variable-bandwidth connections. * **Network connectivity:** TURN over TLS for ICE, improving session establishment behind corporate firewalls and VPNs. **Fixes** * Fixed ElevenLabs pronunciation issues with certain text patterns. * Fixed text sanitization causing incorrect punctuation in TTS output. * Fixed silent responses not being detected correctly. ## SDK/API Changes **Improvements** * **Tool call event handlers:** `onToolCallStarted`, `onToolCallCompleted`, and `onToolCallFailed` handlers for tracking tool execution on the client. * **Documents accessed:** `ToolCallCompletedPayload` now includes a `documentsAccessed` field for Knowledge Base tool calls. **Fixes** * Fixed duplicate tool call completion events. **February 4th, 2026** Anam Python SDK & ICE recovery ## 🐍 Anam Python SDK Anam now has a [Python SDK](https://github.com/anam-org/python-sdk). It handles WebRTC streaming, audio/video frame delivery, and session management. What's in the box: * **Media handling** — The SDK manages WebRTC connections and signalling. Connect, and you get synchronized audio and video frames back. * **Multiple integration modes** — Use the full pipeline (STT, LLM, TTS, Face) or bring your own TTS via audio passthrough. * **Live transcriptions** — User speech and persona responses stream in as partial transcripts, useful for captions or logging conversations. * **Async-first** — Built on Python's async/await. Process media frames with async iterators or hook into events with decorators. People are already building with it — rendering ascii avatars in the terminal, processing frames with OpenCV, piping audio to custom pipelines. Check the [GitHub repo](https://github.com/anam-org/python-sdk) to get started. *** ## Lab Changes **Improvements** * **Visual refresh:** Updated Lab UI with new brand styling, including new typography (Figtree), refreshed color tokens, and consistent component styles across all pages. ## Persona Changes **Improvements** * **ICE recovery grace period:** WebRTC sessions now survive brief network disconnections instead of terminating immediately. The engine detects ICE connection drops and holds the session open, allowing the client to reconnect without losing conversation state. * **Language configuration:** You can now set a language code on your persona, ensuring the STT pipeline uses the correct language from session start. * **Voice generation options:** Added configurable voice generation parameters for more control over TTS output. * **ElevenLabs streaming:** Removed input buffering for ElevenLabs TTS, reducing time-to-first-audio for all sessions using ElevenLabs voices. **January 29th, 2026** Session recordings & two-pass avatar refinement ## 🎬 Session recordings By default, every session is now recorded and saved for 30 days. Watch back any conversation in the Lab (lab.anam.ai/sessions) to see exactly how users interact with your personas, including the full video stream and conversation flow. Recordings and transcripts are also available via API. Use `GET /v1/sessions/{id}/transcript` to fetch the full conversation programmatically for analytics, QA, or archival. For privacy-sensitive applications, you can disable recording in your persona config. ## 🎨 Two-pass avatar refinement One-shot avatar creation now refines images in two passes. Upload an image, and the system generates an initial avatar, then refines it for better likeness and expression. Available to all users. *** ## Lab Changes **Improvements** * Added `speechEnhancementLevel` (0-1) to `voiceDetectionOptions` for control over how aggressively background noise is filtered from user audio * Support for ephemeral tool IDs, so you can configure tools dynamically per session * Added delete account and organization buttons **Fixes** * Fixed terminology on tools tab * Fixed RAG default parameters not being passed * Fixed custom LLM default settings ## Persona Changes **Improvements** * Support for Gemini thinking/reasoning models * The `speechEnhancementLevel` parameter now passes through via `voiceDetectionOptions` * Engine optimizations for lower latency under load **Fixes** * Fixed GPT-5 tool calls returning errors * Fixed audio frame padding that could cause playback issues * Fixed repeated silence messages * Fixed silence breaker not responding to typed messages **January 18th, 2026** Speech Enhancement & Reasoning Models ## 🎧 User Speech Enhancement We've integrated [ai-coustics](https://ai-coustics.com/) as a preprocessing layer in our user audio pipeline. It enhances audio quality before it reaches speech detection, cleaning up background noise and improving signal clarity in real-world conditions. This reduces false transcriptions from ambient sounds and improves endpointing accuracy, especially in noisy environments like cafes, offices, or outdoor settings. ## 🎛️ Configurable Persona Responsiveness Control how quickly your persona responds with [voiceDetectionOptions](https://anam.ai/docs/personas/session/voice-detection) in the persona config: * `endOfSpeechSensitivity` (0-1): How eager the persona is to jump in. 0 waits until it's confident you're done talking, 1 responds sooner. * `silenceBeforeSkipTurnSeconds`: How long before the persona prompts a quiet user. * `silenceBeforeSessionEndSeconds`: How long silence ends the session. * `silenceBeforeAutoEndTurnSeconds`: How long a mid-sentence pause waits before the persona responds. ## 🧠 Reasoning Model Support Added support for OpenAI reasoning models and custom Groq LLMs. Reasoning models can think through complex scenarios before responding, while Groq's high-throughput infrastructure makes these typically-slower models respond with conversational latencies suitable for real-time interactions. Add your reasoning model in the lab: [https://lab.anam.ai/llms](https://lab.anam.ai/llms). ## Persona Changes **Fixes** * Fixed Knowledge Base (RAG) tool calling with proper default query parameters * Fixed panic crashes when sessions error during startup ## Lab Changes **Fixes** * Fixed `Powered by Anam` text visibility when watermark removal is enabled * Updated API responses for GET/UPDATE persona endpoints ## SDK/API Changes **Improvements** * Introduced agent audio input streaming for BYO audio workflows, allowing you to integrate with arbitrary voice agents, eg ElevenLabs agents (see the [ElevenLabs server-side agents recipe](https://anam.ai/cookbook/elevenlabs-server-side-agents) on how to integrate). * Added WebRTC reasoning event handlers for reasoning model support **December 21st, 2025** Cara 3 Avatar Model & SOC-2 Compliance ## 🎭 Introducing Cara 3: our most expressive model yet The accumulation of over 6 months of research, **Cara 3** is now available. This new model delivers significantly more expressive avatars featuring realistic eye movement, more dynamic head motion, smoother transitions in and out of idling, and improved lip sync. You can opt-in to the new model in your persona config using `avatarModel: 'cara-3'` or by selecting it in the Lab UI. Note that all new custom avatars will use Cara 3 exclusively, while existing personas will continue to use the Cara 2 model by default unless explicitly updated. ## 🛡️ SOC-2 Type II compliance Anam has achieved SOC-2 Type II compliance. This milestone validates that our security, availability, and data protection controls have been independently audited and proven over time. For customers building across learning, enablement, or live production use cases, this provides formal assurance regarding how we handle security, access, and reliability.\ [**Visit the Trust Center**](https://trust.anam.ai/) ## 🔌 Integrations **Model Context Protocol (MCP) server**\ Manage your personas and avatars directly within Claude Desktop, Cursor, and other MCP-compatible clients. Use your favorite LLM-assisted tools to interact with the Anam API. **Anam x ElevenLabs agents**\ Turn any ElevenLabs conversational AI agent into a visual avatar using Anam's audio passthrough.\ [Watch the demo](https://anam.ai/cookbook/elevenlabs-server-side-agents) *** ## Lab Changes **Improvements** * **UI overhaul:** A redesigned Homepage and Build page make persona creation more intuitive. You can now preview voices/avatars without starting a chat and create custom assets directly within the Build flow. Sidebar and Pricing pages have also been refreshed. * **Performance:** Implemented Tanstack caching to significantly improve Lab responsiveness. **Fixes** * Fixed a bug where client tool events were not appearing in the Build page chat. * Resolved an issue where tool calls and RAG were not passing parameters correctly. ## Persona Changes **Improvements** * **More voices:** Added \~100 new Cartesia voices (Sonic-3) and \~180 new ElevenLabs voices (Flash v2.5), covering languages and accents from all over the world. * **New default LLM:** `kimi-k2-instruct-0905` is now available. This SOTA open-source model offers high intelligence and excellent conversational abilities. (Note: Standard `kimi-k2` remains recommended for heavy tool-use scenarios). * **Configurable greetings:** Added `skip_greeting` parameter, allowing you to configure whether the persona initiates the conversation or waits for the user. * **Latency reductions:** * **STT optimization:** We are now self-hosting Deepgram for Speech-to-Text, resulting in a **\~30ms (p50)** and **\~170ms (p90)** latency improvement. * **Frame buffering:** Optimized output frame buffer, shaving off an additional **\~40ms** of latency per response. **Fixes** * Corrected header handling to ensure reliable data center failover. * Fixed a visual artifact where Cara 3 video frames occasionally displayed random noise. * Resolved a freeze-frame issue affecting \~1% of sessions ([Incident Report](https://status.anam.ai/incidents/01KC7A6Q9Q6H1JDZ83TP1EF1Z1)). ## SDK/API Changes **Improvements** * **API gateway guide:** added documentation and an example repository for routing Anam SDK traffic through your own API Gateway server. [View on GitHub](https://github.com/anam-org/anam-gateway-example). **November 27th, 2025** Livekit out of Beta and new sub-latency record ## 🎥 Livekit out of Beta and new latency record LiveKit integration is now generally available: drop Anam's expressive real-time avatars into any LiveKit Agents app so your AI can join LiveKit rooms as synchronised voice + video participants.\ It turns voice-only agents into face-and-voice experiences for calls, livestreams, and collaborative WebRTC spaces, with LiveKit handling infra and Anam handling the human layer. Docs *** ## ⚡ Record-breaking latency: 330 ms decrease in latency for all customers Server-side optimisations cuts average end-to-end latency by 330 ms for all customers, thanks to cumulative engine optimisations across transcription, frame generation, and frame writing, plus upgraded Deepgram Flux endpointing for faster, best in class turn-taking without regressions in voice quality or TTS. *** ## Lab Changes **Improvements** • Overhaul to avatar video upload and management system • Upgraded default Cartesia voices to Sonic 3 • Standardised voice model selection across the platform **Fixes** • Enhanced share-link management capabilities • Corrected LiveKit persona type identification logic *** ## Persona Changes **Improvements** • Server-side optimisations to our frame buffering to reduce latency of responses by \~250ms for all personas. **Fixes** • Changed timeout behavior to never time out based on heartbeats; only time out when websocket is disconnected for 10 seconds or more. • Fixed intermittent issue where persona stopped responding • Set pix\_fmt for video output, moving from yuvj420p (JPEG) to yuv420 color space to avoid incorrect encoding/output. • Added timeout in our silence breaking logic to prevent hangs. **November 6th, 2025** Introducing Anam Agents ## 🚀 Introducing Anam Agents Build and deploy AI agents in Anam that can engage alongside you. With Anam Agents, your Personas can now interact with your applications, access your knowledge, and trigger workflows directly through natural conversation. This marks Anam's evolution from conversational Personas to agentic Personas that think, decide, and execute. ## Knowledge Tools Give your Personas access to your company's knowledge. Upload docs to the Lab, and they'll use semantic retrieval to integrate the right info.\ [Docs for Knowledge Base](https://anam.ai/docs/personas/knowledge/overview) ## Client Tools Personas can control your interface in real time—open checkout, display modals, navigate UI, and update state by voice.\ [Docs for Client Tools](https://anam.ai/docs/personas/tools/client-tools) ## Webhook Tools Connect your Personas to external APIs and services. Create tickets, fetch status, update records, or fetch live data.\ [Docs for Webhook Tools](https://anam.ai/docs/personas/tools/webhook-tools) ## Intelligent Tool Selection Each Persona's LLM chooses tools based on intent—not scripts. You can create/manage tools on the Tools page in the Lab and attach them to any Persona from Build. **Anam Agents are available in beta for all users:** [https://lab.anam.ai/login](https://lab.anam.ai/login) *** ## Lab Changes **Improvements** * Cartesia Sonic-3 voices: the most expressive TTS model. * Voice modal expanded: 70+ languages, voice samples, Cartesia TTS now default. * Session reports work for custom LLMs. **Fixes** * Prevented auto-logout when switching contexts. * Fixed race conditions in cookie handling. * Resolved legacy session token issues. * Removed problematic voices. * Corrected player/stream aspect ratios on mobile. ## Persona Changes **Improvements** * Deepgram Flux support for turn-taking ([Deepgram Flux Details](https://deepgram.com/learn/introducing-flux-conversational-speech-recognition)) * Server-side optimization: reduced GIL contention and latency, faster connections. **Fixes** * Bug-fix for dangling LiveKit connections. ## Research **Improvements** * Our first open-source library!\ Metaxy, a metadata layer for ML/data pipelines:\ [Read more](https://anam-org.github.io/metaxy/main/#3-run-user-defined-computation-over-the-metadata-increment) | [GitHub](https://github.com/anam-org/metaxy) **October 6, 2025** Anam is now HIPAA compliant ## 🛡️ Anam is now HIPAA compliant A big milestone for our customers and partners. Anam now meets HIPAA requirements for handling protected health information. [**Learn more at the Anam Trust Center**](https://trust.anam.ai/) ## Lab Changes **Improvements** * Enhanced voice selection: search by use case/conversational style, 70+ languages. * Product tour update. * Streamlined One-Shot avatar creation. * Auto-generated Persona names based on selected avatar. * Session start now 1.1s faster. **Fixes** * Share links: fixed extra concurrency slot usage. ## Persona Changes **Improvements** * Improved TTS pronunciation via smarter text chunking. * Traceability and monitoring for session IDs. * Increased internal audio sampling rate to 24kHz. * Increased max websocket size to 16Mb. **Fixes** * Concurrency calculation now only considers sessions from last 2 hours. * Less freezing for slower LLMs. **September 21, 2025** Session Analytics ## 📊 Session Analytics Once a conversation ends, how do you review what happened? To help you understand and improve your Persona's performance, we're launching Session Analytics in the Lab. Now you can access a detailed report for every conversation, complete with a full transcript, performance metrics, and AI-powered analysis. * **Full Conversation Transcripts.** Review every turn of a conversation with a complete, time-stamped transcript. See what the user said and how your Persona responded, making it easy to diagnose issues and identify successful interaction patterns. * **Detailed Analytics & Timeline.** Alongside the transcript, a new Analytics tab provides key metrics grouped into "Transcript Metrics" (word count, turns) and "Processing Metrics" (e.g., LLM latency). A visual timeline charts the entire conversation, showing who spoke when and highlighting any technical warnings. * **AI-Powered Insights.** For a deeper analysis, you can generate an AI-powered summary and review key insights. This feature, currently powered by gpt-5-mini, evaluates the conversation for highlights, adherence to the system prompt, and user interruption rates. You can find your session history on the Sessions page in the Lab. Click on any past session to explore the new analytics report. This is available today for all session types, except for LiveKit sessions. For privacy-sensitive applications, session logging can be disabled via the SDK. ## Lab Changes **Improvements** * Improved Voice Discovery: The Voices page has been updated to be more searchable, allowing you to preview voices with a single click, and view new details like gender, TTS-model and language. **Fixes** * Fixed share-link session bug: Fixed bug of share-link sessions taking an extra concurrency slot. ## Persona Changes **Improvements** * Small improvement to connection time: Tweaks to how we perform webrtc signalling which allows for slightly faster connection times (\~900ms faster for p95 connection time). * Improvement to output audio quality for poor connections: Enabled Opus in-band FEC to improve audio quality under packet loss. * Small reduction in network latency: Optimisations have been made to our outbound media streams to reduce A/V jitter (and hence jitter buffer delay). Expected latency improvement is modest (\<50ms). **Fixes** * Fix for livekit sessions with slow TTS audio: Stabilizes LiveKit streaming by pacing output and duplicating frames during slowdowns to prevent underflow. **September 11, 2025** Intelligent LLM Routing for Faster Responses ## ⚡ Intelligent LLM Routing for Faster Responses The performance of LLM endpoints can be highly variable, with time-to-first-token latencies sometimes fluctuating by as much as 500ms from one day to the next depending on regional load. To solve this and ensure your personas respond as quickly and reliably as possible, we've rolled out a new intelligent routing system for LLM requests. This is active for both our turnkey customers and for customers using their own server-side **Custom LLMs** if they deploy multiple endpoints. This new system constantly monitors the health and performance of all configured LLM endpoints by sending lightweight probes at regular intervals. Using a time-aware moving average, it builds a real-time picture of network latency and processing speed for each endpoint. When a request is made, the system uses this data to calculate the optimal route, automatically shedding load from any overloaded or slow endpoints within a region. ## Lab Changes **Improvements** * Generate one-shot avatars from text prompts: You can now generate one-shot avatars from text prompts within the lab, powered by Gemini's new Nano Banana model. The one-shot creation flow has been redesigned for speed and ease-of-use. Text-to-Avatar and Image Upload Avatars are available across plans, subject to each plan's custom avatar allowance. * Improved management of published embed widgets: Published embed widgets can now be configured and monitored from the lab at [https://lab.anam.ai/personas/published](https://lab.anam.ai/personas/published). ## Persona Changes **Improvements** * Automatic failover to backup data centres: To ensure maximum uptime and reliability for our personas, we've implemented automatic failover to backup data centres. **Fixes** * Prevent session crash on long user speech: Previously, unbroken user speech exceeding 30 seconds would trigger a transcription error and crash the session. We now automatically truncate continuous speech to 30 seconds, preventing sessions from failing in these rare cases. * Allow configurable session lengths for Growth and above: We had a bug where longer sessions could hit an outdated timeout. This has now been fixed. * Resolved slow connection times caused by incorrect database region selection: An undocumented issue with our database provider led to incorrect region selection for our databases. Simply refreshing our credentials resolved the problem, resulting in a \~1s improvement in median connection times and \~3s faster p95 times. While our provider works on a permanent fix, we're actively monitoring for any recurrence. **September 4, 2025** Embed Widget ## 🔌 Embed Widget Embed personas directly into your website with our new widget. Within the **lab's build page** click Publish then generate your unique html snippet. This snippet will work in most common website builders, eg Wordpress.org or SquareSpace. For added security we recommend adding a whitelist with your domain url. This will lock down the persona to only work on your website. You can also cap the number of sessions or give the widget an expiration period. ## Lab Changes **Improvements** * ONE-SHOT avatars available via API: Accounts can now create one-shot avatars via API, subject to each plan's custom avatar allowance. Docs **here**. * Spend caps: It's now possible to set a spend cap on your account. Available in **profile settings**. ## Persona Changes **Fixes** * Prevent Cartesia from timing out when using slow custom LLMs: We've added a safeguard to prevent Cartesia contexts from unexpectedly closing during pauses in text streaming. With slower llms or if there's a break or slow-down in text being sent, your connection will now stay alive, ensuring smoother, uninterrupted interactions. For full legal and policy information, see: * [Trust Center](https://trust.anam.ai/) * [AI Governance](https://anam.ai/ai-governance) * [Terms of Service](https://anam.ai/terms-of-service) * [DPA](https://anam.ai/data-processing) * [Acceptable Use Policy](https://anam.ai/acceptable-use-policy) * [Privacy Policy](https://anam.ai/privacy-policy) # Embed Anam on your website Source: https://anam.ai/docs/embed/overview Add an Anam avatar to any website using the Widget, Player, or SDK. Compare options and follow platform-specific setup guides. There are three ways to add an Anam avatar to your site: the Widget, the Player, or the SDK. ## Which option should I use? > [!TIP] > > **Widget** — A pre-built Web Component. The avatar loads directly on your page with its own UI. You can listen to events, handle tool calls, and control it from JavaScript. > > **Player** — A single iframe. The avatar runs inside a sandboxed frame, completely isolated from your page. The most compatible option across website builders, but you can't interact with it from your own code. > > **SDK** — A JavaScript library for building your own interface from scratch. Use this when the pre-built UIs don't fit your design and you want full control over the experience. ## Widget The Widget loads as a `` [Web Component](https://developer.mozilla.org/en-US/docs/Web/API/Web_Components) on your page. It handles its own authentication, renders inside a Shadow DOM (so it won't clash with your styles), and dispatches DOM events you can listen to. > [tab] Features > > * Floating overlay or inline layout modes > * DOM events for analytics, error handling, and custom behavior > * Supports tool calls and text input > * Configure appearance from Lab or HTML attributes > [tab] Requirements > > * Your site must allow external JavaScript > * Configure your website origin under **Embed > Widget > Allowed Domains** in Lab and publish your changes; see [domain allowlisting](/docs/embed/widget/installation#domain-allowlisting) > * Microphone access required for voice > [tab] Example code > > ```html theme={"system"} > > > ``` See the [Widget documentation](https://anam.ai/docs/embed/widget/overview) for configuration, events, and framework-specific setup. ## Player The Player runs inside an iframe. Your page and the avatar are fully isolated from each other — different JavaScript contexts, different stylesheets, no interaction between the two. This makes it the most broadly compatible option, especially on platforms that restrict custom JavaScript. Open your persona in the [Anam Lab](https://lab.anam.ai) editor, select **Embed**, and choose **Iframe**. Enter your website origin under **Allowed Domains**, select **+** to add the origin, select **Publish**, then copy the iframe embed code. Widget and iframe embeds use the same persona origin settings. See [origin format and matching rules](/docs/embed/widget/installation#domain-allowlisting). > [tab] Features > > * Full Anam interface in a sandboxed frame > * Isolated from your site's CSS and JavaScript > * Works on platforms that block custom scripts but allow iframes > [tab] Requirements > > * Your site must allow iframe embedding > * Configure allowed origins in Lab, or intentionally enable **Allow everywhere** > * HTTPS required > * Microphone access required for voice > [tab] Example code > > ```html theme={"system"} > > ``` ## SDK The SDK gives you a JavaScript client and raw media streams. There's no pre-built UI — you build your own. Use this when you need complete control over how the avatar looks and behaves on your page. > [tab] Features > > * Full control over layout and appearance > * Direct access to video/audio streams > * Programmatic session management > [tab] Requirements > > * Your site must allow external JavaScript > * HTTPS required > * Microphone access required for voice See the [SDK Reference](https://anam.ai/docs/javascript-sdk/reference/basic-usage) for usage details. ## Platform compatibility Not every website builder supports every embed type. This depends on whether the platform lets you add custom JavaScript, iframes, or both. | Platform | Widget | Player | SDK | Notes | | - | - | - | - | - | | WordPress.org | ✅ | ✅ | ✅ | | | Webflow | ✅ | ✅ | ✅ | May need enterprise plan for script whitelisting | | Squarespace | ✅ | ✅ | ✅ | Requires paid plan | | Jimdo Creator | ✅ | ✅ | ✅ | Requires paid plan | | Shopify | ✅ | ✅ | ❌ | | | WordPress.com | ✅ | ✅ | ❌ | Requires paid plan | | GoDaddy | ✅ | ✅ | ❌ | | | Wix | ✅ | ❌ | ❌ | Requires paid plan | > [accordion] Platform-specific instructions > > ### WordPress.com > > Requires Business plan (\$25/month) or higher. Add Widget or Player code via Custom HTML block. SDK is not supported. > > ### WordPress.org (self-hosted) > > All three embed options work. Add code via the Gutenberg editor (Custom HTML block), your theme's `footer.php`, or a plugin like "Insert Headers and Footers". > > ### Shopify > > **Player:** Go to Online Store > Themes > Customize, add a "Custom Liquid" section, paste the iframe code. > > **Widget/SDK:** Go to Online Store > Themes > Actions > Edit code, open `theme.liquid`, add the code before ``. You may need to update your theme's Content Security Policy. > > ### Wix > > Requires a paid plan for custom code. Add Widget or Player code via Wix's HTML/Embed elements. SDK is not supported. > > ### Squarespace > > Requires Business plan or higher. Use a Code Block (HTML mode) for the Player, or Settings > Advanced > Code Injection for Widget/SDK. > > ### Webflow > > **Player:** Add an Embed element and paste the iframe code. Check Site Settings > Security > Secure Frame Headers if it doesn't load. > > **Widget/SDK:** Go to Project Settings > Custom Code, add to Footer Code. Changes aren't visible in the designer — publish first. > > ### GoDaddy > > **Widget/Player:** Add a "Custom Code" section and paste the embed code. SDK is not supported. > > ### Jimdo Creator > > Requires "Creator" mode (not "Dolphin"). Add an HTML/Widget element for the Player, or use Settings > Edit Head for Widget/SDK scripts. ## Security All embed options require HTTPS and microphone access. Users are prompted for microphone permissions the first time they interact with the avatar. ### Content Security Policy (CSP) If your site has a CSP, add these directives for the option you're using: ```http theme={"system"} # Widget Content-Security-Policy: script-src https://unpkg.com/@anam-ai/; connect-src https://api.anam.ai wss://connect.anam.ai wss://connect-us.anam.ai wss://connect-eu.anam.ai; # Player Content-Security-Policy: frame-src https://lab.anam.ai; # SDK Content-Security-Policy: connect-src https://api.anam.ai wss://connect.anam.ai wss://connect-us.anam.ai wss://connect-eu.anam.ai; ``` ### Browser support Use a browser that supports WebRTC and the browser APIs required by your integration. The SDK's video-element playback path uses `requestVideoFrameCallback()`. Test microphone permission, audio playback, and background/resume behavior on the devices and browser versions you deploy. See [Browser and mobile checks](/docs/resources/session-performance#browser-and-mobile-checks); API availability is not an Anam-tested support matrix. ## Troubleshooting > [accordion] Embed not appearing > > * Check the persona ID in the embed code copied from Lab; if using an existing share-link embed, check its share token instead > * Open browser DevTools (F12) and look for errors in the console > * Confirm your site is served over HTTPS, not HTTP > * Check that your platform plan supports custom embeds > * Try disabling ad blockers > [accordion] Microphone not working > > * Click the lock icon in the address bar to check permissions > * Microphone only works over HTTPS > * Try Chrome or Edge for best compatibility > * Disable privacy extensions that might block permissions > * Look for "NotAllowedError" or "NotFoundError" in the console > [accordion] Cross-origin errors > > * Add the required domains to your Content Security Policy (see above) > * For Player: check that X-Frame-Options isn't set to DENY > * For Widget and persona iframe embeds: make sure your website origin is in **Allowed Domains** in Lab's **Embed** tab and your changes are published > * Some platforms have non-configurable security policies ## FAQ > [accordion] Can I use multiple embed options on the same page? > > No. Use one Anam instance per page. > [accordion] What's the difference between a share token and an agent ID? > > The Widget's agent ID is your persona ID. Iframe code copied from **Embed > Iframe** also uses your persona ID. Both use the persona's **Allowed Domains** settings. Existing share-link embeds use a share token instead and have separate origin restrictions; changing the persona's embed settings does not change those share links. > [accordion] Can I customize the appearance? > > **Widget:** Yes — layout, position, UI toggles, and more. Configure from Lab or with HTML attributes. See [Widget configuration](https://anam.ai/docs/embed/widget/configuration). > > **Player:** Limited to sizing the iframe. > > **SDK:** Full control — you build the UI yourself. > [accordion] What if users deny microphone access? > > The Widget and SDK support text input as a fallback (enable with the `ui-text-input` attribute or SDK configuration). The Player shows a message asking users to grant access. ## Next steps > [card] [Widget documentation](https://anam.ai/docs/embed/widget/overview) > > Configuration, events, and framework-specific setup guides. > [card] [SDK reference](https://anam.ai/docs/javascript-sdk/reference/basic-usage) > > Build your own interface with the JavaScript SDK. # Configure the Anam Widget Source: https://anam.ai/docs/embed/widget/configuration Configure the Anam Widget with HTML attributes and Lab settings, then control its appearance, position, persona, and runtime behaviour. The widget loads its configuration from your published persona settings in [Anam Lab](https://lab.anam.ai). You can override any setting by adding HTML attributes directly to the `` element. ## Layout modes ### Floating The default mode. The widget renders as a fixed-position overlay, anchored to a corner of the viewport. Users click to expand it into a conversation panel. ```html theme={"system"} ``` The `initial-state` attribute controls whether the widget starts expanded or minimized: * `"expanded"` (default) the conversation panel is open immediately * `"minimized"` only the floating orb is visible; the user clicks to expand ### Inline The widget fills its parent container and becomes part of your page layout. There is no floating orb or expand/collapse behavior. ```html theme={"system"}
``` > [!TIP] > > The inline widget inherits the dimensions of its parent. Make sure the parent has explicit width and height (or aspect-ratio) set. ## Custom positioning For `floating` layout, the `position` attribute supports both predefined corners and custom CSS values using bracket syntax. ### Predefined positions | Value | CSS Result | | - | - | | `"bottom-right"` | `bottom: 24px; right: 24px` | | `"bottom-left"` | `bottom: 24px; left: 24px` | | `"top-right"` | `top: 24px; right: 24px` | | `"top-left"` | `top: 24px; left: 24px` | ### Bracket syntax For precise control, use bracket syntax to set arbitrary CSS position values: ```html theme={"system"} {/* 20px from the top, flush to the right edge */} {/* 100px from the bottom, 40px from the left */} ``` The format is `[property-value,property-value,...]` where: * Allowed properties: `top`, `right`, `bottom`, `left`, `margin`, `margin-top`, `margin-right`, `margin-bottom`, `margin-left` * Bare numbers are treated as pixels (e.g., `top-20` becomes `top: 20px`) * CSS units can be specified directly (e.g., `top-2rem`) ## Preview video Before a call starts, the widget plays a short, muted loop of the avatar over its still image. To show only the still image, turn off **Preview video** under **Interface** in the **Embed** tab in Anam Lab, then publish the persona. Embedded widgets can take a few minutes to pick up the change. You can also set the attribute on the element: ```html theme={"system"} ``` With the preview video off, the widget doesn't download the video. The attribute overrides the Lab setting for that element. ## Attributes reference `agent-id` is required. All other attributes are optional and will fall back to your Lab configuration. | Attribute | Type | Default | Description | | - | - | - | - | | `agent-id` | `string` | | Persona ID. Required for fetching config and creating sessions. | | `api-base-url` | `string` | `https://api.anam.ai` | API URL override. Only needed for non-production environments. | | `layout` | `"floating"` \| `"inline"` | `"floating"` | Widget layout mode. | | `initial-state` | `"expanded"` \| `"minimized"` | `"expanded"` | Initial state when layout is `floating`. Ignored for `inline`. | | `position` | `string` | `"bottom-right"` | Corner position or custom bracket syntax. Only applies to `floating` layout. | | `ui-mute-button` | `"true"` \| `"false"` | `"true"` | Show the microphone mute button. | | `ui-text-input` | `"true"` \| `"false"` | `"true"` | Show the text input field. | | `call-to-action` | `string` | `"Talk to our assistant"` | Custom text for the start button. | | `avatar-url` | `string` | | Override avatar thumbnail image URL. | | `avatar-video-url` | `string` | | Override avatar preview video URL. | | `ui-preview-video` | `"true"` \| `"false"` | `"true"` | Play the avatar preview video before a call. `"false"` shows the still image. | | `agent-name` | `string` | | Override persona name displayed in the default CTA. | > [!TIP] > > You can get avatar preview media from [GET `/v1/avatars/{id}`](/docs/api-reference/avatars/get-avatar). > The returned `videoUrl` expires after 1 hour, so use a freshly fetched URL or > self-host the MP4 before putting it in long-lived widget configuration. # Anam Widget Events Source: https://anam.ai/docs/embed/widget/events Listen for Anam Widget lifecycle and conversation events so your site can record analytics, update its interface, and respond to sessions. The `` element dispatches standard [DOM Custom Events](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) that cross the Shadow DOM boundary, so you can listen to them with `addEventListener` on the element itself or any ancestor. Event data is available on `event.detail`. ## Listening to events ```javascript theme={"system"} const widget = document.querySelector("anam-agent"); widget.addEventListener("anam-agent:session-started", (e) => { console.log("Session started:", e.detail.sessionId); }); widget.addEventListener("anam-agent:message-received", (e) => { console.log(`${e.detail.role}: ${e.detail.content}`); }); widget.addEventListener("anam-agent:error", (e) => { console.error(`Error [${e.detail.code}]: ${e.detail.message}`); }); ``` ## Events reference | Event Name | Payload | Description | | - | - | - | | `anam-agent:session-started` | `{ sessionId: string }` | A WebRTC session has been established. | | `anam-agent:session-ended` | `{ sessionId: string, reason: string }` | The session has ended (user-initiated or server-side). | | `anam-agent:message-received` | `{ role: "user" \| "agent", content: string }` | A transcript message was received from either party. | | `anam-agent:message-sent` | `{ content: string }` | The user sent a text message via the input field. | | `anam-agent:expanded` | `{}` | The widget was expanded (floating layout only). | | `anam-agent:collapsed` | `{}` | The widget was collapsed (floating layout only). | | `anam-agent:error` | `{ code: string, message: string }` | An error occurred (auth failure, network issue, etc.). | | `anam-agent:mic-muted` | `{}` | The user muted their microphone. | | `anam-agent:mic-unmuted` | `{}` | The user unmuted their microphone. | | `anam-agent:tool-call-started` | `{ toolName: string, toolCallId: string, toolType: string, toolSubtype?: string, arguments: object }` | The persona invoked a tool. | | `anam-agent:tool-call-completed` | `{ toolName: string, toolCallId: string, toolType: string, toolSubtype?: string, result: unknown, executionTime: number, documentsAccessed?: string[] }` | A tool call finished successfully. | | `anam-agent:tool-call-failed` | `{ toolName: string, toolCallId: string, toolType: string, toolSubtype?: string, errorMessage: string, executionTime: number }` | A tool call failed. | In the tool-call payloads, `toolType` is `"client"` for browser-side tools and `"server"` for tools that run on Anam's side. The optional `toolSubtype` further identifies the tool and is currently set for server tools, such as `"webhook"` or `"knowledge"`. `executionTime` is in milliseconds, and `documentsAccessed` is present only for knowledge (RAG) tools. ## Reacting to tool calls When your persona invokes a [tool](https://anam.ai/docs/personas/tools/overview), the widget surfaces the tool-call lifecycle as DOM events, so your page can react to it without wiring up the JavaScript SDK directly. Use the `toolType` field to act only on client-side tools (those meant to run in the browser, such as navigation or cart updates) and ignore server-side tools (webhook and knowledge tools that run on Anam's side): ```javascript theme={"system"} const widget = document.querySelector("anam-agent"); widget.addEventListener("anam-agent:tool-call-started", (e) => { const { toolName, toolType, arguments: args } = e.detail; // Server-side tools (webhook, knowledge) run on Anam's side — ignore them here. if (toolType !== "client") return; if (toolName === "redirect") { window.location.href = args.url; } }); ``` The `tool-call-completed` and `tool-call-failed` events report the outcome of each call, which is useful for logging and analytics: ```javascript theme={"system"} widget.addEventListener("anam-agent:tool-call-completed", (e) => { const { toolName, executionTime, documentsAccessed } = e.detail; console.log(`${toolName} finished in ${executionTime}ms`); if (documentsAccessed) { console.log("Documents used:", documentsAccessed); } }); widget.addEventListener("anam-agent:tool-call-failed", (e) => { const { toolName, errorMessage } = e.detail; console.error(`${toolName} failed: ${errorMessage}`); }); ``` You still define and configure the tools on your persona in [Anam Lab](https://lab.anam.ai). See [Client Tools and Events](https://anam.ai/docs/personas/tools/client-tools) for how tools are created. > [!NOTE] > > These are notification events — the widget reports tool calls but does not send a value back to the persona. Use client-side tools with the widget as fire-and-forget actions (`awaitResult: false`). If you need to return a result to the LLM, integrate with the JavaScript SDK's [`registerToolCallHandler`](https://anam.ai/docs/personas/tools/client-tools#using-registertoolcallhandler-recommended) instead of the embed widget. ## Common patterns > [accordion] Analytics tracking > > Track session starts, message counts, and engagement duration: > > ```javascript theme={"system"} > const widget = document.querySelector("anam-agent"); > let sessionStart; > > widget.addEventListener("anam-agent:session-started", (e) => { > sessionStart = Date.now(); > analytics.track("avatar_session_started", { > sessionId: e.detail.sessionId, > }); > }); > > widget.addEventListener("anam-agent:session-ended", (e) => { > const duration = Date.now() - sessionStart; > analytics.track("avatar_session_ended", { > sessionId: e.detail.sessionId, > reason: e.detail.reason, > durationMs: duration, > }); > }); > > widget.addEventListener("anam-agent:message-received", (e) => { > if (e.detail.role === "agent") { > analytics.track("avatar_message", { > contentLength: e.detail.content.length, > }); > } > }); > ``` > [accordion] Show or hide page elements > > React to widget expand/collapse to adjust your page layout: > > ```javascript theme={"system"} > const widget = document.querySelector("anam-agent"); > const sidebar = document.getElementById("sidebar"); > > widget.addEventListener("anam-agent:expanded", () => { > sidebar.style.marginRight = "420px"; > }); > > widget.addEventListener("anam-agent:collapsed", () => { > sidebar.style.marginRight = "0"; > }); > ``` > [accordion] Error handling > > Display user-facing messages or trigger fallback behavior: > > ```javascript theme={"system"} > const widget = document.querySelector("anam-agent"); > > widget.addEventListener("anam-agent:error", (e) => { > const { code, message } = e.detail; > > if (message.includes("Origin not allowed")) { > showBanner("Widget configuration required. Contact your admin."); > } else if (message.includes("Too many requests")) { > showBanner("Please wait a moment before trying again."); > } else { > showBanner("Something went wrong. Please try again."); > } > }); > ``` # Add the Anam Widget to Framer Source: https://anam.ai/docs/embed/widget/framer Add a conversational Anam avatar to a Framer site, configure the widget, and verify that domain authentication and microphone access work. Add an Anam avatar to your Framer site with the [Anam Widget](/docs/embed/widget/overview). > [card] > > [Open](https://www.framer.com/marketplace/plugins/anam-avatar/preview/) ## Quick Start **1. Configure a persona** Open a persona in [Anam Lab](https://lab.anam.ai) and configure its avatar, voice, and behavior. **2. Publish and copy the widget code** In the **Embed** tab, choose **Widget** and enter your Framer domain under **Allowed Domains**, then select **+** to add the origin. Select **Publish**, then copy the widget embed code. Add the origin visitors actually use, including any custom domain. See [origin format and matching rules](/docs/embed/widget/installation#domain-allowlisting). **3. Add the widget in Framer** Open the [Anam Avatar plugin](https://www.framer.com/marketplace/plugins/anam-avatar/preview/) in Framer and paste the widget code. ## Next Steps > [card] [Widget Configuration](https://anam.ai/docs/embed/widget/configuration) > > Customize the widget's appearance and behavior > [card] [Widget Events](https://anam.ai/docs/embed/widget/events) > > Listen for widget events in your Framer website # Install the Anam Widget Source: https://anam.ai/docs/embed/widget/installation Install the Anam Widget from the CDN or npm, load it in popular JavaScript frameworks, and connect it to the configuration in Anam Lab. > [tab] CDN (Recommended) > > Include a script tag and the custom element. No build step required. > > ```html unpkg theme={"system"} > > > ``` > > ```html jsdelivr theme={"system"} > > > ``` > > The script auto-registers the `` custom element. Place it anywhere in your HTML. The `async` attribute ensures it doesn't block page rendering. > [tab] npm > > For projects with a build system, install the package and register the element in your application code. > > ```bash theme={"system"} > npm install @anam-ai/agent-widget > ``` > > ```javascript theme={"system"} > import { registerWidget } from "@anam-ai/agent-widget"; > > registerWidget(); > ``` > > Then use `` anywhere in your templates or JSX. ## Framework-specific setup > [tab] Plain HTML > > Add the snippet before the closing `` tag: > > ```html theme={"system"} > > > > My Site > > > > > > > > > ``` > [tab] Next.js > > Use the `Script` component and render the custom element in a client component: > > ```tsx app/components/AnamWidget.tsx theme={"system"} > "use client"; > > import Script from "next/script"; > > export function AnamWidget() { > return ( > <> > ``` ## Next steps > [card] [Installation](https://anam.ai/docs/embed/widget/installation) > > CDN, npm, and framework-specific setup guides. > [card] [Configuration](https://anam.ai/docs/embed/widget/configuration) > > All HTML attributes, layout options, and positioning. > [card] [Shopify](https://anam.ai/docs/embed/widget/shopify) > > Add the widget to your Shopify store. > [card] [WordPress](https://anam.ai/docs/embed/widget/wordpress) > > Add the widget to your WordPress site. # Add the Anam Widget to Shopify Source: https://anam.ai/docs/embed/widget/shopify Add the Anam Widget to a Shopify theme, place the avatar across your storefront, and configure the allowed domain in Anam Lab. Add a conversational AI avatar to your Shopify store using the [Anam Widget](https://anam.ai/docs/embed/widget/overview) -- no coding required. > [card] [Cookbook: Adding the Anam Widget to Shopify](https://anam.ai/cookbook/widget-shopify) > > Step-by-step guide with screenshots for embedding the widget in your Shopify theme ## Overview The Anam widget can be added to any Shopify store by editing the `theme.liquid` file. Once installed, the avatar appears on every page (or specific pages using Liquid conditionals). ## Quick Start **1. Create a persona in Anam Lab** Go to [Anam Lab](https://lab.anam.ai), create a persona, and configure its avatar, voice, and behavior. Navigate to the **Embed** tab and choose **Widget** to get your persona ID and configure the widget appearance. **2. Allowlist your Shopify domain** In the **Embed** tab, choose **Widget** and enter your Shopify domain (e.g., `https://your-store.myshopify.com`) under **Allowed Domains**, then select **+** to add the origin. Select **Publish** before testing the embed. Add the origin visitors actually use, including any custom domain. See [origin format and matching rules](/docs/embed/widget/installation#domain-allowlisting). **3. Edit your Shopify theme** In your Shopify admin, go to **Online Store > Themes > Edit code** and open `theme.liquid`. Add the widget snippet after the opening `` tag: ```html theme={"system"} ``` **4. Publish** Click **Publish** in Anam Lab to make the persona live on your store. > [!TIP] > > Use Shopify's Liquid conditionals to show the widget only on specific pages. See the [cookbook](https://anam.ai/cookbook/widget-shopify) for examples. ## Next Steps > [card] [Widget Configuration](https://anam.ai/docs/embed/widget/configuration) > > Customize the widget's appearance and behavior > [card] [Widget Events](https://anam.ai/docs/embed/widget/events) > > Listen for widget events in your Shopify theme # Add the Anam Widget to Squarespace Source: https://anam.ai/docs/embed/widget/squarespace Add the Anam Widget to a Squarespace site with code injection, then configure placement, domain access, and the avatar experience. Add a conversational AI avatar to your Squarespace site using the [Anam Widget](https://anam.ai/docs/embed/widget/overview) and Squarespace's code injection feature -- no coding required. > [card] [Cookbook: Adding the Anam Widget to Squarespace](https://anam.ai/cookbook/widget-squarespace) > > Step-by-step guide for embedding the widget using Squarespace's code injection ## Quick Start **1. Create a persona in Anam Lab** Go to [Anam Lab](https://lab.anam.ai), create a persona, and configure its avatar, voice, and behavior. Navigate to the **Embed** tab and choose **Widget** to get your persona ID. **2. Allowlist your domain** In the **Embed** tab, choose **Widget** and enter your Squarespace domain under **Allowed Domains**, then select **+** to add the origin. Select **Publish** before testing the embed. Add the origin visitors actually use, including any custom domain. See [origin format and matching rules](/docs/embed/widget/installation#domain-allowlisting). **3. Add to Squarespace** In your Squarespace dashboard, go to **Settings > Advanced > Code Injection**. Paste the following into the **Header** section: ```html theme={"system"} ``` Then paste into the **Footer** section: ```html theme={"system"} ``` **4. Publish** Click **Publish** in Anam Lab and save your Squarespace settings. ## Next Steps > [card] [Widget Configuration](https://anam.ai/docs/embed/widget/configuration) > > Customize the widget's appearance and behavior > [card] [Widget Events](https://anam.ai/docs/embed/widget/events) > > Listen for widget events # Add the Anam Widget to Wix Source: https://anam.ai/docs/embed/widget/wix Add the Anam Widget to a Wix site, choose where it appears, and configure the site domain and avatar behaviour in Anam Lab. Add a conversational AI avatar to your Wix website using the [Anam Widget](https://anam.ai/docs/embed/widget/overview) and Wix's Custom Code feature -- no coding required. > [card] [Cookbook: Adding the Anam Widget to Wix](https://anam.ai/cookbook/widget-wix) > > Step-by-step guide for embedding the widget on your Wix site ## Quick Start **1. Create a persona in Anam Lab** Go to [Anam Lab](https://lab.anam.ai), create a persona, and configure its avatar, voice, and behavior. Navigate to the **Embed** tab and choose **Widget** to get your persona ID. **2. Allowlist your domain** In the **Embed** tab, choose **Widget** and enter your Wix domain under **Allowed Domains**, then select **+** to add the origin. Select **Publish** before testing the embed. Add the origin visitors actually use, including any custom domain. See [origin format and matching rules](/docs/embed/widget/installation#domain-allowlisting). **3. Add to Wix** In your Wix dashboard, go to **Settings > Custom Code**. Click **Add Custom Code** and paste: ```html theme={"system"} ``` Set placement to **All pages** and loading to **Load code once**. **4. Publish** Click **Publish** in Anam Lab and publish your Wix site. ## Next Steps > [card] [Widget Configuration](https://anam.ai/docs/embed/widget/configuration) > > Customize the widget's appearance and behavior > [card] [Widget Events](https://anam.ai/docs/embed/widget/events) > > Listen for widget events # Add the Anam Widget to WordPress Source: https://anam.ai/docs/embed/widget/wordpress Add the Anam Widget to a WordPress site using a code block or theme integration, then configure domain access and presentation. Add a conversational AI avatar to your WordPress site using the [Anam Widget](https://anam.ai/docs/embed/widget/overview) and the WPCode plugin -- no coding required. > [card] [Cookbook: Adding the Anam Widget to WordPress](https://anam.ai/cookbook/widget-wordpress) > > Step-by-step guide for embedding the widget using WPCode ## Quick Start **1. Create a persona in Anam Lab** Go to [Anam Lab](https://lab.anam.ai), create a persona, and configure its avatar, voice, and behavior. Navigate to the **Embed** tab and choose **Widget** to get your persona ID. **2. Allowlist your domain** In the **Embed** tab, choose **Widget** and enter your WordPress domain under **Allowed Domains**, then select **+** to add the origin. Select **Publish** before testing the embed. Add the origin visitors actually use, including any custom domain. See [origin format and matching rules](/docs/embed/widget/installation#domain-allowlisting). **3. Install WPCode** In your WordPress admin, go to **Plugins > Add New** and search for **WPCode**. Install and activate it. **4. Add the widget code** Go to **Code Snippets > Add Snippet** and create a new **HTML Snippet**. Paste: ```html theme={"system"} ``` Set the insertion method to **Site Wide Header** and activate the snippet. **5. Publish** Click **Publish** in Anam Lab to make the persona live. ## Next Steps > [card] [Widget Configuration](https://anam.ai/docs/embed/widget/configuration) > > Customize the widget's appearance and behavior > [card] [Widget Events](https://anam.ai/docs/embed/widget/events) > > Listen for widget events # Step 1: Agent configuration Source: https://anam.ai/docs/integrations/elevenlabs/agent-configuration Configure your ElevenLabs agent for Anam, including audio format, voice settings, response speed, and language model choice. Start here. In this step, configure the ElevenLabs agent that will provide speech recognition, responses, and a voice for your Anam avatar. ## Configure the audio format 1. Open your agent in the [ElevenLabs agent dashboard](https://elevenlabs.io/app/agents/agents). 2. In the **Advanced** tab, set the user input audio format to **PCM 16000Hz** and save the change. Anam also supports other PCM sample rates and resamples audio automatically. 3. Keep the agent ID available. You will use it when connecting the browser in step three. ## Recommended settings Adjust these settings in the same dashboard to suit your application. **LLM choice.** Choose a low-latency model and test its response time with your agent's prompts and tools. If the model supports reasoning, start with a low reasoning budget or effort level. See [ElevenLabs' model selection guide](https://elevenlabs.io/docs/eleven-agents/customization/llm#choosing-a-model) for current options. If slower LLM responses are a problem, set a soft timeout in the Advanced tab (e.g. 2 seconds) and configure it to either use a fixed filler phrase or generate one with a faster LLM while the main response generates. **Voices.** In the **Agent Voice** settings, select **Eleven v4 Turbo** (`eleven_v4_turbo`). We recommend it over **Eleven v4** (`eleven_v4`) for higher throughput and lower latency. Both models support audio tags, and existing v3 Conversational agents can keep using the same tags. Anam maps [recognized tags](/docs/integrations/elevenlabs/director-notes), such as `[laughs]`, `[whispers]`, and `[gasps]`, to Director Notes for the avatar's performance. The model is configured in ElevenLabs, so changing it does not require changes to the Anam session code. **Background noise.** If background noise is being picked up, turn on the Filter Background Speech toggle in the Advanced menu. It's unclear whether this has an effect on latency. **Response speed.** For the quickest responses, set Eagerness to Eager in the Advanced menu. Your agent is configured. Next, connect it to Anam. > [card] [Step 2: Set up the server](/docs/integrations/elevenlabs/server-side-setup) > > Create the API route that fetches an ElevenLabs signed URL and returns an Anam session token. # Server-Side ElevenLabs Agents with Anam Avatars Source: https://anam.ai/docs/integrations/elevenlabs/agents Build a server-side ElevenLabs Conversational AI agent with a real-time Anam avatar using audio passthrough. Build this quickstart with a coding agent Paste this prompt into your coding agent to set up and run the Next.js demo. Copy prompt [View on GitHub](https://github.com/anam-org/anam-cookbook/tree/main/examples/elevenlabs-server-side-agent-nextjs) ## Overview Anam's server-side ElevenLabs integration connects an Anam avatar to an ElevenLabs Conversational AI agent. Your server fetches a short-lived ElevenLabs signed URL and includes it when creating an Anam session token. The browser uses the Anam JavaScript SDK to start the WebRTC session and render the avatar. Anam sends conversation audio to ElevenLabs, receives the generated speech, and keeps the avatar in sync. API keys stay on the server. Completed sessions appear in Anam Lab with a transcript and, when available, a [recording](/docs/personas/session/recordings). [Zero Data Retention](/docs/security/privacy) sessions store neither. ## Quickstart Follow these three steps to give your ElevenLabs agent a face: 1. [Configure your ElevenLabs agent](/docs/integrations/elevenlabs/agent-configuration) for the audio format and voice settings. 2. [Set up the server](/docs/integrations/elevenlabs/server-side-setup) to fetch a signed URL and create an Anam session token. 3. [Start the avatar session](/docs/integrations/elevenlabs/start-session) in your browser. ### Upgrade your avatar Build on your working session with [Director Notes](/docs/integrations/elevenlabs/director-notes) for expressive avatar performance, [session customisation](/docs/integrations/elevenlabs/session-customisation) for personalised conversations, and [client tools](/docs/integrations/elevenlabs/client-tools) for actions in your app. For connection and playback issues, see [Troubleshooting](/docs/integrations/elevenlabs/troubleshooting). ## How it works The session is split between your Next.js server, the browser, and Anam's engine: ``` Server: 1. Fetch signed URL from ElevenLabs API 2. Create Anam session token with Cara 4 Director Notes and elevenLabsAgentSettings Client: 3. createClient(sessionToken) 4. streamToVideoElement("avatar-video") Engine (automatic): 5. Connects to ElevenLabs agent via signed URL 6. User speech → ElevenLabs STT → LLM → TTS → Anam face rendering 7. Supported audio tags → Director Notes cues 8. Avatar video delivered over WebRTC 9. Client tool calls and results forwarded over the same connection ``` The Next.js route supplies the ElevenLabs settings when it creates the session token. The browser receives that token and uses the Anam JavaScript SDK to start the avatar stream. ## Supported features These ElevenLabs agent features work through the server-side integration: voice intelligence (STT, LLM, TTS), expressive voices, mapped Director Notes cues, interruption handling, custom knowledge bases, server-side tools (webhooks), conversation history, and client tools. The ElevenLabs connection and API keys remain server-side when client tools are enabled. Only the specific handler code runs in the browser. > [card] [Step 1: Configure your agent](/docs/integrations/elevenlabs/agent-configuration) > > Configure the ElevenLabs agent before adding the server route and browser client. # Add ElevenLabs client tools Source: https://anam.ai/docs/integrations/elevenlabs/client-tools Configure an ElevenLabs client tool and register a JavaScript SDK handler to display notifications and return results to the conversation. Let your agent take action in your app, such as displaying a notification during a conversation. Build on your working session from the [three-step quickstart](/docs/integrations/elevenlabs/agents#quickstart) by adding client tools. This example includes an ElevenLabs client tool named `show_notification`. When the agent calls it, Anam forwards the call to the JavaScript SDK in the browser. The handler displays the requested message and returns a result to the ElevenLabs conversation. Start with the [browser session setup](/docs/integrations/elevenlabs/start-session), then add the tool and handler below. ## Configure the tool in ElevenLabs In the ElevenLabs agent dashboard, open **Tools** and add the following tool: | Setting | Value | | - | - | | Tool Type | **Client** | | Name | `show_notification` | | Wait for response | Enabled | | Required parameter | `message` (String) | Tool and parameter names are case-sensitive. Describe the tool as displaying a message on screen when the user asks for one. The [ElevenLabs client tools guide](https://elevenlabs.io/docs/eleven-agents/customization/tools/client-tools) shows where to find these settings. ## Register the handler Register the handler before starting the Anam stream: ```typescript theme={"system"} const unregisterToolHandlers = [ anamClient.registerToolCallHandler("show_notification", { onStart: async ({ arguments: args }) => { if (typeof args.message !== "string" || !args.message.trim()) { throw new Error("message must be a non-empty string"); } const message = args.message.trim(); setNotification(message); return `Displayed the notification: ${message}`; }, onFail: async ({ errorMessage }) => { console.error("show_notification failed:", errorMessage); }, }), ]; await anamClient.streamToVideoElement("avatar-video"); ``` Returning a string from `onStart` sends that value back as the tool result. With **Wait for response** enabled, ElevenLabs adds it to the conversation context before the agent continues. Keep the functions in `unregisterToolHandlers` and call them when the session ends or the component unmounts. The [Anam client tools docs](/docs/personas/tools/client-tools) cover the full handler lifecycle. The [complete example](https://github.com/anam-org/anam-cookbook/tree/main/examples/elevenlabs-server-side-agent-nextjs) includes argument validation, a notification UI, handler cleanup, and a status panel for checking tool calls. ## Keep building > [card] [Director Notes](/docs/integrations/elevenlabs/director-notes) > > Add expressions that follow your agent's voice. > [card] [Session customisation](/docs/integrations/elevenlabs/session-customisation) > > Personalise conversations with user-specific variables and agent settings. # Director Notes with ElevenLabs Source: https://anam.ai/docs/integrations/elevenlabs/director-notes Configure avatar expression with ElevenLabs audio tags, Anam Director Notes styles, and cue events for Cara 4 avatars. Give your avatar more expression with cues that follow the agent's voice. Start with a working session from the [three-step quickstart](/docs/integrations/elevenlabs/agents#quickstart), then add Director Notes. Director Notes give the avatar a baseline performance style and temporary expression cues. The [server route](/docs/integrations/elevenlabs/server-side-setup) starts with the `warm` preset at `0.5` expressivity. Expressivity accepts values from `0` to `1`; higher values strengthen both the active style and speech-driven motion. > [!WARNING] > > Director Notes only work with Cara 4 avatars. Use a Cara 4 avatar ID and set `avatarModel` to `"cara-4"`, as shown in the [server route](/docs/integrations/elevenlabs/server-side-setup). Select **Eleven v4 Turbo** (`eleven_v4_turbo`) in the ElevenLabs **Agent Voice** settings. Eleven v4 and v3 Conversational also support audio tags. Add a short rule to the agent's system prompt: ```text theme={"system"} Use ElevenLabs audio tags sparingly when the delivery should change. For testing, use tags such as [excited], [laughs], [whispers], [sighs], [gasps], [angrily], [sarcastic], or [nervous]. Place each tag immediately before the words it should affect. Do not explain or read the tags aloud. ``` [ElevenLabs uses the same audio tags for v3 and v4](https://elevenlabs.io/docs/help-center/product/core-capabilities/text-to-speech/how-do-audio-tags-work-with-eleven-v3-and-v4), including v4 Turbo. Anam recognizes the following provider tags and maps each group to one Director Note cue: | Director Note cue | Recognized ElevenLabs tags | | - | - | | `happy` | `[excited]`, `[happily]`, `[cheerfully]`, `[elated]` | | `laughter` | `[laugh]`, `[laughs]`, `[laughing]`, `[laughs harder]`, `[starts laughing]`, `[chuckles]`, `[chuckling]`, `[giggles]`, `[giggling]` | | `warm` | `[whispers]`, `[whispering]`, `[quietly]` | | `playful` | `[sarcastic]`, `[playfully]` | | `curious` | `[curiously]`, `[quizzical]`, `[quizzically]` | | `concerned` | `[sigh]`, `[sighs]`, `[exhales]` | | `sad` | `[sadly]`, `[sorrowful]`, `[tearful]`, `[crying]` | | `surprised` | `[gasp]`, `[gasps]`, `[startled]` | | `angry` | `[angrily]`, `[furious]`, `[intensely]` | | `distressed` | `[nervous]`, `[fearful]`, `[scared]` | This table is the complete alias list that Anam recognizes. ElevenLabs supports other audio tags, but Anam does not map them to Director Notes. A recognized tag is removed from the transcript before it reaches the browser. An unknown bracketed tag remains ordinary transcript text. To see whether the engine recognized and applied a tag, listen for `DIRECTOR_NOTE_CUE_APPLIED` in the [step 3 component](/docs/integrations/elevenlabs/start-session#working-component-example): ```typescript theme={"system"} // In the component body const [directorNoteActivity, setDirectorNoteActivity] = useState<{ cueTag: string; correlationId: string; } | null>(null); // Inside start(), with the other listeners anamClient.addListener(AnamEvent.DIRECTOR_NOTE_CUE_APPLIED, (evt) => { setDirectorNoteActivity({ cueTag: evt.cueTag, correlationId: evt.correlationId, }); }); // In the returned JSX {directorNoteActivity &&

Last cue: {directorNoteActivity.cueTag}

} ``` The event contains the normalized Anam cue. For example, ElevenLabs `[laughs]` produces a `laughter` cue, while `[whispers]` produces `warm`. The [Anam Director Notes guide](/docs/personas/director-notes) covers baseline styles, expressivity, cue events, and Cara 4 requirements. ## Keep building > [card] [Session customisation](/docs/integrations/elevenlabs/session-customisation) > > Personalise conversations with user-specific variables and agent settings. > [card] [Client tools](/docs/integrations/elevenlabs/client-tools) > > Let your agent trigger actions in your app. # Step 2: Server-side setup Source: https://anam.ai/docs/integrations/elevenlabs/server-side-setup Create a Next.js API route that fetches an ElevenLabs signed URL and returns an Anam session token while keeping API keys on the server. Complete [step one: Agent configuration](/docs/integrations/elevenlabs/agent-configuration) first. In this step, add the server route that connects your ElevenLabs agent to Anam. ## Prerequisites * Node.js 20.9+ * A Next.js project using the App Router, or the [demo project](https://github.com/anam-org/anam-cookbook/tree/main/examples/elevenlabs-server-side-agent-nextjs) * An [Anam](https://anam.ai) account and API key (sign up free at [lab.anam.ai](https://lab.anam.ai)) * A Cara 4 avatar from the Anam Lab Avatars page * An [ElevenLabs](https://elevenlabs.io) account with a Conversational AI agent configured via the dashboard ## Create the server route You need one API route. It fetches a signed URL from ElevenLabs, then passes it to Anam when creating a session token. API keys stay server-side. The client sends only the `avatarId` (which face to render) and `agentId` (which ElevenLabs agent to use). ### Environment variables ```bash theme={"system"} ANAM_API_KEY=your_anam_api_key ELEVENLABS_API_KEY=your_elevenlabs_api_key ``` ### API route ```typescript theme={"system"} // app/api/anam-session/route.ts import { NextResponse } from "next/server"; export async function POST(request: Request) { const anamApiKey = process.env.ANAM_API_KEY; if (!anamApiKey) { return NextResponse.json( { error: "ANAM_API_KEY must be set" }, { status: 500 } ); } const elevenLabsApiKey = process.env.ELEVENLABS_API_KEY; if (!elevenLabsApiKey) { return NextResponse.json( { error: "ELEVENLABS_API_KEY must be set" }, { status: 500 } ); } const body = await request.json().catch(() => ({})); const { avatarId, agentId } = body; if (!avatarId) { return NextResponse.json( { error: "avatarId is required" }, { status: 400 } ); } if (!agentId) { return NextResponse.json( { error: "agentId is required" }, { status: 400 } ); } // 1. Get a signed URL from ElevenLabs const elRes = await fetch( `https://api.elevenlabs.io/v1/convai/conversation/get-signed-url?agent_id=${agentId}`, { headers: { "xi-api-key": elevenLabsApiKey }, } ); if (!elRes.ok) { const text = await elRes.text(); return NextResponse.json( { error: `ElevenLabs API error: ${elRes.status} ${text}` }, { status: elRes.status } ); } const { signed_url: signedUrl } = await elRes.json(); // 2. Create an Anam session token with the ElevenLabs agent settings const anamRes = await fetch("https://api.anam.ai/v1/auth/session-token", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${anamApiKey}`, }, body: JSON.stringify({ personaConfig: { avatarId, avatarModel: "cara-4", directorNotes: { presetStyle: "warm", expressivity: 0.5, }, }, environment: { elevenLabsAgentSettings: { signedUrl, agentId, }, }, }), }); if (!anamRes.ok) { const text = await anamRes.text(); return NextResponse.json( { error: `Anam API error: ${anamRes.status} ${text}` }, { status: anamRes.status } ); } const data = await anamRes.json(); return NextResponse.json({ sessionToken: data.sessionToken }); } ``` The `environment.elevenLabsAgentSettings` field configures ElevenLabs as the session's speech recognition, language model, and text-to-speech provider. `avatarModel` and `directorNotes` enable a warm Cara 4 performance at the start of the session. > [!NOTE] > > The signed URL is short-lived (typically valid for 15 minutes). Anam uses it immediately when the client connects, so there's no issue with expiry in normal usage. If you're pre-fetching tokens, create them just before the client needs them. Your server route is ready. Next, start an avatar session in your browser. > [card] [Step 3: Start the avatar session](/docs/integrations/elevenlabs/start-session) > > Connect the browser, enable your microphone, and have your first conversation with the avatar. # Customise an ElevenLabs session Source: https://anam.ai/docs/integrations/elevenlabs/session-customisation Personalise ElevenLabs conversations through Anam session tokens with dynamic variables, configuration overrides, user IDs, and custom LLM parameters. Make conversations personal with user-specific greetings, language preferences, and agent instructions. Build on your working session from the [three-step quickstart](/docs/integrations/elevenlabs/agents#quickstart). The Anam session token API accepts additional fields that are passed through to ElevenLabs when starting the conversation. These let you personalise each session — greet users by name, switch languages, override the system prompt, or pass data to a custom LLM backend. See the [ElevenLabs personalisation overview](https://elevenlabs.io/docs/eleven-agents/customization/personalization) for full details. All of these fields are optional and go inside `elevenLabsAgentSettings` alongside `signedUrl` and `agentId` in your [server route](/docs/integrations/elevenlabs/server-side-setup): ```typescript theme={"system"} body: JSON.stringify({ personaConfig: { avatarId }, environment: { elevenLabsAgentSettings: { signedUrl, agentId, dynamicVariables: { ... }, // optional conversationConfigOverride: { ... }, // optional userId: "...", // optional customLlmExtraBody: { ... }, // optional }, }, }), ``` ## Dynamic variables Dynamic variables are the simplest way to personalise a conversation at runtime. Define placeholders like `{{user_name}}` in your agent's system prompt or first message in the ElevenLabs dashboard, then fill them in when creating the session token: ```typescript theme={"system"} body: JSON.stringify({ personaConfig: { avatarId }, environment: { elevenLabsAgentSettings: { signedUrl, agentId, dynamicVariables: { user_name: "Alice", account_type: "premium", }, }, }, }), ``` See [ElevenLabs dynamic variables docs](https://elevenlabs.io/docs/eleven-agents/customization/personalization/dynamic-variables) for the full syntax. ## Overrides Overrides let you change agent behaviour per conversation — things like the first message, language, system prompt, or TTS voice. Only include the fields you want to override; everything else keeps its default from the ElevenLabs dashboard. ```typescript theme={"system"} body: JSON.stringify({ personaConfig: { avatarId }, environment: { elevenLabsAgentSettings: { signedUrl, agentId, conversationConfigOverride: { agent: { prompt: { prompt: "You are a helpful assistant. Always respond in Spanish.", }, firstMessage: "¡Hola! ¿En qué puedo ayudarte hoy?", language: "es", }, }, }, }, }), ``` See [ElevenLabs overrides docs](https://elevenlabs.io/docs/eleven-agents/customization/personalization/overrides) for the full list of overridable fields. ## User ID Pass `userId` to identify the caller in ElevenLabs analytics and conversation history: ```typescript theme={"system"} elevenLabsAgentSettings: { signedUrl, agentId, userId: "user_abc123", }, ``` ## Custom LLM extra body If your ElevenLabs agent is configured to call a custom LLM backend, `customLlmExtraBody` lets you pass arbitrary parameters alongside each request: ```typescript theme={"system"} body: JSON.stringify({ personaConfig: { avatarId }, environment: { elevenLabsAgentSettings: { signedUrl, agentId, customLlmExtraBody: { session_context: { region: "eu", tier: "enterprise" }, }, }, }, }), ``` See [ElevenLabs custom LLM docs](https://elevenlabs.io/docs/eleven-agents/customization/llm/custom-llm) for how to set up a custom LLM backend. ## Keep building > [card] [Director Notes](/docs/integrations/elevenlabs/director-notes) > > Add expressions that follow your agent's voice. > [card] [Client tools](/docs/integrations/elevenlabs/client-tools) > > Let your agent trigger actions in your app. # Step 3: Start the avatar session Source: https://anam.ai/docs/integrations/elevenlabs/start-session Connect the browser to your Anam session token, stream the ElevenLabs avatar, and handle transcripts and session lifecycle in React. This is the final step of the quickstart. With the [server route from step two](/docs/integrations/elevenlabs/server-side-setup) in place, connect the browser and start a conversation with your avatar. ## Install the JavaScript SDK In your Next.js project, install the SDK with your package manager: ```bash theme={"system"} npm install @anam-ai/js-sdk ``` ## Connect the browser Request the session token, create an Anam client, and attach its stream to your video element: ```typescript theme={"system"} import { createClient } from "@anam-ai/js-sdk"; const res = await fetch("/api/anam-session", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ avatarId, agentId }), }); const { sessionToken } = await res.json(); const client = createClient(sessionToken); await client.streamToVideoElement("avatar-video"); ``` `streamToVideoElement()` starts microphone capture and renders the avatar's video and audio in the element with the matching ID. ## Working component example Below is a React component with connection lifecycle and a streaming transcript. The `MESSAGE_STREAM_EVENT_RECEIVED` event fires for each chunk of text from both the user and the agent. Accumulate chunks by message ID to build the full transcript. ```typescript theme={"system"} "use client"; import { useRef, useState, useCallback } from "react"; import { AnamEvent, createClient, type AnamClient } from "@anam-ai/js-sdk"; type Message = { id: string; role: "user" | "persona"; content: string; interrupted?: boolean; }; export default function AvatarChat({ avatarId, agentId, }: { avatarId: string; agentId: string; }) { const clientRef = useRef(null); const [status, setStatus] = useState<"idle" | "connecting" | "connected">("idle"); const [messages, setMessages] = useState([]); const start = useCallback(async () => { setStatus("connecting"); setMessages([]); try { const res = await fetch("/api/anam-session", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ avatarId, agentId }), }); const body = await res.json(); if (!res.ok) { throw new Error(body.error ?? "Failed to create a session token"); } const anamClient = createClient(body.sessionToken); clientRef.current = anamClient; // Accumulate transcript chunks by message ID anamClient.addListener( AnamEvent.MESSAGE_STREAM_EVENT_RECEIVED, (evt: { id: string; content: string; role: string; interrupted: boolean; }) => { setMessages((prev) => { const idx = prev.findIndex((m) => m.id === evt.id); if (idx >= 0) { const next = [...prev]; next[idx] = { ...next[idx], content: next[idx].content + evt.content, interrupted: evt.interrupted, }; return next; } return [ ...prev, { id: evt.id, role: evt.role as "user" | "persona", content: evt.content, interrupted: evt.interrupted, }, ]; }); } ); anamClient.addListener(AnamEvent.CONNECTION_CLOSED, () => { setStatus("idle"); }); await anamClient.streamToVideoElement("avatar-video"); setStatus("connected"); } catch (error) { console.error("Failed to start the avatar session:", error); clientRef.current = null; setStatus("idle"); } }, [avatarId, agentId]); const stop = useCallback(async () => { await clientRef.current?.stopStreaming(); clientRef.current = null; setStatus("idle"); }, []); return (
); } ``` ## Run your first conversation 1. Save the component above as `AvatarChat.tsx` and render it on a page in your Next.js app. Pass your Cara 4 avatar ID as `avatarId` and the ElevenLabs agent ID from step one as `agentId`. 2. Start your development server with your project's dev command, such as `npm run dev`. Open the page on localhost. 3. Click **Start** and allow microphone access. The avatar video should appear and the button should change to **Stop**. 4. Speak to the agent. Confirm that you hear its reply, see the avatar speaking in sync, and see both sides of the conversation in the transcript. 5. Click **Stop** to end the session. Click **Start** again to check that you can reconnect, then stop the session when you finish testing. > [!TIP] > > **Quickstart complete.** You now have a working ElevenLabs agent with an Anam avatar. If the video or conversation does not start, follow [Troubleshooting](/docs/integrations/elevenlabs/troubleshooting). ## Upgrade your avatar Your avatar session is running. Build on it with expressive performance, personalised conversations, and actions in your app: * [Director Notes](/docs/integrations/elevenlabs/director-notes): add expressions that follow ElevenLabs audio tags. * [Session customisation](/docs/integrations/elevenlabs/session-customisation): pass user-specific variables, override settings, or attach a user ID. * [Client tools](/docs/integrations/elevenlabs/client-tools): let the agent trigger actions in your browser and receive the results. For more on event handling, message history, and connection lifecycle, see the [basic Next.js app recipe](https://anam.ai/cookbook/basic-nextjs-app). > [card] [Next: Add Director Notes](/docs/integrations/elevenlabs/director-notes) > > Connect ElevenLabs audio tags to the avatar's performance. # Troubleshoot ElevenLabs Agents Source: https://anam.ai/docs/integrations/elevenlabs/troubleshooting Resolve ElevenLabs signed URL failures, connection problems, missing Director Notes, client-tool issues, and avatar playback errors. **"Failed to get ElevenLabs signed URL"** * Verify `ELEVENLABS_API_KEY` is set and valid * Confirm the `agentId` matches an agent in your ElevenLabs dashboard * Check that your ElevenLabs plan includes Conversational AI access **Avatar connects but no conversation starts** * The signed URL may have expired. Create the session token right before the client needs it, not minutes in advance * Verify the ElevenLabs agent is active and not paused in the dashboard **Director Notes status stays "waiting"** * Confirm the avatar is a Cara 4 avatar and `avatarModel` is set to `cara-4` * Select Eleven v4 Turbo, Eleven v4, or v3 Conversational in ElevenLabs and prompt the agent to emit one of the [recognized tags](/docs/integrations/elevenlabs/director-notes) * Check the response transcript in ElevenLabs to confirm the LLM produced the tag * Confirm the Anam engine build includes the ElevenLabs Director Notes aliases **Client tool status stays "ready"** * Confirm the tool type is **Client** in ElevenLabs * Match the registered tool and parameter names exactly; they are case-sensitive * Enable **Wait for response** if the agent needs to receive the handler's returned string **"Anam API error: 400" when creating the session token** * Check that `avatarId` is valid. Find available avatars at [lab.anam.ai/avatars](https://lab.anam.ai/avatars) * Make sure the `elevenLabsAgentSettings` object includes both `signedUrl` and `agentId` **Avatar lips not syncing / no audio** * Anam matches the agent's output audio format automatically. If you hit this, check the ElevenLabs agent configuration and make sure it's using a supported voice model **Session recordings not appearing in Anam Lab** * Recordings are generated after the session ends. Allow a few minutes for processing * Check the session completed cleanly (the client called `stopStreaming()` or the connection closed normally) # LiveKit Configuration Source: https://anam.ai/docs/integrations/livekit/configuration Configuration options, advanced examples, and API reference for the Anam LiveKit plugin ## Installation ```bash theme={"system"} pip install livekit-plugins-anam ``` ## Environment variables | Service | Where to get it | | - | - | | **Anam** | [lab.anam.ai](https://lab.anam.ai) | | **LiveKit** | [LiveKit Cloud](https://livekit.io) or self-hosted | | **LLM providers** | DeepGram, ElevenLabs, OpenAI, Google AI Studio, etc. | ```bash .env theme={"system"} ANAM_API_KEY=your_anam_api_key ANAM_AVATAR_ID=your_avatar_id LIVEKIT_URL=wss://your-project.livekit.cloud LIVEKIT_API_KEY=your_livekit_api_key LIVEKIT_API_SECRET=your_livekit_api_secret OPENAI_API_KEY=your_openai_api_key # or GEMINI_API_KEY=your_gemini_api_key ``` > [!NOTE] > > **LiveKit endpoint requirements:** `LIVEKIT_URL` must be reachable from the public internet because Anam's engine joins your room as a participant. Loopback hosts (`localhost`, `127.0.0.1`, `::1`), private, link-local, reserved and documentation addresses, cluster-internal names such as `*.svc`, `*.local`, and `*.internal`, and single-label hosts are rejected when the session token is created (HTTP 400 at `details.environment.livekitUrl`). > > Hostnames must resolve only to public addresses. DNS resolution is checked when the session starts; an unresolvable hostname or one with any non-public address returns HTTP 400 with `invalid_livekit_url`. This also applies to previously issued tokens. > > Public `ws://` and `wss://` endpoints and the SDK's `http://` and `https://` aliases are accepted. ## PersonaConfig Configure the avatar identity and model: ```python theme={"system"} persona_config = anam.PersonaConfig( name="Maya", # Display name for the avatar avatarId="uuid-here", # Avatar appearance ID avatarModel="cara-4", # Avatar model version ) ``` **name** `string` *required* Display name for the avatar. Used in logs and debugging. **avatarId** `string` *required* UUID of the avatar to use. Get this from the [Avatar Gallery](/docs/resources/avatar-gallery) or [Anam Lab](https://lab.anam.ai/avatars). **avatarModel** `string` Avatar model version to use when rendering the avatar. Use `cara-4` for new production avatars. ## AvatarSession ```python theme={"system"} avatar = anam.AvatarSession( persona_config=anam.PersonaConfig(...), api_key="your_api_key", api_url="https://api.anam.ai", # Optional ) ``` **persona\_config** `PersonaConfig` *required* Configuration for the avatar's identity and appearance. **api\_key** `string` *required* Your Anam API key. **api\_url** `string` (default: [https://api.anam.ai](https://api.anam.ai)) Anam API endpoint. Override for staging or self-hosted deployments. ### start() Starts the avatar session and connects it to the LiveKit room. ```python theme={"system"} await avatar.start(session, room=ctx.room) ``` **session** `AgentSession` *required* The LiveKit agent session to connect the avatar to. **room** `rtc.Room` *required* The LiveKit room instance from the job context. ## Director Notes cues Inline **cues** let the avatar shift emotion or delivery mid-turn (see [Director Notes](https://anam.ai/docs/personas/director-notes) for the cue list and preset styles). Your LLM writes cues as square-bracketed tags in the spoken text, for example `[warm] Hello there. [curious] What brings you here?`. Director Notes require a Cara 4 avatar. They work best with a voice that matches the intended performance and a neutral-expression avatar source image; an overly smiley, sad, or angry source image can limit how far cues can move the performance. In a LiveKit agent, Anam reads those cues from the agent's **TTS-aligned transcript**, which you publish to the room. Wiring this up takes two things: 1. **`use_tts_aligned_transcript=True`** on the `AgentSession`, so the agent produces a transcript with per-word timings. 2. A **JSON transcription sink** scoped to the agent's own identity, so that timed transcript (cue tags included) is published to the room on the `lk.transcription` stream, where the Anam engine reads it to drive per-utterance expression. > [!WARNING] > > This path leaves the `[cue]` tags in the text sent to your TTS, so it only works with a TTS that does **not** read square-bracketed cues aloud — for example Cartesia `sonic-3.6` or ElevenLabs `eleven_v3_conversational`. Cue support varies by model; do not use a model that speaks the tags aloud. ```python theme={"system"} from livekit.agents import AgentSession from livekit.agents.voice.room_io import _ParticipantTranscriptionOutput from livekit.plugins import anam, cartesia session = AgentSession( # ... stt / llm / vad / turn_detection ... tts=cartesia.TTS(model="sonic-3.6"), # does not vocalise "[cue]" tags use_tts_aligned_transcript=True, ) avatar = anam.AvatarSession( persona_config=anam.PersonaConfig( name="Cara", avatarId=os.getenv("ANAM_AVATAR_ID"), avatarModel="cara-4", ), api_key=os.getenv("ANAM_API_KEY"), ) # Order matters: avatar.start sets the audio sink, then attach the transcription # sink, then session.start — both sinks stay in place. await avatar.start(session, room=ctx.room) # Publish the timed, cue-tagged transcript so the engine can resolve cues against it. # `participant` MUST be the agent's own identity (it is the transcript's sender); # leave it unset and every chunk is silently dropped. session.output.transcription = _ParticipantTranscriptionOutput( room=ctx.room, is_delta_stream=True, participant=ctx.room.local_participant.identity, json_format=True, ) await session.start(agent=Assistant(), room=ctx.room) ``` > [!NOTE] > > `_ParticipantTranscriptionOutput` is currently an internal LiveKit Agents API. Set the transcription sink **after** `avatar.start()` and **before** `session.start()`. ### Prompt your LLM to emit cues The transcript sink only forwards cues that are already in the agent's replies — nothing generates them for you. Your LLM has to write the `[cue]` tags inline, so add a short instruction to the agent's system prompt: ```text theme={"system"} Use Anam cue tags sparingly and naturally to mark emotional shifts in your spoken replies. Available cue tags are: [happy], [warm], [playful], [curious], [supportive], [concerned], [sad], [surprised], [angry], [distressed], and [laughter]. Place tags inline before the words they should affect. Only use a tag when the delivery should noticeably change. Do not explain the tags. ``` See [Prompting an LLM to use cues](/docs/personas/director-notes#prompting-an-llm-to-use-cues) for more detail. ## Advanced examples ### Gemini with Vision Use Gemini Live for multimodal conversations with screen share analysis: ```python theme={"system"} import os from livekit.agents import Agent, AgentSession, JobContext, WorkerOptions, cli from livekit.agents.voice import VoiceActivityVideoSampler, room_io from livekit.plugins import anam, google async def entrypoint(ctx: JobContext): await ctx.connect() llm = google.realtime.RealtimeModel( model="gemini-2.0-flash-exp", api_key=os.getenv("GEMINI_API_KEY"), voice="Aoede", instructions="You are a helpful assistant that can see the user's screen.", ) avatar = anam.AvatarSession( persona_config=anam.PersonaConfig( name="Maya", avatarId=os.getenv("ANAM_AVATAR_ID"), avatarModel="cara-4", ), api_key=os.getenv("ANAM_API_KEY"), ) session = AgentSession( llm=llm, video_sampler=VoiceActivityVideoSampler( speaking_fps=0.2, silent_fps=0.1, ), ) await avatar.start(session, room=ctx.room) await session.start( agent=Agent(instructions="Help the user with what you see on their screen."), room=ctx.room, room_input_options=room_io.RoomInputOptions(video_enabled=True), ) if __name__ == "__main__": cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint)) ``` ### Function tools Extend your agent with custom tools: ```python theme={"system"} from livekit.agents import function_tool @function_tool async def fill_form_field(field_name: str, value: str) -> str: """Fill in a form field on the user's screen. Args: field_name: The name of the field to fill value: The value to enter Returns: Confirmation message """ await send_command_to_frontend("fill_field", {"field": field_name, "value": value}) return "Field filled successfully" session = AgentSession( llm=llm, tools=[fill_form_field], ) ``` ## Running your agent > [tab] Development > > ```bash theme={"system"} > python agent.py dev > ``` > > Connects to your LiveKit server and automatically joins rooms when participants connect. > [tab] Production > > ```bash theme={"system"} > python agent.py > ``` > > Deploy using Docker, Kubernetes, or your preferred container platform. See the [LiveKit Agents deployment guide](https://docs.livekit.io/agents/deployment) for details. ## Optimize latency Time to first visible speech depends on your STT, LLM, and TTS latency—including your TTS provider's time to first byte (TTFB)—and how quickly your agent delivers audio. At the start of each response, Anam waits for **480 ms of audio** before it starts generating frames. This is measured in audio duration, not elapsed time, so how long the wait takes depends on how quickly your agent delivers audio. You can't change this buffer per account or per session. * **Reduce TTS TTFB.** Choose a low-latency TTS model, reuse provider connections where supported, and start TTS as soon as response text is available. * **Stream audio immediately.** Do not wait for the full utterance. Configure your TTS provider to produce small chunks frequently so LiveKit can forward them as they arrive. * **Deliver audio at least as fast as real time.** Forward audio without pacing it or adding your own buffer. Audio that arrives faster than real time fills the 480 ms buffer sooner; audio streamed at speaking speed takes about 480 ms to fill it. Sustained delivery slower than real time can cause choppy playback. * **Minimize network distance.** Where your architecture permits, run your LiveKit agent, TTS, and orchestration close to Anam's `eu-south` infrastructure for European traffic or `us-east` infrastructure for US traffic. Keep your LiveKit server close to the agent and users when possible. The final media path still runs through LiveKit to the client, so test latency from the locations your users connect from. ## Troubleshooting > [accordion] Agent won't connect to LiveKit > > * Verify `LIVEKIT_URL`, `LIVEKIT_API_KEY`, and `LIVEKIT_API_SECRET` are correct > * If session-token creation returns HTTP 400 at `details.environment.livekitUrl`, replace local development URLs such as `ws://localhost:7880` with a LiveKit endpoint reachable from the public internet > * Check that your LiveKit server is accessible > * Ensure WebSocket connections aren't blocked by a firewall > * Test connectivity at [meet.livekit.io](https://meet.livekit.io) > [accordion] Avatar not appearing > > * Verify your `ANAM_API_KEY` is valid > * Check that `ANAM_AVATAR_ID` matches an existing avatar > * Review agent logs for Anam connection errors > * Ensure the avatar session starts before the agent session > [accordion] No voice response > > * Check your LLM API key is valid (OpenAI, Gemini, etc.) > * Verify microphone permissions in the browser > * Look for API errors in the agent logs > * Confirm the agent is receiving audio tracks > [accordion] High latency or choppy audio > > * Check your network connection stability > * Consider using LiveKit Cloud for optimized routing > * Reduce video sampling frequency if CPU-bound > * Monitor your LLM API response times When a session ends unexpectedly, use the [session termination reasons](/docs/resources/session-termination-reasons) shown in Anam Lab to diagnose LiveKit room and identity errors. # LiveKit Integration Source: https://anam.ai/docs/integrations/livekit/overview Connect an Anam avatar to a LiveKit voice agent, understand the room architecture, and choose the configuration for your STT, LLM, and TTS stack. The Anam LiveKit plugin adds a visual avatar face to your LiveKit voice agents. Combine Anam's avatar technology with any STT, LLM, or TTS — including OpenAI Realtime, Gemini Live, or your own custom models. ## How it works LiveKit uses a room-based architecture. Human users and AI agents both connect to rooms as participants. Anam plugs into this as a video layer: ``` User Input (Voice/Video) ↓ LiveKit Room (Real-time Communication) ↓ Your LLM (OpenAI, Gemini, Claude, etc.) ↓ Text Response → Anam Avatar (TTS + Video) ↓ User sees and hears the avatar ``` The Anam plugin listens to the audio being sent to users and generates a synchronized video stream of the avatar speaking. The video is published to the room as a separate track that clients display. > [!TIP] > > **Bring Your Own LLM**: Anam handles only the visual avatar. You choose the ears, intelligence, and voice — whether that's DeepGram, ElevenLabs, Cartesia, OpenAI, Gemini, Claude, or a custom model. ## Demo See the integration in action with our onboarding assistant demo: [![Anam LiveKit Demo - AI Onboarding Assistant](https://img.youtube.com/vi/9mxK5HdHzes/0.jpg)](https://youtu.be/9mxK5HdHzes) ## Use cases The Anam + LiveKit combination is ideal for scenarios requiring voice interaction with visual presence: > [accordion] Employee Onboarding > > Guide new hires through forms and processes with screen share analysis. The AI sees what they see and provides contextual help. > [accordion] Educational Tutoring > > Help students with homework by seeing their work. The avatar can point out errors and explain concepts visually. > [accordion] Technical Support > > See customer screens and provide step-by-step guidance with a friendly visual presence. > [accordion] Healthcare Intake > > Assist patients filling out medical forms with a calm, reassuring avatar presence. > [accordion] Financial Services > > Guide users through account opening, KYC processes, and complex financial forms. ## Resources > [card] [Cookbook: Getting Started](https://anam.ai/cookbook/getting-started-with-livekit) > > Build a LiveKit voice agent with an Anam avatar from scratch > [card] [Cookbook: Gemini Vision](https://anam.ai/cookbook/gemini-vision-with-anam-livekit) > > Add Gemini Vision to a LiveKit agent for screen share analysis > [card] [Demo Source Code](https://github.com/anam-org/anam-livekit-demo) > > Full source code for the onboarding assistant demo > [card] [LiveKit Docs](https://docs.livekit.io) > > Official LiveKit documentation # LiveKit Quickstart Source: https://anam.ai/docs/integrations/livekit/quickstart Add an Anam avatar to a LiveKit agent, install the plugin, configure credentials, and run a first real-time conversation. This quickstart shows how to add an Anam avatar face to a LiveKit voice agent using OpenAI Realtime for the LLM. Build this LiveKit quickstart with a coding agent Paste this prompt into Cursor, Claude Code, Codex, or another coding agent. Copy prompt ## Prerequisites * [LiveKit CLI](https://docs.livekit.io/home/cli/cli-setup/) installed * A [LiveKit Cloud](https://cloud.livekit.io) account * An OpenAI API key * An Anam API key from [lab.anam.ai](https://lab.anam.ai) ## Set up the agent Clone the LiveKit Node.js agent starter and install dependencies: ```bash theme={"system"} git clone https://github.com/livekit-examples/agent-starter-node.git cd agent-starter-node pnpm install ``` Download the required model files (VAD and turn detection): ```bash theme={"system"} pnpm run download-files ``` Install the Anam plugin: ```bash theme={"system"} pnpm add @livekit/agents-plugin-anam ``` ## Configure credentials Create a `.env.local` file: ```bash .env.local theme={"system"} # LiveKit Cloud credentials (from cloud.livekit.io) LIVEKIT_URL=wss://your-project.livekit.cloud LIVEKIT_API_KEY=your_api_key LIVEKIT_API_SECRET=your_api_secret # OpenAI (for voice + LLM) OPENAI_API_KEY=your_openai_key # Anam (for avatar face) ANAM_API_KEY=your_anam_key ANAM_AVATAR_ID=edf6fdcb-acab-44b8-b974-ded72665ee26 ``` The avatar ID above is "Mia", one of Anam's stock avatars. Browse others in the [Avatar Gallery](/docs/resources/avatar-gallery) or create your own at [lab.anam.ai/avatars](https://lab.anam.ai/avatars). ## Add the avatar to your agent Replace the contents of `src/agent.ts`: ```typescript theme={"system"} import { type JobContext, ServerOptions, cli, defineAgent, voice } from '@livekit/agents'; import * as anam from '@livekit/agents-plugin-anam'; import * as openai from '@livekit/agents-plugin-openai'; import { BackgroundVoiceCancellation } from '@livekit/noise-cancellation-node'; import dotenv from 'dotenv'; import { fileURLToPath } from 'node:url'; dotenv.config({ path: '.env.local' }); class Assistant extends voice.Agent { constructor() { super({ instructions: `You are a helpful voice AI assistant. You eagerly assist users with their questions. Your responses are concise, to the point, and without any complex formatting or punctuation including emojis, asterisks, or other symbols. You are curious, friendly, and have a sense of humor.`, }); } } export default defineAgent({ entry: async (ctx: JobContext) => { await ctx.connect(); // Start the voice session with OpenAI Realtime const session = new voice.AgentSession({ llm: new openai.realtime.RealtimeModel({ voice: 'alloy' }), }); await session.start({ agent: new Assistant(), room: ctx.room, inputOptions: { noiseCancellation: BackgroundVoiceCancellation(), }, }); // Start the Anam avatar session const avatarId = process.env.ANAM_AVATAR_ID; if (!avatarId) { console.warn('ANAM_AVATAR_ID is not set. Avatar will not start.'); return; } const avatarSession = new anam.AvatarSession({ personaConfig: { name: 'Mia', avatarId, avatarModel: 'cara-4', }, }); await avatarSession.start(session, ctx.room); console.log('Agent and avatar session started'); }, }); cli.runApp(new ServerOptions({ agent: fileURLToPath(import.meta.url) })); ``` ## Test locally ```bash theme={"system"} pnpm run dev ``` The agent connects to LiveKit Cloud and waits for rooms. You need a frontend to create a room and connect. ## Set up the frontend In a new terminal, create the React frontend: ```bash theme={"system"} lk app create --template agent-starter-react cd agent-starter-react pnpm install ``` Create a `.env.local` with your LiveKit credentials: ```bash .env.local theme={"system"} LIVEKIT_URL=wss://your-project.livekit.cloud LIVEKIT_API_KEY=your_api_key LIVEKIT_API_SECRET=your_api_secret ``` Start the dev server: ```bash theme={"system"} pnpm dev ``` Open `http://localhost:3000`, click connect, and the avatar appears as the agent speaks. ## Deploy to LiveKit Cloud ```bash theme={"system"} lk agent deploy --secrets-file=.env.local ``` This uploads your agent code and environment variables. The agent will now automatically join any rooms created in your project. ## Next steps * [Configuration](/docs/livekit/configuration) — persona config, advanced examples, and API reference * [Avatar Gallery](/docs/resources/avatar-gallery) — browse stock avatars * [Create a custom avatar](https://lab.anam.ai/avatars) — use your own face # Other SDKs & Integrations Source: https://anam.ai/docs/integrations/sdks Choose an official or community SDK, plugin, or integration for connecting Anam avatars to JavaScript, Python, LiveKit, Pipecat, and other stacks. Beyond the [JavaScript SDK](https://anam.ai/docs/javascript-sdk/quickstart) and [Python SDK](https://anam.ai/docs/python-sdk/overview), Anam can be integrated through several partner and community-built SDKs. ## Official Integrations > [card] [Pipecat](https://docs.pipecat.ai/api-reference/server/services/video/anam) > > Build voice AI pipelines with Pipecat and render them with Anam avatars. Official plugin maintained by Anam. > [card] [Agora Conversational AI](https://docs.agora.io/en/conversational-ai/models/avatar/anam) > > Use Anam avatars as the visual layer for Agora's Conversational AI platform. > [card] [VideoSDK](https://anam.ai/cookbook/videosdk-anam-avatar) > > Add Anam avatars to VideoSDK voice agent pipelines. Works with both RealTimePipeline and CascadingPipeline. ## Community SDKs These are built and maintained by the community. We can't guarantee their functionality or maintenance, but we're excited to see them. > [card] [Kotlin Multiplatform](https://github.com/anam-org/kmp-sdk) > > Kotlin Multiplatform SDK for Android, iOS, and desktop targets. > [card] [Flutter](https://github.com/stukennedy/anam_flutter_sdk) > > Community-maintained Flutter SDK by Stu Kennedy for mobile applications. ## Built something? If you've built an SDK, plugin, or integration for Anam, reach out at [info@anam.ai](mailto:info@anam.ai) and we'll add it here. # Choose an Anam Avatar Model Source: https://anam.ai/docs/introduction/models Choose a Cara avatar model for live conversations and set its model name in Anam Lab or the API. For new integrations, use **Cara-4.1 Express** (`cara-4.1-express`). Choose it in [Anam Lab](https://lab.anam.ai/) or set `avatarModel` in your persona configuration through the API. Avatar models control the persona's facial animation and lip sync. They are separate from the voice and language model you choose for the conversation. ## Available models ### Cara-4.1 Express Set `avatarModel` to `cara-4.1-express` for the latest release. It brings more expressive animation and better adherence to [Director Notes](/docs/personas/director-notes), including custom performance styles and cues that change the avatar's delivery during a conversation. Cara-4.1 Express is available on all plans and supports both landscape and portrait video. ### Cara 4 Set `avatarModel` to `cara-4` to keep using the previous stable Cara 4 release. Existing integrations can continue using this model. ### Cara 4 Latest Set `avatarModel` to `cara-4-latest` to try the latest avatar model from our research. The model it selects is subject to change and may be unstable. We do not recommend it for production. For production, choose a released model by name, such as `cara-4.1-express`. ### Cara 3 Set `avatarModel` to `cara-3` for existing avatars or integrations that need the previous generation. Cara 3 supports landscape video only and does not support Director Notes. ## Select a model through the API Add the model name to your persona configuration when [creating a persona](/docs/api-reference/personas/create-persona) or [creating a session token](/docs/api-reference/sessions/create-session-token): ```json theme={"system"} { "avatarModel": "cara-4.1-express" } ``` This is one field in your persona configuration; keep your existing avatar, voice and language model settings. If you omit `avatarModel`, Anam uses the saved persona's model or chooses a model supported by the avatar. Set it explicitly when you need a particular release. ## Video output | Model | Landscape (default) | Portrait | | - | - | - | | Cara-4.1 Express | `1152x768` | `768x1152` | | Cara 4 | `1152x768` | `768x1152` | | Cara 4 Latest | `1152x768` | `768x1152` | | Cara 3 | `720x480` | Not supported | To request portrait output, set `videoWidth` to `768` and `videoHeight` to `1152` in `sessionOptions`. Supply both fields together. See [Video options](/docs/personas/session/video) for the full configuration and crop behavior. ## Use an existing avatar Your avatar must support the model you request. If the API rejects the combination, choose a compatible avatar or [create a custom avatar](/docs/personas/avatars/custom-avatars). Changing the model name does not regenerate an avatar. Test the model with your avatar before updating a production integration. # Anam Documentation Source: https://anam.ai/docs/introduction/overview Learn how Anam personas combine an avatar, voice, language model, and prompt, then choose the quickest integration path for your application. ![Anam AI Avatars](https://mintcdn.com/anam/N9CYPb8uZ5o0w31N/images/docs-banner.png?fit=max\&auto=format\&n=N9CYPb8uZ5o0w31N\&q=85\&s=fba5b553c554fa4df8d85307f4f9fdea) Anam builds interactive AI avatars: photorealistic digital humans that talk, listen, and perform actions based on your conversations. A persona is the combination of a face, a voice, an LLM, and a system prompt. You integrate a persona with your webpage and it holds live conversations with your users. ## Who builds with Anam Teams use Anam to build interactive agents from scratch, or to put a face on agents they already have. Common cases include customer support, sales and lead qualification, language tutoring, skill training, and medical front-desk assistance. In each of these cases, talking with an Anam avatar feels closer to a face-to-face conversation than text or voice alone. ## How it works Every live conversation with a persona runs through a four-stage pipeline: 1. Speech-to-text (STT) listens to the user 2. An LLM decides what to say back 3. Text-to-speech (TTS) turns the reply into audio 4. Anam turns the audio into a live video of the persona speaking The default setup, which we call Turnkey, runs the whole pipeline for you. You can also bring your own LLM, your own STT, your own TTS, or stream us pre-generated audio and have us run face generation only. ## Three ways to start > [card] [Learn](https://anam.ai/docs/personas/overview) > > Read how personas work. Avatars, voices, LLMs, and how they fit together. > [card] [Embed](https://anam.ai/docs/embed/overview) > > Add an avatar to a site you already have. Widget, Player, or platforms like Framer and Shopify. > [card] [Build](https://anam.ai/docs/javascript-sdk/quickstart) > > Use the JavaScript or Python SDK to build your own. The pipeline and the UI are yours. > [card] Or build from your AI app > > Connect Claude, ChatGPT, Cursor, or VS Code to Anam's MCP server, then ask your app to create a persona, attach knowledge, or write the integration code. You sign in with your Anam account. > > [All apps](https://anam.ai/docs/resources/mcp) # Get your API Key Source: https://anam.ai/docs/javascript-sdk/api-key Learn how to create and manage your Anam API key from the Lab. Required to authenticate requests and integrate personas into your app. Your API key is used to authenticate your requests to the Anam API and is required for integrating the Personas you create into your own applications. API keys are managed via the [Anam Lab](https://lab.anam.ai/). ### Create a new API key From the [API keys page](https://lab.anam.ai/api-keys), click on the "New Key" button (on a phone, the "+" button). This opens the "Create API key" dialog. Enter an optional label, then choose what the key can access: * **Full access**: the key can read and write everything, and create session tokens. * **Restricted**: choose None, Read, or Write for each resource, and whether the key can create session tokens. Write includes read. Restricted starts with every permission turned on, so turn off what the key does not need. > [!NOTE] > > The label is only used to help you identify the API key. It is not used for authentication. ![The Create API key dialog with a Label field and the Full access and Restricted options](https://mintcdn.com/anam/eiaNFs4qEk6dmdnI/images/get-started/create-api-key-dark.png?fit=max\&auto=format\&n=eiaNFs4qEk6dmdnI\&q=85\&s=a52502349c7d9eebdc2a4cb0e05b58cd) Click "Create key" and your new API key will be shown to you in the "Save your new API key" dialog. Remember to save it somewhere safe as you will not be able to access it later. Click "Copy key" to copy it, or "Copy as ANAM\_API\_KEY" to copy it as an environment variable line. The "I've saved it" button stays disabled until you click one of them. If your browser blocks clipboard access, select the key and copy it yourself. > [!WARNING] > > Anam encrypts and store your API keys securely. For this reason, we are unable to recover lost API keys. If you lose your API key, you will need to create a new key via the Anam Lab. # JavaScript SDK Authentication Source: https://anam.ai/docs/javascript-sdk/authentication Keep Anam API keys on your server, create short-lived session tokens, and authenticate browser sessions with the JavaScript SDK. Anam uses a two-tier authentication system: API keys for server-side requests and session tokens for client connections. ## Tier 1: API Key Your API key authenticates server-side requests to the Anam API. > [!WARNING] > > **Never expose your API key on the client side**. It should only exist in your > server environment. ### Getting Your API Key See the [API key page](/docs/api-key) for details on how to get your API key from the Anam Lab. ## Tier 2: Session Tokens Session tokens are temporary credentials (valid for 1 hour) that allow client applications to connect to Anam's streaming infrastructure without exposing your API key. ### How Session Tokens Work **1. Token Request** Your server requests a session token from Anam using your API key and persona configuration **2. Token Generation** Anam generates a temporary token tied to your specific persona configuration **3. Client Connection** Your client uses the session token with the Anam SDK to establish a direct WebRTC connection **4. Real-time Communication** Once connected, the client can send messages and receive video/audio streams directly ### Creating Session Tokens Below is a basic Express server that exposes an endpoint for creating session tokens. ```typescript server.ts theme={"system"} import express, { Request, Response } from "express"; interface PersonaConfig { name: string; avatarId: string; avatarModel: string; voiceId: string; llmId?: string; systemPrompt?: string; } interface SessionTokenResponse { sessionToken: string; } const app = express(); app.use(express.json()); app.post("/api/session-token", async (req: Request, res: Response) => { try { const response = await fetch("https://api.anam.ai/v1/auth/session-token", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.ANAM_API_KEY}`, }, body: JSON.stringify({ personaConfig: { name: "Cara", avatarId: "071b0286-4cce-4808-bee2-e642f1062de3", avatarModel: "cara-4", voiceId: "de23e340-1416-4dd8-977d-065a7ca11697", llmId: "a7cf662c-2ace-4de1-a21e-ef0fbf144bb7", systemPrompt: "You are a helpful assistant.", } satisfies PersonaConfig, }), }); if (!response.ok) { const errorData = await response.json(); console.error("Token creation failed:", errorData); return res.status(response.status).json({ error: "Token creation failed" }); } const { sessionToken }: SessionTokenResponse = await response.json(); res.json({ sessionToken }); } catch (error) { console.error("Network error:", error); res.status(500).json({ error: "Failed to create session" }); } }); app.listen(3000, () => console.log("Server running on port 3000")); ``` ```javascript server.js theme={"system"} const express = require("express"); const app = express(); app.use(express.json()); app.post("/api/session-token", async (req, res) => { try { const response = await fetch("https://api.anam.ai/v1/auth/session-token", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.ANAM_API_KEY}`, }, body: JSON.stringify({ personaConfig: { name: "Cara", avatarId: "071b0286-4cce-4808-bee2-e642f1062de3", avatarModel: "cara-4", voiceId: "de23e340-1416-4dd8-977d-065a7ca11697", llmId: "a7cf662c-2ace-4de1-a21e-ef0fbf144bb7", systemPrompt: "You are a helpful assistant.", }, }), }); if (!response.ok) { const errorData = await response.json(); console.error("Token creation failed:", errorData); return res.status(response.status).json({ error: "Token creation failed" }); } const { sessionToken } = await response.json(); res.json({ sessionToken }); } catch (error) { console.error("Network error:", error); res.status(500).json({ error: "Failed to create session" }); } }); app.listen(3000, () => console.log("Server running on port 3000")); ``` ### Using the Session Token (Client-Side) After your server creates a session token, your client fetches it and uses the Anam SDK to start streaming: ```typescript theme={"system"} import { createClient } from "@anam-ai/js-sdk"; async function startPersonaSession() { // Fetch token from your server const response = await fetch("/api/session-token", { method: "POST" }); const { sessionToken } = await response.json(); // Create client with the session token const anamClient = createClient(sessionToken); // Start streaming to a video element await anamClient.streamToVideoElement("persona-video"); } ``` ### Dynamic Persona Configuration Instead of using the same persona for all users, you can customize based on context: #### User-based Personalization ```javascript theme={"system"} app.post("/api/session-token", authenticateUser, async (req, res) => { const user = req.user; const personaConfig = { name: `Persona for user: ${user.id}`, avatarId: user.preferredAvatar || defaultAvatarId, avatarModel: user.preferredAvatarModel || "cara-4", voiceId: user.preferredVoice || defaultVoiceId, llmId: user.preferredllmId || "a7cf662c-2ace-4de1-a21e-ef0fbf144bb7", systemPrompt: buildPersonalizedPrompt(user), }; const sessionToken = await fetchAnamSessionToken(personaConfig); res.json({ sessionToken }); }); ``` #### Context-aware Sessions ```javascript theme={"system"} app.post("/api/session-token", authenticateUser, async (req, res) => { const { context, metadata } = req.body; let personaConfig; switch (context) { case "customer-support": personaConfig = buildSupportPersona(metadata); break; case "sales": personaConfig = buildSalesPersona(metadata); break; case "training": personaConfig = buildTrainingPersona(metadata); break; default: personaConfig = defaultPersonaConfig; } const sessionToken = await fetchAnamSessionToken(personaConfig); res.json({ sessionToken }); }); ``` ## Environment Setup Store your API key securely: ```bash .env theme={"system"} ANAM_API_KEY=your-api-key-here NODE_ENV=production ``` ```javascript config.js theme={"system"} const config = { anamApiKey: process.env.ANAM_API_KEY, anamApiUrl: process.env.ANAM_API_URL || "https://api.anam.ai", }; if (!config.anamApiKey) { throw new Error("ANAM_API_KEY environment variable is required"); } module.exports = config; ``` ## Next Steps # Basic application Source: https://anam.ai/docs/javascript-sdk/examples/basic-app Build a complete browser application with an Anam persona, including token creation, client setup, session controls, and event handling. This guide creates a minimal but complete web application with an interactive AI persona. You will build a Node.js server that handles authentication and a client that streams the persona to a video element. > [!NOTE] > > Looking for a faster start? The [Quickstart](https://anam.ai/docs/javascript-sdk/quickstart) guide gets you running in a single HTML file without a server. ## Prerequisites * **Node.js** (version 16 or higher) and **npm** installed on your system * Basic knowledge of JavaScript * An Anam API key ([get one here](/docs/api-key)) * A microphone and speakers for voice interaction ## Project Setup This example creates a web application with three main files: ``` my-anam-app/ ├── server.js # Express server for secure API key handling ├── package.json # Node.js dependencies ├── public/ # Static files served to the browser │ ├── index.html # Main HTML page with video element │ └── script.js # Client-side JavaScript for persona control └── .env # Environment variables (optional) ``` **1. Create project directory** ```bash theme={"system"} mkdir my-anam-app cd my-anam-app ``` **2. Initialize Node.js project** ```bash theme={"system"} npm init -y ``` **3. Create public directory** ```bash theme={"system"} mkdir public ``` **4. Install dependencies** ```bash theme={"system"} npm install express dotenv ``` **5. Create environment file** Create a `.env` file in your project root to store your API key securely: ```bash .env theme={"system"} ANAM_API_KEY=your-api-key-here ``` > [!WARNING] > > Replace `your-api-key-here` with your actual Anam API key. Never commit this file to version control. ## Step 1: Set up your server Create a basic Express server to handle session token generation. In a production application, integrate this into your existing backend service. ```javascript server.js theme={"system"} require("dotenv").config(); const express = require("express"); const app = express(); app.use(express.json()); app.use(express.static("public")); app.post("/api/session-token", async (req, res) => { try { const response = await fetch("https://api.anam.ai/v1/auth/session-token", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.ANAM_API_KEY}`, }, body: JSON.stringify({ personaConfig: { name: "Cara", avatarId: "071b0286-4cce-4808-bee2-e642f1062de3", avatarModel: "cara-4", voiceId: "de23e340-1416-4dd8-977d-065a7ca11697", llmId: "a7cf662c-2ace-4de1-a21e-ef0fbf144bb7", systemPrompt: "You are Cara, a helpful customer service representative. Be friendly and concise in your responses.", }, }), }); if (!response.ok) { const errorData = await response.json().catch(() => ({})); console.error("Anam API error:", response.status, errorData); return res.status(response.status).json({ error: errorData.message || "Failed to create session token", }); } const data = await response.json(); res.json({ sessionToken: data.sessionToken }); } catch (error) { console.error("Server error:", error); res.status(500).json({ error: "Internal server error" }); } }); app.listen(3000, () => { console.log("Server running on http://localhost:3000"); }); ``` The server exchanges your API key for a temporary session token. This token has limited scope and expires, so your API key stays secure on the server. ## Step 2: Set up your HTML Create an HTML page with a video element for the persona and controls to start/stop the chat: ```html public/index.html theme={"system"} My First Anam Persona

Chat with Cara

``` ## Step 3: Initialize the Anam client Create the client-side JavaScript to control your persona connection: ```javascript public/script.js theme={"system"} import { createClient } from "https://esm.sh/@anam-ai/js-sdk@latest"; let anamClient = null; const startButton = document.getElementById("start-button"); const stopButton = document.getElementById("stop-button"); const videoElement = document.getElementById("persona-video"); const statusElement = document.getElementById("status"); function setStatus(message) { statusElement.textContent = message; } async function startChat() { try { startButton.disabled = true; setStatus("Creating session..."); // Get session token from your server const response = await fetch("/api/session-token", { method: "POST", }); if (!response.ok) { const error = await response.json(); throw new Error(error.error || "Failed to get session token"); } const { sessionToken } = await response.json(); setStatus("Connecting..."); // Create the Anam client anamClient = createClient(sessionToken); // Start streaming to the video element await anamClient.streamToVideoElement("persona-video"); startButton.disabled = true; stopButton.disabled = false; setStatus("Connected - start speaking!"); } catch (error) { console.error("Failed to start chat:", error); setStatus(`Error: ${error.message}`); startButton.disabled = false; } } function stopChat() { if (anamClient) { anamClient.stopStreaming(); anamClient = null; videoElement.srcObject = null; startButton.disabled = false; stopButton.disabled = true; setStatus("Chat ended"); } } startButton.addEventListener("click", startChat); stopButton.addEventListener("click", stopChat); ``` For details on `createClient`, `streamToVideoElement`, and `stopStreaming`, see the [SDK Reference](https://anam.ai/docs/javascript-sdk/reference/basic-usage). ## Step 4: Run your application 1. Start your server: ```bash theme={"system"} node server.js ``` 2. Open [http://localhost:3000](http://localhost:3000) in your browser 3. Click "Start Chat" to begin your conversation with Cara > [!TIP] > > You should see Cara appear in the video element, ready to chat through voice interaction. ## How it works 1. **Server-side authentication**: Your server exchanges the API key for a session token, keeping credentials secure 2. **Client connection**: The SDK creates a WebRTC connection for real-time video streaming 3. **Voice interaction**: Cara listens for your voice input and responds with synchronized audio and video 4. **Connection control**: Start and stop buttons control when the persona is active ## Next steps > [card] [Cookbook: Basic Next.js App](https://anam.ai/cookbook/basic-nextjs-app) > > Full tutorial for building a Next.js app with the Anam SDK > [card] [Core Concepts](https://anam.ai/docs/personas/overview) > > Learn how personas, tokens, and streaming work > [card] [Handle Events](https://anam.ai/docs/javascript-sdk/reference/event-types) > > React to conversation events and user interactions > [card] [Production Setup](https://anam.ai/docs/javascript-sdk/production) > > Deploy your persona securely at scale ## Common issues **Persona not appearing?** * Check that your API key is set correctly in `.env` * Ensure the video element has `autoplay` and `playsinline` attributes * Check the browser console for errors **No audio?** * Make sure your browser allows autoplay with sound * The user must interact with the page first (clicking "Start Chat" satisfies this) **Connection issues?** * Verify your server can reach api.anam.ai * Check network connectivity and firewall settings # Custom LLM (client-side) Source: https://anam.ai/docs/javascript-sdk/examples/custom-llm Build your own AI conversation logic with OpenAI, Anthropic, and other language models Learn how to bypass Anam's built-in language models and integrate your own custom LLM for complete control over conversation logic. This guide uses OpenAI as an example, but the pattern works with any LLM provider (Anthropic, Google Gemini, Groq, Mistral, etc.). > [card] [Cookbook: Custom LLM (Client-Side)](https://anam.ai/cookbook/custom-llm-client-side) > > Step-by-step tutorial with full source code > [!NOTE] > > **New Feature**: Anam now supports [server-side custom LLMs](/docs/concepts/custom-llms) where we > handle the LLM calls for you, improving latency and simplifying development. This guide shows the > client-side approach where you manage the LLM calls yourself. ## What You'll Build By the end of this guide, you'll have a persona application featuring: * **Custom AI Brain** using your own language model (OpenAI GPT-4.1-mini) * **Streaming Responses** with real-time text-to-speech conversion * **Turn-taking Management** that handles conversation flow * **Message History Integration** that maintains conversation context * **Error Handling & Recovery** for production use > [!TIP] > > After completing the initial setup (Steps 1-4), you can extend this foundation by adding features > like conversation memory, different LLM providers, custom system prompts, or specialized AI > behaviors. > [!NOTE] > > This guide uses **OpenAI's GPT-4.1-mini** as an example custom LLM for demonstration purposes. In > your actual application, you would replace the OpenAI integration with calls to your specific LLM > provider. The core integration pattern remains the same regardless of your LLM choice. ## Prerequisites * **Node.js** (version 18 or higher) and **npm** installed * Understanding of modern JavaScript/TypeScript and streaming APIs * An Anam API key ([get one here](/docs/api-key)) * An OpenAI API key ([get one here](https://platform.openai.com/api-keys)) * Basic knowledge of Express.js and modern web development * A microphone and speakers for voice interaction ## Understanding the Custom LLM Flow Before diving into the implementation, here is how custom LLM integration works with Anam personas. Regardless of your custom LLM provider, the implementation pattern follows these steps: **1. Disable Default Brain** The `llmId: "CUSTOMER_CLIENT_V1"` setting in the session token request disables Anam's default AI, allowing you to handle all conversation logic. **2. Listen for User Input** The `MESSAGE_HISTORY_UPDATED` event fires when the user finishes speaking, providing the complete conversation history including the new user message. **3. Process with Custom LLM** Your server endpoint receives the conversation history and generates a streaming response using your chosen LLM (OpenAI in this example). **4. Stream to Persona** The LLM response is streamed back to the client and forwarded to the persona using `createTalkMessageStream()` for text-to-speech conversion. Using these core concepts, we'll build a simple web application that allows you to chat with your custom LLM-powered persona. ## Basic Setup Let's start by building the foundation with custom LLM integration. This setup creates a web application with four main components: ``` anam-custom-llm-app/ ├── server.js # Express server with streaming LLM endpoint ├── package.json # Node.js dependencies ├── public/ # Static files served to the browser │ ├── index.html # Main HTML page with video element │ └── script.js # Client-side JavaScript for persona control └── .env # Environment variables ``` **1. Create project directory** ```bash theme={"system"} mkdir anam-custom-llm-app cd anam-custom-llm-app ``` **2. Initialize Node.js project** ```bash theme={"system"} npm init -y ``` This creates a `package.json` file for managing dependencies. **3. Create public directory** ```bash theme={"system"} mkdir public ``` > [!NOTE] > > The `public` folder will contain your HTML and JavaScript files that are served to the browser. **4. Install dependencies** ```bash theme={"system"} npm install express dotenv openai ``` > [!NOTE] > > We're installing Express for the server, dotenv for environment variables, and the OpenAI SDK > for custom LLM integration. The Anam SDK will be loaded directly from a CDN in the browser. **5. Configure environment variables** Create a `.env` file in your project root to store your API keys securely: ```bash .env theme={"system"} ANAM_API_KEY=your-anam-api-key-here OPENAI_API_KEY=your-openai-api-key-here ``` > [!WARNING] > > Replace the placeholder values with your actual API keys. Never commit this file to version control. ### Step 1: Set up your server with LLM streaming Create an Express server that handles both session token generation and LLM streaming: ```javascript server.js theme={"system"} require('dotenv').config(); const express = require('express'); const OpenAI = require('openai'); const app = express(); // Initialize OpenAI client const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); app.use(express.json()); app.use(express.static('public')); // Session token endpoint with custom brain configuration app.post('/api/session-token', async (req, res) => { try { const response = await fetch('https://api.anam.ai/v1/auth/session-token', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${process.env.ANAM_API_KEY}`, }, body: JSON.stringify({ personaConfig: { name: 'Cara', avatarId: '071b0286-4cce-4808-bee2-e642f1062de3', avatarModel: 'cara-4', voiceId: 'de23e340-1416-4dd8-977d-065a7ca11697', // This disables Anam's default brain and enables custom LLM integration llmId: 'CUSTOMER_CLIENT_V1', }, }), }); const data = await response.json(); res.json({ sessionToken: data.sessionToken }); } catch (error) { console.error('Session token error:', error); res.status(500).json({ error: 'Failed to create session' }); } }); // Custom LLM streaming endpoint app.post('/api/chat-stream', async (req, res) => { try { const { messages } = req.body; // Create a streaming response from OpenAI const stream = await openai.chat.completions.create({ model: 'gpt-4.1-mini', messages: [ { role: 'system', content: 'You are Cara, a helpful AI assistant. Be friendly, concise, and conversational in your responses. Keep responses under 100 words unless specifically asked for detailed information.', }, ...messages, ], stream: true, temperature: 0.7, }); // Set headers for streaming response res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); // Process the OpenAI stream and forward to client for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content || ''; if (content) { // Send each chunk as JSON res.write(JSON.stringify({ content }) + '\n'); } } res.end(); } catch (error) { console.error('LLM streaming error:', error); res.status(500).json({ error: 'An error occurred while streaming response' }); } }); app.listen(8000, () => { console.log('Server running on http://localhost:8000'); console.log('Custom LLM integration ready!'); }); ``` > [!NOTE] > > The key difference here is setting `llmId: "CUSTOMER_CLIENT_V1"` which disables Anam's default AI > and enables custom LLM integration. The `/api/chat-stream` endpoint handles the actual AI > conversation logic. ### Step 2: Set up your HTML Create a simple HTML page with video element and conversation display: ```html public/index.html theme={"system"} Custom LLM Persona - Anam Integration

Custom LLM Persona

Ready to connect

Conversation

Start a conversation to see your chat history...
``` ### Step 3: Implement the client-side custom LLM integration Create the client-side JavaScript that handles the custom LLM integration: ```javascript public/script.js theme={"system"} import { createClient } from 'https://esm.sh/@anam-ai/js-sdk@latest'; import { AnamEvent } from 'https://esm.sh/@anam-ai/js-sdk@latest/dist/module/types'; let anamClient = null; // Get DOM elements const startButton = document.getElementById('start-button'); const stopButton = document.getElementById('stop-button'); const videoElement = document.getElementById('persona-video'); const statusElement = document.getElementById('status'); const chatHistory = document.getElementById('chat-history'); // Status management function updateStatus(message, type = 'normal') { statusElement.textContent = message; const colors = { loading: '#f39c12', connected: '#28a745', error: '#dc3545', normal: '#333', }; statusElement.style.color = colors[type] || colors.normal; } // Chat history management function updateChatHistory(messages) { if (!chatHistory) return; chatHistory.innerHTML = ''; if (messages.length === 0) { chatHistory.innerHTML = '
Start a conversation to see your chat history...
'; return; } messages.forEach((message) => { const messageDiv = document.createElement('div'); const isUser = message.role === 'user'; messageDiv.style.cssText = ` margin-bottom: 10px; padding: 8px 12px; border-radius: 8px; max-width: 85%; background: ${isUser ? '#e3f2fd' : '#f1f8e9'}; ${isUser ? 'margin-left: auto; text-align: right;' : ''} `; messageDiv.innerHTML = `${isUser ? 'You' : 'Cara'}: ${message.content}`; chatHistory.appendChild(messageDiv); }); // Scroll to bottom chatHistory.scrollTop = chatHistory.scrollHeight; } // Custom LLM response handler async function handleUserMessage(messageHistory) { // Only respond to user messages if (messageHistory.length === 0 || messageHistory[messageHistory.length - 1].role !== 'user') { return; } if (!anamClient) return; try { console.log('Getting custom LLM response for:', messageHistory); // Convert Anam message format to OpenAI format const openAIMessages = messageHistory.map((msg) => ({ role: msg.role === 'user' ? 'user' : 'assistant', content: msg.content, })); // Create a streaming talk session // You can optionally pass a correlationId to track this specific message stream const talkStream = anamClient.createTalkMessageStream(); // Call our custom LLM streaming endpoint const response = await fetch('/api/chat-stream', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messages: openAIMessages }), }); if (!response.ok) { throw new Error(`LLM request failed: ${response.status}`); } const reader = response.body?.getReader(); if (!reader) { throw new Error('Failed to get response stream reader'); } const textDecoder = new TextDecoder(); console.log('Streaming LLM response to persona...'); // Stream the response chunks to the persona while (true) { const { done, value } = await reader.read(); if (done) { console.log('LLM streaming complete'); if (talkStream.isActive()) { talkStream.endMessage(); } break; } if (value) { const text = textDecoder.decode(value); const lines = text.split('\n').filter((line) => line.trim()); for (const line of lines) { try { const data = JSON.parse(line); if (data.content && talkStream.isActive()) { talkStream.streamMessageChunk(data.content, false); } } catch (parseError) { // Ignore parse errors in streaming } } } } } catch (error) { console.error('Custom LLM error:', error); if (anamClient) { anamClient.talk( "I'm sorry, I encountered an error while processing your request. Please try again." ); } } } async function startConversation() { try { startButton.disabled = true; updateStatus('Connecting...', 'loading'); // Get session token from server const response = await fetch('/api/session-token', { method: 'POST', }); if (!response.ok) { throw new Error('Failed to get session token'); } const { sessionToken } = await response.json(); // Create Anam client anamClient = createClient(sessionToken); // Set up event listeners anamClient.addListener(AnamEvent.SESSION_READY, () => { console.log('Session ready!'); updateStatus('Connected - Custom LLM active', 'connected'); startButton.disabled = true; stopButton.disabled = false; // Send initial greeting anamClient.talk("Hello! I'm Cara, powered by a custom AI brain. How can I help you today?"); }); anamClient.addListener(AnamEvent.CONNECTION_CLOSED, () => { console.log('Connection closed'); stopConversation(); }); // This is the key event for custom LLM integration anamClient.addListener(AnamEvent.MESSAGE_HISTORY_UPDATED, handleUserMessage); // Update chat history in real-time anamClient.addListener(AnamEvent.MESSAGE_HISTORY_UPDATED, (messages) => { updateChatHistory(messages); }); // Handle stream interruptions (user interrupted the persona while speaking) anamClient.addListener(AnamEvent.TALK_STREAM_INTERRUPTED, () => { console.log('Talk stream interrupted by user'); }); // Start streaming to video element await anamClient.streamToVideoElement('persona-video'); console.log('Custom LLM persona started successfully!'); } catch (error) { console.error('Failed to start conversation:', error); updateStatus(`Error: ${error.message}`, 'error'); startButton.disabled = false; } } function stopConversation() { if (anamClient) { anamClient.stopStreaming(); anamClient = null; } // Reset UI videoElement.srcObject = null; updateChatHistory([]); updateStatus('Disconnected', 'normal'); startButton.disabled = false; stopButton.disabled = true; console.log('Conversation stopped'); } // Add event listeners startButton.addEventListener('click', startConversation); stopButton.addEventListener('click', stopConversation); // Cleanup on page unload window.addEventListener('beforeunload', stopConversation); ``` ### Step 4: Test your custom LLM integration 1. Start your server: ```bash theme={"system"} node server.js ``` 2. Open [http://localhost:8000](http://localhost:8000) in your browser 3. Click "Start Conversation" to begin chatting with your custom LLM-powered persona! > [!TIP] > > You should see Cara appear and greet you, powered by your custom OpenAI integration. Try having a > conversation - your voice will be transcribed, sent to OpenAI's GPT-4.1-mini, and the response will > be streamed back through the persona's voice and video. ## Advanced Features ### Enhanced Error Handling Add retry logic to improve reliability: ```javascript theme={"system"} // Add this to your script.js handleUserMessage function async function handleUserMessage(messageHistory) { if (messageHistory.length === 0 || messageHistory[messageHistory.length - 1].role !== 'user') { return; } if (!anamClient) return; const maxRetries = 3; let retryCount = 0; while (retryCount < maxRetries) { try { // ... existing LLM call code ... return; // Success, exit retry loop } catch (error) { retryCount++; console.error(`Custom LLM error (attempt ${retryCount}):`, error); if (retryCount >= maxRetries) { // Final fallback response if (anamClient) { anamClient.talk( "I'm experiencing some technical difficulties. Please try rephrasing your question or try again in a moment." ); } } else { // Wait before retry await new Promise((resolve) => setTimeout(resolve, 1000 * retryCount)); } } } } ``` ## What You've Built You've integrated a custom language model with Anam's persona system. Your application includes: * **Custom AI Brain**: Control over your persona's intelligence using OpenAI's GPT-4.1-mini, with the ability to customize personality, knowledge, and behavior. * **Real-time Streaming**: Responses stream from your LLM through the persona's voice. * **Conversation Context**: Full conversation history is maintained and provided to your LLM for contextually aware responses. * **Error Handling**: Retry logic and fallback responses for reliability. * **Extensible Architecture**: The modular design allows you to swap LLM providers, add custom logic, or integrate with other AI services. ## Troubleshooting > [accordion] LLM Responses Not Streaming > > **Symptoms**: Persona doesn't speak or responses are delayed > > **Solutions**: > > * Verify OpenAI API key is correctly configured > * Check that `llmId: "CUSTOMER_CLIENT_V1"` is set in session token > * Ensure `MESSAGE_HISTORY_UPDATED` event listener is properly connected > * Check browser console for JavaScript errors > * Verify the `/api/chat-stream` endpoint is responding correctly > [accordion] Streaming Performance Issues > > **Symptoms**: Slow or choppy persona responses > > **Solutions**: > > * Optimize LLM model parameters (reduce max\_tokens, adjust temperature) > * Implement response caching for common queries > * Use faster models like `gpt-4.1-mini` instead of `gpt-4` > * Consider chunking large responses for better streaming > * Monitor network latency and server performance *** # Custom TTS (client-side) Source: https://anam.ai/docs/javascript-sdk/examples/custom-tts Use your own text-to-speech provider with Anam avatars via audio passthrough mode. > [!NOTE] > > **Want to use ElevenLabs Agents with Anam?** We recommend the [server-side ElevenLabs integration](/docs/integrations/elevenlabs/agents) instead—it's simpler and has lower latency. This page covers the client-side approach for when you need direct control over the audio pipeline. This guide shows how to use Anam's **audio passthrough** mode to pipe externally-generated speech audio into an avatar for real-time lip-sync. The example below uses [ElevenLabs Conversational AI](https://elevenlabs.io/conversational-ai) as the TTS source, but the same pattern works with **any TTS provider** (Cartesia, PlayHT, Azure Speech, Google Cloud TTS, etc.)—you just need to deliver PCM audio chunks to the Anam SDK. [YouTube video player](https://www.youtube.com/embed/07nyP8nYzg0) > [card] [View Example](https://github.com/anam-org/11labs_agent_demo) > > Full source code for the ElevenLabs conversational agent with Anam avatar (client-side). ## How It Works The integration uses Anam's **audio passthrough** mode, where Anam renders an avatar that lip-syncs to audio you provide—without using Anam's own AI or microphone input. ![](https://mintcdn.com/anam/2nHPhouImh2qBLQ2/images/audio_passthrough2.png?fit=max\&auto=format\&n=2nHPhouImh2qBLQ2\&q=85\&s=0949c9e72a7a08b380fd343989da8195) > [!TIP] > > **Bring Your Own Voice**: Your TTS provider generates the speech audio. Anam renders the lip-synced avatar video. ## Quick Start ### Prerequisites * An account with your TTS provider (ElevenLabs used in this example) * [Anam](https://anam.ai) account with API access * Node.js or Bun runtime * Modern browser with WebRTC support (Chrome, Firefox, Safari, Edge) ### Installation ```bash theme={"system"} npm install @anam-ai/js-sdk chatdio ``` `chatdio` provides microphone capture utilities used to send user audio to ElevenLabs. ### Basic Integration Here's the core pattern for connecting an external TTS source to Anam: ```typescript theme={"system"} import { createClient } from "@anam-ai/js-sdk"; // 1. Create Anam client with audio passthrough session const anamClient = createClient(sessionToken, { disableInputAudio: true, // Your TTS provider handles microphone }); await anamClient.streamToVideoElement("video-element"); // 2. Create agent audio input stream const audioInputStream = anamClient.createAgentAudioInputStream({ encoding: "pcm_s16le", sampleRate: 16000, channels: 1, }); // 3. Connect to your TTS provider and forward audio // (ElevenLabs WebSocket shown here as an example) const ws = new WebSocket(`wss://api.elevenlabs.io/v1/convai/conversation?agent_id=${agentId}`); ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "audio" && msg.audio_event?.audio_base_64) { // Forward audio chunks to Anam for lip-sync audioInputStream.sendAudioChunk(msg.audio_event.audio_base_64); } if (msg.type === "agent_response_complete") { // Signal that ElevenLabs completed this response audioInputStream.endSequence(); } if (msg.type === "interruption") { // Handle barge-in: stop the avatar animation and end the audio sequence anamClient.interruptPersona(); audioInputStream.endSequence(); } }; ``` ## Full Example ### Project Structure ``` src/ ├── client.ts # Main client orchestration ├── elevenlabs.ts # ElevenLabs WebSocket handling └── routes/ └── api/ └── config.ts # Server-side session token endpoint ``` ### Server: Create Anam Session Your server creates an Anam session token with `enableAudioPassthrough: true`: ```typescript config.ts theme={"system"} const response = await fetch("https://api.anam.ai/v1/auth/session-token", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${ANAM_API_KEY}`, }, body: JSON.stringify({ personaConfig: { avatarId: AVATAR_ID, avatarModel: "cara-4", enableAudioPassthrough: true, // Enable external audio input }, }), }); const { sessionToken } = await response.json(); ``` ### Client: ElevenLabs Module Handle the WebSocket connection and microphone capture: ```typescript elevenlabs.ts theme={"system"} import { MicrophoneCapture, arrayBufferToBase64 } from "chatdio"; const SAMPLE_RATE = 16000; export interface ElevenLabsCallbacks { onReady?: () => void; onAudio?: (base64Audio: string) => void; onUserTranscript?: (text: string) => void; onAgentResponse?: (text: string) => void; onAgentResponseComplete?: () => void; onInterrupt?: () => void; onError?: () => void; onDisconnect?: () => void; } export async function connectElevenLabs(agentId: string, callbacks: ElevenLabsCallbacks) { const ws = new WebSocket(`wss://api.elevenlabs.io/v1/convai/conversation?agent_id=${agentId}`); // Set up microphone capture const mic = new MicrophoneCapture({ sampleRate: SAMPLE_RATE, echoCancellation: true, noiseSuppression: true, }); mic.on("data", (data: ArrayBuffer) => { if (ws.readyState === WebSocket.OPEN) { ws.send( JSON.stringify({ user_audio_chunk: arrayBufferToBase64(data), }) ); } }); ws.onopen = async () => { await mic.start(); callbacks.onReady?.(); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); switch (msg.type) { case "audio": callbacks.onAudio?.(msg.audio_event.audio_base_64); break; case "agent_response": callbacks.onAgentResponse?.(msg.agent_response_event.agent_response); break; case "agent_response_complete": callbacks.onAgentResponseComplete?.(); break; case "user_transcript": callbacks.onUserTranscript?.(msg.user_transcription_event.user_transcript); break; case "interruption": callbacks.onInterrupt?.(); break; case "ping": ws.send(JSON.stringify({ type: "pong", event_id: msg.ping_event.event_id })); break; } }; ws.onclose = () => { mic.stop(); callbacks.onDisconnect?.(); }; } ``` ### Client: Main Integration Wire everything together: ```typescript client.ts theme={"system"} import { createClient } from "@anam-ai/js-sdk"; import { connectElevenLabs } from "./elevenlabs"; let anamClient: ReturnType | undefined; async function startConversation() { // Get session config from your server const { anamSessionToken, elevenLabsAgentId } = await fetch("/api/config").then((r) => r.json()); // Initialize Anam avatar (disable input audio since ElevenLabs handles mic) anamClient = createClient(anamSessionToken, { disableInputAudio: true, }); await anamClient.streamToVideoElement("anam-video"); // Create agent audio input stream const audioInputStream = anamClient.createAgentAudioInputStream({ encoding: "pcm_s16le", sampleRate: 16000, channels: 1, }); // Connect to ElevenLabs await connectElevenLabs(elevenLabsAgentId, { onAudio: (audio) => { audioInputStream.sendAudioChunk(audio); }, onAgentResponseComplete: () => { audioInputStream.endSequence(); }, onInterrupt: () => { anamClient.interruptPersona(); audioInputStream.endSequence(); }, }); } ``` ### Cleanup Stop the conversation and release resources: ```typescript theme={"system"} async function stopConversation() { await anamClient?.stopStreaming(); } ``` ## Configuration ### Environment Variables **1. Get your API credentials** You'll need credentials from both services: | Service | Where to get it | | - | - | | **Anam** | [lab.anam.ai](https://lab.anam.ai) → API Keys | | **ElevenLabs** | [elevenlabs.io](https://elevenlabs.io) → Agents | **2. Set environment variables** ```bash .env theme={"system"} # Anam credentials ANAM_API_KEY=your_anam_api_key ANAM_AVATAR_ID=your_avatar_id # ElevenLabs credentials ELEVENLABS_AGENT_ID=your_agent_id ``` ### ElevenLabs Agent Setup When configuring your ElevenLabs agent, set the output audio format to match Anam's expectations: | Setting | Value | | - | - | | **Format** | PCM 16-bit | | **Sample Rate** | 16000 Hz | | **Channels** | Mono | Enable the `agent_response_complete` and `interruption` events in the agent's **Advanced → Client Events** settings. The `agent_response` event is sent with the first audio chunk, so it does not indicate that the audio sequence is complete. See [ElevenLabs client events](https://elevenlabs.io/docs/eleven-agents/customization/events/client-events). > [!WARNING] > > The stream configuration must match the audio you send. This example uses signed 16-bit PCM at 16 kHz with one channel. Anam processes audio at **24 kHz**. If your provider outputs 24 kHz PCM, send it as is with `sampleRate: 24000`. Anam resamples other rates, including the 16 kHz used in this example, so you don't need to convert 24 kHz audio to 16 kHz. ### Choosing an Avatar > [card] [Stock Avatars](https://anam.ai/docs/personas/avatars/gallery) > > Browse ready-to-use avatars in our gallery. Copy the avatar ID directly into your config. > [card] [Custom Avatars](https://lab.anam.ai/avatars) > > Create your own personalized avatar in Anam Lab with custom appearance and style. ## Audio Passthrough API > [!NOTE] > > To guide avatar expression in audio passthrough sessions, send Director Notes cues over the data channel. See [Director Notes](/docs/personas/director-notes#send-cues-over-the-data-channel). ### createAgentAudioInputStream() Creates a stream for sending audio chunks to the avatar for lip-sync. Must be called **after** `streamToVideoElement()` resolves (the session must be started first). ```typescript theme={"system"} const audioInputStream = anamClient.createAgentAudioInputStream({ encoding: "pcm_s16le", sampleRate: 16000, channels: 1, }); ``` **encoding** `string` *required* Audio encoding format. Only `pcm_s16le` (16-bit signed little-endian PCM) is supported. **sampleRate** `number` *required* Sample rate in Hz. This must match the PCM audio sent to the stream. `24000` is Anam's native rate; Anam resamples other rates, such as `16000`. **channels** `number` *required* Number of audio channels in each chunk. Must be `1`: Anam accepts mono audio only and ignores chunks with any other channel count. Convert stereo audio to mono before sending it. ### sendAudioChunk() Send a PCM audio chunk for lip-sync rendering. The method accepts an `ArrayBuffer`, `Uint8Array`, or base64-encoded string. The SDK converts binary input to base64, attaches the stream configuration, and increments the sequence number for each chunk. ```typescript theme={"system"} function forwardTtsAudio(chunk: ArrayBuffer | Uint8Array | string) { audioInputStream.sendAudioChunk(chunk); } ``` ### endSequence() Signal that the current audio sequence has ended. The SDK sends an end-of-sequence message and resets its sequence number to `0` for the next turn. ```typescript theme={"system"} audioInputStream.endSequence(); ``` Call this when: * Your TTS provider confirms that it has sent the final audio chunk for the turn * The user interrupts (barge-in) Do not call `endSequence()` when response text first becomes available if the provider can still send audio for that response. > [!TIP] > > For diagnostics, `getSequenceNumber()` returns the number of chunks sent in the current sequence, and `getConfig()` returns the stream's audio configuration. ## Handling Interruptions When a user speaks while the agent is talking (barge-in), your TTS provider sends an interruption event. Handle it by interrupting the avatar and ending the audio sequence: ```typescript theme={"system"} onInterrupt: () => { anamClient.interruptPersona(); audioInputStream.endSequence(); }, ``` `interruptPersona()` stops the avatar's current speech. `endSequence()` closes the current input sequence and resets chunk numbering. Call both so the avatar stops and the next utterance starts a new sequence. ## Optimize latency Time to first visible speech depends on your TTS provider's time to first byte (TTFB) and how quickly you deliver enough audio for Anam to begin rendering. At the start of each audio sequence, Anam waits for **480 ms of audio** before it starts generating frames. This is measured in audio duration, not elapsed time, so how long the wait takes depends on how quickly you send audio. You can't change this buffer per account or per session. Optimize both parts of the path: * **Reduce TTS TTFB.** Use a low-latency TTS model, reuse connections where the provider supports it, and send text to the provider as soon as it is ready. * **Forward the first audio immediately.** Call `sendAudioChunk()` as each chunk arrives. Don't wait for the full response, pace the audio, or add your own buffer. * **Deliver audio at least as fast as real time.** Audio that arrives faster than real time fills the 480 ms buffer sooner; audio streamed at speaking speed takes about 480 ms to fill it. Sustained delivery slower than real time can cause stutter or dropped frames. * **Minimize network distance.** Where your architecture permits, place server-side TTS and orchestration close to Anam's `eu-south` infrastructure for `eu` sessions or `us-east` infrastructure for `us` sessions. Use `eu` or `us` when [selecting a session region](/docs/personas/session/regions). In a browser-only integration, audio still travels through the user's client, so server co-location cannot remove that network leg. For lower latency requirements, consider using Anam's [turnkey solution](https://anam.ai/docs/javascript-sdk/quickstart) which handles STT, LLM, and TTS in an optimized pipeline, or the [server-side ElevenLabs integration](/docs/integrations/elevenlabs/agents) which reduces latency through server-to-server audio flow. ## Browser compatibility The integration requires WebRTC support. Tested browsers: | Browser | Support | | - | - | | Chrome 80+ | Full support | | Firefox 75+ | Full support | | Safari 14+ | Full support | | Edge 80+ | Full support | > [!NOTE] > > Mobile browsers are supported but may have higher latency on cellular networks. ## Billing When using audio passthrough mode: * **Anam**: Billed for avatar streaming time (session duration) * **TTS Provider**: Billed separately for STT, LLM, and TTS usage Check both [Anam pricing](https://anam.ai/pricing) and your TTS provider's pricing to understand total costs. ## When to Use This Approach This **client-side** approach is a good fit when you: * Need direct control over the audio pipeline in the browser * Want to use client-side tools with your TTS provider's agent * Have an existing client-side integration you want to add avatars to For most new projects, we recommend the **[server-side integration](/docs/integrations/elevenlabs/agents)** instead—it's simpler to set up and has lower latency. ## Troubleshooting > [accordion] Avatar lips not moving > > * Verify the stream configuration matches the audio you send: signed 16-bit little-endian PCM, mono, at the sample rate you set. Anam ignores chunks that aren't mono. > * Check that `sendAudioChunk()` is receiving data > * Ensure the audio input stream was created successfully > * Look for errors in browser console > [accordion] Audio/lip-sync out of sync > > * Call `endSequence()` after the final audio chunk for each response > * Ensure you're handling interruptions correctly > * Check network latency to both services > [accordion] No audio from agent > > * Verify your TTS provider agent is configured correctly > * Check the WebSocket connection is established > * Look for audio events in the message handler > * Confirm your agent ID is correct > [accordion] Microphone not working > > * Check browser permissions for microphone access > * Ensure `echoCancellation` is enabled to prevent feedback > * Verify the microphone is sending data at 16kHz > [accordion] Session token errors > > * Verify your `ANAM_API_KEY` is valid > * Check that `enableAudioPassthrough: true` is set in the session request > * Ensure the avatar ID exists in your account ## Resources > [card] [Server-Side Integration](/docs/integrations/elevenlabs/agents) > > Recommended: simpler setup with lower latency > [card] [Client-Side Source Code](https://github.com/robbie-anam/elevenlabs-agent/tree/clientside_version) > > Full source code for the client-side integration > [card] [Example: Expressive Voice Agents](/docs/integrations/elevenlabs/agents) > > Guide to using ElevenLabs V3 expressive voices with Anam > [card] [Avatar Gallery](https://anam.ai/docs/personas/avatars/gallery) > > Browse available stock avatars # Full application Source: https://anam.ai/docs/javascript-sdk/examples/full-app Build a production-style Anam web application with a richer interface, session lifecycle handling, audio controls, and conversation events. Build a web application that uses the Anam SDK's advanced features. This guide walks you through creating an interactive AI assistant with modern UI components, real-time event handling, chat history, talk commands, and production-grade security practices. ## How to use this guide This guide takes an **additive approach**, covering a range of Anam features and implementation patterns. Each section builds upon the previous ones, allowing you to add functionality progressively. > [!NOTE] > > We provide detailed, complete code examples to make integration > with AI coding assistants straightforward. Use the buttons in the top-right corner of > this page to open the content in your preferred LLM or copy the entire guide > for easy reference. > [!TIP] > > You likely won't need every component shown in this guide. After completing > the initial setup (Steps 1-4), use the **right-hand navigation** to jump > directly to the specific features you want to implement. Start with the basic setup, then selectively add the advanced features that match your use case. ## What You'll Build By the end of this guide, you'll have a persona application featuring: * **Modern UI/UX** with loading states, connection status, and responsive design * **Chat History Panel** showing conversation transcripts in real-time * **Advanced Event Handling** for connection management and user feedback * **Talk Commands** for programmatic persona control * **Audio Management** with mute/unmute functionality * **Production Security** with proper authentication and rate limiting * **Error Handling & Retry Logic** for better user experience ## Prerequisites * **Node.js** (version 18 or higher) and **npm** installed * Understanding of modern JavaScript/TypeScript * An Anam API key ([get one here](/docs/api-key)) * Basic knowledge of Express.js and modern web development * A microphone and speakers for voice interaction ## Basic App > [!NOTE] > > If you've already completed the [Basic Application](/docs/examples/basic-app) guide, you can skip to [Listening to events](#listening-to-events). The setup below is similar but included here for completeness. Let's start by building a simple working version, then enhance it with advanced features. This foundational setup creates a minimal web application with three main files: ``` anam-production-app/ ├── server.js # Express server for secure API key handling ├── package.json # Node.js dependencies ├── public/ # Static files served to the browser │ ├── index.html # Main HTML page with video element │ └── script.js # Client-side JavaScript for persona control └── .env # Environment variables ``` **1. Create project directory** ```bash theme={"system"} mkdir anam-production-app cd anam-production-app ``` **2. Initialize Node.js project** `bash npm init -y ` This creates a `package.json` file for managing dependencies. **3. Create public directory** `bash mkdir public ` > [!NOTE] > > The `public` folder will contain your HTML and JavaScript files that are served to the browser. **4. Install dependencies** `bash npm install express dotenv ` > [!NOTE] > > We're installing Express for the server and dotenv for environment variable management. The Anam SDK will be loaded directly from a CDN in the browser. **5. Configure environment variables** Create a `.env` file in your project root to store your API key securely: ```bash .env theme={"system"} ANAM_API_KEY=your-api-key-here ``` > [!WARNING] > > Replace `your-api-key-here` with your actual Anam API key. Never commit this file to version control. ### Step 1: Set up your server Create a basic Express server to handle session token generation: ```javascript server.js theme={"system"} require("dotenv").config(); const express = require("express"); const app = express(); app.use(express.json()); app.use(express.static("public")); app.post("/api/session-token", async (req, res) => { try { const response = await fetch("https://api.anam.ai/v1/auth/session-token", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.ANAM_API_KEY}`, }, body: JSON.stringify({ personaConfig: { name: "Cara", avatarId: "071b0286-4cce-4808-bee2-e642f1062de3", avatarModel: "cara-4", voiceId: "de23e340-1416-4dd8-977d-065a7ca11697", llmId: "a7cf662c-2ace-4de1-a21e-ef0fbf144bb7", systemPrompt: "You are Cara, a helpful AI assistant. Be friendly, concise, and helpful in your responses.", }, }), }); const data = await response.json(); res.json({ sessionToken: data.sessionToken }); } catch (error) { res.status(500).json({ error: "Failed to create session" }); } }); app.listen(8000, () => { console.log("Server running on http://localhost:8000"); }); ``` ### Step 2: Set up your HTML Create a simple HTML page with a video element and basic controls: ```html public/index.html theme={"system"} Anam AI Assistant - Production App

Chat with Cara

``` ### Step 3: Initialize the Anam client Create the client-side JavaScript to control your persona: ```javascript public/script.js theme={"system"} import { createClient } from "https://esm.sh/@anam-ai/js-sdk@latest"; let anamClient = null; // Get DOM elements const startButton = document.getElementById("start-button"); const stopButton = document.getElementById("stop-button"); const videoElement = document.getElementById("persona-video"); async function startChat() { try { startButton.disabled = true; // Get session token from your server const response = await fetch("/api/session-token", { method: "POST", }); const { sessionToken } = await response.json(); // Create the Anam client anamClient = createClient(sessionToken); // Start streaming to the video element await anamClient.streamToVideoElement("persona-video"); // Update button states startButton.disabled = true; stopButton.disabled = false; console.log("Chat started successfully!"); } catch (error) { console.error("Failed to start chat:", error); startButton.disabled = false; } } function stopChat() { if (anamClient) { // Disconnect the client anamClient.stopStreaming(); anamClient = null; // Clear video element videoElement.srcObject = null; // Update button states startButton.disabled = false; stopButton.disabled = true; console.log("Chat stopped."); } } // Add event listeners startButton.addEventListener("click", startChat); stopButton.addEventListener("click", stopChat); ``` ### Step 4: Test your basic setup 1. Start your server: ```bash theme={"system"} node server.js ``` 2. Open [http://localhost:8000](http://localhost:8000) in your browser 3. Click "Start Chat" to begin your conversation! > [!TIP] > > You should see Cara appear in the video element and be ready to chat through > voice interaction. Now that you have a working basic app, let's enhance it with production-ready features. ## Listening to events Anam personas communicate through an event system that allows your application to respond to connection changes, conversation updates, and user interactions. Let's enhance our basic app with event handling to create a more responsive experience. ### Understanding the Event System The Anam SDK uses an event-driven architecture where you can listen for specific events and react accordingly. Here's the process for listening to events: **1. Import the event types** Import the specific event types you want to listen to: ```javascript theme={"system"} import { AnamEvent } from "https://esm.sh/@anam-ai/js-sdk@latest/dist/module/types"; ``` **2. Define your event listener function** Create a function to handle the event: ```javascript theme={"system"} function onSessionReady() { console.log('Session Ready!'); // Do something when the session is ready } ``` **3. Add your event listener to the client** Register your listener function with the client: ```javascript theme={"system"} anamClient.addListener(AnamEvent.SESSION_READY, onSessionReady); ``` > [!TIP] > > For a full list of events, see the [Event Handling](https://anam.ai/docs/javascript-sdk/reference/event-types) > documentation. Now let's implement this pattern in our app by adding a loading state. ### Adding a loading state Loading states provide important user feedback during connection establishment. Let's add a simple loading indicator to our HTML: #### Step 1: Update the UI ```html public/index.html theme={"system"} Anam AI Assistant - Production App

Chat with Cara

``` #### Step 2: Adding the event listener Now let's update our JavaScript to handle the loading state by adding the following to our `script.js` file: ```javascript public/script.js {2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,39,40,41,42,43,44} theme={"system"} import { createClient } from "https://esm.sh/@anam-ai/js-sdk@latest"; import { AnamEvent } from "https://esm.sh/@anam-ai/js-sdk@latest/dist/module/types"; let anamClient = null; // Get DOM elements const startButton = document.getElementById("start-button"); const stopButton = document.getElementById("stop-button"); const videoElement = document.getElementById("persona-video"); const loadingMessage = document.getElementById("loading-message"); function showLoadingState() { if (loadingMessage) { loadingMessage.style.display = "block"; } } function hideLoadingState() { if (loadingMessage) { loadingMessage.style.display = "none"; } } async function startChat() { try { startButton.disabled = true; showLoadingState(); // Get session token from your server const response = await fetch("/api/session-token", { method: "POST", }); const { sessionToken } = await response.json(); // Create the Anam client anamClient = createClient(sessionToken); // Listen for SESSION_READY event to hide loading state anamClient.addListener(AnamEvent.SESSION_READY, () => { console.log("Session is ready!"); hideLoadingState(); startButton.disabled = true; stopButton.disabled = false; }); // Start streaming to the video element await anamClient.streamToVideoElement("persona-video"); console.log("Chat started successfully!"); } catch (error) { console.error("Failed to start chat:", error); startButton.disabled = false; hideLoadingState(); } } function stopChat() { if (anamClient) { // Disconnect the client anamClient.stopStreaming(); anamClient = null; // Clear video element videoElement.srcObject = null; // Update button states startButton.disabled = false; stopButton.disabled = true; console.log("Chat stopped."); } } // Add event listeners startButton.addEventListener("click", startChat); stopButton.addEventListener("click", stopChat); ``` ### Adding a chat history panel A common use case for event listeners is to update the UI based on the transcription of the conversation. Let's look at how we can implement this using Anam events. #### Understanding Message Events Anam provides two key events for tracking conversation transcriptions: | Event | Description | | - | - | | `MESSAGE_HISTORY_UPDATED` | Provides the complete conversation history each time someone finishes speaking | | `MESSAGE_STREAM_EVENT_RECEIVED` | Provides real-time transcription updates as speech occurs | Let's start with the `MESSAGE_HISTORY_UPDATED` event to build a basic chat history. #### Step 1: Add chat history UI First, update your HTML to include a simple chat panel: ```html public/index.html theme={"system"} Anam AI Assistant - Production App

Chat with Cara

Start a conversation to see your chat history

``` #### Step 2: Listen for updates Now let's add the event listener to handle complete conversation updates: ```javascript public/script.js {25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,74,75,76,77,78,79,99} theme={"system"} import { createClient } from "https://esm.sh/@anam-ai/js-sdk@latest"; import { AnamEvent } from "https://esm.sh/@anam-ai/js-sdk@latest/dist/module/types"; let anamClient = null; // Get DOM elements const startButton = document.getElementById("start-button"); const stopButton = document.getElementById("stop-button"); const videoElement = document.getElementById("persona-video"); const loadingMessage = document.getElementById("loading-message"); const chatHistory = document.getElementById("chat-history"); function showLoadingState() { if (loadingMessage) { loadingMessage.style.display = "block"; } } function hideLoadingState() { if (loadingMessage) { loadingMessage.style.display = "none"; } } function updateChatHistory(messages) { if (!chatHistory) return; // Clear existing content chatHistory.innerHTML = ""; if (messages.length === 0) { chatHistory.innerHTML = "

Start a conversation to see your chat history

"; return; } // Add each message to the chat history messages.forEach((message) => { const messageDiv = document.createElement("div"); messageDiv.style.marginBottom = "10px"; messageDiv.style.padding = "5px"; messageDiv.style.borderRadius = "5px"; if (message.role === "user") { messageDiv.style.backgroundColor = "#e3f2fd"; messageDiv.innerHTML = `You: ${message.content}`; } else { messageDiv.style.backgroundColor = "#f1f8e9"; messageDiv.innerHTML = `Cara: ${message.content}`; } chatHistory.appendChild(messageDiv); }); // Scroll to bottom chatHistory.scrollTop = chatHistory.scrollHeight; } async function startChat() { try { startButton.disabled = true; showLoadingState(); // Get session token from your server const response = await fetch("/api/session-token", { method: "POST", }); const { sessionToken } = await response.json(); // Create the Anam client anamClient = createClient(sessionToken); // Listen for SESSION_READY event to hide loading state anamClient.addListener(AnamEvent.SESSION_READY, () => { console.log("Session is ready!"); hideLoadingState(); startButton.disabled = true; stopButton.disabled = false; }); // Listen for MESSAGE_HISTORY_UPDATED to update chat history anamClient.addListener(AnamEvent.MESSAGE_HISTORY_UPDATED, (messages) => { console.log("Conversation updated:", messages); updateChatHistory(messages); }); // Start streaming to the video element await anamClient.streamToVideoElement("persona-video"); console.log("Chat started successfully!"); } catch (error) { console.error("Failed to start chat:", error); startButton.disabled = false; hideLoadingState(); } } function stopChat() { if (anamClient) { // Disconnect the client anamClient.stopStreaming(); anamClient = null; // Clear video element and chat history videoElement.srcObject = null; updateChatHistory([]); // Update button states startButton.disabled = false; stopButton.disabled = true; console.log("Chat stopped."); } } // Add event listeners startButton.addEventListener("click", startChat); stopButton.addEventListener("click", stopChat); ``` > [!NOTE] > > The `MESSAGE_HISTORY_UPDATED` event provides an array of message objects with > `role` ("user" or "assistant") and `content` properties. This gives you the > complete conversation transcript each time someone finishes speaking. #### Step 3: Add real-time transcription Now let's enhance the experience by showing live transcription as the persona speaks using the `MESSAGE_STREAM_EVENT_RECEIVED` event: ```html theme={"system"}
Persona Live:
``` And update your JavaScript to handle real-time events: ```javascript theme={"system"} // Add this event listener inside your startChat function after the MESSAGE_HISTORY_UPDATED listener // Listen for real-time transcription events anamClient.addListener(AnamEvent.MESSAGE_STREAM_EVENT_RECEIVED, (event) => { const liveTranscript = document.getElementById("live-transcript"); const transcriptText = document.getElementById("transcript-text"); console.log("event", event); if (event.role === "persona") { // Show persona speaking in real-time if (liveTranscript && transcriptText) { transcriptText.textContent = transcriptText.textContent + event.content; } } else if (event.role === "user") { // clear the persona live transcript when the user speaks if (liveTranscript && transcriptText) { transcriptText.textContent = ""; } } }); ``` > [!TIP] > > The `MESSAGE_STREAM_EVENT_RECEIVED` event fires continuously as speech is > being processed. Use `event.role` to distinguish between "persona" (AI > speaking) and "user" (user speaking) events. > [!TIP] > > Your app now displays both complete conversation history and real-time > transcription as the persona speaks! ## Sending commands Beyond voice interaction, you can programmatically send messages to your persona using the talk command. This is useful for creating interactive experiences, automated workflows, or custom UI controls. ### Using the talk command The talk command allows you to send text messages that the persona will speak directly. This can be used to instruct the persona to say something in response to a user action other than voice input, such as a button click or when certain UI elements are shown on screen. You can send a talk command by calling the `talk` method on the Anam client during a session. ```javascript theme={"system"} anamClient.talk("Hello, how are you?"); ``` Let's use this to add a talk command UI to our app. #### Step 1: Update the UI First, update your HTML to include a text input and send button ```html public/index.html theme={"system"} Anam AI Assistant - Production App

Chat with Cara

Start a conversation to see your chat history

Persona Live:

Send Message

``` #### Step 2: Add the code Now let's add the code to our `script.js` file to send the command to the persona ```javascript public/script.js theme={"system"} // Add these functions to your existing script.js file async function sendTalkMessage() { const messageInput = document.getElementById("message-input"); const sendButton = document.getElementById("send-message"); if (!anamClient || !messageInput) return; const message = messageInput.value.trim(); if (!message) { alert("Please enter a message"); return; } try { sendButton.disabled = true; sendButton.textContent = "Sending..."; // Send the message to the persona await anamClient.talk(message); // Clear the input messageInput.value = ""; } catch (error) { console.error("Failed to send message:", error); alert("Failed to send message. Please try again."); } finally { sendButton.disabled = false; sendButton.textContent = "Send Message"; } } function updateTalkControls(connected) { const sendButton = document.getElementById("send-message"); const messageInput = document.getElementById("message-input"); if (sendButton) { sendButton.disabled = !connected; sendButton.style.opacity = connected ? "1" : "0.5"; } if (messageInput) { messageInput.disabled = !connected; messageInput.placeholder = connected ? "Type a message for Cara to respond to..." : "Connect to start chatting..."; } } // Update your startChat function to enable talk controls async function startChat() { try { startButton.disabled = true; showLoadingState(); const response = await fetch("/api/session-token", { method: "POST", }); const { sessionToken } = await response.json(); anamClient = createClient(sessionToken); anamClient.addListener(AnamEvent.SESSION_READY, () => { console.log("Session is ready!"); hideLoadingState(); startButton.disabled = true; stopButton.disabled = false; updateTalkControls(true); // Enable talk controls }); anamClient.addListener(AnamEvent.MESSAGE_HISTORY_UPDATED, (messages) => { console.log("Conversation updated:", messages); updateChatHistory(messages); }); anamClient.addListener(AnamEvent.MESSAGE_STREAM_EVENT_RECEIVED, (event) => { const liveTranscript = document.getElementById("live-transcript"); const transcriptText = document.getElementById("transcript-text"); if (event.role === "persona") { if (liveTranscript && transcriptText) { transcriptText.textContent = transcriptText.textContent + event.content; } } else if (event.role === "user") { if (liveTranscript && transcriptText) { transcriptText.textContent = ""; } } }); await anamClient.streamToVideoElement("persona-video"); console.log("Chat started successfully!"); } catch (error) { console.error("Failed to start chat:", error); startButton.disabled = false; hideLoadingState(); } } // Add event listeners for talk functionality document.addEventListener("DOMContentLoaded", () => { const sendButton = document.getElementById("send-message"); const messageInput = document.getElementById("message-input"); if (sendButton) { sendButton.addEventListener("click", sendTalkMessage); } if (messageInput) { // Send message with Enter key (Shift+Enter for new line) messageInput.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendTalkMessage(); } }); } }); ``` ## Advanced Stream Management For applications that require more control over audio and video streams, you have two main approaches for customizing the streaming behavior: 1. **Custom Input Streams**: Pass your own audio input to `streamToVideoElement` 2. **Output Stream Capture**: Use `stream()` to capture and process persona output ### Custom Input Streams The `streamToVideoElement()` method accepts an optional audio input stream, allowing you to process or record user audio before sending it to the persona: ```javascript theme={"system"} // Get and potentially process user audio const userInputStream = await navigator.mediaDevices.getUserMedia({ audio: true, }); // Start recording user input const userRecorder = new MediaRecorder(userInputStream); userRecorder.start(); // Use the same stream for persona input await anamClient.streamToVideoElement("persona-video", userInputStream); ``` This approach is useful when you want to: * Record user audio input * Apply audio filters or effects to user input * Monitor user audio levels * Handle custom microphone setups ### Output Stream Capture For capturing and processing the persona's output (video and audio), use the `stream()` method which returns the raw output streams: ```javascript theme={"system"} const userInputStream = await navigator.mediaDevices.getUserMedia({ audio: true, }); const [videoStream] = await anamClient.stream(userInputStream); // Now you have full control over the output stream videoElement.srcObject = videoStream; // Extract audio for separate processing const audioTracks = videoStream.getAudioTracks(); const personaAudioStream = new MediaStream(audioTracks); ``` This approach enables: * Recording persona video and audio output * Custom video rendering and effects * Audio analysis and processing * Streaming to multiple destinations ## What You've Built You now have a working Anam application with these core patterns: * **WebRTC Streaming**: Real-time video connection for voice conversations with an AI persona * **Event Handling**: Responding to session state changes and conversation updates using the SDK's event system * **Live Transcription**: Real-time display of what the persona is saying via `MESSAGE_STREAM_EVENT_RECEIVED` * **Conversation History**: Complete transcript tracking via `MESSAGE_HISTORY_UPDATED` * **Talk Commands**: Programmatic text input to trigger persona responses * **Session Management**: Secure server-side token generation with proper API key protection * **Stream Recording**: Manual stream management for custom audio processing workflows ## What's Next Ready to take your persona application further? Here are your next steps: **Explore Advanced Features**: Continue reading our guides to learn about [audio control](https://anam.ai/docs/javascript-sdk/reference/audio-control), [custom personas](https://anam.ai/docs/personas/overview), and [production deployment](https://anam.ai/docs/javascript-sdk/production) best practices. **Integrate Your Own AI**: Want to use your own language model instead of Anam's default brain? Check out our [Custom LLM Integration](/docs/examples/custom-llm) guide to learn how to connect your persona to custom AI models and APIs. ## Advanced Customization ### Persona Configuration Modify the `getDefaultPersonaConfig()` method to customize: * Avatar appearance and voice selection * System prompts and personality traits * Custom brain types and LLM integration ### UI Theming Update the CSS variables in `app.css` to match your brand: * Color schemes and gradients * Typography and spacing * Animation timing and effects ### Event Integration Extend the event handlers to integrate with your existing systems: * Analytics and user behavior tracking * Customer service platforms * CRM and database systems ## Troubleshooting > [accordion] Connection Issues > > **Symptoms**: Persona fails to connect or frequently disconnects > > **Solutions**: > > * Verify your API key is correctly configured > * Check network connectivity and firewall settings > * Ensure WebRTC is supported in your browser > * Review server logs for authentication errors > [accordion] Audio Problems > > **Symptoms**: No audio input/output or poor quality > > **Solutions**: > > * Grant microphone permissions in browser settings > * Check audio device configuration > * Ensure HTTPS is enabled (required for microphone access) > * Test with different browsers or devices > [accordion] Performance Issues > > **Symptoms**: Slow loading or laggy interactions > > **Solutions**: > > * Optimize network bandwidth and connection quality > * Reduce video quality if needed > * Implement connection pooling and caching > * Monitor server resource usage > [accordion] UI Responsiveness > > **Symptoms**: Interface doesn't work on mobile or different screen sizes > > **Solutions**: > > * Test on various devices and screen sizes > * Verify CSS media queries are working > * Check touch event handling > * Validate accessibility compliance # Deploy the JavaScript SDK to Production Source: https://anam.ai/docs/javascript-sdk/production Deploy Anam safely in production with server-side token creation, stateful and ephemeral session tokens, and client initialization. ## Overview When deploying to production, do not expose your API key publicly. Instead: 1. Exchange your API key for a short-lived session token on the server side 2. Pass this token to the client 3. Initialize the Anam SDK with the session token Anam AI offers two types of session tokens: **Stateful** and **Ephemeral**. ## Session Token Types ### Stateful Session Tokens Stateful tokens reference a persona that you've created and configured in the Anam AI Lab, or using the [Anam AI API](/docs/api-reference/personas/create-persona). These are referenced by a unique ID. > [card] Pros > > Configuration changes are managed in the Lab interface without needing code > changes. Ideal for personas that don't need to change from session to > session. > [card] Cons > > Less flexibility for per-user customization. ### Ephemeral Session Tokens Ephemeral tokens allow you to define the persona configuration at runtime. > [card] Pros > > Define your persona configuration at runtime, enabling per-session > customization and fast feedback during development. > [card] Cons > > Requires managing persona configuration inside your application. ## Getting a Session Token > [!NOTE] > > Session tokens are valid for **1 hour** by default. You should request a new token for each user session rather than caching tokens long-term. > [!WARNING] > > The session token endpoint must be called from your **server**, not from client-side code. Making this request from the browser would expose your API key. ### Stateful Session Token From your server, make a request to get a stateful session token, referencing your persona ID (found in the [Anam Lab](https://lab.anam.ai) under your persona's settings): ```typescript Fetching a stateful session token on your server theme={"system"} interface SessionTokenResponse { sessionToken: string; } async function getStatefulSessionToken( apiKey: string, personaId: string ): Promise { const response = await fetch("https://api.anam.ai/v1/auth/session-token", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}`, }, body: JSON.stringify({ personaConfig: { personaId, }, }), }); if (!response.ok) { const error = await response.text(); throw new Error(`Failed to get session token: ${response.status} ${error}`); } const data: SessionTokenResponse = await response.json(); return data.sessionToken; } ``` ### Ephemeral Session Token From your server, make a request to get an ephemeral session token with your persona configuration: ```typescript Fetching an ephemeral session token on your server theme={"system"} interface EphemeralPersonaConfig { name: string; avatarId: string; avatarModel: string; voiceId: string; llmId: string; systemPrompt: string; } interface SessionTokenResponse { sessionToken: string; } async function getEphemeralSessionToken( apiKey: string, personaConfig: EphemeralPersonaConfig ): Promise { const response = await fetch("https://api.anam.ai/v1/auth/session-token", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}`, }, body: JSON.stringify({ personaConfig, }), }); if (!response.ok) { const error = await response.text(); throw new Error(`Failed to get session token: ${response.status} ${error}`); } const data: SessionTokenResponse = await response.json(); return data.sessionToken; } // Example usage const sessionToken = await getEphemeralSessionToken(apiKey, { name: "Cara", avatarId: "071b0286-4cce-4808-bee2-e642f1062de3", avatarModel: "cara-4", voiceId: "de23e340-1416-4dd8-977d-065a7ca11697", llmId: "a7cf662c-2ace-4de1-a21e-ef0fbf144bb7", systemPrompt: "[STYLE] Reply in natural speech without formatting. Add pauses using '...' and very occasionally a disfluency. [PERSONALITY] You are Cara, a helpful assistant.", }); ``` ### Common Error Responses | Status Code | Meaning | Solution | | - | - | - | | 401 | Invalid or missing API key | Check your API key is correct and included in the Authorization header | | 403 | API key does not have permission | Verify your API key has the correct permissions in the Lab | | 404 | Persona not found (stateful tokens) | Check the persona ID exists and belongs to your account | | 429 | Rate limited | Reduce request frequency or contact support for higher limits | ## Client Initialization Once you have a session token from your server, use the `createClient` method to initialize the Anam client: ```typescript HelloWorld.ts theme={"system"} import { createClient } from "@anam-ai/js-sdk"; const anamClient = createClient(sessionToken); ``` > [!NOTE] > > The client exposes the same methods whether initialized with an API key or > session token. See [Basic Usage](https://anam.ai/docs/javascript-sdk/reference/basic-usage) for streaming and interaction examples. ## Understanding a Session The sequence diagram below shows how a typical session is started. ![Session initialization sequence diagram](https://mintcdn.com/anam/C1_yhmh0z2cLMID5/images/start-session.png?fit=max\&auto=format\&n=C1_yhmh0z2cLMID5\&q=85\&s=e1af3c048119abc5681d3823a3fe4923) ## Next Steps > [card] [Talk Commands](https://anam.ai/docs/javascript-sdk/reference/talk-commands) > > Control persona output using talk commands > [card] [Audio Control](https://anam.ai/docs/javascript-sdk/reference/audio-control) > > Control audio input and streaming behavior # JavaScript SDK Quickstart Source: https://anam.ai/docs/javascript-sdk/quickstart Create an Anam session token, install the JavaScript SDK, and run your first interactive avatar conversation in a browser. Build this JavaScript quickstart with a coding agent Paste this prompt into Cursor, Claude Code, Codex, or another coding agent. Copy prompt The Anam API provides a simple interface for implementing digital AI personas within your web applications. This guide will walk you through the process of setting up a minimal example of an interactive AI persona. By the end, you'll have a working persona that can have real-time conversations in your web browser. ## Prerequisites * An Anam API key ([get one here](/docs/api-key)) * A modern web browser with microphone access * A local web server (we'll show you how) ## Run this with your own persona Create a persona and API key in Anam Lab, then use them in the quickstart. > [card] [Create a persona](https://lab.anam.ai/build?action=create\&tab=persona\&cta_id=sdk-quickstart-persona) > > Configure the avatar, voice, model, and instructions for your persona. > [card] [Get an API key](https://lab.anam.ai/api-keys?cta_id=sdk-quickstart-api-key) > > Create the key used to authenticate the quickstart request. ## Create Your First Persona **1. Create the HTML structure** Create a new file called `index.html` and add this basic structure: ```html index.html theme={"system"} Hello Cara

Chat with Cara

Your AI persona will appear below and start automatically

Loading...
``` **2. Add the JavaScript** Now add the script that will automatically start your persona. Add this ` ``` **3. Add your API key** Replace `your-api-key-here` with your actual Anam API key in the script. **4. Complete file example** Your final `index.html` file should look like this: ```html index.html [expandable] theme={"system"} Hello Cara

Chat with Cara

Your AI persona will appear below and start automatically

Loading...
``` **5. Start a local server** To serve your html file, you'll need a local web server. You can use one of the following methods depending on which development tools you have installed. ```bash Node.js theme={"system"} npx http-server -p 8000 ``` ```bash Python 3 theme={"system"} python -m http.server 8000 ``` ```bash Python 2 theme={"system"} python -m SimpleHTTPServer 8000 ``` ```bash PHP theme={"system"} php -S localhost:8000 ``` **6. Open and test** 1. Navigate to `http://localhost:8000` in your browser 2. Allow microphone access when prompted 3. Cara will appear automatically and you can start talking! 4. When you're done, close the browser tab to end the session. ## What just happened? * **Obtaining a Session Token**: Your API key was exchanged for a temporary session token that enables the persona connection * **Establishing a WebRTC Stream**: The Anam SDK established a real-time video/audio connection to display your persona * **Voice Interaction**: Cara listens to your microphone and responds with natural speech and facial expressions ## What's next? Now that you have Cara running, here are some directions to explore: > [card] [Customize your persona](https://anam.ai/docs/personas/overview) > > Change your persona's appearance, voice, and personality > [card] [Build a full application](examples/basic-app) > > Create a complete app with proper client/server architecture > [card] [Handle conversation events](https://anam.ai/docs/javascript-sdk/reference/event-types) > > React when your persona speaks, listens, or encounters errors # JavaScript SDK Audio Control Source: https://anam.ai/docs/javascript-sdk/reference/audio-control Control microphone input, mute state, and audio streaming during an Anam session with the JavaScript SDK audio methods. ## Audio Input State By default, the Anam client starts capturing input audio from the user's microphone when a session starts and stops capturing when the session ends. For certain use cases, you may wish to control the input audio state programmatically. ### The InputAudioState Type The `InputAudioState` interface contains two properties: ```typescript theme={"system"} interface InputAudioState { isMuted: boolean; permissionState: AudioPermissionState; } enum AudioPermissionState { PENDING = 'pending', GRANTED = 'granted', DENIED = 'denied', NOT_REQUESTED = 'not_requested', } ``` ### Getting the Current State To check the current input audio state: ```typescript theme={"system"} import { InputAudioState, AudioPermissionState } from '@anam-ai/js-sdk'; const audioState: InputAudioState = anamClient.getInputAudioState(); // { isMuted: false, permissionState: 'granted' } // Check if microphone permission was granted if (audioState.permissionState === AudioPermissionState.DENIED) { console.log('Microphone access was denied'); } ``` ### Mute Audio Input To mute the input audio: ```typescript theme={"system"} const audioState: InputAudioState = anamClient.muteInputAudio(); // { isMuted: true, permissionState: 'granted' } ``` > [!NOTE] > > If you mute the input audio before starting a stream, the session will start with microphone input disabled. ### Unmute Audio Input To unmute the input audio: ```typescript theme={"system"} const audioState: InputAudioState = anamClient.unmuteInputAudio(); // { isMuted: false, permissionState: 'granted' } ``` ## Changing Audio Input Device To switch to a different microphone during an active session: ```typescript theme={"system"} // Get available audio input devices const devices = await navigator.mediaDevices.enumerateDevices(); const audioInputs = devices.filter(device => device.kind === 'audioinput'); // Switch to a specific device by its ID await anamClient.changeAudioInputDevice(audioInputs[1].deviceId); ``` > [!NOTE] > > You must be actively streaming to change the audio input device. This method throws an error if called before `streamToVideoElement()`. ## Configuration Options ### Disabling Audio Input To completely disable microphone input (useful for text-only interactions or when using custom input streams): ```typescript theme={"system"} import { createClient } from '@anam-ai/js-sdk'; const anamClient = createClient(sessionToken, { disableInputAudio: true, }); ``` When `disableInputAudio` is `true`: * The SDK will not request microphone permissions * `muteInputAudio()` and `unmuteInputAudio()` will have no effect * Any user-provided audio stream will be ignored ### Specifying an Audio Device To use a specific microphone at initialization: ```typescript theme={"system"} const anamClient = createClient(sessionToken, { audioDeviceId: 'specific-device-id', }); ``` ## Custom Input Streams If you wish to control the microphone input audio capture yourself, you can pass your own `MediaStream` object when starting a stream: ```typescript theme={"system"} // Get your own media stream const userProvidedMediaStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false, }); anamClient.streamToVideoElement( 'video-element-id', userProvidedMediaStream ); ``` > [!NOTE] > > The `userProvidedMediaStream` object must be an instance of `MediaStream` and the user input audio should be the first audio track returned from the `MediaStream.getAudioTracks()` method. > [!TIP] > > This is the default behavior if you are using `navigator.mediaDevices.getUserMedia()`. # JavaScript SDK Basic Usage Source: https://anam.ai/docs/javascript-sdk/reference/basic-usage Install and initialise the Anam JavaScript SDK, configure the client, start and stop sessions, and prepare the integration for deployment. ## Installation Install the SDK in your project using npm: ```bash theme={"system"} npm install @anam-ai/js-sdk ``` ## Browser Requirements The Anam SDK uses WebRTC for real-time video and audio streaming. Ensure your target browsers support: * WebRTC (Chrome 56+, Firefox 44+, Safari 11+, Edge 79+) * MediaDevices API for microphone access ## HTML Setup This example requires a video element to display the persona: ```html theme={"system"} ``` > [!NOTE] > > `autoplay` starts the stream when the page loads. `playsinline` prevents > fullscreen mode on mobile devices. ## Basic Usage To keep your API key secure, exchange it for a short-lived session token on your server before initializing the client. See [Usage in Production](https://anam.ai/docs/javascript-sdk/production) for detailed session token information. ### Initialize the Client Use `createClient` with your session token: ```typescript theme={"system"} import { createClient, AnamEvent } from "@anam-ai/js-sdk"; const anamClient = createClient(sessionToken); ``` ### Start Streaming Stream the persona to your video element: ```typescript theme={"system"} try { await anamClient.streamToVideoElement("video-element-id"); } catch (error) { console.error("Failed to start stream:", error); } ``` ### Listen for Events Handle connection lifecycle events: ```typescript theme={"system"} import { AnamEvent, ConnectionClosedCode } from "@anam-ai/js-sdk"; anamClient.addListener(AnamEvent.CONNECTION_ESTABLISHED, () => { console.log("Connected to persona"); }); anamClient.addListener(AnamEvent.CONNECTION_CLOSED, (code: ConnectionClosedCode) => { console.log("Connection closed:", code); }); ``` ## Stopping a Stream To stop an active session and release resources: ```typescript theme={"system"} await anamClient.stopStreaming(); ``` ## Client Options The `createClient` function accepts an optional second parameter for configuration: ```typescript theme={"system"} import { createClient } from "@anam-ai/js-sdk"; const anamClient = createClient(sessionToken, { disableInputAudio: false, // Set true to disable microphone audioDeviceId: "device-id", // Specify audio input device voiceDetection: { endOfSpeechSensitivity: 0.5, // 0-1, higher = more sensitive }, iceServers: [], // Custom ICE/TURN servers for WebRTC rtcConfiguration: { // Full RTCConfiguration passthrough (advanced) iceTransportPolicy: "relay", // Force TURN-relay-only on UDP-blocked networks }, metrics: { disableClientMetrics: false, // Disable telemetry for air-gapped environments }, }); ``` **Forcing TURN relay** — `rtcConfiguration` is passed directly to the browser's `RTCPeerConnection`, so you can set any native WebRTC option. The most common is `iceTransportPolicy: "relay"`, which routes all media through Anam's TURN servers on networks that block direct or UDP connectivity. See [Network Configuration](https://anam.ai/docs/security/network). ICE-server precedence (highest to lowest): the top-level `iceServers` option, then `rtcConfiguration.iceServers`, then Anam's server-provided defaults. The resolved `iceServers` always takes the `iceServers` field, so combining both options is safe. ## Troubleshooting | Issue | Solution | | - | - | | Video not appearing | Verify the video element ID matches and has `autoplay playsinline` attributes | | No microphone access | Ensure HTTPS (required for getUserMedia) and user has granted permission | | Connection fails | Check browser console for errors; verify session token is valid and not expired | ## Next Steps > [card] [Talk Commands](https://anam.ai/docs/javascript-sdk/reference/talk-commands) > > Control persona output using talk commands > [card] [Audio Control](https://anam.ai/docs/javascript-sdk/reference/audio-control) > > Control audio input and streaming behavior > [card] [User Messages](https://anam.ai/docs/javascript-sdk/reference/user-messages) > > Send messages programmatically on behalf of the user > [card] [Events](https://anam.ai/docs/javascript-sdk/reference/event-types) > > Handle connection and conversation events # JavaScript SDK Event Types Source: https://anam.ai/docs/javascript-sdk/reference/event-types Understand the events emitted during Anam conversations and use their payloads to update your interface, analytics, tools, and session state. Anam personas communicate through an event system that lets you respond to connection changes, conversation updates, and user interactions. Understanding these events helps you build responsive, interactive applications. ## How Events Work The Anam SDK uses an event-driven architecture where your application listens for specific events and reacts accordingly. This allows you to: * Update your UI based on connection status * Track conversation history in real-time * Handle user interruptions * Monitor stream quality and performance ### Register Handlers Before Starting Register event listeners and tool call handlers before starting the session with `stream()` or `streamToVideoElement()`. The SDK emits startup events while the session is being created, so handlers added afterward can miss events that already fired. > [!WARNING] > > Handlers must be attached before the session starts if you need to handle startup events or client tool calls reliably. ```javascript theme={"system"} import { createClient, AnamEvent } from "@anam-ai/js-sdk"; const anamClient = createClient(sessionToken); anamClient.addListener(AnamEvent.SESSION_READY, (sessionId) => { console.log("Session ready:", sessionId); }); anamClient.registerToolCallHandler("navigate_to_page", { onStart: async (payload) => { window.location.href = `/${payload.arguments.page}`; }, }); await anamClient.streamToVideoElement("persona-video"); ``` ## Available Events ### Connection Events These events track the connection lifecycle between your client and Anam's streaming infrastructure: #### `CONNECTION_ESTABLISHED` Fired when the WebRTC connection is successfully established. ```javascript theme={"system"} import { AnamEvent } from "@anam-ai/js-sdk"; anamClient.addListener(AnamEvent.CONNECTION_ESTABLISHED, () => { console.log("Connected to Anam streaming service"); updateConnectionStatus("connected"); hideLoadingSpinner(); }); ``` #### `SESSION_READY` Fired after the session initializes and all backend components are ready. Use this to remove loading indicators. ```javascript theme={"system"} anamClient.addListener(AnamEvent.SESSION_READY, (sessionId) => { console.log("Session ready:", sessionId); setIsLoading(false); }); ``` #### `CONNECTION_CLOSED` Fired when the connection is terminated. Receives a reason code and optional details. ```javascript theme={"system"} anamClient.addListener(AnamEvent.CONNECTION_CLOSED, (reason, details) => { console.log("Connection closed:", reason, details); updateConnectionStatus("disconnected"); showReconnectButton(); }); ``` ### Video Events #### `VIDEO_STREAM_STARTED` Fired when the video MediaStream becomes available. ```javascript theme={"system"} anamClient.addListener(AnamEvent.VIDEO_STREAM_STARTED, (videoStream) => { console.log("Video stream available"); // You can attach this to a video element if using manual stream handling }); ``` #### `VIDEO_PLAY_STARTED` Fired when the first video frames begin playing. Ideal for removing loading indicators. ```javascript theme={"system"} anamClient.addListener(AnamEvent.VIDEO_PLAY_STARTED, () => { console.log("Video stream started"); hideVideoLoadingState(); showPersonaInterface(); }); ``` ### Audio Events #### `AUDIO_STREAM_STARTED` Fired when the audio MediaStream from the persona becomes available. ```javascript theme={"system"} anamClient.addListener(AnamEvent.AUDIO_STREAM_STARTED, (audioStream) => { console.log("Audio stream available"); }); ``` #### `INPUT_AUDIO_STREAM_STARTED` Fired when microphone input is successfully initialized. ```javascript theme={"system"} anamClient.addListener(AnamEvent.INPUT_AUDIO_STREAM_STARTED, (stream) => { console.log("Microphone access granted"); showMicrophoneIndicator(); updateAudioInputStatus("active"); }); ``` #### `INPUT_AUDIO_DEVICE_CHANGED` Fired when the input audio device changes. ```javascript theme={"system"} anamClient.addListener(AnamEvent.INPUT_AUDIO_DEVICE_CHANGED, (deviceId) => { console.log("Audio input device changed to:", deviceId); }); ``` ### Microphone Permission Events These events track the state of microphone permission requests: #### `MIC_PERMISSION_PENDING` Fired when the browser is requesting microphone permission from the user. ```javascript theme={"system"} anamClient.addListener(AnamEvent.MIC_PERMISSION_PENDING, () => { showMicPermissionPrompt(); }); ``` #### `MIC_PERMISSION_GRANTED` Fired when the user grants microphone permission. ```javascript theme={"system"} anamClient.addListener(AnamEvent.MIC_PERMISSION_GRANTED, () => { hideMicPermissionPrompt(); }); ``` #### `MIC_PERMISSION_DENIED` Fired when the user denies microphone permission. ```javascript theme={"system"} anamClient.addListener(AnamEvent.MIC_PERMISSION_DENIED, (error) => { console.error("Microphone permission denied:", error); showMicPermissionError(); }); ``` ### Conversation Events These events help you track and respond to conversation flow: #### `MESSAGE_HISTORY_UPDATED` Provides the complete conversation history each time a participant finishes speaking. ```javascript theme={"system"} anamClient.addListener(AnamEvent.MESSAGE_HISTORY_UPDATED, (messages) => { console.log("Conversation updated:", messages); updateChatHistory(messages); // Example message structure: // [ // { role: "user", content: "Hello" }, // { role: "persona", content: "Hi there! How can I help?" } // ] }); ``` #### `MESSAGE_STREAM_EVENT_RECEIVED` Provides real-time transcription updates as speech occurs. ```javascript theme={"system"} anamClient.addListener(AnamEvent.MESSAGE_STREAM_EVENT_RECEIVED, (event) => { if (event.role === "persona") { // Persona is speaking - show real-time transcription updatePersonaTranscript(event.content); } else if (event.role === "user") { // User finished speaking - complete transcription updateUserTranscript(event.content); } }); ``` With `@anam-ai/js-sdk` version 4.25.0 or later, persona messages can include an `utterances` array and streamed persona chunks can include an `utteranceId`. See [Multi-utterance Persona Turns](/docs/javascript-sdk/reference/events#multi-utterance-persona-turns) for the payload shape, compatibility details, and a rendering example. ### Reasoning Events These events provide insight into the persona's reasoning process (when using models that support it): #### `REASONING_HISTORY_UPDATED` Provides the complete reasoning history. ```javascript theme={"system"} anamClient.addListener(AnamEvent.REASONING_HISTORY_UPDATED, (thoughts) => { console.log("Reasoning updated:", thoughts); }); ``` #### `REASONING_STREAM_EVENT_RECEIVED` Provides real-time reasoning updates as the persona thinks. ```javascript theme={"system"} anamClient.addListener(AnamEvent.REASONING_STREAM_EVENT_RECEIVED, (event) => { updateReasoningDisplay(event); }); ``` ### Talk Stream Events #### `TALK_STREAM_INTERRUPTED` Fired when a user interrupts a `TalkMessageStream` by speaking. Receives the correlation ID directly. ```javascript theme={"system"} anamClient.addListener(AnamEvent.TALK_STREAM_INTERRUPTED, (correlationId) => { console.log("Talk stream interrupted:", correlationId); handleStreamInterruption(correlationId); stopCurrentGeneration(); }); ``` #### `MESSAGE_DELIVERY_FAILED` Available in JavaScript SDK v4.29.1 or later. Receives a `MessageDeliveryFailure` payload with `messageType: "talkStream"` and the stream's `correlationId`. The affected stream stops accepting chunks and enters `TalkMessageStreamState.DELIVERY_FAILED`. Delivery confirmation depends on engine support. The SDK does not resend chunks, and retrying can repeat speech that already arrived. See [Handling Delivery Failures](/docs/javascript-sdk/reference/talk-commands#handling-delivery-failures) for a listener example and recovery guidance. ### Server Events #### `SERVER_WARNING` Fired when the server sends a warning message. ```javascript theme={"system"} anamClient.addListener(AnamEvent.SERVER_WARNING, (message) => { console.warn("Server warning:", message); }); ``` ### Tool Call Events All tool calls emit lifecycle events — `started`, `completed`, and `failed` — that you can use to trigger client-side actions or for monitoring. For client tools, use `registerToolCallHandler` to define per-tool handlers before the session starts. It automatically emits `completed` or `failed` events when the handler completes. #### Using `registerToolCallHandler` (Recommended) Register handlers for specific tools by name before the session starts. For client tools, the return value from `onStart` is sent back to the LLM as the tool result: ```javascript theme={"system"} // Register a handler — returns a cancel function const cancelNavHandler = anamClient.registerToolCallHandler("navigate_to_page", { onStart: async (payload) => { const { page, section } = payload.arguments; window.location.href = `/${page}`; return `Navigated to ${page}`; }, onComplete: async (payload) => { console.log(`Completed in ${payload.executionTime}ms`); }, onFail: async (payload) => { console.error(`Failed: ${payload.errorMessage}`); }, }); // Clean up when done cancelNavHandler(); ``` #### `TOOL_CALL_STARTED` Fired when any tool call begins. Receives a `ToolCallStartedPayload` with the tool name, type, and arguments. ```javascript theme={"system"} anamClient.addListener(AnamEvent.TOOL_CALL_STARTED, (event) => { const { toolName, arguments: args } = event; console.log(`Tool started: ${toolName}`, args); }); ``` #### `TOOL_CALL_COMPLETED` Fired when a tool call completes successfully. Includes the result and execution time. ```javascript theme={"system"} anamClient.addListener(AnamEvent.TOOL_CALL_COMPLETED, (event) => { const { toolName, result, executionTime } = event; console.log(`Tool ${toolName} completed in ${executionTime}ms:`, result); }); ``` #### `TOOL_CALL_FAILED` Fired when a tool call fails. Includes the error message and execution time. ```javascript theme={"system"} anamClient.addListener(AnamEvent.TOOL_CALL_FAILED, (event) => { const { toolName, errorMessage, executionTime } = event; console.error(`Tool ${toolName} failed after ${executionTime}ms: ${errorMessage}`); }); ``` #### `CLIENT_TOOL_EVENT_RECEIVED` (Deprecated) A legacy event for client tools. Replaced by `TOOL_CALL_STARTED` and `registerToolCallHandler` as of SDK v4.9.0. ```javascript theme={"system"} // Deprecated — use registerToolCallHandler instead anamClient.addListener(AnamEvent.CLIENT_TOOL_EVENT_RECEIVED, (event) => { const { eventName, eventData } = event; switch (eventName) { case "navigate_to_page": window.location.href = `/${eventData.page}`; break; case "open_modal": openModal(eventData.modalType, eventData.data); break; } }); ``` > [!NOTE] > > Client tools enable voice-driven or chat-driven UI control. For a complete guide on creating and configuring client tools, see the [Client Tools Guide](https://anam.ai/docs/personas/tools/client-tools). ## Removing Event Listeners Remove listeners when components unmount or sessions end to prevent memory leaks: ```javascript theme={"system"} const handleMessage = (messages) => { updateChatHistory(messages); }; // Add listener anamClient.addListener(AnamEvent.MESSAGE_HISTORY_UPDATED, handleMessage); // Remove listener when done anamClient.removeListener(AnamEvent.MESSAGE_HISTORY_UPDATED, handleMessage); ``` ## Learn More > [card] [Events API Reference](https://anam.ai/docs/javascript-sdk/reference/events) > > Complete event reference with callback signatures > [card] [Client Tools Guide](https://anam.ai/docs/personas/tools/client-tools) > > Guide for creating and handling client tools # Listen for JavaScript SDK Events Source: https://anam.ai/docs/javascript-sdk/reference/events Subscribe to Anam session, conversation, tool, and media events with the JavaScript SDK and handle their typed payloads. ## Adding Event Listeners Register event listeners after creating the Anam client and before starting the session with `stream()` or `streamToVideoElement()`. > [!WARNING] > > Event handlers must be registered before the session starts. Startup events such as microphone permission, connection, stream, and `SESSION_READY` can fire while `stream()` or `streamToVideoElement()` is running, and late listeners will not receive events that already fired. This also applies to `registerToolCallHandler`. Use the `addListener` method before the start call: ```typescript theme={"system"} import { createClient, AnamEvent } from "@anam-ai/js-sdk"; const anamClient = createClient(sessionToken); anamClient.addListener(AnamEvent.CONNECTION_ESTABLISHED, () => { console.log("Connection Established"); }); anamClient.addListener(AnamEvent.MESSAGE_HISTORY_UPDATED, (messages) => { console.log("Updated Messages:", messages); }); await anamClient.streamToVideoElement("video-element-id"); ``` ## Available Events | Event Name | Description | Callback Parameters | | - | - | - | | `CONNECTION_ESTABLISHED` | Fired when the WebRTC connection is established | None | | `CONNECTION_CLOSED` | Fired when the connection is terminated | `reason: ConnectionClosedCode`, `details?: string` | | `SESSION_READY` | Fired after the session initializes and backend components are ready | `sessionId: string` | | `VIDEO_STREAM_STARTED` | Fired when the video stream becomes available | `videoStream: MediaStream` | | `VIDEO_PLAY_STARTED` | Fired when the first video frames start playing | None | | `AUDIO_STREAM_STARTED` | Fired when the audio stream becomes available | `audioStream: MediaStream` | | `INPUT_AUDIO_STREAM_STARTED` | Fired when microphone input is initialized | `audioStream: MediaStream` | | `USER_SPEECH_STARTED` | The user started speaking. No transcript yet — useful for showing a listening indicator. | `correlationId: string` | | `USER_SPEECH_ENDED` | The user stopped speaking. A transcript event may follow in `MESSAGE_STREAM_EVENT_RECEIVED`. | `correlationId: string` | | `MESSAGE_HISTORY_UPDATED` | Fired when a participant finishes speaking with full history | `messages: Message[]` | | `MESSAGE_STREAM_EVENT_RECEIVED` | Fired with real-time transcription updates | `event: MessageStreamEvent` | | `DIRECTOR_NOTE_CUE_APPLIED` | Fired when a Director Notes cue is applied to the avatar | `event: DirectorNoteCueAppliedEvent` | | `TALK_STREAM_INTERRUPTED` | Fired when a user interrupts a `TalkMessageStream` | `correlationId: string` | | `MESSAGE_DELIVERY_FAILED` | A talk-stream chunk could not be sent or its delivery could not be confirmed (v4.29.1+) | `failure: MessageDeliveryFailure` | | `TOOL_CALL_STARTED` | Fired when any tool call begins | `event: ToolCallStartedPayload` | | `TOOL_CALL_COMPLETED` | Fired when a tool call completes successfully | `event: ToolCallCompletedPayload` | | `TOOL_CALL_FAILED` | Fired when a tool call fails | `event: ToolCallFailedPayload` | | `CLIENT_TOOL_EVENT_RECEIVED` | **Deprecated** - Use `TOOL_CALL_STARTED` instead | `event: ClientToolEvent` | | `SERVER_WARNING` | Fired when the server sends a warning message | `message: string` | | `MIC_PERMISSION_PENDING` | Fired when microphone permission is being requested | None | | `MIC_PERMISSION_GRANTED` | Fired when microphone permission is granted | None | | `MIC_PERMISSION_DENIED` | Fired when microphone permission is denied | `error: string` | | `INPUT_AUDIO_DEVICE_CHANGED` | Fired when the input audio device changes | `deviceId: string` | | `REASONING_HISTORY_UPDATED` | Fired when reasoning/thought history is updated | `messages: ReasoningMessage[]` | | `REASONING_STREAM_EVENT_RECEIVED` | Fired with real-time reasoning updates | `event: ReasoningStreamEvent` | ## Type Definitions ### Message ```typescript theme={"system"} interface MessageUtterance { id: string; content: string; } interface Message { id: string; content: string; role: MessageRole; // 'user' | 'persona' interrupted?: boolean; utterances?: MessageUtterance[]; // Persona messages only } ``` ### MessageStreamEvent ```typescript theme={"system"} interface MessageStreamEvent { id: string; content: string; role: MessageRole; // 'user' | 'persona' endOfSpeech: boolean; interrupted: boolean; utteranceId?: string; // Groups persona chunks into utterances cueTag?: string; // Director Notes cue that takes effect from the start of this text chunk } ``` ### DirectorNoteCueAppliedEvent ```typescript theme={"system"} interface DirectorNoteCueAppliedEvent { cueTag: string; correlationId: string; // Correlation ID for the associated user action } ``` ### ToolCallStartedPayload ```typescript theme={"system"} interface ToolCallStartedPayload { eventUid: string; // Unique ID for this event toolCallId: string; // ID of the tool call sessionId: string; // ID of the active session toolName: string; // The tool name (e.g., "navigate_to_page") toolType: string; // Tool type (e.g., "client", "server") toolSubtype?: string; // Tool subtype for server events (e.g., "webhook", "knowledge") arguments: Record; // LLM-generated parameters timestamp: string; // ISO timestamp timestampUserAction: string; // Timestamp of the user action that triggered the tool call userActionCorrelationId: string; // Id of the user action that triggered the tool call } ``` ### ToolCallCompletedPayload ```typescript theme={"system"} interface ToolCallCompletedPayload { eventUid: string; // Unique ID for this event toolCallId: string; // ID of the tool call sessionId: string; // ID of the active session toolName: string; // The tool name toolType: string; // Tool type toolSubtype?: string; // Tool subtype result: any; // Result returned by the handler executionTime: number; // Execution time in milliseconds timestamp: string; // ISO timestamp documentsAccessed?: string[]; // List of file names accessed during the tool call, if applicable (Knowledge tools only) timestampUserAction: string; // Timestamp of the user action that triggered the tool call userActionCorrelationId: string; // Id of the user action that triggered the tool call } ``` ### ToolCallFailedPayload ```typescript theme={"system"} interface ToolCallFailedPayload { eventUid: string; // Unique ID for this event toolCallId: string; // ID of the tool call sessionId: string; // ID of the active session toolName: string; // The tool name toolType: string; // Tool type toolSubtype?: string; // Tool subtype errorMessage: string; // Error description executionTime: number; // Execution time in milliseconds timestamp: string; // ISO timestamp timestampUserAction: string; // Timestamp of the user action that triggered the tool call userActionCorrelationId: string; // Id of the user action that triggered the tool call } ``` ### ToolCallHandler ```typescript theme={"system"} interface ToolCallHandler { onStart?: (payload: ToolCallStartedPayload) => Promise; onFail?: (payload: ToolCallFailedPayload) => Promise; onComplete?: (payload: ToolCallCompletedPayload) => Promise; } ``` ### ClientToolEvent (Deprecated) > [!WARNING] > > `ClientToolEvent` is deprecated as of SDK v4.9.0. Use `ToolCallStartedPayload` with `registerToolCallHandler` or `TOOL_CALL_STARTED` events instead. ```typescript theme={"system"} interface ClientToolEvent { eventUid: string; // Unique ID for this event sessionId: string; // Session ID eventName: string; // The tool name (e.g., "navigate_to_page") eventData: Record; // LLM-generated parameters timestamp: string; // ISO timestamp when event was created timestampUserAction: string; // ISO timestamp of user action that triggered this userActionCorrelationId: string; // Correlation ID for tracking } ``` ### ConnectionClosedCode ```typescript theme={"system"} enum ConnectionClosedCode { NORMAL = 'CONNECTION_CLOSED_CODE_NORMAL', MICROPHONE_PERMISSION_DENIED = 'CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED', SIGNALLING_CLIENT_CONNECTION_FAILURE = 'CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE', WEBRTC_FAILURE = 'CONNECTION_CLOSED_CODE_WEBRTC_FAILURE', SERVER_CLOSED_CONNECTION = 'CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION', } ``` ### ReasoningMessage ```typescript theme={"system"} interface ReasoningMessage { id: string; content: string; role: string; } ``` ### ReasoningStreamEvent ```typescript theme={"system"} interface ReasoningStreamEvent { id: string; content: string; endOfThought: boolean; role: string; } ``` ## Example Usage ### Loading States Use connection events to manage loading states: ```typescript theme={"system"} anamClient.addListener(AnamEvent.CONNECTION_ESTABLISHED, () => { setIsConnecting(false); }); anamClient.addListener(AnamEvent.SESSION_READY, (sessionId: string) => { console.log("Session ready:", sessionId); setIsLoading(false); }); ``` ### Connection Closed Handling Handle connection closures with reason codes: ```typescript theme={"system"} import { AnamEvent, ConnectionClosedCode } from "@anam-ai/js-sdk"; anamClient.addListener( AnamEvent.CONNECTION_CLOSED, (reason: ConnectionClosedCode, details?: string) => { switch (reason) { case ConnectionClosedCode.NORMAL: console.log("Connection closed normally"); break; case ConnectionClosedCode.MICROPHONE_PERMISSION_DENIED: showError("Microphone access is required"); break; case ConnectionClosedCode.WEBRTC_FAILURE: showError("Connection failed. Please check your network."); break; default: console.log("Connection closed:", reason, details); } } ); ``` ### Microphone Permission Flow Track microphone permission state: ```typescript theme={"system"} anamClient.addListener(AnamEvent.MIC_PERMISSION_PENDING, () => { showPermissionPrompt("Please allow microphone access"); }); anamClient.addListener(AnamEvent.MIC_PERMISSION_GRANTED, () => { hidePermissionPrompt(); showMicrophoneIndicator(); }); anamClient.addListener(AnamEvent.MIC_PERMISSION_DENIED, (error: string) => { showError(`Microphone access denied: ${error}`); }); ``` ### Speech detection Know when the user starts and stops speaking, before any transcript is available: ```typescript theme={"system"} anamClient.addListener(AnamEvent.USER_SPEECH_STARTED, (correlationId: string) => { setIsUserSpeaking(true); showListeningIndicator(); }); anamClient.addListener(AnamEvent.USER_SPEECH_ENDED, (correlationId: string) => { setIsUserSpeaking(false); showProcessingIndicator(); }); ``` These fire as soon as the server-side VAD picks up voice activity, before the full transcript arrives via `MESSAGE_STREAM_EVENT_RECEIVED`. The `correlationId` ties the speech start/end pair to the eventual transcript. If `USER_SPEECH_ENDED` doesn't arrive within \~10 seconds of a `USER_SPEECH_STARTED`, treat it as a dropped detection and reset your UI. This can happen if the connection drops mid-speech. ### Message History Track conversation history: ```typescript theme={"system"} import { Message } from "@anam-ai/js-sdk"; anamClient.addListener( AnamEvent.MESSAGE_HISTORY_UPDATED, (messages: Message[]) => { setConversationHistory(messages); } ); ``` ### Multi-utterance Persona Turns In a tool-driven response, a persona can speak before a tool call and continue after the tool returns. With `@anam-ai/js-sdk` version 4.25.0 or later, one completed persona `Message` can contain an ordered `utterances` array for those spoken parts: ```typescript theme={"system"} import { AnamEvent, Message, MessageRole } from "@anam-ai/js-sdk"; anamClient.addListener( AnamEvent.MESSAGE_HISTORY_UPDATED, (messages: Message[]) => { const message = messages[messages.length - 1]; if (!message || message.role !== MessageRole.PERSONA) return; const bubbles = message.utterances ?? [ { id: message.id, content: message.content }, ]; setPersonaBubbles(bubbles); } ); ``` `message.content` remains the complete concatenated turn. `message.utterances` is optional and appears only on persona messages when the engine provides utterance IDs. Use the `content` fallback shown above for user messages, older SDK behavior, and models that do not produce utterance boundaries. For live captions, each persona `MESSAGE_STREAM_EVENT_RECEIVED` payload includes an optional `utteranceId`. Consecutive chunks with the same ID belong to the same utterance; append their `content` in arrival order. > [!NOTE] > > Multi-utterance turns require an LLM that supports interleaved tool calling: text before and after a tool call in one turn. Anam-provided LLMs hosted by OpenAI or Azure support this behavior; LLMs hosted by Groq do not. ### Real-time Transcription Monitor speech in real-time: ```typescript theme={"system"} import { MessageStreamEvent, MessageRole } from "@anam-ai/js-sdk"; anamClient.addListener( AnamEvent.MESSAGE_STREAM_EVENT_RECEIVED, (event: MessageStreamEvent) => { if (event.role === MessageRole.PERSONA) { updatePersonaSpeech(event.content); } else { updateUserSpeech(event.content); } if (event.endOfSpeech) { finalizeSpeech(event.id); } } ); ``` ### Director Notes Cues Listen for `DIRECTOR_NOTE_CUE_APPLIED` when your application needs to react after Anam confirms that a [Director Notes](https://anam.ai/docs/personas/director-notes) cue was applied to the avatar. > [!NOTE] > > Director Notes cue events require `@anam-ai/js-sdk` version 4.20.0 or later. ```typescript theme={"system"} import { AnamEvent, DirectorNoteCueAppliedEvent } from "@anam-ai/js-sdk"; anamClient.addListener( AnamEvent.DIRECTOR_NOTE_CUE_APPLIED, ({ cueTag, correlationId }: DirectorNoteCueAppliedEvent) => { showCueIndicator(cueTag); console.log(`Applied cue ${cueTag}`, { correlationId }); } ); ``` Use `correlationId` to associate the cue with other events from the same user action. Each `MESSAGE_STREAM_EVENT_RECEIVED` payload also includes an optional `cueTag` when a Director Notes cue takes effect from the start of that text chunk. If the field is absent, no new cue takes effect at that chunk boundary. Cue boundaries can split persona speech into multiple streamed text chunks, so append `event.content` in arrival order instead of assuming one event per response. `MESSAGE_HISTORY_UPDATED` is unchanged. Its `Message` items do not include cue metadata. ### Tool Call Handlers (Recommended) Use `registerToolCallHandler` to register handlers for specific tools before starting the session. This automatically emits `completed` or `failed` events when the handler completes. ```typescript theme={"system"} import { createClient } from "@anam-ai/js-sdk"; const anamClient = createClient(sessionToken); const cancelNavHandler = anamClient.registerToolCallHandler("navigate_to_page", { onStart: async (payload) => { const { page, section } = payload.arguments; router.push(`/${page}${section ? `#${section}` : ""}`); }, onComplete: async (payload) => { console.log(`tool call completed ${payload.toolName}`); }, onFail: async (payload) => { console.log(`tool call failed ${payload.toolName}`); }, }); // you can also register partial handlers const cancelModalHandler = anamClient.registerToolCallHandler("open_modal", { onStart: async (payload) => { openModal(payload.arguments.modalType, payload.arguments.data); return `Opened ${payload.arguments.modalType} modal`; }, }); // start the session after handlers are attached await anamClient.streamToVideoElement("video-element-id"); // unsubscribe when no longer needed cancelNavHandler(); cancelModalHandler(); ``` > [!TIP] > > `registerToolCallHandler` is the recommended approach for client tools. Register tool call handlers before `stream()` or `streamToVideoElement()` so the persona cannot invoke a tool before your handler is attached. ### Tool Call Events Listen for tool call lifecycle events across all tool types — client, webhook, and knowledge tools all emit these events, so you can use them for logging, analytics, or monitoring: ```typescript theme={"system"} import { AnamEvent, ToolCallStartedPayload, ToolCallCompletedPayload, ToolCallFailedPayload } from "@anam-ai/js-sdk"; anamClient.addListener( AnamEvent.TOOL_CALL_STARTED, (event: ToolCallStartedPayload) => { console.log(`Tool started: ${event.toolName} (${event.toolType})`, event.arguments); } ); anamClient.addListener( AnamEvent.TOOL_CALL_COMPLETED, (event: ToolCallCompletedPayload) => { console.log(`Tool completed: ${event.toolName} in ${event.executionTime}ms`); } ); anamClient.addListener( AnamEvent.TOOL_CALL_FAILED, (event: ToolCallFailedPayload) => { console.error(`Tool failed: ${event.toolName} - ${event.errorMessage}`); } ); ``` Use `toolType` and `toolSubtype` to distinguish between tool types in your listeners: ```typescript theme={"system"} anamClient.addListener(AnamEvent.TOOL_CALL_COMPLETED, (event) => { switch (event.toolType) { case "client": console.log(`Client action completed: ${event.toolName}`); break; case "server": if (event.toolSubtype === "webhook") { console.log(`Webhook responded: ${event.toolName} in ${event.executionTime}ms`); } else if (event.toolSubtype === "knowledge") { console.log(`Knowledge search completed: ${event.toolName}`); } break; } }); ``` > [!TIP] > > These events fire for all tool types. For guides on configuring each type, see [Client Tools](https://anam.ai/docs/personas/tools/client-tools), [Webhook Tools](https://anam.ai/docs/personas/tools/webhook-tools), and [Knowledge Tools](https://anam.ai/docs/personas/knowledge/tools). ### Server Warnings Handle server-side warnings: ```typescript theme={"system"} anamClient.addListener(AnamEvent.SERVER_WARNING, (message: string) => { console.warn("Server warning:", message); showWarningToast(message); }); ``` ### Reasoning Events (Extended Thinking) Track AI reasoning when using models with extended thinking: ```typescript theme={"system"} import { ReasoningMessage, ReasoningStreamEvent } from "@anam-ai/js-sdk"; // Get complete reasoning history anamClient.addListener( AnamEvent.REASONING_HISTORY_UPDATED, (messages: ReasoningMessage[]) => { setReasoningHistory(messages); } ); // Stream reasoning in real-time anamClient.addListener( AnamEvent.REASONING_STREAM_EVENT_RECEIVED, (event: ReasoningStreamEvent) => { updateReasoningDisplay(event.content); if (event.endOfThought) { finalizeThought(event.id); } } ); ``` ## Removing Event Listeners Remove listeners to prevent memory leaks, especially in single-page applications: ```typescript theme={"system"} const handleMessages = (messages: Message[]) => { setConversationHistory(messages); }; // Add listener anamClient.addListener(AnamEvent.MESSAGE_HISTORY_UPDATED, handleMessages); // Remove listener when done anamClient.removeListener(AnamEvent.MESSAGE_HISTORY_UPDATED, handleMessages); ``` ### React Example ```typescript theme={"system"} useEffect(() => { const cancelNav = client.registerToolCallHandler("navigate_to_page", { onStart: async (payload) => { router.push(`/${payload.arguments.page}`); }, }); const cancelModal = client.registerToolCallHandler("open_modal", { onStart: async (payload) => { openModal(payload.arguments.modalType); return "Modal opened"; }, }); return () => { cancelNav(); cancelModal(); }; }, [client]); ``` ## Learn More > [card] [Client Tools Guide](https://anam.ai/docs/personas/tools/client-tools) > > Guide with examples for navigation, modals, UI updates, and more > [card] [Tools Overview](https://anam.ai/docs/personas/tools/overview) > > Learn about all tool types: client, webhook, and knowledge tools # Interrupt an Anam Persona Source: https://anam.ai/docs/javascript-sdk/reference/interrupt-command Use the JavaScript SDK's interruptPersona method to stop a speaking persona, handle session errors, and continue with new user input or context. ## Overview The `interruptPersona()` method allows you to programmatically stop the persona while it's speaking. > [!NOTE] > > Requires SDK version 3.4.0 or higher ## Method Signature ```typescript theme={"system"} interruptPersona(): void ``` ## Basic Usage Stop the persona from speaking immediately: ```javascript theme={"system"} anamClient.interruptPersona(); ``` The persona will stop its current speech and be ready to receive new input. ## Prerequisites Before calling `interruptPersona()`, you must: 1. Have an active streaming session (call `stream()` or `streamToVideoElement()` first) 2. Have successfully connected to the Anam Engine ## Error Handling The method throws errors in the following cases: ```javascript theme={"system"} try { anamClient.interruptPersona(); } catch (error) { // Handle the error console.error(error.message); } ``` | Error Message | Cause | | - | - | | `Failed to send interrupt command: not currently streaming` | Called before starting a stream or after stopping | | `Failed to send interrupt command: no active session` | No session ID available | ## Behavior The `interruptPersona()` method: * Immediately stops any ongoing speech from the persona * The persona remains ready to receive new input after being interrupted * Has no effect if the persona is not currently speaking (no error thrown in this case) ## Use Cases ### User-Initiated Interruption Allow users to interrupt the persona when they want to ask a different question or change topics: ```javascript theme={"system"} document.getElementById("interrupt-btn").addEventListener("click", () => { try { anamClient.interruptPersona(); } catch (error) { console.error("Could not interrupt:", error.message); } }); ``` > [!NOTE] > > Voice activity detection automatically interrupts the persona when the user starts speaking. Use this method for programmatic interruption or when you need immediate response to UI actions. ### Topic Change Handling Stop the persona when users navigate to a different section or topic: ```javascript theme={"system"} function handleNavigationChange(newSection) { // Stop any ongoing explanation try { anamClient.interruptPersona(); } catch (error) { // May fail if not streaming - that's fine for navigation } // Add context about the new topic without triggering a response anamClient.addContext(`User navigated to ${newSection}`); } ``` ## Next Steps > [card] [Events](https://anam.ai/docs/javascript-sdk/reference/events) > > Learn about speech events to track when the persona is speaking > [card] [User Messages](https://anam.ai/docs/javascript-sdk/reference/user-messages) > > Send messages or add context programmatically after interrupting # Mid-Session Updates Source: https://anam.ai/docs/javascript-sdk/reference/mid-session-updates Change voice, language, and turn-taking settings while an Anam session is running, without reconnecting or rebuilding the persona. ## Overview You can update a persona's language, voice generation settings, and voice detection settings **during a live session** — no reconnect required. Updates are sent over the data channel using `sendDataMessage()`. > [!NOTE] > > Updates are best-effort. Where possible they take effect immediately; in some > cases they are applied at the start of the next user turn. ## Method Signature ```typescript theme={"system"} sendDataMessage(message: string): void ``` ## Basic Usage Send a `persona_config` message containing only the fields you want to change: ```javascript theme={"system"} anamClient.sendDataMessage( JSON.stringify({ message_type: "persona_config", data: { voiceGenerationOptions: { speed: 1.1 }, }, }), ); ``` Include any combination of `languageCode`, `voiceGenerationOptions`, and `voiceDetectionOptions` inside `data`. Only the fields you send are changed — everything else keeps its current value. ## What you can update ### Language Set `languageCode` to an [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes) code: ```javascript theme={"system"} anamClient.sendDataMessage( JSON.stringify({ message_type: "persona_config", data: { languageCode: "fr" }, }), ); ``` ### Voice generation Adjust speed, volume, emotion, and provider-specific settings. The available fields and their valid ranges depend on your voice provider and model — see [Voice Configuration](https://anam.ai/docs/personas/voices/configuration) for the full list. For ElevenLabs v3 voices, send only `stability` in `voiceGenerationOptions`, for example `{ stability: 0.5 }`. The speed and volume example below applies to Cartesia voices, not ElevenLabs v3. ```javascript theme={"system"} anamClient.sendDataMessage( JSON.stringify({ message_type: "persona_config", data: { voiceGenerationOptions: { speed: 1.2, volume: 1.5 }, }, }), ); ``` ### Voice detection Adjust turn-taking and silence handling. See [Voice Detection](https://anam.ai/docs/personas/session/voice-detection) for all options and ranges. ```javascript theme={"system"} anamClient.sendDataMessage( JSON.stringify({ message_type: "persona_config", data: { voiceDetectionOptions: { endOfSpeechSensitivity: 0.7 }, }, }), ); ``` ## Validation Updates are validated before they are applied: * At least one field must be present — an empty `data: {}` is ignored. * Unknown field names are rejected. * Values must be within the valid range for your provider and model. * Sending a voice generation field your provider or model doesn't support is rejected. If an update is rejected, **the session continues** and the invalid update is dropped. The reason is delivered as a [`SERVER_WARNING`](https://anam.ai/docs/javascript-sdk/reference/event-types) event: ```javascript theme={"system"} import { AnamEvent } from "@anam-ai/js-sdk"; anamClient.addListener(AnamEvent.SERVER_WARNING, (message) => { console.warn("Config update rejected:", message); }); ``` ## Prerequisites Before sending an update, you must: 1. Have an active streaming session (call `stream()` or `streamToVideoElement()` first). 2. Have successfully connected to the Anam Engine. ## Next Steps > [card] [Voice Configuration](https://anam.ai/docs/personas/voices/configuration) > > See every voice generation option and its valid range per provider > [card] [Voice Detection](https://anam.ai/docs/personas/session/voice-detection) > > See every turn-taking and silence option > [card] [Event Types](https://anam.ai/docs/javascript-sdk/reference/event-types) > > Listen for `SERVER_WARNING` and other session events > [card] [User Messages](https://anam.ai/docs/javascript-sdk/reference/user-messages) > > Send messages and context programmatically # JavaScript SDK Talk Commands Source: https://anam.ai/docs/javascript-sdk/reference/talk-commands Send text for an Anam persona to speak, stream ordered utterances, and control how commands interact with current output. ## Basic Usage During a persona session, you can force a response from the persona using the `talk` method. This is useful when the user interacts with a UI element or when you use your own LLM instead of Anam's built-in models. > [!NOTE] > > Both `talk()` and `createTalkMessageStream()` require an active streaming session. Call `stream()` or `streamToVideoElement()` first. ```typescript theme={"system"} await anamClient.talk("Hello, how are you?"); ``` This sends the text to the persona, which then speaks it aloud. > [!NOTE] > > To learn more about using the `talk` method with your own LLM, see the [Custom LLMs](https://anam.ai/docs/personas/llms/custom-llms) guide. ## Streaming Talk Input For lower latency, stream messages to the persona in chunks. This works well when streaming output from a custom LLM. ```typescript theme={"system"} const talkMessageStream = anamClient.createTalkMessageStream(); const chunks = ["He", "l", "lo", ", how are you?"]; for (const chunk of chunks) { if (talkMessageStream.isActive()) { await talkMessageStream.streamMessageChunk( chunk, chunk === chunks[chunks.length - 1] // endOfSpeech: true on last chunk ); } } ``` > [!NOTE] > > Each `TalkMessageStream` represents one conversation turn. Once the turn ends, create a new stream for the next turn. ### Available Methods The `TalkMessageStream` object provides these methods: | Method | Description | | - | - | | `streamMessageChunk(content, endOfSpeech, utteranceId?)` | Send a text chunk. Set `endOfSpeech: true` on the final chunk. Optionally start a new utterance with `utteranceId`. | | `endMessage()` | End the stream without sending more content and preserve its latest utterance ID. Alternative to `endOfSpeech: true`. | | `isActive()` | Returns `true` if the stream can still accept chunks. | | `getState()` | Returns a `TalkMessageStreamState` value: `UNSTARTED`, `STREAMING`, `INTERRUPTED`, `ENDED`, or `DELIVERY_FAILED`. | | `getCorrelationId()` | Returns the correlation ID for this stream. | ### Streaming Multiple Utterances With `@anam-ai/js-sdk` version 4.26.0 or later, you can divide one `TalkMessageStream` into ordered utterances. A new utterance waits for the previous one to finish playing while both remain part of the same conversation turn. This lets the persona speak before a tool call and continue when the result is ready. > [!NOTE] > > Multi-utterance talk streams require a [Cara 4 avatar](/docs/introduction/models#cara-4). With Cara 3, the persona still speaks the text, but Anam treats the stream as one utterance and does not return your utterance IDs. The SDK does not throw an error or warning. Pass an `utteranceId` as the third argument on the first chunk of each utterance. The ID must be a lowercase UUID v4; `crypto.randomUUID()` returns the required format. The method throws before sending the chunk if the ID is invalid. Omit the ID from later chunks in the same utterance. ```typescript theme={"system"} const talkMessageStream = anamClient.createTalkMessageStream(); const beforeToolUtteranceId = crypto.randomUUID(); // The first utterance can play while the tool runs. await talkMessageStream.streamMessageChunk( "Let me check ", false, beforeToolUtteranceId ); await talkMessageStream.streamMessageChunk("that for you.", false); const toolResultText = await runToolCall(); const toolResultUtteranceId = crypto.randomUUID(); // A new ID starts the next utterance after the first one. await talkMessageStream.streamMessageChunk( toolResultText, true, toolResultUtteranceId ); ``` The IDs are returned in persona `MESSAGE_STREAM_EVENT_RECEIVED` events as `utteranceId`. Use them to match streamed captions to the utterances you sent. See [Listen for JavaScript SDK Events](/docs/javascript-sdk/reference/events) for the event payload. > [!WARNING] > > Send the next text chunk within 15 seconds. After 15 seconds without a chunk that contains text, the server closes the stream and rejects later chunks with the same correlation ID. Empty chunks do not reset the timeout. For a longer tool call, end the first stream and create a new one for the result. ### Ending a Stream End a conversation turn in one of two ways: **Option 1: Set `endOfSpeech` on the last chunk** ```typescript theme={"system"} await talkMessageStream.streamMessageChunk("final text", true); ``` **Option 2: Call `endMessage()` separately** ```typescript theme={"system"} await talkMessageStream.streamMessageChunk("final text", false); await talkMessageStream.endMessage(); ``` ### Handling Interruptions When a user speaks during a stream, the SDK emits `AnamEvent.TALK_STREAM_INTERRUPTED` and closes the stream: ```typescript theme={"system"} import { AnamEvent } from "@anam-ai/js-sdk"; anamClient.addListener(AnamEvent.TALK_STREAM_INTERRUPTED, (correlationId) => { console.log("Stream interrupted:", correlationId); // Handle the interruption - e.g., stop your LLM generation }); ``` ### Checking Stream State Check whether a stream can still accept chunks: ```typescript theme={"system"} if (talkMessageStream.isActive()) { await talkMessageStream.streamMessageChunk(chunk, false); } // Or check the specific state const state = talkMessageStream.getState(); // Returns a TalkMessageStreamState enum value, including DELIVERY_FAILED. ``` ### Error Handling The `streamMessageChunk` method throws an error if the stream is not active: ```typescript theme={"system"} try { await talkMessageStream.streamMessageChunk("text", false); } catch (error) { // Stream is in INTERRUPTED, ENDED, or DELIVERY_FAILED state console.error("Cannot send chunk:", error.message); } ``` ### Handling Delivery Failures With `@anam-ai/js-sdk` version 4.29.1 or later, talk streams report chunks that cannot be sent or whose delivery cannot be confirmed. On engines that answer heartbeats, the SDK detects an unresponsive signalling WebSocket and reconnects automatically. If a chunk is not confirmed within about 3 seconds, the stream moves to `TalkMessageStreamState.DELIVERY_FAILED` and the client emits `AnamEvent.MESSAGE_DELIVERY_FAILED`. Further calls to `streamMessageChunk()` reject. Register the listener once, before starting the session. Use `correlationId` to match the failure to the answer your application is generating: ```typescript theme={"system"} import { AnamEvent, type MessageDeliveryFailure } from "@anam-ai/js-sdk"; anamClient.addListener( AnamEvent.MESSAGE_DELIVERY_FAILED, (failure: MessageDeliveryFailure) => { if (failure.messageType === "talkStream") { console.warn("Talk stream delivery unconfirmed:", failure.correlationId); } } ); ``` The SDK does not resend chunks. Chunks sent before the signalling connection first opens are queued. After it has opened, sending while it reconnects or stops answering fails the stream instead of queuing chunks for replay. Resolving `streamMessageChunk()` or `endMessage()` does not confirm delivery; a failure can arrive after the final chunk, even when the stream was already `ENDED`. You can stop generating text for the failed stream, show the answer as text, or use `talk()` to send the complete answer through REST. If you choose a fallback, keep it limited to the current answer and cancel it when the user interrupts or the session ends. > [!WARNING] > > A delivery failure means receipt was not confirmed. The persona may already have spoken some of the answer, so retrying with `talk()` can repeat speech. An interruption can also be missed during a disconnection or arrive after recovery has started. Treat `CONNECTION_CLOSED` as the end of all open streams. Calling `stopStreaming()`, or closing the session because the server ended it or the media connection failed, discards pending chunks without a delivery-failure event. If signalling closes permanently on its own, pending chunks fail before `CONNECTION_CLOSED`. ## Correlation IDs Attach a correlation ID to track streams, especially useful for matching interruption events: ```typescript theme={"system"} const correlationId = "request-123"; const talkMessageStream = anamClient.createTalkMessageStream(correlationId); // Later, when handling interruptions: anamClient.addListener(AnamEvent.TALK_STREAM_INTERRUPTED, (interruptedCorrelationId) => { if (interruptedCorrelationId === correlationId) { // This specific stream was interrupted } }); ``` > [!NOTE] > > Use unique correlation IDs for each `TalkMessageStream`. The ID appears in `TALK_STREAM_INTERRUPTED` events, helping you identify which stream was interrupted. ## Next Steps > [card] [Audio Control](https://anam.ai/docs/javascript-sdk/reference/audio-control) > > Learn how to control audio input in your Anam sessions # Send User Messages with the JavaScript SDK Source: https://anam.ai/docs/javascript-sdk/reference/user-messages Send programmatic user messages into an Anam conversation and understand when to use text input instead of microphone audio. ## Overview The `sendUserMessage()` method sends text messages on behalf of the user programmatically. Use it when you want the persona to treat the text as a user turn and respond. Use `addContext()` when you want to add application state or user-action context without triggering an immediate persona response. > [!NOTE] > > `sendUserMessage()` requires SDK version 3.3.0 or higher ## Basic Usage Send a message as if the user typed or spoke it: ```javascript theme={"system"} anamClient.sendUserMessage("Hello, how can you help me today?"); ``` The persona will receive this message and respond as if the user had actually said it. ## Important Considerations > [!WARNING] > > Messages sent via `sendUserMessage()` are not automatically added to the > transcript. To maintain an accurate conversation history, you must manually > add these messages to your transcript display. The `sendUserMessage()` method differs from regular user messages in that: * It does not trigger message events that would normally update your UI * The message is sent directly to the persona without going through the normal message pipeline * You need to handle transcript updates separately in your application ## Use Cases ### Simulating User Input ```javascript theme={"system"} // Simulate a user greeting when the session starts anamClient.sendUserMessage("Hi there!"); ``` ### Providing Context to the LLM Use `addContext()` to provide contextual information that the LLM can use on the next user turn: ```javascript theme={"system"} // Add context without sending a user message anamClient.addContext("User clicked the checkout button"); ``` The persona will not respond immediately. The context is available the next time the user speaks or sends a message. > [!NOTE] > > `addContext()` requires SDK version 4.11.0 or higher and an active streaming > session. It throws an error if the client is not streaming or there is no > active session. ### Triggering Specific Flows ```javascript theme={"system"} // Add context without triggering a response anamClient.addContext( "User navigated to pricing page and spent 30 seconds reading", ); // Trigger a specific conversation flow anamClient.sendUserMessage("I want to learn about your pricing plans"); ``` ### Custom Client-Side Transcription Use `sendUserMessage()` to implement your own client-side speech-to-text transcription. Capture and transcribe audio using your preferred service, then send the transcribed messages directly: ```javascript theme={"system"} // Example using a custom transcription service async function handleCustomTranscription(audioStream) { // Use your preferred transcription service (e.g., Web Speech API, Whisper, etc.) const transcribedText = await customTranscriptionService.transcribe(audioStream); // Send the transcribed message to the persona anamClient.sendUserMessage(transcribedText); // Update your UI transcript addMessageToTranscript(transcribedText, "user"); } ``` > [!NOTE] > > With this approach you can use specialized transcription models, handle multiple > languages, or implement custom preprocessing of the audio before sending it to the persona. ## Complete Example Here's a complete example showing how to use `sendUserMessage()` with proper transcript management: ```javascript theme={"system"} import { createClient } from "@anam-ai/js-sdk"; // Initialize the client const anamClient = createClient(sessionToken); await anamClient.streamToVideoElement("video-element-id"); // Function to update your UI transcript function addMessageToTranscript(message, sender) { const transcript = document.getElementById("transcript"); const messageElement = document.createElement("div"); messageElement.className = sender === "user" ? "user-message" : "ai-message"; messageElement.textContent = message; transcript.appendChild(messageElement); } // Send a message and update the transcript function sendMessage(message) { // Add to transcript manually since sendUserMessage doesn't trigger events addMessageToTranscript(message, "user"); // Send the message to the persona anamClient.sendUserMessage(message); } // Example usage sendMessage("What products do you recommend?"); // Add context about user actions without updating the transcript anamClient.addContext("User added item to cart with ID product_123"); ``` ## Error Handling The `sendUserMessage()` method throws errors in two scenarios: ```javascript theme={"system"} // Error: Not currently streaming try { anamClient.sendUserMessage("Hello"); } catch (error) { // "Failed to send user message: not currently streaming" } // Error: No active session try { anamClient.sendUserMessage("Hello"); } catch (error) { // "Failed to send user message: no active session" } ``` Always ensure the client is streaming before calling this method: ```javascript theme={"system"} if (anamClient.isStreaming()) { anamClient.sendUserMessage("Hello"); } ``` ## Next Steps > [card] [Events](https://anam.ai/docs/javascript-sdk/reference/events) > > Learn how to handle message events and build interactive experiences > [card] [Interrupt Command](https://anam.ai/docs/javascript-sdk/reference/interrupt-command) > > Stop the persona from speaking mid-response # Custom Avatar Best Practices Source: https://anam.ai/docs/personas/avatars/custom-avatar-best-practices Technical specifications and source image guidelines for creating custom avatars with Cara 4. > [!WARNING] > > This page is for Cara 4 custom avatars, not Cara 3. Cara 3 follows similar pose and background guidance, but it uses different source image constraints. Cara 4 uses a square source image that can be cropped into landscape and portrait video. The safest upload is a high-resolution square image with clear margins around the subject. ![Diagram showing centered landscape and portrait crops from a square avatar source image](https://mintcdn.com/anam/ILnzlVWrdD50F9dt/images/session-options/avatar-aspect-ratio-crops-v2.png?fit=max\&auto=format\&n=ILnzlVWrdD50F9dt\&q=85\&s=15f3777e78d26cb121615be5e49aa02a) See [Models](https://anam.ai/docs/introduction/models) for when to use `cara-4` and [Video Options](https://anam.ai/docs/personas/session/video) for supported output sizes. ## Source image * **Format:** Use `.png`, `.jpg`/`.jpeg`, or `.webp`, up to 4.5MB. * **Resolution:** Use at least `1152x1152`. Higher resolution is better. * **Margins:** Leave room around the head, shoulders, and chest so Anam can crop in for landscape or portrait output instead of extending the image with outpainting. * **Automatic fixes:** Anam may crop, pad, or outpaint when the source image does not cover the required crop. Do not rely on this for best quality. To skip automatic image processing through the API, use [preserve mode](/docs/personas/avatars/custom-avatars#preserve-your-source-image). It requires an image prepared to the exact specifications in that guide. ## Subject * Use a relaxed, natural pose with a neutral expression. * Keep the face sharp and visible. A mild angle is acceptable if both eyes and the full face remain visible. * Use an eye-level or slightly low camera angle. Cara 4 does not require a low-angle or fully front-on shot. * Keep the mouth closed, but not tense. * Keep hands completely out of view. ## Background and appearance * Use a plain, simple background. * Avoid busy rooms, strong patterns, large text, and distracting logos. * Keep the head, shoulders, and upper chest visible. Avoid tight crops. ## Make the background transparent in your app To place an avatar over your own UI, create a custom avatar from an image with a consistent green background. In your browser app, render the avatar stream to a video element, use a WebGL canvas to remove the green pixels, then place the transparent canvas over your page. The stream contains the green background; your app removes it during rendering. Choose an avatar without green clothing or green spill around the subject. Fine details such as complex hair can be difficult to key cleanly. See the [transparent avatar backgrounds cookbook](https://anam.ai/cookbook/transparent-backgrounds-canvas-greenscreen) for a working example and controls for tuning the result. # Create your own custom avatar Source: https://anam.ai/docs/personas/avatars/custom-avatars Create a custom avatar in Anam Lab or through the API. Preserve a prepared source image without cropping or outpainting. Upload a photo or use your camera, then test your avatar in a live conversation. Anam's one-shot avatar generator creates a personalized avatar from a single photo of a real person, a stock photo, or an AI-generated image with compatible facial features. To change an existing avatar with prompts and reference images, see [Avatar personalization](/docs/personas/avatars/personalization). Every plan, including Free, supports unlimited saved custom avatars in the Lab and through the API. [Image-generation, moderation and creation limits](/docs/resources/billing-and-limits#custom-avatars-and-creation-requests) still apply. ## Before you create * Use a `.png`, `.jpg`/`.jpeg`, or `.webp` image up to 4.5MB. * Use a square image at least `1152x1152`, with the face in focus and hands out of view. * Leave clear space around the head, shoulders, and upper chest for landscape and portrait crops. See [Custom avatar best practices](https://anam.ai/docs/personas/avatars/custom-avatar-best-practices) for complete source image guidance. > [card] [Create a custom avatar](https://lab.anam.ai/build?action=create\&tab=avatar\&cta_id=custom-avatar-docs-inline) > > Upload a photo or take one with your camera in Anam Lab. > [card] [View avatar examples](https://anam.ai/docs/personas/avatars/gallery) > > Browse the avatars available for your personas. ## Create in Anam Lab **1. Open the Build page** Go to the [Avatar tab in Anam Lab](https://lab.anam.ai/build?tab=avatar) and select **Add**. **2. Add a new avatar** Click the **Add** button, then either upload a photo or capture one with your webcam. For best results, follow the [custom avatar best practices](https://anam.ai/docs/personas/avatars/custom-avatar-best-practices). **3. Generate** Click **Create** and wait for your avatar to be generated. Once ready, it's available for use in any persona. ## Create via API For programmatic avatar creation, use the [Create Avatar](/docs/api-reference/avatars/create-avatar) endpoint. This is useful for building custom onboarding flows or batch-creating avatars. ```javascript theme={"system"} const response = await fetch("https://api.anam.ai/v1/avatars", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}`, }, body: JSON.stringify({ displayName: "My Custom Avatar", imageUrl: "https://example.com/photo.jpg", }), }); ``` ### Preserve your source image Set `imageProcessing` to `"preserve"` when you want to use a prepared image without resizing, cropping, padding, outpainting or alignment/refinement. This option is **API-only** and is not available in Anam Lab. The default, `"auto"`, applies normal image processing. Prepare an image that meets all of these requirements: * Exactly **1152×1152 pixels**. * A static, 8-bit RGB or RGBA PNG, up to **4.5 MB**. * Fully opaque, including every alpha value in an RGBA image. * No EXIF metadata or animation. Animated PNGs are rejected. Use a supported Cara 4 creation model: `cara-4`, `cara-4.1-express` or `cara-4-latest`. Do not combine `imageProcessing: "preserve"` with `zoomOutPercent`. ```bash theme={"system"} curl --fail-with-body https://api.anam.ai/v1/avatars \ -H "Authorization: Bearer $ANAM_API_KEY" \ -F 'displayName=My character' \ -F 'imageProcessing=preserve' \ -F 'imageFile=@character.png;type=image/png' ``` You can also send `imageProcessing: "preserve"` in a JSON request with `imageUrl`. Images that do not meet the requirements are rejected rather than converted. Moderation, [creation limits](/docs/resources/billing-and-limits#custom-avatars-and-creation-requests) and facial compatibility checks still apply. Illustrated characters may work, but compatibility and animation quality depend on how human-like their facial features are. Preserve mode does not guarantee support for every character design. The source stays unchanged, but animation frames can change. Retrieve the square source through `sourceImageUrl`. The `imageUrl` field returns the landscape still. Generated video still uses the normal [landscape or portrait framing](/docs/personas/session/video); preserve mode does not change those output crops. ## Using your avatar Once created, reference the avatar by its ID in your persona configuration: ```javascript theme={"system"} const personaConfig = { name: "My Persona", avatarId: "your-custom-avatar-id", avatarModel: "cara-4", voiceId: "de23e340-1416-4dd8-977d-065a7ca11697", llmId: "a7cf662c-2ace-4de1-a21e-ef0fbf144bb7", systemPrompt: "You are a helpful assistant.", }; ``` You can find the avatar ID in Lab by clicking the three-dot menu on any avatar and selecting **Copy ID**. > [card] [Create a custom avatar](https://lab.anam.ai/build?action=create\&tab=avatar\&cta_id=custom-avatar-docs-footer) > > Upload a photo or use your camera, then test your avatar in a live conversation. # Avatar Gallery Source: https://anam.ai/docs/personas/avatars/gallery Browse available Anam avatars, preview their appearance, and copy the avatar identifier needed when creating or updating a persona. ## Premium Avatars Click on an avatar to copy the avatar ID. > [!NOTE] > > Use the copied avatar ID when creating your session token. See the [Usage in > Production](/docs/production) guide for more information. ## Avatar media Fetch an avatar resource to get the media URLs for your own app: * `imageUrl` is the still preview image used for selection screens and loading states. * `videoUrl` is a muted idling MP4 preview, about 30 seconds long, or `null` if the video is still generating. Call [GET `/v1/avatars/{id}`](/docs/api-reference/avatars/get-avatar) from your server to fetch fresh URLs. Never expose your API key in browser code. ```bash theme={"system"} curl https://api.anam.ai/v1/avatars/071b0286-4cce-4808-bee2-e642f1062de3 \ -H "Authorization: Bearer $ANAM_API_KEY" ``` The response includes both fields: ```json theme={"system"} { "id": "071b0286-4cce-4808-bee2-e642f1062de3", "displayName": "Liv", "variantName": "home", "imageUrl": "https://lab.anam.ai/persona_thumbnails/liv_home.png", "videoUrl": "https://anam-prod.../idling_video.mp4?X-Amz-Signature=..." } ``` Use the video as a lightweight preview before the live session starts: ```jsx theme={"system"}