> ## Documentation Index
> Fetch the complete documentation index at: https://www.studyfetch.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Scenarios

> Interactive learning scenarios and case studies

## Overview

The Scenarios component creates interactive learning experiences through case studies, role-playing exercises, and problem-solving scenarios. These immersive experiences help students apply theoretical knowledge in practical contexts.

You can create scenarios components through the API. Optionally pass **`criteria`** to define how student performance is graded; if you omit it or send an empty list, the AI generates criteria at create time.

<Note>
  **Validation on create and update.** When you provide **`characters`**, **`tools`**, or **`criteria`**, every entry must include its required fields:

  * **Character** — `id`, `name`, `role`
  * **Tool** — `id`, `name`, `description`, `type`
  * **Evaluation criterion** — `id`, `description`, `weight` (number, 1–10)

  Send an empty array (or omit the field) to let the AI fill it in at create time. Updates are not auto-filled, so any item you send must already be complete.

  **Narrative fields on update.** On a `PUT/PATCH` to a scenarios component, the server merges your changes with the existing scenario and then requires the merged result to keep these non-empty:

  * `context`, `goal`, `greetingMessage`
  * `finalAnswerPrompt` — only when `requiresFinalAnswer` is `true`

  `format` is optional — leave it empty and the runtime falls back to a generic conversational interaction.

  Partial updates (sending just `criteria`, just `tools`, etc.) are fine — the existing values fill in. The call only fails (`400 Bad Request`) if your update would clear one of the required fields above.
</Note>

## Creating a Scenarios Component

