> ## Documentation Index
> Fetch the complete documentation index at: https://developer.suki.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Create Session

> Learn to create a session and implement controlled session management with the Suki Web SDK

<Callout title="Updates" color="orange" icon="bell">
  **Updated**

  From **`v2.2.0+`**, you can pass **optional session-level metadata** in `ambientOptions` (in `mount` or `setAmbientOptions`) to improve note generation. When you set **`visitType`**, the Web SDK also uses it as the **note title** in the patient note list (see [Note list titles](/web-sdk/guides/note-management#note-titles-in-the-web-sdk-ui)).

  Learn more in the [AmbientOptions](/web-sdk/api-reference/types/ambient-options#properties) reference. **These parameters are optional**; omitting them does not break existing flows.
</Callout>

Before you can start recording audio and generating clinical notes using the Web SDK, you must create an ambient session. This guide shows you how to create a session and provide clinical context that helps Suki generate more accurate notes.

**What will you learn?**

In this guide, you will learn how to:

* Configure the SDK client with `initialize()` in JavaScript or `init()` from the `useSuki()` hook in React
* Provide session context through `mount()` or the `<SukiAssistant>` component
* Start an ambient session with `startAmbient()` and read the active session ID from `activeAmbientId`

## Controlled session management

To create an ambient session with the Suki Web SDK, follow this three-step workflow:

<Steps>
  <Step title="Configure the client">
    You must first initialize the client to establish a connection.

    * **JavaScript:** Call `initialize(options)` to get back an [`SDKClientInstance`](/web-sdk/api-reference/classes#sdkclient-instance).
    * **React:** Call `init()` from the `useSuki()` hook.
  </Step>

  <Step title="Provide session context">
    You provide the encounter data and `ambientOptions`, such as patient details, note sections, and visit type, to improve note quality. Detailed context helps the Suki generate more accurate clinical notes.

    * **JavaScript:** Pass the context through `sdkClient.mount()`.
    * **React:** Use the props on the `<SukiAssistant>` component.

    <Note>
      **`patient.identifier`** is required; **`encounter.identifier`** is optional. Each must be a string **at most 36 characters** (<Tooltip tip="VARCHAR is a variable-length SQL string type. varchar(36) caps these identifiers at 36 characters. See the Glossary." cta="View in Glossary" href="/Glossary/v#varchar-36">varchar(36)</Tooltip>). Longer strings can fail during composition or ambient workflows. See [Patient](/web-sdk/api-reference/types/patient) and [Encounter](/web-sdk/api-reference/types/encounter).
    </Note>
  </Step>

  <Step title="Start the session">
    Once you have configured the client and context, you can start the ambient recording.

    * **Start:** Call `startAmbient()` on the client in JavaScript, or from the `useSuki()` hook in React.
    * **Track:** Read the active session ID from `sdkClient.activeAmbientId`, or from the `useSuki()` hook in React, to display the status of the current session.
  </Step>
</Steps>

<Tip>
  Providing richer metadata in the `ambientOptions` ensures the Suki Web SDK has the necessary context to generate more accurate clinical notes.
</Tip>

The following example shows how to create an ambient session in JavaScript and React using the Suki Web SDK.

<View title="JavaScript" icon="js">
  ```js controlled.js expandable theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
  import { SukiAuthManager } from "@suki-sdk/core";
  import { initialize } from "@suki-sdk/js";

  let isSukiReady = false;

  // Replace with your actual encounter data
  const encounterDetails = {
    identifier: "6ec3920f-b0b1-499d-a4e9-889bf788e5ab",
    patient: {
      identifier: "905c2521-25eb-4324-9978-724636df3436",
      name: {
        use: "official",
        family: "Doe",
        given: ["John"],
        suffix: ["MD"],
      },
      birthDate: "1990-01-01",
      gender: "Male",
    },
  };

  const authManager = new SukiAuthManager({
    partnerId: "f80c8db8-a4d0-4b75-8d63-56c82b5413f0", // Replace with your actual partner ID
    partnerToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", // Replace with your actual partner token
    providerName: "John Doe", // Replace with the full name of the provider
    providerOrgId: "1234", // Replace with the provider's organization ID
    providerSpecialty: "FAMILY_MEDICINE", // Replace with the provider's specialty
    environment: "production",
    loginOnInitialize: true, 
    providerId: "1234567890", // Replace with the provider's ID
    providerName: "John Doe", // Replace with the full name of the provider
    providerOrgId: "1234", // Replace with the provider's organization ID
    providerSpecialty: "FAMILY_MEDICINE", // Replace with the provider's specialty
  });

  const sdkClient = initialize({
    authManager,
  });

  const unsubscribeInit = sdkClient.on("init:change", (isInitialized) => {
    if (isInitialized) {
      sdkClient.mount({
        rootElement: document.getElementById("suki-root"), // The root element to mount the SDK into
        encounter: encounterDetails,
        ambientOptions: {
          sections: [
            { loinc: "51848-0" },
            { loinc: "11450-4" },
            { loinc: "29545-1" },
          ],
          diagnoses: { // [!code ++:14] New in v2.1.2
            values: [
              {
                codes: [
                  {
                    code: "I10",
                    description: "Essential hypertension",
                    type: "ICD10",
                  },
                ],
                diagnosisNote: "Hypertension",
              },
            ],
          },
          // Optional session context (visit_type, encounter_type, provider_role, reason_for_visit, chief_complaint)
          visitType: "ESTABLISHED_PATIENT", // [!code ++:6] New in v2.2.0
          encounterType: "AMBULATORY",
          providerRole: "PRIMARY/ATTENDING",
          reasonForVisit: "Follow-up for hypertension",
          chiefComplaint: "Headache",
        },
      });
    } else {
      isSukiReady = false; // Reset the ready state if initialization fails
    }
  });

  const unsubscribeReady = sdkClient.on("ready", () => {
    isSukiReady = true;
  });

  // Ambient session control functions
  function startAmbient() {
    if (isSukiReady) {
      sdkClient.startAmbient();
    } else {
      console.error("Suki SDK is not ready yet.");
    }
  }

  function pauseAmbient() {
    if (isSukiReady) {
      sdkClient.pauseAmbient();
    } else {
      console.error("Suki SDK is not ready yet.");
    }
  }

  function resumeAmbient() {
    if (isSukiReady) {
      sdkClient.resumeAmbient();
    } else {
      console.error("Suki SDK is not ready yet.");
    }
  }

  function cancelAmbient() {
    if (isSukiReady) {
      sdkClient.cancelAmbient();
    } else {
      console.error("Suki SDK is not ready yet.");
    }
  }

  function submitAmbient() {
    if (isSukiReady) {
      sdkClient.submitAmbient();
    } else {
      console.error("Suki SDK is not ready yet.");
    }
  }

  // Attach event listeners to buttons
  document.getElementById("start-ambient").addEventListener("click", startAmbient);
  document.getElementById("pause-ambient").addEventListener("click", pauseAmbient);
  document.getElementById("resume-ambient").addEventListener("click", resumeAmbient);
  document.getElementById("cancel-ambient").addEventListener("click", cancelAmbient);
  document.getElementById("submit-ambient").addEventListener("click", submitAmbient);

  // Cleanup function to destroy the SDK and event listeners
  // Call this function when you no longer need the SDK
  function destroy() {
    isSukiReady = false;
    unsubscribeInit();
    unsubscribeReady();
    sdkClient.destroy();
    
    // Remove event listeners
    document.getElementById("start-ambient").removeEventListener("click", startAmbient);
    document.getElementById("pause-ambient").removeEventListener("click", pauseAmbient);
    document.getElementById("resume-ambient").removeEventListener("click", resumeAmbient);
    document.getElementById("cancel-ambient").removeEventListener("click", cancelAmbient);
    document.getElementById("submit-ambient").removeEventListener("click", submitAmbient);
    
    // Clear the root element
    document.getElementById("suki-root").innerHTML = "";
  }
  ```
</View>

<View title="React" icon="react">
  ```jsx controlled.jsx expandable theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
  import { useState, useEffect, useMemo } from "react";
  import { SukiAuthManager } from "@suki-sdk/core";
  import { useSuki, SukiAssistant } from "@suki-sdk/react";

  function Controlled() {
    const authManager = useMemo(
      () =>
        new SukiAuthManager({
          partnerId: "f80c8db8-a4d0-4b75-8d63-56c82b5413f0", // Replace with your actual partner ID
          partnerToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", // Replace with your actual partner token
          providerName: "John Doe", // Replace with the full name of the provider
          providerOrgId: "1234", // Replace with the provider's organization ID
          environment: "production",
          loginOnInitialize: true,
          providerId: "1234567890", // Replace with the provider's ID
          providerName: "John Doe", // Replace with the full name of the provider
          providerOrgId: "1234", // Replace with the provider's organization ID
          providerSpecialty: "FAMILY_MEDICINE", // Replace with the provider's specialty
        }),
      [],
    );

    const {
      cancelAmbient,
      pauseAmbient,
      resumeAmbient,
      startAmbient,
      submitAmbient,
      init,
      on,
      isInitialized,
    } = useSuki();
    const [isSukiReady, setIsSukiReady] = useState(false);

    // Replace with your actual encounter data
    const currentEncounter = useMemo(
      () => ({
        identifier: "6ec3920f-b0b1-499d-a4e9-889bf788e5ab",
        patient: {
          identifier: "905c2521-25eb-4324-9978-724636df3436",
          name: {
            use: "official",
            family: "Doe",
            given: ["John"],
            suffix: ["MD"],
          },
          birthDate: "1990-01-01",
          gender: "Male",
        },
      }),
      []
    );

    // Initialize SDK when component mounts
    useEffect(() => {
      if (!isInitialized) {
        init({ authManager });
      }
    }, [init, isInitialized, authManager]);

    // Set up event listeners for SDK initialization and readiness
    useEffect(() => {
      const unsubscribeInit = on("init:change", (isInitialized) => {
        if (!isInitialized) {
          setIsSukiReady(false); // Reset the ready state if initialization fails
        }
      });

      const unsubscribeReady = on("ready", () => {
        setIsSukiReady(true);
      });

      return () => {
        unsubscribeInit();
        unsubscribeReady();
      };
    }, [on]);

    return (
      <>
        <SukiAssistant
          encounter={currentEncounter}
          ambientOptions={{
            sections: [
              { loinc: "51848-0" },
              { loinc: "11450-4" },
              { loinc: "29545-1" },
            ],
            diagnoses: { // [!code ++:14] New in v2.1.2
              values: [
                {
                  codes: [
                    {
                      code: "I10",
                      description: "Essential hypertension",
                      type: "ICD10",
                    },
                  ],
                  diagnosisNote: "Hypertension",
                },
              ],
            },
            visitType: "ESTABLISHED_PATIENT", // [!code ++:6] New in v2.2.0
            encounterType: "AMBULATORY",
            providerRole: "PRIMARY/ATTENDING",
            reasonForVisit: "Follow-up for hypertension",
            chiefComplaint: "Headache",
          }}
        />

        {isSukiReady && (
          <div>
            <button onClick={startAmbient}>Start Ambient</button>
            <button onClick={pauseAmbient}>Pause Ambient</button>
            <button onClick={resumeAmbient}>Resume Ambient</button>
            <button onClick={cancelAmbient}>Cancel Ambient</button>
            <button onClick={submitAmbient}>Submit Ambient</button>
          </div>
        )}
        {/* Rest of your code */}
      </>
    );
  }
  ```
</View>

## Update session encounter and ambient options

You can update the session encounter and ambient options whenever a new encounter loads in your EHR. Providing current context ensures that the Suki Platform generates accurate documentation for the specific visit.

### Update the encounter

When the patient or visit details change, you must update the encounter context.

* **JavaScript:** Call `setEncounter()` on the client.
* **React:** Use the `encounter` prop on the `<SukiAssistant>` component.

### Update ambient options

You can also update the ambient options, such as required note sections or diagnoses, during an active session.

* **JavaScript:** Call `setAmbientOptions()` on the client.
* **React:** Use the `ambientOptions` prop on the `<SukiAssistant>` component.

<Tip>
  Updating the encounter and ambient options as soon as the EHR context changes ensures that the session is in sync with the latest context.
</Tip>

<View title="JavaScript" icon="js">
  ```js JavaScript theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
  // Update encounter data
  sdkClient.setEncounter({
    identifier: "qsc2393g-b0b1-499d-a4e9-983cq125g5op",
    patient: {
      identifier: "25eb905-1232-082132-aw12320do4r",
      name: {
        use: "official",
        family: "Smith",
        given: ["Jane"],
        suffix: [],
      },
      birthDate: "1985-05-15",
      gender: "Female",
    },
  });

  // Update ambient options
  sdkClient.setAmbientOptions({
    sections: [
      { loinc: "48765-2" },
      { loinc: "10157-6" },
      { loinc: "10164-2" },
    ],
    diagnoses: {
      values: [
        {
          codes: [
            { code: "I10", description: "Essential hypertension", type: "ICD10" },
          ],
          diagnosisNote: "Hypertension",
        },
      ],
    },
    visitType: "ESTABLISHED_PATIENT",
    encounterType: "AMBULATORY",
    providerRole: "PRIMARY/ATTENDING",
    reasonForVisit: "Follow-up for hypertension",
    chiefComplaint: "Blood pressure check",
  });
  ```
</View>

<View title="React" icon="react">
  ```jsx React theme={"theme":{"light":"github-dark","dark":"material-theme-darker"}}
  <SukiAssistant
    encounter={{
      identifier: "qsc2393g-b0b1-499d-a4e9-983cq125g5op",
      patient: {
        identifier: "25eb905-1232-082132-aw12320do4r",
        name: {
          use: "official",
          family: "Smith",
          given: ["Jane"],
          suffix: [],
        },
        birthDate: "1985-05-15",
        gender: "Female",
      },
    }}
    ambientOptions={{
      sections: [
        { loinc: "48765-2" },
        { loinc: "10157-6" },
        { loinc: "10164-2" },
      ],
      diagnoses: {
        values: [
          {
            codes: [
              { code: "I10", description: "Essential hypertension", type: "ICD10" },
            ],
            diagnosisNote: "Hypertension",
          },
        ],
      },
      visitType: "ESTABLISHED_PATIENT",
      encounterType: "AMBULATORY",
      providerRole: "PRIMARY/ATTENDING",
      reasonForVisit: "Follow-up for hypertension",
      chiefComplaint: "Blood pressure check",
    }}
  />
  ```

  <Info>
    Passing new encounter data or ambient options to the `SukiAssistant` component automatically updates the encounter details or sections for note generation.
  </Info>
</View>

## Next steps

<Icon icon="file-lines" iconType="solid" /> Track session state: [Ambient session status](/web-sdk/guides/ambient-session-status)

<Icon icon="file-lines" iconType="solid" /> Configure problem-based notes: [PBC](/web-sdk/guides/ambient-problem-based-charting)

<Icon icon="file-lines" iconType="solid" /> Return to [Ambient session](/web-sdk/guides/ambient) overview
