Extracting Intake Forms with BAML and CocoIndex

Use BAML and CocoIndex v1 to extract typed patient records from PDF intake forms into Postgres with pgvector, and avoid the role("user") PDF gotcha on OpenAI.

TutorialUpdated 7 min read

Structured data from intake forms

BAML & CocoIndex

  1. Intake formPatient · address · medical history
  2. BAML extractionTyped, nested patient information
  3. {
      "name": "…",
      "address": { "city": "…" },
      "past_conditions": [],
      "pharmacy": null
    }

BAML and CocoIndex extract typed records from PDF intake forms with an LLM. BAML, from BoundaryML, is a typed prompt language: you write the output schema, the prompt, and the model client in .baml files, and it generates a Python client whose functions return Pydantic objects. CocoIndex reads the PDFs, calls that client once per form, and keeps one Postgres row per form in step with the folder, with a pgvector embedding of the visit for search.

This post covers the BAML side: the schema, the prompt, a provider gotcha with PDF input, and what happens to the cache when you edit a .baml file. The CocoIndex app is the same as in the DSPy version of this post, so it is shown once, in a collapsed block. For a no-framework baseline and a comparison of plain prompts, BAML, DSPy and a local Ollama model, see Extract patient intake forms with an LLM.

The BAML schema and function come from the patient intake example in the CocoIndex repo, which runs on CocoIndex v1 and writes one JSON file per form. This post writes to Postgres instead and adds the embedding.

  • Agents query typed fieldsWith a typed Patient in Postgres, an agent or a SQL query asks for patient_info->'insurance'->>'provider' or the medication list. It does not re-read the form on every question.
  • The schema is checked at the boundaryBAML parses the model's answer into the generated Pydantic class. A response that does not fit Patient raises in extract_patient_info, before a row is written.
  • One LLM call per changed formprocess_patient_form is memoized. A rerun skips every form whose bytes and code have not changed, so a run makes one Gemini call per new or changed form.
  • Edits and deletes reach the recordsA replaced PDF updates its row and a deleted PDF removes it. An agent does not answer from a record whose form is gone.

What you build

PatientIntakeExtractionBaml

main.py + baml_src/patient.baml

localfs.walk_dirdata/patient_forms/**/*.pdf
process_patient_form
extract_patient_infoBAML extractExtractPatientInfo · Gemini
Patient
EMBEDDERembed visit_summaryall-MiniLM-L6-v2
vector(384)
postgres · table.declare_rowpatientskey: filename
namereason_for_visitpatient_info jsonbembedding vector

Patient · baml_client.types
namedobgender
address Address
streetcitystatezip_code
phoneemailpreferred_contact_method
emergency_contact Contact
namephonerelationship
insurance Insurance?
providerpolicy_numbergroup_numberpolicyholder_namerelationship_to_patient
reason_for_visitsymptoms_duration
past_conditions Condition[]
namediagnosed
current_medications Medication[]
namedosage
allergies Allergy[]
name
surgeries Surgery[]
namedate
occupation
pharmacy Pharmacy?
namephone
address Address
streetcitystatezip_code
consent_givenconsent_date
  • Read the PDF intake forms from a local directory.
  • For each PDF, call the BAML function to get a typed Patient, and embed a short summary of the visit.
  • Write one row per form to a Postgres table: a few columns for the key fields, the whole Patient as jsonb, and the embedding as a pgvector vector.

The 4 sample forms that ship with the example use 4 different layouts. The extraction returns the same Patient shape for each. The values below come from a run of the BAML function over those forms:

data/patient_forms/ → patients.patient_info

4 layouts, 1 Patient shape

