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

# Advanced Document Generation

> Custom template definition and document requests

## Overview

In the Corti API, Templates define the structure for documents that are generated by Corti AI models from various inputs, such as conversational transcripts, facts, or other medical documents.

Read more about [Templates](/textgen/templates).

This page walks through advanced document generation workflows to cater to more specific needs.

<Note>This feature requires human oversight of its outputs</Note>

## Assemble Templates with Existing Sections

If templates are difficult to predefine upfront due to the large variety in clinical documentation use cases, it might be better to approach things more flexibly.

To do so, you can map the existing template sections to the relevant fields in the EHR or documentation. Then, assemble at run-time only the relevant sections to produce the documentation.

<Tip>You can query the available sections via the [/templateSections](/api-reference/templates/list-template-sections) endpoint.</Tip>

Instead of providing the `templateKey` in the request, you need to provide the array of `sections` you want to use, see the example request below.

<Warning>We are deprecating `sectionKeys` in favour of `sections`. Read all details [here](/release-notes/changelog-upcoming#request-schema-change-for-post-documents-template-object)</Warning>

<CodeGroup>
  ```ts title="JavaScript" expandable theme={null}
  const document = await client.documents.create(interactionId, {
    context: [
      {
        type: "facts",
        data: [
          { text: "32 year-old female", group: "demographics", source: "system" },
          { text: "itchy rash, started last week", group: "history-of-present-illness", source: "core" },
          { text: "allergic to birch pollen since childhood", group: "allergies", source: "core" },
          { text: "typical eczema appearance", group: "assessment", source: "core" },
          { text: "corticosteroid treatment, follow-up in 4 weeks", group: "plan", source: "user" },
        ],
      },
    ],
    template: {
      sections: [
        { key: "corti-hpi" },
        { key: "corti-allergies" },
        { key: "corti-social-history" },
        { key: "corti-plan" },
      ],
    },
    outputLanguage: "en",
    name: "Test from assembled sections",
    documentationMode: "routed_parallel",
  });
  ```

  ```csharp title="C# .NET" expandable theme={null}
  var document = await client.Documents.CreateAsync(
      interactionId,
      DocumentsCreateRequest.FromDocumentsCreateRequestWithTemplate(
          new DocumentsCreateRequestWithTemplate
          {
              Context =
              [
                  new DocumentsContextWithFacts
                  {
                      Type = DocumentsContextWithFactsType.Facts,
                      Data =
                      [
                          new FactsContext
                          {
                              Text = "32 year-old female",
                              Group = "demographics",
                              Source = CommonSourceEnum.System,
                          },
                          new FactsContext
                          {
                              Text = "itchy rash, started last week",
                              Group = "history-of-present-illness",
                              Source = CommonSourceEnum.Core,
                          },
                          new FactsContext
                          {
                              Text = "allergic to birch pollen since childhood",
                              Group = "allergies",
                              Source = CommonSourceEnum.Core,
                          },
                          new FactsContext
                          {
                              Text = "typical eczema appearance",
                              Group = "assessment",
                              Source = CommonSourceEnum.Core,
                          },
                          new FactsContext
                          {
                              Text = "corticosteroid treatment, follow-up in 4 weeks",
                              Group = "plan",
                              Source = CommonSourceEnum.User,
                          },
                      ],
                  },
              ],
              Template = DocumentsTemplate.FromDocumentsTemplateWithSections(
                  new DocumentsTemplateWithSections
                  {
                      Sections =
                      [
                          new DocumentsSectionOverride { Key = "corti-hpi" },
                          new DocumentsSectionOverride { Key = "corti-allergies" },
                          new DocumentsSectionOverride { Key = "corti-social-history" },
                          new DocumentsSectionOverride { Key = "corti-plan" },
                      ],
                  }
              ),
              OutputLanguage = "en",
              Name = "Test from assembled sections",
              DocumentationMode = TemplatesDocumentationModeEnum.RoutedParallel,
          }
      )
  );
  ```

  ```python title="Python" expandable theme={null}
  import requests

  # Replace these with your values
  ENVIRONMENT = "<eu-or-us>"
  INTERACTION_ID = "<your-interaction-id>"
  TENANT = "<your-tenant-name>"
  TOKEN = "<your-access-token>"

  response = requests.post(
      f"https://api.{ENVIRONMENT}.corti.app/v2/interactions/{INTERACTION_ID}/documents",
      headers={
          "Authorization": f"Bearer {TOKEN}",
          "Tenant-Name": TENANT,
          "Content-Type": "application/json",
      },
      json={
          "context": [
              {
                  "type": "facts",
                  "data": [
                      {"text": "32 year-old female", "group": "demographics", "source": "system"},
                      {"text": "itchy rash, started last week", "group": "history-of-present-illness", "source": "core"},
                      {"text": "allergic to birch pollen since childhood", "group": "allergies", "source": "core"},
                      {"text": "typical eczema appearance", "group": "assessment", "source": "core"},
                      {"text": "corticosteroid treatment, follow-up in 4 weeks", "group": "plan", "source": "user"},
                  ],
              }
          ],
          "template": {
              "sections": [
                  {"key": "corti-hpi"},
                  {"key": "corti-allergies"},
                  {"key": "corti-social-history"},
                  {"key": "corti-plan"},
              ]
          },
          "outputLanguage": "en",
          "name": "Test from assembled sections",
          "documentationMode": "routed_parallel",
      },
  )
  response.raise_for_status()
  document = response.json()
  ```

  ```bash title="cURL" expandable theme={null}
  # Replace these with your values
  ENVIRONMENT="<eu-or-us>"
  INTERACTION_ID="<your-interaction-id>"
  TENANT="<your-tenant-name>"
  TOKEN="<your-access-token>"

  curl --request POST \
    --url "https://api.${ENVIRONMENT}.corti.app/v2/interactions/${INTERACTION_ID}/documents" \
    --header "Authorization: Bearer ${TOKEN}" \
    --header "Tenant-Name: ${TENANT}" \
    --header "Content-Type: application/json" \
    --data '{
      "context": [
        {
          "type": "facts",
          "data": [
            { "text": "32 year-old female", "group": "demographics", "source": "system" },
            { "text": "itchy rash, started last week", "group": "history-of-present-illness", "source": "core" },
            { "text": "allergic to birch pollen since childhood", "group": "allergies", "source": "core" },
            { "text": "typical eczema appearance", "group": "assessment", "source": "core" },
            { "text": "corticosteroid treatment, follow-up in 4 weeks", "group": "plan", "source": "user" }
          ]
        }
      ],
      "template": {
        "sections": [
          { "key": "corti-hpi" },
          { "key": "corti-allergies" },
          { "key": "corti-social-history" },
          { "key": "corti-plan" }
        ]
      },
      "outputLanguage": "en",
      "name": "Test from assembled sections",
      "documentationMode": "routed_parallel"
    }'
  ```
</CodeGroup>

<Info>Any of the context types works with this method. The above request is for context.type: facts. Check the [API reference](/api-reference/documents/generate-document) for the different request formats depending on context being facts, transcript or string or see our [guide here](/textgen/documents-standard#generate-document-from-facts-vs-from-transcript)</Info>

<Tip>Take things further by [customizing existing sections](/textgen/documents-customize)</Tip>

## Working with Other Existing Documents

Your use case might also involve already existing documents such as reports, referral letters, etc. The Corti API was designed to offer such flexibility. Some of the use cases Corti has facilitated via the `/documents` endpoint include:

* Summarizing an existing document or multiple documents
* Identifying a match of an existing document based on defined criteria
* Extracting action items for clinicians out of existing documents

Let's look at the payload request in such a scenario:

<CodeGroup>
  ```ts title="JavaScript" expandable theme={null}
  const document = await client.documents.create(interactionId, {
    context: [
      {
        type: "string",
        data: "<contents of documents or notes as string>",
      },
    ],
    templateKey: "summary-of-notes",
    outputLanguage: "en",
    name: "Test summary of past notes",
  });
  ```

  ```csharp title="C# .NET" expandable theme={null}
  var document = await client.Documents.CreateAsync(
      interactionId,
      new DocumentsCreateRequestWithTemplateKey
      {
          Context =
          [
              new DocumentsContextWithString
              {
                  Type = DocumentsContextWithStringType.String,
                  Data = "<contents of documents or notes as string>",
              },
          ],
          TemplateKey = "summary-of-notes",
          OutputLanguage = "en",
          Name = "Test summary of past notes",
      }
  );
  ```

  ```python title="Python" expandable theme={null}
  import requests

  # Replace these with your values
  ENVIRONMENT = "<eu-or-us>"
  INTERACTION_ID = "<your-interaction-id>"
  TENANT = "<your-tenant-name>"
  TOKEN = "<your-access-token>"

  response = requests.post(
      f"https://api.{ENVIRONMENT}.corti.app/v2/interactions/{INTERACTION_ID}/documents",
      headers={
          "Authorization": f"Bearer {TOKEN}",
          "Tenant-Name": TENANT,
          "Content-Type": "application/json",
      },
      json={
          "context": [
              {
                  "type": "string",
                  "data": "<contents of documents or notes as string>",
              }
          ],
          "templateKey": "summary-of-notes",
          # outputLanguage is a BCP-47 code (e.g. "en", "en-US")
          "outputLanguage": "en",
          "name": "Test summary of past notes",
      },
  )
  response.raise_for_status()
  document = response.json()
  ```

  ```bash title="cURL" expandable theme={null}
  # Replace these with your values
  ENVIRONMENT="<eu-or-us>"
  INTERACTION_ID="<your-interaction-id>"
  TENANT="<your-tenant-name>"
  TOKEN="<your-access-token>"

  curl --request POST \
    --url "https://api.${ENVIRONMENT}.corti.app/v2/interactions/${INTERACTION_ID}/documents" \
    --header "Authorization: Bearer ${TOKEN}" \
    --header "Tenant-Name: ${TENANT}" \
    --header "Content-Type: application/json" \
    --data '{
      "context": [
        {
          "type": "string",
          "data": "<contents of documents or notes as string>"
        }
      ],
      "templateKey": "summary-of-notes",
      "outputLanguage": "en",
      "name": "Test summary of past notes"
    }'
  ```
</CodeGroup>

<Note>The template used here is for demonstration purposes and will need tailoring for your specific use case. If you are interested in such a use case, please contact your Corti representative</Note>
