Extract Metadata from Research Paper PDFs with an LLM

Index academic papers with CocoIndex: read the first page of each PDF, extract title, authors, and abstract with an LLM, and embed them for semantic search.

TutorialUpdated 7 min read
Extract metadata from research paper PDFs with an LLM. Page 1 of Attention Is All You Need, with 8 authors and a 3-chunk abstract, goes through one gpt-4o call and becomes 13 Postgres rows: 1 paper_metadata row, 8 author_papers rows and 4 metadata_embeddings rows.
Enlarge cover

Extract Metadata from Research Paper PDFs with an LLM

Zoom in to see details.

Extract metadata from research paper PDFs with an LLM. Page 1 of Attention Is All You Need, with 8 authors and a 3-chunk abstract, goes through one gpt-4o call and becomes 13 Postgres rows: 1 paper_metadata row, 8 author_papers rows and 4 metadata_embeddings rows.

The first page of a paper holds the fields this example queries (title, authors and abstract), written as PDF prose. This walkthrough reads only that page, sends the text to an LLM with a fixed schema, validates the response into a pydantic object, and embeds the metadata so you can search papers by meaning. One PDF fans out into three Postgres tables, and CocoIndex keeps all three in sync as the folder changes.

The LLM call is the expensive step. The last sections show which changes to the folder or the code make CocoIndex call the LLM again, and three small edits that remove the calls you do not need.

The full code is in the CocoIndex v1 repo.

What we’ll build

Each PDF flows through one processing component: slice out the first page, pull its text, extract metadata with the LLM, and embed the title and abstract. The component declares rows into three tables.