<CodeGroup>
  ```javascript JavaScript theme={null}
  import StudyfetchSDK from '@studyfetch/sdk';

  const client = new StudyfetchSDK({
    apiKey: 'your-api-key',
    baseURL: 'https://studyfetchapi.com',
  });

  const scenarioComponent = await client.v1.components.create({
    name: 'Medical Emergency Room Scenario',
    type: 'scenarios',
    config: {
      context: 'You are a medical resident in a busy emergency room. A patient has just arrived with chest pain.',
      goal: 'Properly assess the patient, order appropriate tests, and make a diagnosis',
      format: 'Interactive dialogue with patient and medical staff',
      greetingMessage: 'Welcome Dr. [Student Name]. Your patient, Mr. Johnson, has just arrived in room 3 complaining of chest pain.',
      greetingCharacterId: 'nurse-jane',
      requiresFinalAnswer: true,
      finalAnswerPrompt: 'Based on your assessment, what is your diagnosis and treatment plan?',
      criteria: [
        { id: 'history-taking', description: 'Structured history and focused questions', weight: 7 },
        { id: 'clinical-reasoning', description: 'Sound differential and next steps', weight: 8 },
      ],
      characters: [
        {
          id: 'patient-johnson',
          name: 'Mr. Johnson',
          role: 'Patient',
          description: '58-year-old male with chest pain'
        },
        {
          id: 'nurse-jane',
          name: 'Nurse Jane',
          role: 'Emergency Room Nurse',
          description: 'Experienced ER nurse who assists with procedures'
        }
      ],
      tools: [
        {
          id: 'ekg-machine',
          name: 'EKG Machine',
          description: 'Performs 12-lead electrocardiogram',
          type: 'diagnostic',
          dataFormat: 'EKG readings with intervals and interpretation'
        },
        {
          id: 'lab-results',
          name: 'Lab Results System',
          description: 'Provides blood test results',
          type: 'diagnostic',
          dataFormat: 'Complete blood count, cardiac enzymes, etc.'
        }
      ]
    }
  });

  console.log('Scenario component created:', scenarioComponent._id);
  ```

  ```python Python theme={null}
  from studyfetch_sdk import StudyfetchSDK

  client = StudyfetchSDK(
      api_key="your-api-key",
      base_url="https://studyfetchapi.com",
  )

  scenario_component = client.v1.components.create(
      name="Medical Emergency Room Scenario",
      type="scenarios",
      config={
          "context": "You are a medical resident in a busy emergency room. A patient has just arrived with chest pain.",
          "goal": "Properly assess the patient, order appropriate tests, and make a diagnosis",
          "format": "Interactive dialogue with patient and medical staff",
          "greetingMessage": "Welcome Dr. [Student Name]. Your patient, Mr. Johnson, has just arrived in room 3 complaining of chest pain.",
          "greetingCharacterId": "nurse-jane",
          "requiresFinalAnswer": True,
          "finalAnswerPrompt": "Based on your assessment, what is your diagnosis and treatment plan?",
          "criteria": [
              {"id": "history-taking", "description": "Structured history and focused questions", "weight": 7},
              {"id": "clinical-reasoning", "description": "Sound differential and next steps", "weight": 8},
          ],
          "characters": [
              {
                  "id": "patient-johnson",
                  "name": "Mr. Johnson",
                  "role": "Patient",
                  "description": "58-year-old male with chest pain"
              },
              {
                  "id": "nurse-jane",
                  "name": "Nurse Jane",
                  "role": "Emergency Room Nurse",
                  "description": "Experienced ER nurse who assists with procedures"
              }
          ],
          "tools": [
              {
                  "id": "ekg-machine",
                  "name": "EKG Machine",
                  "description": "Performs 12-lead electrocardiogram",
                  "type": "diagnostic",
                  "dataFormat": "EKG readings with intervals and interpretation"
              },
              {
                  "id": "lab-results",
                  "name": "Lab Results System",
                  "description": "Provides blood test results",
                  "type": "diagnostic",
                  "dataFormat": "Complete blood count, cardiac enzymes, etc."
              }
          ]
      }
  )

  print(f"Scenario component created: {scenario_component._id}")
  ```

  ```java Java theme={null}
  import com.studyfetch.javasdk.client.StudyfetchSdkClient;
  import com.studyfetch.javasdk.client.okhttp.StudyfetchSdkOkHttpClient;
  import com.studyfetch.javasdk.models.v1.components.ComponentResponse;
  import com.studyfetch.javasdk.models.v1.components.ComponentCreateParams;

  import java.util.List;

  public class CreateScenariosComponent {
      public static void main(String[] args) {
          StudyfetchSdkClient client = StudyfetchSdkOkHttpClient.builder()
                  .fromEnv()
                  .baseUrl("https://studyfetchapi.com")
                  .build();

          ComponentCreateParams params = ComponentCreateParams.builder()
                  .name("Medical Emergency Room Scenario")
                  .type(ComponentCreateParams.Type.SCENARIOS)
                  .config(ComponentCreateParams.Config.ScenariosConfigDto.builder()
                          .context("You are a medical resident in a busy emergency room. A patient has just arrived with chest pain.")
                          .goal("Properly assess the patient, order appropriate tests, and make a diagnosis")
                          .format("Interactive dialogue with patient and medical staff")
                          .greetingMessage("Welcome Dr. [Student Name]. Your patient, Mr. Johnson, has just arrived in room 3 complaining of chest pain.")
                          .greetingCharacterId("nurse-jane")
                          .requiresFinalAnswer(true)
                          .finalAnswerPrompt("Based on your assessment, what is your diagnosis and treatment plan?")
                          .criteria(List.of(
                                  ComponentCreateParams.Config.ScenariosConfigDto.Criterion.builder()
                                          .id("history-taking")
                                          .description("Structured history and focused questions")
                                          .weight(7.0)
                                          .build(),
                                  ComponentCreateParams.Config.ScenariosConfigDto.Criterion.builder()
                                          .id("clinical-reasoning")
                                          .description("Sound differential and next steps")
                                          .weight(8.0)
                                          .build()
                          ))
                          .characters(List.of(
                                  ComponentCreateParams.Config.ScenariosConfigDto.Character.builder()
                                          .id("patient-johnson")
                                          .name("Mr. Johnson")
                                          .role("Patient")
                                          .description("58-year-old male with chest pain")
                                          .build(),
                                  ComponentCreateParams.Config.ScenariosConfigDto.Character.builder()
                                          .id("nurse-jane")
                                          .name("Nurse Jane")
                                          .role("Emergency Room Nurse")
                                          .description("Experienced ER nurse who assists with procedures")
                                          .build()
                          ))
                          .tools(List.of(
                                  ComponentCreateParams.Config.ScenariosConfigDto.Tool.builder()
                                          .id("ekg-machine")
                                          .name("EKG Machine")
                                          .description("Performs 12-lead electrocardiogram")
                                          .type("diagnostic")
                                          .dataFormat("EKG readings with intervals and interpretation")
                                          .build(),
                                  ComponentCreateParams.Config.ScenariosConfigDto.Tool.builder()
                                          .id("lab-results")
                                          .name("Lab Results System")
                                          .description("Provides blood test results")
                                          .type("diagnostic")
                                          .dataFormat("Complete blood count, cardiac enzymes, etc.")
                                          .build()
                          ))
                          .build())
                  .build();

          ComponentResponse component = client.v1().components().create(params);
          System.out.println("Scenario component created: " + component._id());
      }
  }
  ```

  ```csharp C# theme={null}
  using StudyfetchSDK;
  using StudyfetchSDK.Models.V1.Components;
  using StudyfetchSDK.Models.V1.Components.ComponentCreateParamsProperties.ConfigProperties.ScenariosConfigDtoProperties;
  using System;
  using System.Collections.Generic;
  using System.Threading.Tasks;
  public class CreateScenariosComponent
  {
      public static async Task CreateScenario()
      {
          var client = new StudyfetchSDKClient()
          {
              APIKey = Environment.GetEnvironmentVariable("STUDYFETCH_API_KEY"),
              BaseUrl = new Uri("https://studyfetchapi.com")
          };

          var scenarioComponent = await client.V1.Components.Create(new()
          {
              Name = "Medical Emergency Room Scenario",
              Type = StudyfetchSDK.Models.V1.Components.ComponentCreateParamsProperties.Type.Scenarios,
              Config = new StudyfetchSDK.Models.V1.Components.ComponentCreateParamsProperties.ConfigProperties.ScenariosConfigDto()
              {
                  Context = "You are a medical resident in a busy emergency room. A patient has just arrived with chest pain.",
                  Goal = "Properly assess the patient, order appropriate tests, and make a diagnosis",
                  Format = "Interactive dialogue with patient and medical staff",
                  GreetingMessage = "Welcome Dr. [Student Name]. Your patient, Mr. Johnson, has just arrived in room 3 complaining of chest pain.",
                  GreetingCharacterID = "nurse-jane",
                  RequiresFinalAnswer = true,
                  FinalAnswerPrompt = "Based on your assessment, what is your diagnosis and treatment plan?",
                  Criteria = new List<EvaluationCriterion>
                  {
                      new EvaluationCriterion
                      {
                          ID = "history-taking",
                          Description = "Structured history and focused questions",
                          Weight = 7,
                      },
                      new EvaluationCriterion
                      {
                          ID = "clinical-reasoning",
                          Description = "Sound differential and next steps",
                          Weight = 8,
                      },
                  },
                  Characters = new List<Character>
                  {
                      new Character()
                      {
                          ID = "patient-johnson",
                          Name = "Mr. Johnson",
                          Role = "Patient",
                          Description = "58-year-old male with chest pain"
                      },
                      new Character()
                      {
                          ID = "nurse-jane",
                          Name = "Nurse Jane",
                          Role = "Emergency Room Nurse",
                          Description = "Experienced ER nurse who assists with procedures"
                      }
                  },
                  Tools = new List<Tool>
                  {
                      new Tool()
                      {
                          ID = "ekg-machine",
                          Name = "EKG Machine",
                          Description = "Performs 12-lead electrocardiogram",
                          Type = "diagnostic",
                          DataFormat = "EKG readings with intervals and interpretation"
                      },
                      new Tool()
                      {
                          ID = "lab-results",
                          Name = "Lab Results System",
                          Description = "Provides blood test results",
                          Type = "diagnostic",
                          DataFormat = "Complete blood count, cardiac enzymes, etc."
                      }
                  }
              }
          });

          Console.WriteLine($"Scenario component created: {scenarioComponent._ID}");
      }
  }
  ```