Patient_Intake_Form_Emily_Artificial.pdf3 pages, one labeled field per line
{
  "name": "Emily Carter",
  "dob": "07/22/1992",
  "gender": "Female",
  "address": {
    "street": "456 Oak Avenue",
    "city": "Denver",
    "state": "CO",
    "zip_code": "80203"
  },
  "phone": "(555) 678-9012",
  "email": "[email protected]",
  …
}
Patient_Intake_Form_David_Artificial.pdf2 pages, the whole address on one line
{
  "name": "David Thompson",
  "dob": "05/10/1980",
  "gender": "Male",
  "address": {
    "street": "789 Pine Street",
    "city": "Austin",
    "state": "TX",
    "zip_code": "73301"
  },
  "phone": "(555) 321-7890",
  "email": "[email protected]",
  …
}
Patient_Intake_Form_Joe_Artificial.pdf1 page, gender and contact method as checkboxes
{
  "name": "John Doe",
  "dob": "01/15/1985",
  "gender": "Male",
  "address": {
    "street": "123 Main St",
    "city": "Springfield",
    "state": "IL",
    "zip_code": "62701"
  },
  "phone": "(555) 123-4567",
  "email": "[email protected]",
  …
}
Patient_Intake_From_Jane_Artificial.pdf1 page, only name, DOB, gender and address
{
  "name": "Jane Doe",
  "dob": "01/16/1985",
  "gender": "Female",
  "address": {
    "street": "123 Main St",
    "city": "Springfield",
    "state": "IL",
    "zip_code": "62701"
  },
  "phone": "N/A",
  "email": "N/A",
  …
}

The Jane Doe form has no phone or email field, so those come back as "N/A", which the prompt asks for when a required field is missing.

Prerequisites

  1. Run Postgres with the pgvector extension. With Docker:

    sh
    docker run -d --name pgvector -p 5432:5432 \
      -e POSTGRES_USER=cocoindex -e POSTGRES_PASSWORD=cocoindex -e POSTGRES_DB=cocoindex \
      pgvector/pgvector:pg17
  2. Install CocoIndex with its Postgres and sentence-transformers extras, and the other dependencies:

    sh
    pip install -U "cocoindex[postgres,sentence_transformers]" baml-py==0.213.0 pgvector python-dotenv
  3. Create a .env file in the project directory. COCOINDEX_DB is the local file where CocoIndex keeps its state between runs, and POSTGRES_URL is the database that holds the patients table:

    sh
    COCOINDEX_DB=./cocoindex.db
    POSTGRES_URL=postgres://cocoindex:cocoindex@localhost/cocoindex
    GEMINI_API_KEY=your_api_key_here
  4. Copy a few intake forms to data/patient_forms/. The example ships 4 artificial PDFs in that folder.

Define Patient in patient.baml

Create a baml_src/ directory and save the schema as baml_src/patient.baml. The classes follow a FHIR-inspired patient schema, and the field map in the figure above shows how they nest. A plain type is required, ? makes a field optional, and [] makes it a list.

patient.baml
class Contact {
  name string
  phone string
  relationship string
}

class Address {
  street string
  city string
  state string
  zip_code string
}

class Pharmacy {
  name string
  phone string
  address Address
}

class Insurance {
  provider string
  policy_number string
  group_number string?
  policyholder_name string
  relationship_to_patient string
}

class Condition {
  name string
  diagnosed bool
}

class Medication {
  name string
  dosage string
}

class Allergy {
  name string
}

class Surgery {
  name string
  date string
}

class Patient {
  name string
  dob string
  gender string
  address Address
  phone string
  email string
  preferred_contact_method string
  emergency_contact Contact
  insurance Insurance?
  reason_for_visit string
  symptoms_duration string
  past_conditions Condition[]
  current_medications Medication[]
  allergies Allergy[]
  surgeries Surgery[]
  occupation string?
  pharmacy Pharmacy?
  consent_given bool
  consent_date string?
}

Write the extraction function

The same file declares the function. It takes a pdf and returns a Patient:

