> ## 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.

# Pick and fill a clinical form

> Build one schema tool, form_patch, that fills whichever clinical form is open from dictation and suggests the next form when one is done.

A clinician **speaks** during a patient encounter, and an agent fills whichever clinical form is open, such as a triage assessment, a SOAP note, or a PHQ-9 screening. When a form is done, the agent can suggest the next one, and the client swaps forms without losing the conversation. Nothing is saved until the clinician confirms.

The recommended setup leaves dictation running for the whole encounter, so the form fills while the clinician talks, as described under **Keep dictation running** below.

![Form-fill flow: the clinician dictates, the client sends the current form state, the agent emits a patch, and the client applies it. The loop repeats with each message. When a form is done, the client may offer the next form. The clinician confirms before anything is saved.](https://mintcdn.com/corti/OdqulwjO6Fo6Jlod/images/recipes-formfill-light.svg?fit=max\&auto=format\&n=OdqulwjO6Fo6Jlod\&q=85\&s=88d72b0ffc5ce712d6ac34e669562e58)

The agent fills a form from dictation, patching only what changed with each message. When one form is done, the client can offer the next. The clinician confirms before anything is saved.

This page builds on [Build a schema tool](https://docs.corti.ai/agentic/cookbook/extract.md#build-a-schema-tool), which explains each part of a schema tool. What is new here is a generic schema tool whose vocabulary arrives at runtime: one `form_patch` tool fills every form, because the paths, collections, and fields it may name come from the form schema the client sends with each message.

## Build the form-fill tool

The target: the clinician says "Patient is Daniel, a 34-year-old man, sharp right lower quadrant pain since this morning." and the agent fills the matching fields of whichever form is open, here a triage form.

### 1. Define a generic tool with an ops array

`form_patch` names no form fields. Its schema pins a `type` discriminator with a `const` and holds an `ops` array. Each op is one flat object: only `op` is required, and `op` is an `enum` of six change kinds.

```json theme={null}
"required": ["type", "ops"],
"properties": {
  "type": { "type": "string", "const": "form_patch" },
  "ops": {
    "type": "array", "minItems": 0,
    "items": {
      "type": "object", "additionalProperties": false, "required": ["op"],
      "properties": { "op": { "type": "string", "enum": ["set", "unset", "upsert", "remove", "setField", "string"] } }
    }
  }
}
```

The other op fields, such as `path`, `collection`, and `field`, are all optional on that one object. Which fields each op uses, and which values are valid, is stated in each field's `description`, as in [Build a schema tool](https://docs.corti.ai/agentic/cookbook/extract.md#build-a-schema-tool). For example, the `path` description says that valid paths are defined in the form schema's `scalar_fields`.

### 2. Give each op the fields it needs

Each op targets one kind of form field. `set` and `unset` take a `path` to a single-value field. `upsert`, `remove`, and `setField` take a `collection`. `upsert` targets the item's `item.id`, while `remove` and `setField` take an `id`. Any of the three can use `match` instead. `string` edits a prose `field` with a `mode`:

```json theme={null}
"mode": { "type": "string", "enum": ["append", "prepend", "replace"] },
"text": { "type": "string", "description": "Text to add for 'append'/'prepend'. Omit for 'replace'." },
"find": { "type": "string", "description": "For 'replace': an exact, unique substring already present in the field to locate the edit point. Required for 'replace'." },
"replace": { "type": "string", "description": "For 'replace': the new substring to substitute. Empty string ('') DELETES the matched substring." }
```

`replace` edits text in place, so a correction keeps the surrounding sentence intact. [The ops table](#the-full-body) lists the fields of every op.

### 3. Describe each form as a schema

The vocabulary lives in a form schema, one per form. `form_type` names the form. `scalar_fields` hold single values addressed by a dot `path`, `collections` hold lists of items described by `item_fields`, and `string_fields` hold prose with `writing_guidance`. This fragment is from the triage form:

```json theme={null}
{
  "form_type": "triage_assessment",
  "scalar_fields": [
    { "path": "urgency", "type": "string", "description": "Triage urgency level. ...", "enum": ["low", "moderate", "high", "critical"] }
  ],
  "collections": [
    {
      "name": "vitals",
      "description": "Vital signs observed during triage.",
      "item_fields": [
        { "name": "id", "type": "string", "description": "Stable identifier for the item.", "required": true },
        { "name": "name", "type": "string", "description": "Vital sign name (e.g. 'Temperature', 'Heart rate', 'BP').", "required": true },
        { "name": "value", "type": "string", "description": "Vital value including unit.", "required": true }
      ]
    }
  ],
  "string_fields": [
    { "field": "triage_note", "description": "A brief narrative summary of the triage assessment ...", "writing_guidance": "Write 2–4 sentences summarizing the triage assessment. ..." }
  ]
}
```

The `description` and `enum` on each field do the job they do in a schema tool, but they reach the agent as data, not as a connector. A coded field is an `object` whose `description` names its parts. In the SOAP form, for example, an allergy's `allergen` is described as a SNOMED CT code with `conceptId`, `term`, and `codeSystem`.

### 4. Send the form in a form\_state data part

The client owns the form. With each message, it sends the clinician's words plus a `form_state` [data part](https://docs.corti.ai/agentic/guides/send-message.md#using-data-parts-for-structured-context) holding the current `values`. The first message also carries the full `schema` and a `form_catalog` listing every form you offer:

```json theme={null}
{
  "type": "form_state",
  "values": { "status": "draft" },
  "form_catalog": [
    {
      "form_type": "triage_assessment",
      "description": "Rapid triage assessment — chief complaint, vitals, urgency",
      "when_to_use": "Triage a new patient — establish chief complaint, vitals, and urgency level before further documentation.",
      "triggers": ["new patient arrival", "chief complaint stated", "vitals taken", "urgency needs assigning"]
    },
    { "form_type": "soap_clinical_note", "...": "one entry per form you offer" }
  ],
  "description": "The current authoritative state of the form. Read `schema` to learn what fields exist and how to fill them. Read `values` as your source of truth ...",
  "schema": { "form_type": "triage_assessment", "...": "the full form schema" },
  "schema_changed": true
}
```

When the schema is unchanged, the client leaves `schema` out and sends `"schema_ref": "triage_assessment"` with `"schema_changed": false`, so the agent uses the schema from earlier in the conversation. The client sends the full schema again whenever it changes: after a form swap, when a conditional field appears, or when Text Generation guidance arrives.

### 5. Finish the form and attach the tool

Next to `ops`, the patch can carry a `status` and a `suggestion` for the next form, picked from the catalog:

```json theme={null}
"status": { "type": "string", "enum": ["draft", "complete"] },
"suggestion": {
  "type": "object",
  "properties": { "target_form": { "type": "string" }, "reason": { "type": "string" } },
  "required": ["target_form", "reason"]
}
```

The connector uses `"transition": "complete"`, so the run ends each time the agent calls `form_patch`. Attach the tool with the `coding-expert` registry connector, which resolves concepts for coded fields. See [Medical Coding](https://docs.corti.ai/agentic/registry/medical-coding.md).

```json theme={null}
{
  "connectors": [
    { "type": "schema", "name": "form_patch", "...": "the full body below" },
    { "type": "registry", "name": "coding-expert" }
  ]
}
```

## The full body

```json expandable theme={null}
{
  "type": "schema",
  "name": "form_patch",
  "description": "Apply INCREMENTAL updates to the form. This is a PATCH tool: call this tool with ONLY the changes for this turn, never the whole form. The client holds the authoritative form state and merges your ops into it on every turn. Call this tool with one or more `ops` describing what to add, change, or remove since your last turn. The valid field names, collections, item shapes, and guidance for how to fill each field are NOT defined here — they arrive in the `form_state` data part every turn. Read `form_state` to learn what fields exist and how to fill them, then call this tool with ops that reference only those fields. Give every new list item a stable `id` so you can edit or remove it later. Never ask the user questions — just describe the changes to apply.",
  "schema": {
    "type": "object",
    "additionalProperties": false,
    "required": ["type", "ops"],
    "properties": {
      "type": {
        "type": "string",
        "const": "form_patch",
        "description": "Discriminator — always 'form_patch'. Marks this data as a form patch."
      },
      "ops": {
        "type": "array",
        "minItems": 0,
        "description": "The incremental changes to apply to the form, in order. Only the diff — do not resend unchanged content. Empty when the message only marks the form complete. Each op is one of: set, unset, upsert, remove, setField, string. The valid paths, collections, and field names come from the form schema in the `form_state` data part.",
        "items": {
          "type": "object",
          "additionalProperties": false,
          "required": ["op"],
          "properties": {
            "op": {
              "type": "string",
              "enum": ["set", "unset", "upsert", "remove", "setField", "string"],
              "description": "Which kind of change to apply."
            },
            "path": {
              "type": "string",
              "description": "Dot path of a scalar field to set or remove. Valid paths are defined in the form schema's scalar_fields. Used by 'set' and 'unset'."
            },
            "value": {
              "description": "The new value for 'set' (string, number, boolean, or object when setting a whole nested object). Omit for 'unset'."
            },
            "collection": {
              "type": "string",
              "description": "Which list field an 'upsert', 'remove', or 'setField' operates on. Valid collection names are defined in the form schema's collections."
            },
            "id": {
              "type": "string",
              "description": "Stable identifier of the target item for 'setField' and 'remove'. Always include it once you have created an item with that id."
            },
            "match": {
              "type": "object",
              "additionalProperties": true,
              "description": "Alternative to 'id' for 'upsert'/'remove'/'setField': a subset of fields used to find an existing item. Only for arrays; matched against item values. If combined with 'id', 'id' wins."
            },
            "item": {
              "type": "object",
              "description": "The full item to add or fully replace for 'upsert'. Must carry an 'id' when it is a list item so it can later be targeted. The fields a valid item carries are defined in the form schema's collection item_fields.",
              "properties": {
                "id": { "type": "string", "description": "Stable identifier. Reuse an existing id to REPLACE that item, or supply a new id to ADD it." }
              }
            },
            "fieldPath": {
              "type": "string",
              "description": "Dot path to a field WITHIN an existing item for 'setField'. Resolved relative to the matched item. Valid field paths are defined in the collection's item_fields."
            },
            "field": {
              "type": "string",
              "description": "Which string field a 'string' op edits. Valid field names are defined in the form schema's string_fields."
            },
            "mode": {
              "type": "string",
              "enum": ["append", "prepend", "replace"],
              "description": "How to edit the string field: append (add 'text' to the end), prepend (add 'text' to the start), or replace (find 'find' and swap it for 'replace' — the in-place edit/delete mechanism)."
            },
            "text": {
              "type": "string",
              "description": "Text to add for 'append'/'prepend'. Omit for 'replace'."
            },
            "find": {
              "type": "string",
              "description": "For 'replace': an exact, unique substring already present in the field to locate the edit point. Required for 'replace'."
            },
            "replace": {
              "type": "string",
              "description": "For 'replace': the new substring to substitute. Empty string ('') DELETES the matched substring."
            }
          }
        }
      },
      "status": {
        "type": "string",
        "enum": ["draft", "complete"],
        "description": "Optional. When 'complete', marks the form ready to save. Only include when the user indicates the form is done."
      },
      "suggestion": {
        "type": "object",
        "description": "Optional. When status is 'complete', suggest a clinically relevant next form. Include target_form (a form_type from form_catalog) and a one-line reason explaining why this form is recommended.",
        "properties": {
          "target_form": { "type": "string", "description": "The form_type of the suggested next form." },
          "reason": { "type": "string", "description": "A concise one-line clinical reason for the suggestion." }
        },
        "required": ["target_form", "reason"]
      }
    }
  },
  "transition": "complete"
}
```

| Op | Fields | What the client does |
| - | - | - |
| `set` | `path`, `value` | Writes `value` at the dot path, such as `patient.age` |
| `unset` | `path` | Removes the field at the path |
| `upsert` | `collection`, `item` with an `id`, optional `match` | Replaces the item with the same `id` (or that fits `match`), or adds it |
| `remove` | `collection`, `id` or `match` | Deletes the matching item |
| `setField` | `collection`, `id` or `match`, `fieldPath`, `value` | Writes one field inside the matching item |
| `string` | `field`, `mode`, then `text` (append, prepend) or `find` and `replace` (replace) | Edits a prose field. An empty `replace` deletes the matched text |

`status` and `suggestion` sit on the patch object next to `ops`, not inside it. The framework validates each patch against this generic shape, but it cannot know whether a `path` exists in the open form, so check each op's target against the current form schema before you apply it.

## Point the system prompt at the tool

The tool and the form schema carry most of the rules. The prompt only needs the role, the tools, and the rules specific to filling a form from live dictation:

```text theme={null}
Role: fill the open clinical form from what the clinician says, while they speak.

Tools:
- form_patch: apply incremental changes to the form. Calling it ends the run.
- coding-expert: resolve a clinical concept to a code when a field's description asks for a coded concept.

Never ask the clinician a question. If a field is missing or ambiguous, leave it blank and keep filling.

Every message carries a form_state data part. Its schema lists the fields you may fill and how to fill them. Its values are the current form and your source of truth.
When schema_changed is true, read the full schema again. When it is false, use the earlier schema that schema_ref names.

Call form_patch with only the diff from values to the new state. Never resend what values already holds.
Fill string_fields with the string op, never with set.

When the clinician says the form is done, add status "complete", and add a suggestion if form_catalog indicates a next form.
```

Three of [the rules every flow shares](https://docs.corti.ai/agentic/cookbook/overview#write-the-system-prompt) apply here. The agent makes one `form_patch` call per message, which the `complete` transition also enforces. It fills only what the clinician said. And it never reports a form as saved, because a patch is a suggestion until the clinician confirms. The rule about requested data does not apply, because this agent never asks the client for data. If patches resend content the form already holds, check that the client sends the updated `values` with each message before adding prompt rules.

> [accordion] Run it: an example encounter
>
> Each time the clinician speaks, the same loop runs:
>
> 1. The client sends the clinician's words and a `form_state` data part on the same `contextId`.
> 2. The agent reads `form_state`, codes any concepts a coded field needs, and calls `form_patch` with the diff.
> 3. The client applies the ops to its local form and shows the result.
>
> The clinician says: "Patient is Daniel, a 34-year-old man, sharp right lower quadrant pain since this morning, nauseated. Temp 38.4, heart rate 104, BP 128 over 82. This is high urgency." The first `form_state` carries the triage schema and the catalog, as in step 4. The agent answers:
>
> ```json theme={null}
> {
>   "type": "form_patch",
>   "ops": [
>     { "op": "set", "path": "patient.name", "value": "Daniel" },
>     { "op": "set", "path": "patient.age", "value": "34" },
>     { "op": "set", "path": "patient.gender", "value": "male" },
>     { "op": "set", "path": "chief_complaint", "value": "Sharp right lower quadrant abdominal pain since this morning, with nausea" },
>     { "op": "set", "path": "urgency", "value": "high" },
>     { "op": "upsert", "collection": "vitals", "item": { "id": "temp", "name": "Temperature", "value": "38.4°C" } },
>     { "op": "upsert", "collection": "vitals", "item": { "id": "hr", "name": "Heart rate", "value": "104 bpm" } },
>     { "op": "upsert", "collection": "vitals", "item": { "id": "bp", "name": "BP", "value": "128/82" } },
>     { "op": "string", "field": "triage_note", "mode": "append", "text": "A 34-year-old man presents with sharp right lower quadrant abdominal pain since this morning, with nausea. He is febrile at 38.4°C and tachycardic at 104 bpm, with BP 128/82. Urgency is high given the fever, tachycardia, and localized abdominal pain." }
>   ]
> }
> ```
>
> The client applies the ops in order. `set` writes at the dot path, creating `patient` if needed. `upsert` adds each vital, or replaces an item that has the same `id`. `string` with `append` fills the empty `triage_note`.
>
> The clinician then says: "Disposition is admit. That's the triage done." The schema has not changed, so the next `form_state` carries the updated `values` with `"schema_ref": "triage_assessment"` and `"schema_changed": false`. The agent sends only the new disposition, marks the form complete, and suggests the next form from the catalog:
>
> ```json theme={null}
> {
>   "type": "form_patch",
>   "ops": [{ "op": "set", "path": "disposition", "value": "admit" }],
>   "status": "complete",
>   "suggestion": { "target_form": "soap_clinical_note", "reason": "Patient is being admitted with acute abdominal pain and fever, so document the full encounter." }
> }
> ```
>
> The client sets `values.status` to `complete`, runs any computed fields, and offers the suggestion. Nothing is saved until the clinician confirms.

> [accordion] Keep dictation running
>
> Leave dictation on for the whole encounter instead of asking the clinician to start and stop it. The form then fills while the clinician talks, and a later correction, such as "actually, temp 38.9", patches the value set earlier.
>
> * Stream the clinician's speech with [Corti dictation](https://docs.corti.ai/sdk/dictation/overview.md). Show interim results on screen, but send only final transcript segments to the agent.
> * Send each final segment as its own message, with the current `form_state`.
> * Send one message at a time, in order. Queue segments that arrive while a run is in progress, and send each with the form state as it is after the previous patch.

> [accordion] Form swap and linked forms
>
> When a form completes, the client gathers next-form suggestions from two places: the agent's `suggestion`, and the form schema's own `link_rules`, which the client evaluates against `values`. The triage form links to a Glasgow Coma Scale assessment when urgency is critical:
>
> ```json theme={null}
> "link_rules": [
>   {
>     "target_form": "gcs_assessment",
>     "description": "Critical urgency — GCS to assess neurological status.",
>     "when": { "field": "urgency", "op": "==", "value": "critical" }
>   }
> ]
> ```
>
> The client merges both sources, drops duplicates and forms already completed, and lets the clinician accept or dismiss each suggestion. A typical chain runs from triage to a SOAP note to a PHQ-9 screening. The link rules add a Glasgow Coma Scale assessment after a critical triage, and an SBAR handoff after a severe Glasgow Coma Scale score.
>
> When the clinician accepts, the client swaps the form. It keeps a snapshot of the current form's values, so the clinician can go back. It loads the target form schema and carries over values whose top-level key the new form also uses, so `patient` and `vitals` move from triage to the SOAP note. Then it sends the next `form_state` with the new `schema` and `schema_changed: true`. The client keeps the same `contextId`, so the agent still has the conversation history and knows the patient.

> [accordion] Conditional fields, computed fields, and Text Generation guidance
>
> The client keeps form logic out of the prompt. The agent fills whatever fields the current schema lists, and the client changes that schema.
>
> **Conditional fields.** A form schema's `enable_when` rules add a scalar field only when the values meet a condition. In the SOAP form, a high temperature reveals an antipyretics field:
>
> ```json theme={null}
> "enable_when": [
>   {
>     "id": "antipyretics",
>     "when": { "all": [{ "field": "max_temperature", "op": ">=", "value": 39 }] },
>     "field": { "path": "antipyretics_administered", "type": "string", "description": "Whether antipyretics (e.g. paracetamol/acetaminophen) were administered for the fever. ..." }
>   }
> ]
> ```
>
> Before each message, the client evaluates the rules and adds the active fields to `scalar_fields`. When that changes the schema, the client sends the full schema with `schema_changed: true`. A hidden field keeps its value in `values`, so the value returns if the field reappears.
>
> **Computed fields.** `computed_fields` derive values the agent never fills. The client runs them after it applies each patch. In PHQ-9, the agent sets the nine item scores `q1` to `q9`, and the client computes the total and the severity band:
>
> ```json theme={null}
> "computed_fields": [
>   { "path": "total_score", "description": "Sum of all nine question scores (0–27).", "compute": { "op": "sum", "fields": ["q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9"], "as": "number" } }
> ]
> ```
>
> The compute ops are `sum`, `lookup`, `max_in`, `min_in`, `concat`, `avg`, and `custom`. The `max_temperature` field that the antipyretics rule reads is itself computed, with `max_in` over the `vitals` collection.
>
> **Text Generation guidance.** A string field or collection can name a [Text Generation](https://docs.corti.ai/textgen/overview.md) section family, such as `"textgen": { "family": "corti-subjective" }` on `soap.subjective`. When a form opens, the client fetches the published [section](https://docs.corti.ai/textgen/section-creation.md) for each family and overlays it on the schema. The section's `contentPrompt` becomes the field's `description`, and its `writingStylePrompt` and `miscPrompt` become the `writing_guidance`. For a collection, the client converts the section's `outputSchema` into `item_fields`: the fields of the array's item object. The client then sends the enriched schema with `schema_changed: true`.
>
> Text Generation does not write the note. It supplies the instructions for how to write each section, and the agent still fills the form with `form_patch`. You can change how a section is written by editing it in the [Corti Console](https://docs.corti.ai/textgen/console-templates/get-started.md), without changing the flow. If no section is found, the field keeps the guidance written in the form schema.

## Adapt it

* Write one form schema per form you offer, with your own field paths, enums, descriptions, and writing guidance. `form_patch` and the system prompt stay the same.
* List every form in `form_catalog`, and write `when_to_use` and `triggers` in your clinicians' terms.
* Add `link_rules` for the next-form suggestions you always want, and leave the rest to the agent's judgment.
* Add `enable_when` and `computed_fields` for conditional fields and scores, so the client, not the prompt, owns that logic.
* Point string fields and collections at your own Text Generation sections, if you use them.
* Map the completed form to your EHR's write API in the client. Nothing is saved until the clinician confirms.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.