</CodeGroup>

## Configuration Parameters

<ParamField body="name" type="string" required>
  Name of the scenarios component
</ParamField>

<ParamField body="type" type="string" required>
  Must be `"scenarios"`
</ParamField>

<ParamField body="config" type="object" required>
  Scenarios configuration object

  <Expandable title="Configuration Properties">
    <ParamField body="materials" type="array">
      Material IDs to ground the scenario (optional; same as other component configs)
    </ParamField>

    <ParamField body="folders" type="array">
      Folder IDs whose materials are in scope (optional)
    </ParamField>

    <ParamField body="model" type="string">
      AI model for scenario generation (optional)
    </ParamField>

    <ParamField body="context" type="string">
      Overall context and setting of the scenario
    </ParamField>

    <ParamField body="goal" type="string">
      Primary goal or learning objective of the interaction
    </ParamField>

    <ParamField body="format" type="string">
      Interaction format and step-by-step instructions
    </ParamField>

    <ParamField body="greetingMessage" type="string">
      Initial greeting message displayed to users
    </ParamField>

    <ParamField body="greetingCharacterId" type="string">
      Character ID that delivers the greeting message
    </ParamField>

    <ParamField body="requiresFinalAnswer" type="boolean" default="false">
      Whether the scenario requires a final answer submission
    </ParamField>

    <ParamField body="finalAnswerPrompt" type="string">
      Prompt displayed when requesting final answer
    </ParamField>

    <ParamField body="criteria" type="array">
      Authored evaluation criteria for grading. Each entry needs a stable **`id`**, human-readable **`description`**, and **`weight`** from **1–10** (relative importance). If omitted or empty at create time, criteria are AI-generated.

      <Expandable title="Criterion object">
        <ParamField body="id" type="string" required>
          Stable identifier for this criterion
        </ParamField>

        <ParamField body="description" type="string" required>
          What this criterion measures
        </ParamField>

        <ParamField body="weight" type="number" required>
          Importance weight from 1 to 10
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="characters" type="array">
      Array of characters in the scenario

      <Expandable title="Character Properties">
        <ParamField body="id" type="string" required>
          Unique identifier for the character
        </ParamField>

        <ParamField body="name" type="string" required>
          Character's name
        </ParamField>

        <ParamField body="role" type="string" required>
          Character's role in the scenario
        </ParamField>

        <ParamField body="description" type="string">
          Character's description and personality
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="tools" type="array">
      Array of tools available in the scenario

      <Expandable title="Tool Properties">
        <ParamField body="id" type="string" required>
          Unique identifier for the tool
        </ParamField>

        <ParamField body="name" type="string" required>
          Tool's name
        </ParamField>

        <ParamField body="description" type="string" required>
          What the tool does or shows
        </ParamField>

        <ParamField body="type" type="string" required>
          Type of tool (e.g., "Database", "Document", "diagnostic")
        </ParamField>

        <ParamField body="dataFormat" type="string">
          Format of data the tool provides
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="enableHistory" type="boolean">
      Enable conversation history in the embed (optional)
    </ParamField>

    <ParamField body="enableVoice" type="boolean">
      Enable voice in the scenario UI (optional)
    </ParamField>

    <ParamField body="placeholderText" type="string">
      Placeholder text for inputs (optional)
    </ParamField>
  </Expandable>