patient.baml
function ExtractPatientInfo(intake_form: pdf) -> Patient {
  client Gemini
  prompt #"
    Extract all patient information from the following intake form document.
    Please be thorough and extract all available information accurately.

    {{ _.role("user") }}
    {{ intake_form }}

    Fill in with "N/A" for required fields if the information is not available.

    {{ ctx.output_format }}
  "#
}
  • client Gemini picks the model client, declared below.
  • {{ intake_form }} inserts the PDF into the message.
  • {{ ctx.output_format }} is where BAML writes the output schema, derived from the return type, as instructions to the model.
  • {{ _.role("user") }} starts a user message. The next section shows why the PDF has to come after it.

The role("user") gotcha: where the PDF goes

Without a role marker, the whole prompt is a system message in BAML’s rendered prompt. What reaches the provider depends on the client: the OpenAI client sends a system message, and the Gemini and Anthropic clients send a user message. Pick a provider and toggle the line to see the request BAML sends and what happened to it:

Where the PDF lands, and what the provider does with it

Request bodies rendered with BAML 0.213.0
client
prompt

400 Bad Request The PDF is a file part inside the system message, and OpenAI rejects it there.

Invalid value: 'file'. Supported values are: 'text', 'refusal', 'image_url', and 'input_audio'. (param: messages[0].content[1])

Reported in BAML issue #2737 on gpt-4o, gpt-5-mini and gpt-5.1

