---
title: "Build a healthcare intake assistant with an Anam avatar"
date: "2026-02-20"
authors: "Jesse Hall"
tags: "tutorial"
---

# Build a healthcare intake assistant with an Anam avatar

This tutorial walks you through building a voice AI healthcare intake assistant that uses a talking avatar powered by [Anam](https://anam.ai/). A patient opens the app, clicks Start, and speaks with Liv — a lip-synced Anam avatar who guides them through a medical intake form one field at a time. As the user answers each question, the agent calls function tools that push updates to the form on screen using RPC (remote procedure call), a method that lets software trigger actions or exchange data between processes or systems in real time. This keeps both the avatar and the form in sync as the conversation progresses.

For the full source code, see the [anam example](https://github.com/livekit-examples/python-agents-examples/tree/main/complex-agents/avatars/anam).

> **Note:** The `python-agents-examples` repository is archived and is no longer maintained. The code still downloads as shown below, but it isn't updated for newer releases of LiveKit Agents. For maintained examples, see the [LiveKit Agents examples](https://github.com/livekit/agents/tree/main/examples).

## What you'll build

By the end of this tutorial, you'll have a working app that:

- Renders a talking Anam avatar in the browser, lip-synced to the agent's voice.
- Guides a patient through a full intake form using voice, one field at a time.
- Updates each form field in real time as the patient speaks, using LiveKit RPC.
- Handles a final confirmation loop and lets the patient submit the form by voice.
- Works with either a Python or TypeScript backend — both share the same frontend.

## Prerequisites

Before you start, make sure you have:

- Python 3.10 or later and [uv](https://docs.astral.sh/uv/getting-started/installation/) installed (for the Python backend)
- Node.js and [pnpm](https://pnpm.io/installation) installed
- A [LiveKit Cloud](https://cloud.livekit.io/) account (the free tier works)
- An [Anam API key](https://lab.anam.ai/api-keys)

The agent uses LiveKit Inference for STT, LLM, and TTS, so you don't need separate API keys from Deepgram, OpenAI, or ElevenLabs. You do need an Anam API key for the avatar.

## Step 1: get the code

Use `pnpm dlx degit` to download just the anam folder without cloning the entire repository:

```bash
pnpm dlx degit livekit-examples/python-agents-examples/complex-agents/avatars/anam anam
cd anam
```

The directory has three parts:

- `agent-py/` — the Python LiveKit agent
- `agent-ts/` — the TypeScript LiveKit agent (same functionality, different language)
- `frontend/` — a Next.js frontend that works with either backend

You only need to run one backend. Pick the one you're comfortable with.

## Step 2: set up the agent

### Python backend

Install dependencies from the existing `pyproject.toml`:

```bash
cd agent-py
uv sync
```

Copy `.env.example` to `.env.local` and fill in your values:

```bash
cp .env.example .env.local
```

```
LIVEKIT_URL=wss://<project-subdomain>.livekit.cloud
LIVEKIT_API_KEY=<your_api_key>
LIVEKIT_API_SECRET=<your_api_secret>
ANAM_API_KEY=<your_anam_api_key>
```

### TypeScript backend

Install dependencies:

```bash
cd agent-ts
pnpm install
```

Copy `.env.example` to `.env.local` and fill in the same values:

```bash
cp .env.example .env.local
```

***

Get your LiveKit credentials from the [LiveKit Cloud dashboard](https://cloud.livekit.io/) under **Settings > API Keys**. Get your Anam API key from the [Anam Lab](https://lab.anam.ai/api-keys).

## Step 3: understand the agent

This section walks through the key parts of `agent-py/src/agent.py`. The TypeScript version in `agent-ts/src/agent.ts` follows the same design.

### Voice pipeline

The agent uses LiveKit Inference to wire up Deepgram for STT, OpenAI for the LLM, and Cartesia for TTS:

```python
session = AgentSession(
    stt=inference.STT(model="deepgram/nova-3", language="multi"),
    llm=inference.LLM(model="openai/gpt-4o-mini"),
    tts=inference.TTS(
        model="cartesia/sonic-3",
        voice="9626c31c-bec5-4cca-baa8-f8ba9e84c8bc",  # Jacqueline (Cartesia)
        sample_rate=16000,  # Required for Anam avatar compatibility
    ),
    turn_detection=MultilingualModel(),
    vad=ctx.proc.userdata["vad"],
    preemptive_generation=True,
)
```

The `sample_rate=16000` on the TTS is a hard requirement for Anam. Anam's lip-sync engine expects audio at 16kHz. If you change the TTS model or provider, make sure it outputs at that sample rate.

### Function tools as an RPC bridge

The agent has three function tools that act as a bridge to the frontend form. When the patient answers a question, the LLM calls the appropriate tool, which performs an RPC call to the frontend to update the form in real time.

**Python (`agent-py/src/agent.py`):**

```python
@function_tool
async def update_field(
    self,
    context: RunContext,
    field_name: Annotated[str, Field(description="The field ID to update: fullName, dob, address, phone, emergencyName, emergencyRelationship, emergencyPhone, medications, allergies, reasonForVisit")],
    value: Annotated[str, Field(description="The value to set for the field.")],
):
    """Update a form field on the patient intake form."""
    if field_name not in VALID_FIELD_NAMES:
        raise llm.LLMToolException(f"Invalid field name: {field_name}")
    payload = json.dumps({"fieldName": field_name, "value": value})
    response = await perform_rpc_to_frontend(self._ctx, "updateField", payload)
    return response

@function_tool
async def get_form_state(self, context: RunContext):
    """Get the current state of all form fields."""
    response = await perform_rpc_to_frontend(self._ctx, "getFormState", "{}")
    return response

@function_tool
async def submit_form(self, context: RunContext):
    """Submit the completed intake form."""
    response = await perform_rpc_to_frontend(self._ctx, "submitForm", "{}")
    context.session.say("Your form has been submitted. You will be contacted soon. Thank you.")
    return response
```

Each tool calls `perform_rpc_to_frontend`, which uses `local_participant.perform_rpc()` to call a named method on the frontend participant:

```python
async def perform_rpc_to_frontend(ctx: JobContext, method: str, payload: str) -> str:
    destination_identity = get_remote_participant_identity(ctx)
    response = await ctx.room.local_participant.perform_rpc(
        destination_identity=destination_identity,
        method=method,
        payload=payload,
        response_timeout=5.0,
    )
    return response
```

The `get_remote_participant_identity` function skips any participant whose identity starts with `anam-`, because Anam joins the room as a separate participant and you only want to target the actual user:

```python
def get_remote_participant_identity(ctx: JobContext) -> str:
    for participant in ctx.room.remote_participants.values():
        if not participant.identity.startswith("anam-"):
            return participant.identity
    raise llm.LLMToolException("No remote participant found")
```

**TypeScript (`agent-ts/src/agent.ts`)** follows the same pattern using `llm.tool()`:

```tsx
const updateField = llm.tool({
  description: 'Update a form field on the patient intake form.',
  parameters: z.object({
    fieldName: z.string().describe('The field ID to update: fullName, dob, ...'),
    value: z.string().describe('The value to set for the field'),
  }),
  execute: async ({ fieldName, value }) => {
    const response = await performRpcToFrontend(
      'updateField',
      JSON.stringify({ fieldName, value })
    );
    return response;
  },
});
```

Both backends use the exact same RPC method names (`updateField`, `getFormState`, `submitForm`) and the same JSON payload format, so the single Next.js frontend works with either.

### Attaching the Anam avatar

After the session starts, create an `AvatarSession` and start it:

```python
# Start the session first
await session.start(
    agent=IntakeAssistant(ctx),
    room=ctx.room,
    room_options=room_io.RoomOptions(...),
)

# Create Anam avatar — must happen AFTER session.start()
avatar = anam.AvatarSession(
    persona_config=anam.PersonaConfig(
        name="Liv",
        avatarId="071b0286-4cce-4808-bee2-e642f1062de3",
    ),
)

await avatar.start(session, room=ctx.room)
```

Note that `session.start()` comes first here. Anam needs to connect to an active audio stream for lip-sync, so the session must be running before you attach the avatar. This is different from some other avatar plugins where the avatar starts first. Once `avatar.start()` resolves, Anam has joined the room as a separate participant and is publishing a video track.

You can use any stock avatar from the [Anam Avatar Gallery](https://docs.anam.ai/resources/avatar-gallery) or create a custom one in [Anam Lab](https://lab.anam.ai/avatars). The `avatarId` in `PersonaConfig` is the ID you copy from the gallery or lab.

### Agent name

Both backends register the same agent name with LiveKit so the frontend can dispatch to either one.

**Python (`agent-py/src/agent.py`)** — set on the entrypoint decorator:

```python
@server.rtc_session(agent_name="Anam-Demo")
async def intake_agent(ctx: JobContext):
    ...
```

**TypeScript (`agent-ts/src/main.ts`)** — set in `ServerOptions`:

```tsx
cli.runApp(
  new ServerOptions({
    agent: fileURLToPath(import.meta.url),
    agentName: 'Anam-Demo',
  }),
);
```

If you rename the agent, update both the backend and the `AGENT_NAME` variable in the frontend `.env.local`.

### Instruction design

The system prompt is structured to enforce strict one-field-at-a-time behavior. Each turn asks for exactly one piece of information, confirms it, then moves on. This keeps the conversation predictable and ensures `update_field` is called with clean, confirmed values rather than unverified user input. The confirmation step also handles corrections cleanly — if the patient says "actually, it's spelled differently," the agent updates the same field before moving forward.

## Step 4: set up the frontend

Install dependencies and configure the environment:

```bash
cd frontend
cp .env.example .env.local
pnpm install
```

Fill in `.env.local`:

```
LIVEKIT_API_KEY=<your_api_key>
LIVEKIT_API_SECRET=<your_api_secret>
LIVEKIT_URL=wss://<project-subdomain>.livekit.cloud
AGENT_NAME=Anam-Demo
```

`AGENT_NAME` must match the agent name registered in the backend — both backends use `Anam-Demo` as shown in Step 3.

### How RPC handlers work

The frontend registers three RPC methods using the `useRpcHandlers` hook (`frontend/hooks/useRpcHandlers.ts`). These are the methods the agent calls:

```tsx
room.registerRpcMethod('updateField', async (data: RpcInvocationData) => {
  const { fieldName, value } = JSON.parse(data.payload) as {
    fieldName: string;
    value: string;
  };
  if (!isValidFieldName(fieldName)) {
    throw new RpcError(1500, 'Invalid field name', JSON.stringify({ fieldName }));
  }
  setFormData((prev) => ({ ...prev, [fieldName]: value }));
  return JSON.stringify({ success: true, fieldName, value });
});

room.registerRpcMethod('getFormState', async () => {
  return JSON.stringify(formDataRef.current);
});

room.registerRpcMethod('submitForm', async () => {
  setIsSubmitted(true);
  return JSON.stringify({ success: true });
});
```

When `updateField` is called, it updates the local React state, which immediately re-renders the corresponding input on screen. `getFormState` reads from a ref rather than state directly to avoid stale closure issues. `submitForm` flips the `isSubmitted` flag, which replaces the form with a confirmation message.

The hook registers on connect and cleans up on disconnect:

```tsx
return () => {
  room.unregisterRpcMethod('updateField');
  room.unregisterRpcMethod('getFormState');
  room.unregisterRpcMethod('submitForm');
};
```

### Rendering the avatar

The `AvatarPanel` component (`frontend/components/app/avatar-panel.tsx`) locates the Anam video track and renders it with `<VideoTrack>`:

```tsx
const remoteParticipants = useRemoteParticipants();
const worker = remoteParticipants.find(
  (p) =>
    p.kind === ParticipantKind.AGENT &&
    p.attributes['lk.publish_on_behalf'] === agent?.identity
);

const workerTracks = useParticipantTracks(
  [Track.Source.Camera, Track.Source.ScreenShare],
  worker?.identity
);

const trackRef =
  workerTracks.find((t) => t.source === Track.Source.Camera) ?? ...;
```

Anam joins the room as a worker participant publishing video on behalf of the agent. The component finds this worker by checking the `lk.publish_on_behalf` attribute, then gets its camera track. Once `trackRef` resolves, the avatar video renders inside a `<VideoTrack>`.

## Step 5: run the app

Start the agent in one terminal (choose one backend):

```bash
# Python
cd agent-py
lk agent dev

# TypeScript
cd agent-ts
lk agent dev
```

Start the frontend in another terminal:

```bash
cd frontend
pnpm dev
```

Open `http://localhost:3000` and click **Start intake**. Liv will introduce herself and begin walking you through the form.

## How it works

Here's the full session flow:

1. The user opens the app and clicks **Start intake**. The frontend calls `/api/connection-details`, which mints a LiveKit JWT and dispatches the `Anam-Demo` agent.
2. The agent starts an `AgentSession` with Deepgram STT, GPT-4o-mini LLM, and ElevenLabs TTS at 16kHz.
3. `session.start()` runs first, activating the voice pipeline. Then `avatar.start()` connects Anam to the room as a separate participant and begins publishing a video track. The frontend's `AvatarPanel` detects the new track and renders the avatar video.
4. `session.generate_reply()` triggers the agent's opening message. Liv greets the user and asks for their full name.
5. The user speaks. LiveKit routes the audio through Deepgram Nova 3 (STT), GPT-4o-mini (LLM), and ElevenLabs Jessica (TTS). Anam receives the TTS audio and lip-syncs the avatar.
6. When the user answers a question, the LLM calls `update_field`. The agent performs an RPC call to `updateField` on the frontend, which updates the form in React state and re-renders the input.
7. This continues for all ten fields. Before submission, the agent calls `get_form_state` to verify what's been captured, then reads it back to the user for confirmation.
8. When the user confirms, the LLM calls `submit_form`. The agent performs an RPC call to `submitForm`, which marks the form as submitted in the frontend. The avatar delivers a closing message, and the session ends.

## Summary

The key techniques in this app:

- Starting `session.start()` before `avatar.start()` so Anam can connect to the live audio stream for lip-sync.
- Setting `sample_rate=16000` on the ElevenLabs TTS, which is required for Anam avatar compatibility.
- Using function tools that call `local_participant.perform_rpc()` to push form updates from the agent to the frontend in real time.
- Registering RPC handlers on the frontend with `room.registerRpcMethod()` to receive those updates and update React state.
- Filtering out `anam-` prefixed participants when targeting the user with RPC calls, since Anam joins as a separate room participant.

For more information, see:

- [Anam plugin docs](https://docs.livekit.io/agents/models/avatar/plugins/anam/) for the full parameter reference.
- [LiveKit RPC docs](https://docs.livekit.io/transport/data/rpc/) for more on remote procedure calls between room participants.
- [Full source code](https://github.com/livekit-examples/python-agents-examples/tree/main/complex-agents/avatars/anam) including both agent backends and the complete Next.js frontend.