</ParamField>

## Response

```json theme={null}
{
  "_id": "comp_101jkl",
  "name": "Medical Emergency Room Scenario",
  "type": "scenarios",
  "status": "active",
  "config": {
    "context": "You are a medical resident in a busy emergency room. A patient has just arrived with chest pain.",
    "goal": "Properly assess the patient, order appropriate tests, and make a diagnosis",
    "format": "Interactive dialogue with patient and medical staff",
    "greetingMessage": "Welcome Dr. [Student Name]. Your patient, Mr. Johnson, has just arrived in room 3 complaining of chest pain.",
    "greetingCharacterId": "nurse-jane",
    "requiresFinalAnswer": true,
    "finalAnswerPrompt": "Based on your assessment, what is your diagnosis and treatment plan?",
    "criteria": [
      { "id": "history-taking", "description": "Structured history and focused questions", "weight": 7 },
      { "id": "clinical-reasoning", "description": "Sound differential and next steps", "weight": 8 }
    ],
    "characters": [
      {
        "id": "patient-johnson",
        "name": "Mr. Johnson",
        "role": "Patient",
        "description": "58-year-old male with chest pain"
      },
      {
        "id": "nurse-jane",
        "name": "Nurse Jane",
        "role": "Emergency Room Nurse",
        "description": "Experienced ER nurse who assists with procedures"
      }
    ],
    "tools": [
      {
        "id": "ekg-machine",
        "name": "EKG Machine",
        "description": "Performs 12-lead electrocardiogram",
        "type": "diagnostic",
        "dataFormat": "EKG readings with intervals and interpretation"
      },
      {
        "id": "lab-results",
        "name": "Lab Results System",
        "description": "Provides blood test results",
        "type": "diagnostic",
        "dataFormat": "Complete blood count, cardiac enzymes, etc."
      }
    ]
  },
  "createdAt": "2024-01-15T10:00:00Z",
  "updatedAt": "2024-01-15T10:00:00Z",
  "organizationId": "org_456def"
}
```