paper_metadata/main.py→ three tables
source · walk_dirpapers/*.pdf · live
process_file · per PDF
First pagepypdf · page 1
LLM extracttitle · authors · abstract
Embed + declaretitle + abstract chunks
memo=True: skipped while the file, code and embedder are unchanged
postgrespaper_metadataone row per paper
postgresauthor_papersone row per author
postgres · pgvectormetadata_embeddingstitle + chunks

The three tables serve three kinds of queries. paper_metadata holds one row per paper for lookups and joins. author_papers maps each author name to a filename, so “all the papers by Jeff Dean” is a plain SQL WHERE. metadata_embeddings holds one vector per title and per abstract chunk, for semantic search with pgvector.

Define the models and rows

Two pydantic models describe what the LLM must return. If a response does not match them, model_validate_json raises, and no rows are declared for that paper.

models.py
from pydantic import BaseModel, Field


class AuthorModel(BaseModel):
    name: str
    email: str | None = None
    affiliation: str | None = None


class PaperMetadataModel(BaseModel):
    title: str
    authors: list[AuthorModel] = Field(default_factory=list)
    abstract: str

The pydantic models are the LLM contract only. What lands in Postgres is described separately, by three dataclasses, one per table. Keeping the two layers apart lets the table shape differ from the LLM’s: rows add filename and num_pages, and authors are stored as plain dicts. The embedding field is annotated with the embedder so CocoIndex infers the vector size:

main.py
import uuid
from dataclasses import dataclass
from typing import Annotated
from numpy.typing import NDArray

import cocoindex as coco
from cocoindex.ops.sentence_transformers import SentenceTransformerEmbedder

EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
EMBEDDER = coco.ContextKey[SentenceTransformerEmbedder]("embedder", detect_change=True)


@dataclass
class PaperMetadataRow:
    filename: str
    title: str
    authors: list[dict[str, str | None]]
    abstract: str
    num_pages: int


@dataclass
class AuthorPaperRow:
    author_name: str
    filename: str


@dataclass
class MetadataEmbeddingRow:
    id: uuid.UUID
    filename: str
    location: str
    text: str
    embedding: Annotated[NDArray, EMBEDDER]

The database pool and the embedder are created once, in the app lifespan:

main.py
import os
from typing import AsyncIterator

import asyncpg
from cocoindex.connectors import postgres

PG_DB = coco.ContextKey[asyncpg.Pool]("paper_metadata_db")


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

Read the first page

Papers can run long: the Attention Is All You Need PDF in the sample folder has 15 pages and 2,215,244 bytes, and 2502.20346v1.pdf has 53 pages. The metadata we want is on page one, so we slice it out with pypdf and do not send the rest anywhere:

main.py
import io
from pypdf import PdfReader, PdfWriter


@dataclass
class PaperBasicInfo:
    num_pages: int
    first_page: bytes


@coco.fn
def extract_basic_info(content: bytes) -> PaperBasicInfo:
    """Extract first page bytes and page count from a PDF."""
    reader = PdfReader(io.BytesIO(content))

    output = io.BytesIO()
    writer = PdfWriter()
    writer.add_page(reader.pages[0])
    writer.write(output)

    return PaperBasicInfo(num_pages=len(reader.pages), first_page=output.getvalue())
extract_basic_infopage 1 only
input1706.03762v7.pdf15 pages · 2,215,244 bytestitle · authors · abstract all on page 1
PaperBasicInfopypdf: PdfReader → PdfWriter
num_pages
15
first_page
95,744 bytes
a 1-page PDF, 4% of the original bytes
The other 14 pages are never sent anywhere.

A second small function pulls the text off that single page:

main.py
@coco.fn
def pdf_to_markdown(content: bytes) -> str:
    """Convert PDF bytes to text using pypdf."""
    reader = PdfReader(io.BytesIO(content))
    page_text = reader.pages[0].extract_text() if reader.pages else ""
    return page_text or ""

pypdf keeps the example dependency-light. If your PDFs have multi-column layouts, tables or scanned pages, swap this function’s body for Marker or Docling; the rest of the pipeline does not change.

Extract metadata with an LLM

One call turns the first-page prose into typed fields. The system prompt names the fields and response_format makes the model return JSON. temperature=0 reduces variation between runs but does not guarantee identical output. model_validate_json parses the response into the pydantic model:

main.py
import functools
from openai import OpenAI

LLM_MODEL = "gpt-4o"


@functools.cache
def openai_client() -> OpenAI:
    return OpenAI()


@coco.fn
def extract_metadata(markdown: str) -> PaperMetadataModel:
    """Extract paper metadata from first-page text using an LLM."""
    client = openai_client()
    response = client.chat.completions.create(
        model=LLM_MODEL,
        messages=[
            {
                "role": "system",
                "content": (
                    "You extract metadata from academic paper first pages. "
                    "Return only JSON with keys: title, authors, abstract. "
                    "authors is a list of {name, email, affiliation}. "
                    "Use null for missing fields."
                ),
            },
            {
                "role": "user",
                "content": markdown[:4000],
            },
        ],
        response_format={"type": "json_object"},
        temperature=0,
    )

    content = response.choices[0].message.content
    if not content:
        raise RuntimeError("LLM returned empty content.")
    return PaperMetadataModel.model_validate_json(content)
extract_metadataprose → typed fields
first_page_md · strAttention Is All You NeedAshish Vaswani* Noam Shazeer* Niki Parmar*Google Brain · Google Research · U. of Toronto“The dominant sequence transduction models are based on complex recurrent…”
one LLM callextract_metadatagpt-4o · JSON mode · temperature 0
model_validate_json
invalid or off-schema JSON
raises; no rows are declared
PaperMetadataModelvalidated fields
title · str
Attention Is All You Need
authors · list[AuthorModel] · 8
{name: "Ashish Vaswani", affiliation: "Google Brain"} + 7 more
abstract · str
“The dominant sequence transduction models are based on…”

Process one paper into three tables

process_file is the whole per-paper pipeline: read, slice, extract, embed, declare. app_main mounts it once per file. With memo=True, the next run skips a file and keeps its rows while the file, the code and the embedder are unchanged (details in Which changes send a paper back to the LLM):

main.py
from cocoindex.ops.text import CustomLanguageConfig, RecursiveSplitter
from cocoindex.resources.file import FileLike

_abstract_splitter = RecursiveSplitter(
    custom_languages=[
        CustomLanguageConfig(
            language_name="abstract",
            separators_regex=[r"[.?!]+\s+", r"[:;]\s+", r",\s+", r"\s+"],
        )
    ]
)


@coco.fn(memo=True)
async def process_file(
    file: FileLike,
    metadata_table: postgres.TableTarget[PaperMetadataRow],
    author_table: postgres.TableTarget[AuthorPaperRow],
    embedding_table: postgres.TableTarget[MetadataEmbeddingRow],
) -> None:
    content = await file.read()

    basic_info = extract_basic_info(content)
    first_page_md = pdf_to_markdown(basic_info.first_page)
    metadata = extract_metadata(first_page_md)

    metadata_table.declare_row(
        row=PaperMetadataRow(
            filename=str(file.file_path.path),
            title=metadata.title,
            authors=[a.model_dump() for a in metadata.authors],
            abstract=metadata.abstract,
            num_pages=basic_info.num_pages,
        ),
    )

    for author in metadata.authors:
        if author.name:
            author_table.declare_row(
                row=AuthorPaperRow(
                    author_name=author.name,
                    filename=str(file.file_path.path),
                ),
            )

    title_embedding = await coco.use_context(EMBEDDER).embed(metadata.title)
    embedding_table.declare_row(
        row=MetadataEmbeddingRow(
            id=uuid.uuid4(),
            filename=str(file.file_path.path),
            location="title",
            text=metadata.title,
            embedding=title_embedding,
        ),
    )

    abstract_chunks = _abstract_splitter.split(
        metadata.abstract,
        chunk_size=500,
        min_chunk_size=200,
        chunk_overlap=150,
        language="abstract",
    )
    for chunk in abstract_chunks:
        embedding_table.declare_row(
            row=MetadataEmbeddingRow(
                id=uuid.uuid4(),
                filename=str(file.file_path.path),
                location="abstract",
                text=chunk.text,
                embedding=await coco.use_context(EMBEDDER).embed(chunk.text),
            ),
        )

For Attention Is All You Need, the function declares 13 rows. The paper has 8 authors, and its abstract (1,138 characters as printed on page 1) splits into 3 chunks with these settings (sentence separators, chunk size 500, overlap 150). That gives 1 metadata row, 8 author rows and 4 embedding rows (the title plus the 3 chunks):

declare_row1 paper → 13 rows
1706.03762v7.pdfAttention Is All You Need8 authors · Vaswani et al.abstract · 1,138 chars → 3 chunks
paper_metadata× 1
1706.03762v7.pdf · “Attention Is All You Need” · 8 authors · 15 pages
author_papers · one row per author× 8
VaswaniShazeerParmarUszkoreitJonesGomezKaiserPolosukhin
metadata_embeddings · pgvector× 4
titlechunk 1chunk 2chunk 3
Deleting the PDF removes all 13 rows on the next run.

The abstract is chunked because one vector for a long abstract averages several topics; one vector per chunk lets a query match the part of the abstract it is about. Because process_file declares its rows, removing the PDF makes the next run delete all 13 rows from the three tables.

Wire up the app

app_main mounts the three target tables, walks the folder of PDFs, and runs one process_file per file:

main.py
import pathlib
from cocoindex.connectors import localfs
from cocoindex.resources.file import PatternFilePathMatcher

PG_SCHEMA_NAME = "coco_examples_v1"


@coco.fn
async def app_main(sourcedir: pathlib.Path) -> None:
    metadata_table = await postgres.mount_table_target(
        PG_DB,
        table_name="paper_metadata",
        table_schema=await postgres.TableSchema.from_class(
            PaperMetadataRow,
            primary_key=["filename"],
        ),
        pg_schema_name=PG_SCHEMA_NAME,
    )
    author_table = await postgres.mount_table_target(
        PG_DB,
        table_name="author_papers",
        table_schema=await postgres.TableSchema.from_class(
            AuthorPaperRow,
            primary_key=["author_name", "filename"],
        ),
        pg_schema_name=PG_SCHEMA_NAME,
    )
    embedding_table = await postgres.mount_table_target(
        PG_DB,
        table_name="metadata_embeddings",
        table_schema=await postgres.TableSchema.from_class(
            MetadataEmbeddingRow,
            primary_key=["id"],
        ),
        pg_schema_name=PG_SCHEMA_NAME,
    )

    files = localfs.walk_dir(
        sourcedir,
        recursive=True,
        path_matcher=PatternFilePathMatcher(included_patterns=["**/*.pdf"]),
        live=True,
    )
    await coco.mount_each(
        process_file, files.items(), metadata_table, author_table, embedding_table
    )