baml_src/patient.baml
function ExtractPatientInfo(intake_form: pdf) -> Patient {
  client OpenAI
  prompt #"
    Extract all patient information from the following intake form document.
    Please be thorough and extract all available information accurately.
    {{ _.role("user") }}    {# no role line #}
    {{ intake_form }}
    Fill in with "N/A" for required fields if the information is not available.
    {{ ctx.output_format }}
  "#
}
POST api.openai.com/v1/chat/completions
  1. messages[0] role "system"
    1. text"Extract all patient information from the following intake form document. Please be thorough…"
    2. file{ filename: "document.pdf", file_data: "data:application/pdf;base64,…" }
    3. text"Fill in with \"N/A\" for required fields… Answer in JSON using this schema: {…}"
  • OpenAI rejects a file part in a system message. The call fails with 400 Bad Request and Invalid value: 'file', and the BAML function raises an exception. BAML issue #2737 reports it on gpt-4o, gpt-5-mini and gpt-5.1.
  • Gemini and Anthropic get the same request body with or without the line: BAML 0.213.0 sends this prompt to them as one user message. The prompt works there without the line, so the bug appears only when you switch the client to OpenAI.

Put {{ _.role("user") }} before {{ intake_form }}. The instructions above the line stay in the system message, and the PDF and everything after it go in a user message. That one line is the whole fix in the example.

We rendered the request bodies with BAML’s b.request API, which builds the HTTP request without sending it. Thanks to Deepu and Prashanth from the CocoIndex Discord for working through this with us in this thread.

Configure the client and the generator

The same file declares the client. Gemini reads the PDF directly as document input, so there is no separate parsing or OCR step.

patient.baml
client<llm> Gemini {
  provider google-ai
  options {
    model gemini-2.5-flash
    api_key env.GEMINI_API_KEY
  }
}

In the baml_src folder, add generators.baml:

generators.baml
generator python_client {
  output_type python/pydantic
  output_dir "../"
  version "0.213.0"
}

Run baml generate. It compiles the .baml files into a baml_client/ package in your project root:

  • baml_client.types holds the Pydantic classes (Patient and the classes it nests).
  • baml_client exports an async client object b. await b.ExtractPatientInfo(pdf) returns a Patient.

Call BAML from CocoIndex

extract_patient_info is the only place the CocoIndex app touches BAML: PDF bytes in, a typed Patient out. baml_py.Pdf.from_base64 wraps the raw bytes, and the generated b.ExtractPatientInfo runs the call.

main.py
@coco.fn
async def extract_patient_info(content: bytes) -> Patient:
    """Extract patient information from PDF content using BAML."""
    pdf = baml_py.Pdf.from_base64(base64.b64encode(content).decode("utf-8"))
    return await b.ExtractPatientInfo(pdf)

The return type is Patient, the class BAML generated, so everything downstream is typed. @coco.fn puts the function’s Python source under CocoIndex’s change tracking. The prompt is not in that source: it lives in patient.baml, which matters for caching.

The CocoIndex app

The rest of main.py is the same app as in the DSPy post, apart from the imports and the extraction call. Three parts carry it:

  • process_patient_form, decorated with @coco.fn(memo=True), runs once per PDF: it calls extract_patient_info, embeds a short visit summary, and declares one row with table.declare_row. If the PDF’s bytes and the code of the functions it calls are unchanged, the next run skips it, with no Gemini call and no embedding.
  • PatientRow is the table schema. patient_info: dict[str, Any] becomes a jsonb column, and the embedding field, annotated with the embedder, becomes a vector(384) column.
  • app_main mounts the patients table with postgres.mount_table_target, walks data/patient_forms/ with localfs.walk_dir, and mounts one processing component per file with coco.mount_each. A row is a target state: CocoIndex inserts, updates, or deletes it to match what the components declare.
The full main.py (imports, row schema, per-form component, app, search)
main.py
import asyncio
import base64
import os
import pathlib
import sys
from dataclasses import dataclass
from typing import Annotated, Any, AsyncIterator

import asyncpg
from dotenv import load_dotenv
from numpy.typing import NDArray
from pgvector.asyncpg import register_vector

import cocoindex as coco
from cocoindex.resources.file import FileLike, PatternFilePathMatcher
from cocoindex.connectors import localfs, postgres
from cocoindex.ops.sentence_transformers import SentenceTransformerEmbedder
from baml_client import b
from baml_client.types import Patient
import baml_py

DATABASE_URL = os.getenv(
    "POSTGRES_URL", "postgres://cocoindex:cocoindex@localhost/cocoindex"
)
EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
TABLE_NAME = "patients"

PG_DB = coco.ContextKey[asyncpg.Pool]("patient_intake_db")
EMBEDDER = coco.ContextKey[SentenceTransformerEmbedder]("embedder", detect_change=True)


@dataclass
class PatientRow:
    filename: str
    name: str
    reason_for_visit: str
    patient_info: dict[str, Any]
    embedding: Annotated[NDArray, EMBEDDER]


@coco.lifespan
async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
    async with asyncpg.create_pool(DATABASE_URL) as pool:
        builder.provide(PG_DB, pool)
        builder.provide(EMBEDDER, SentenceTransformerEmbedder(EMBED_MODEL))
        yield


@coco.fn
async def extract_patient_info(content: bytes) -> Patient:
    """Extract patient information from PDF content using BAML."""
    pdf = baml_py.Pdf.from_base64(base64.b64encode(content).decode("utf-8"))
    return await b.ExtractPatientInfo(pdf)


@coco.fn
def visit_summary(patient: Patient) -> str:
    """The text to embed: why the patient came in, and their history."""
    conditions = ", ".join(c.name for c in patient.past_conditions)
    medications = ", ".join(m.name for m in patient.current_medications)
    return (
        f"Reason for visit: {patient.reason_for_visit}\n"
        f"Symptoms duration: {patient.symptoms_duration}\n"
        f"Past conditions: {conditions}\n"
        f"Current medications: {medications}"
    )


@coco.fn(memo=True)
async def process_patient_form(
    file: FileLike, table: postgres.TableTarget[PatientRow]
) -> None:
    """Extract one intake form, embed its visit summary, and declare its row."""
    content = await file.read()
    patient_info = await extract_patient_info(content)
    embedding = await coco.use_context(EMBEDDER).embed(visit_summary(patient_info))
    table.declare_row(
        row=PatientRow(
            filename=file.file_path.path.name,
            name=patient_info.name,
            reason_for_visit=patient_info.reason_for_visit,
            patient_info=patient_info.model_dump(mode="json"),
            embedding=embedding,
        ),
    )


@coco.fn
async def app_main(sourcedir: pathlib.Path) -> None:
    """Main application function that processes patient intake forms."""
    table = await postgres.mount_table_target(
        PG_DB,
        table_name=TABLE_NAME,
        table_schema=await postgres.TableSchema.from_class(
            PatientRow, primary_key=["filename"]
        ),
    )
    files = localfs.walk_dir(
        sourcedir,
        path_matcher=PatternFilePathMatcher(included_patterns=["**/*.pdf"]),
    )
    await coco.mount_each(process_patient_form, files.items(), table)


app = coco.App(
    coco.AppConfig(name="PatientIntakeExtractionBaml"),
    app_main,
    sourcedir=pathlib.Path("./data/patient_forms"),
)


async def search(query: str, top_k: int = 3) -> None:
    embedder = SentenceTransformerEmbedder(EMBED_MODEL)
    query_vec = await embedder.embed(query)
    async with asyncpg.create_pool(DATABASE_URL, init=register_vector) as pool:
        rows = await pool.fetch(
            f"""
            SELECT name, reason_for_visit, embedding <=> $1 AS distance
            FROM {TABLE_NAME}
            ORDER BY distance
            LIMIT $2
            """,
            query_vec,
            top_k,
        )
    for r in rows:
        print(f"[{1.0 - r['distance']:.3f}] {r['name']}: {r['reason_for_visit']}")


if __name__ == "__main__":
    load_dotenv()
    asyncio.run(search(" ".join(sys.argv[1:])))

Run it

Generate the BAML client, if you have not yet, then run the app. The update scans the forms, extracts, embeds, writes the rows, and exits:

sh
baml generate
cocoindex update main.py

The patients table now has one row per form:

text
filename                                  | name           | reason_for_visit
------------------------------------------+----------------+-------------------------------------
Patient_Intake_Form_David_Artificial.pdf  | David Thompson | Knee pain
Patient_Intake_Form_Emily_Artificial.pdf  | Emily Carter   | Severe migraines
Patient_Intake_Form_Joe_Artificial.pdf    | John Doe       | Occasional dizziness in the morning
Patient_Intake_From_Jane_Artificial.pdf   | Jane Doe       | N/A

The patient_info column holds the full record, so Postgres can query any field in it, for example patient_info->'address'->>'city'.

python main.py "<query>" runs the search at the end of main.py: it embeds the query with the same model and orders the rows by pgvector’s cosine distance (<=>), so 1 - distance is the cosine similarity. None of the forms uses the words in these queries. We tested the search against Postgres 17 with pgvector, with the extraction filled in from the values written on each sample form:

sh
python main.py "headache"
# [0.496] Emily Carter: Severe migraines
# [0.327] John Doe: Occasional dizziness in the morning
# [0.311] Jane Doe: N/A

python main.py "joint injury"
# [0.378] David Thompson: Knee pain
# [0.141] Jane Doe: N/A
# [0.077] John Doe: Occasional dizziness in the morning

The Jane Doe form has no visit details, so its summary is mostly N/A and it ranks in the middle of most queries. Add WHERE reason_for_visit <> 'N/A' to the query to leave such records out.

What invalidates the cache

Run cocoindex update main.py again after a change, and CocoIndex does only the work the change needs. We checked each case below against the same Postgres table:

  • Nothing changed: every form is a cache hit, and the run makes no LLM call.
  • A form is added: only that PDF is extracted and embedded, and its row is inserted.
  • A form is replaced: it is extracted again and its row is updated. The other forms are skipped.
  • A form is deleted: its component is not mounted on the next run, so CocoIndex deletes the row it declared.
  • The Python code of process_patient_form, extract_patient_info, or visit_summary changes: every form is processed again.

CocoIndex tracks the Python source of @coco.fn functions, and the schema and prompt sit in patient.baml, outside it. An edit to patient.baml leaves every form cached, even after baml generate. To re-extract after such an edit, do one of these:

  • Run cocoindex update main.py --full-reprocess once, which bypasses every cache for that run.
  • Add version= to @coco.fn on extract_patient_info and increase it with each schema or prompt change. With version set, CocoIndex tracks that number instead of the function’s source code.
  • Pass the file’s text as deps=, for example @coco.fn(deps=pathlib.Path("baml_src/patient.baml").read_text()). A change to the file then counts as a change to the function’s logic.

The DSPy post has an interactive table of which edits re-run which forms. The same rules apply here, with patient.baml in the place of models.py.

Frequently asked questions

What is BAML and how does it work with CocoIndex?

BAML, created by BoundaryML, is a typed prompt engineering language that turns prompts into typed functions with defined input parameters, output schemas, and model configurations. BAML describes the output schema and prompt, while CocoIndex reads the PDF files, runs the extraction once per form, and keeps one Postgres row per form in sync with the source folder.

See What you build and The CocoIndex app.

How do you extract structured data from PDF intake forms with BAML and CocoIndex?

The app walks a directory for PDF files with localfs.walk_dir and mounts one process_patient_form component per file with coco.mount_each. Each component calls a BAML function to get a typed Patient, embeds a summary of the visit, and declares one row in a Postgres table with table.declare_row. You define the schema and an ExtractPatientInfo function in BAML, generate a Python client, and call it from a @coco.fn function.

See What you build.

Why must you set role("user") before injecting a PDF in a BAML prompt?

Without a role marker, BAML puts the whole prompt in one system message, and OpenAI rejects a file part there: the call fails with 400 Bad Request and Invalid value: 'file' (reported on gpt-4o, gpt-5-mini and gpt-5.1 in BAML issue #2737). Put {{ _.role("user") }} before {{ intake_form }} so the PDF goes in a user message. For Gemini and Anthropic, BAML 0.213.0 sends the same request with or without the line, which is why the prompt works there and the bug appears only on OpenAI.

See The role("user") gotcha.

How does CocoIndex avoid re-running the LLM on unchanged forms?

process_patient_form is decorated with @coco.fn(memo=True). If a PDF's content and the code of the functions it calls are unchanged, the next cocoindex update skips that form: no Gemini call and no embedding. An added or replaced form is processed, and a deleted form's row is removed from the table.

See The CocoIndex app and What invalidates the cache.

Does CocoIndex re-extract the forms when I change the BAML schema or prompt?

Not on its own. CocoIndex tracks the Python source of @coco.fn functions, and the BAML schema and prompt live in patient.baml. After you edit it and run baml generate, run cocoindex update main.py --full-reprocess once, add version= to @coco.fn on extract_patient_info and increase it with each change, or pass the file's text as deps=.

See What invalidates the cache.

Which Gemini model does this BAML example use, and how is the client configured?

The example configures a client<llm> Gemini block with provider google-ai, model gemini-2.5-flash, and api_key env.GEMINI_API_KEY. The BAML ExtractPatientInfo function references this client via client Gemini. Gemini reads the PDF as vision input, so there is no separate parsing or OCR step.

See Configure the client and the generator.

How do you generate the BAML Python client?

You add a generator python_client block in baml_src/generators.baml with output_type python/pydantic, then run baml generate. This compiles the .baml definitions into a baml_client/ package: baml_client.types holds the Pydantic classes such as Patient, and baml_client exports a client object b, so await b.ExtractPatientInfo(pdf) returns a Patient.

See Configure the client and the generator.

Where does the extracted patient data get stored?

In a Postgres table named patients, keyed by the PDF's file name. postgres.mount_table_target creates the table from the PatientRow dataclass: name and reason_for_visit as text, the whole Patient as jsonb in patient_info, and the embedding as a pgvector vector(384). CocoIndex inserts, updates, or deletes rows to match the source folder.

See The CocoIndex app.

How do you search the extracted patient records with pgvector?

Each row stores an embedding of a short visit summary: the reason for the visit, its duration, past conditions, and current medications, embedded with all-MiniLM-L6-v2. To search, embed the query with the same model and order the rows by pgvector's cosine distance, embedding <=> $1. A search for "headache" returns the patient whose form says "Severe migraines" first, although no form uses the word.

See Run it.

Build fresh context for your agents.

CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.