## Embedding This Component

Once you've created a Scenarios component, you can embed it on your website using the embedding API.

### Generate Embed URL

<CodeGroup>
  ```javascript JavaScript theme={null}
  const embedResponse = await client.v1.components.generateEmbed(scenarioComponent._id, {
    // User tracking
    userId: 'user-456',
    studentName: 'Jane Smith',  // Student name for display
    groupIds: ['class-101', 'class-102'],
    sessionId: 'session-789',
    
    // Scenarios-specific features
    features: {
      enableHistory: true
    },
    
    // Dimensions
    width: '100%',
    height: '600px',
    
    // Token expiry
    expiryHours: 24
  });
  ```

  ```python Python theme={null}
  embed_response = client.v1.components.generateEmbed(
      component_id=scenario_component._id,
      userId="user-456",
      student_name="Jane Smith",  # Student name for display
      groupIds=["class-101", "class-102"],
      sessionId="session-789",
      features={
          "enableHistory": True
      },
      width="100%",
      height="600px",
      expiryHours=24
  )
  ```

  ```java Java theme={null}
  import com.studyfetch.javasdk.client.StudyfetchSdkClient;
  import com.studyfetch.javasdk.client.okhttp.StudyfetchSdkOkHttpClient;
  import com.studyfetch.javasdk.models.v1.components.ComponentGenerateEmbedParams;
  import com.studyfetch.javasdk.models.v1.components.ComponentGenerateEmbedResponse;

  StudyfetchSdkClient client = StudyfetchSdkOkHttpClient.builder()
      .fromEnv()
      .baseUrl("https://studyfetchapi.com")
      .build();

  ComponentGenerateEmbedParams params = ComponentGenerateEmbedParams.builder()
      .id(scenarioComponent._id())
      // User tracking
      .userId("user-456")
      .studentName("Jane Smith")  // Student name for display
      .groupIds(List.of("class-101", "class-102"))
      .sessionId("session-789")
      
      // Scenarios-specific features
      .features(ComponentGenerateEmbedParams.Features.builder()
          .enableHistory(true)
          .build())
      
      // Dimensions
      .width("100%")
      .height("600px")
      
      // Token expiry
      .expiryHours(24)
      .build();

  ComponentGenerateEmbedResponse embedResponse = client.v1().components()
      .generateEmbed(params);
  ```

  ```csharp C# theme={null}
  using StudyfetchSDK;
  using StudyfetchSDK.Models.V1.Components;
  using System;
  using System.Collections.Generic;
  using System.Threading.Tasks;
  public class GenerateScenariosEmbed
  {
      public static async Task GenerateEmbed()
      {
          var client = new StudyfetchSDKClient()
          {
              APIKey = Environment.GetEnvironmentVariable("STUDYFETCH_API_KEY"),
              BaseUrl = new Uri("https://studyfetchapi.com")
          };

          var embedResponse = await client.V1.Components.GenerateEmbed(new()
          {
              ID = "component_123abc", // Replace with your component ID
              UserID = "user-456",
              StudentName = "Jane Smith",  // Student name for display
              GroupIDs = new List<string> { "class-101", "class-102" },
              Width = "100%",
              Height = "600px"
          });

          Console.WriteLine($"Embed URL: {embedResponse.EmbedURL}");
          Console.WriteLine($"Token: {embedResponse.Token}");
      }
  }
  ```
</CodeGroup>

### Scenarios-Specific Embedding Features

<ParamField body="features.enableHistory" type="boolean" default="true">
  Save scenario progress and allow users to resume where they left off
</ParamField>

### Embed in Your HTML

```html theme={null}
<iframe 
  src="https://embed.studyfetch.com/component/comp_101jkl?token=..."
  width="100%"
  height="600px"
  frameborder="0"
  style="border: 1px solid #e5e5e5; border-radius: 8px;">
</iframe>
```