app = coco.App(
    coco.AppConfig(name="PaperMetadataV1"),
    app_main,
    sourcedir=pathlib.Path("./papers"),
)

mount_table_target creates each table and syncs its rows: it inserts new rows, updates changed rows, and deletes rows that are no longer declared. The embedding rows use uuid.uuid4() as their id, so each time a paper is processed again, its embedding rows get new ids: the old rows are deleted and new ones inserted. The demo below shows when that happens. live=True on walk_dir makes the source watchable; when you run with -L, a PDF you add is indexed without another command.

Run it

The example folder has four sample papers in papers/, including Attention Is All You Need, so you can run it before you add your own. Start Postgres with pgvector from the repo’s compose file, copy the environment template, add your OpenAI key, and build the index:

sh
git clone https://github.com/cocoindex-io/cocoindex.git
cd cocoindex/examples/paper_metadata
docker compose -f ../../dev/postgres.yaml up -d
cp .env.example .env    # set OPENAI_API_KEY; POSTGRES_URL already points at the compose database
pip install -e .
cocoindex update main

The cocoindex CLI loads .env from the current directory. The first run extracts and embeds every paper; later runs skip papers whose file, code and embedder are unchanged. Add -L (cocoindex update -L main) to watch the folder and update the index live.

Query the index

Semantic search embeds the query with the same model and asks Postgres for the nearest vectors; <=> is pgvector’s cosine distance. The query uses its own pool, created with init=register_vector so that asyncpg can send the numpy query vector as a pgvector value:

main.py
import asyncio
import sys
from dotenv import load_dotenv
from pgvector.asyncpg import register_vector


async def query_once(pool, embedder, query: str, *, top_k: int = 5) -> None:
    query_vec = await embedder.embed(query)
    async with pool.acquire() as conn:
        rows = await conn.fetch(
            """
            SELECT filename, location, text, embedding <=> $1 AS distance
            FROM "coco_examples_v1"."metadata_embeddings"
            ORDER BY distance ASC
            LIMIT $2
            """,
            query_vec,
            top_k,
        )
    for r in rows:
        score = 1.0 - float(r["distance"])
        print(f"[{score:.3f}] {r['filename']} ({r['location']})")
        print(f"    {r['text']}")


async def query(q: str) -> None:
    embedder = SentenceTransformerEmbedder(EMBED_MODEL)
    async with asyncpg.create_pool(os.getenv("POSTGRES_URL"), init=register_vector) as pool:
        await query_once(pool, embedder, q)


if __name__ == "__main__":
    load_dotenv()
    asyncio.run(query(" ".join(sys.argv[1:])))
sh
python main.py "sequence models without recurrence"

In the example, running python main.py with no argument starts an interactive query loop.

Matches come back from both titles and abstract chunks, with the location column telling you which. The author index needs no embeddings at all:

sql
SELECT filename FROM "coco_examples_v1"."author_papers"
WHERE author_name = 'Ashish Vaswani';

Which changes send a paper back to the LLM

On every run, CocoIndex decides per paper whether process_file must run again. Each paper’s component is keyed by its file path, and its memo stays valid while these are unchanged:

  • the file’s content fingerprint;
  • the logic of process_file and of the @coco.fn functions it calls;
  • the context values it reads with detect_change=True, here EMBEDDER.

embed() is memoized on its own, on the model and the text. extract_metadata is not, so whenever process_file runs again, the paper goes back to the LLM.

Pick a change and compare the example as shipped with the version that has the three edits from the next section:

Change the papers or the code, then count the LLM calls

Counts from running the example's memo structure on its four sample PDFs, with the LLM call replaced by a counter.

Run
Change papers/
Change main.py

Nothing is indexed yet, so every paper runs: one LLM call each, one embedding for the title and one per abstract chunk.

As shipped
examples/paper_metadata
LLM calls
4
embeddings
17 computed
  • 1706.03762v7.pdfnewLLM call
  • 1810.04805v2.pdfnewLLM call
  • 2502.06786v3.pdfnewLLM call
  • 2502.20346v1.pdfnewLLM call
  • paper_metadata+4
  • author_papers+22
  • metadata_embeddings+17
With the three editssame result
memo + deps on extract_metadata · stable ids
LLM calls
4
embeddings
17 computed
  • 1706.03762v7.pdfnewLLM call
  • 1810.04805v2.pdfnewLLM call
  • 2502.06786v3.pdfnewLLM call
  • 2502.20346v1.pdfnewLLM call
  • paper_metadata+4
  • author_papers+22
  • metadata_embeddings+17

+ inserted~ updated− deleted

Two results are easy to miss:

  • Swapping the embedding model re-runs the LLM for every paper in the shipped example. The extraction output does not depend on the embedder, but it is computed inside the same memoized component.
  • Changing LLM_MODEL re-runs nothing. The logic fingerprint is computed from the function’s source code, and the body of extract_metadata names LLM_MODEL but does not contain its value. Papers that are already indexed keep the old model’s output.

Three edits that remove unneeded LLM calls

The shipped example leaves these edits out to keep the code short; the demo’s second column shows their effect:

main.py
from cocoindex.resources.id import UuidGenerator


@coco.fn(memo=True, deps=LLM_MODEL)
def extract_metadata(markdown: str) -> PaperMetadataModel:
    ...  # body unchanged


@coco.fn(memo=True)
async def process_file(...) -> None:
    ...
    ids = UuidGenerator()
    embedding_table.declare_row(
        row=MetadataEmbeddingRow(
            id=ids.next_uuid(metadata.title),
            ...
        ),
    )
    for chunk in abstract_chunks:
        embedding_table.declare_row(
            row=MetadataEmbeddingRow(
                id=ids.next_uuid(chunk.text),
                ...
            ),
        )
  1. memo=True on extract_metadata caches the LLM result per paper, keyed by its page-1 text. When process_file runs again for another reason (an edit after page 1, a new embedding model, a change to the chunking code), the LLM call is skipped if page 1 has the same text.
  2. deps=LLM_MODEL makes the model name part of the function’s logic. Changing it re-extracts every paper with the new model.
  3. UuidGenerator gives the same id to the same text in the same paper on every run. A paper that is processed again then updates its embedding rows in place, or leaves them alone, instead of deleting and inserting them.

The extra memo stores one PaperMetadataModel per paper, and in exchange the LLM call is skipped whenever page 1 is unchanged. Adopting the edits changes the logic of both functions, so the first run after the change processes every paper once: 4 LLM calls, and all 17 embedding rows replaced with stable ids.

Where to go next

The shape here generalizes past papers: any document family with a metadata-rich region (contracts, invoices, intake forms) can use the same slice-extract-validate-embed pipeline. Swap the source for Amazon S3 or Google Drive, swap the target for Qdrant, or feed the metadata tables to an agent. For full-text embedding of the whole PDF body, see text embeddings 101.

Frequently asked questions

How do I extract structured metadata from academic PDFs with an LLM?

Send the first-page text to the LLM with a system prompt that pins the schema (title, authors, abstract), force JSON with response_format={"type": "json_object"}, set temperature=0 to reduce variation between runs, and parse the response with pydantic's model_validate_json. A response that does not match the schema raises a validation error, and no rows are declared for that paper. See Extract metadata with an LLM.

Why extract only the first page of each paper?

Title, authors, and abstract are on page one, and papers can be large: the sample Attention Is All You Need PDF has 15 pages and 2,215,244 bytes, while its first page alone is 95,744 bytes. Slicing page one with pypdf keeps the LLM input small, and the other 14 pages are never sent anywhere. See Read the first page.

How does one paper produce rows in three different tables?

The per-paper function receives three postgres.TableTarget handles and declares rows into each: one paper_metadata row, one author_papers row per author, and one metadata_embeddings row for the title plus one per abstract chunk. CocoIndex keeps all three tables in sync, including cleanup when a paper is removed. See Process one paper into three tables.

How do incremental updates work for this pipeline?

process_file is a memoized component (@coco.fn(memo=True)), so a paper whose content and code are unchanged is skipped and makes no LLM call. Editing the PDF, the extraction prompt or the embedding model runs it again. In the example as shipped, every re-run of process_file also calls the LLM; adding memo=True to extract_metadata skips the call when the page-1 text is the same. Run cocoindex update -L main to watch the folder. See What a re-run costs.

How do I find all papers by a given author?

Query the author_papers table, which holds one row per author name and filename: SELECT filename FROM author_papers WHERE author_name = 'Ashish Vaswani'. The lookup is plain SQL and uses no embeddings. See Query the index.

How do I run semantic search over titles and abstracts?

Embed the query with the same sentence-transformer model, then order by pgvector's cosine distance operator (embedding <=> $1) over the metadata_embeddings table. Each hit's location column tells you whether it matched the title or an abstract chunk. See Query the index.

Build fresh context for your agents.

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