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.
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.
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:
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:
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:
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())
- num_pages
- 15
- first_page
- 95,744 bytes
A second small function pulls the text off that single page:
@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:
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)
- 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):
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):
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:
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:
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:
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:])))
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:
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_fileand of the@coco.fnfunctions it calls; - the context values it reads with
detect_change=True, hereEMBEDDER.
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.
Nothing is indexed yet, so every paper runs: one LLM call each, one embedding for the title and one per abstract chunk.
- 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
- 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
Each file keeps its path and content fingerprint, so every process_file is a memo hit and its rows carry over untouched.
- LLM calls
- 0 · 4 skipped
- embeddings
- 0 computed
- 1706.03762v7.pdfmemo hit
- 1810.04805v2.pdfmemo hit
- 2502.06786v3.pdfmemo hit
- 2502.20346v1.pdfmemo hit
- paper_metadatano writes
- author_papersno writes
- metadata_embeddingsno writes
- LLM calls
- 0 · 4 skipped
- embeddings
- 0 computed
- 1706.03762v7.pdfmemo hit
- 1810.04805v2.pdfmemo hit
- 2502.06786v3.pdfmemo hit
- 2502.20346v1.pdfmemo hit
- paper_metadatano writes
- author_papersno writes
- metadata_embeddingsno writes
Drop 2502.20346v1.pdf into a folder where the other 3 papers are indexed. They hit their memos. The new file has no memo entry, so it makes the only LLM call.
- LLM calls
- 1 · 3 skipped
- embeddings
- 4 computed
- 1706.03762v7.pdfmemo hit
- 1810.04805v2.pdfmemo hit
- 2502.06786v3.pdfmemo hit
- 2502.20346v1.pdfnewLLM call
- paper_metadata+1
- author_papers+5
- metadata_embeddings+4
- LLM calls
- 1 · 3 skipped
- embeddings
- 4 computed
- 1706.03762v7.pdfmemo hit
- 1810.04805v2.pdfmemo hit
- 2502.06786v3.pdfmemo hit
- 2502.20346v1.pdfnewLLM call
- paper_metadata+1
- author_papers+5
- metadata_embeddings+4
Re-save 1810.04805v2.pdf (BERT) without changing it. The modified time changed, so CocoIndex reads the file and compares its content fingerprint. It matches, so the memo is still valid.
- LLM calls
- 0 · 4 skipped
- embeddings
- 0 computed
- 1706.03762v7.pdfmemo hit
- 1810.04805v2.pdfmemo hit
- 2502.06786v3.pdfmemo hit
- 2502.20346v1.pdfmemo hit
- paper_metadatano writes
- author_papersno writes
- metadata_embeddingsno writes
- LLM calls
- 0 · 4 skipped
- embeddings
- 0 computed
- 1706.03762v7.pdfmemo hit
- 1810.04805v2.pdfmemo hit
- 2502.06786v3.pdfmemo hit
- 2502.20346v1.pdfmemo hit
- paper_metadatano writes
- author_papersno writes
- metadata_embeddingsno writes
Edit page 9 of 2502.06786v3.pdf (Matryoshka Quantization). The bytes changed, so process_file runs again. Page 1 is the same, so the LLM input is the same text.
- LLM calls
- 1 · 3 skipped
- embeddings
- 0 computed
- 1706.03762v7.pdfmemo hit
- 1810.04805v2.pdfmemo hit
- 2502.06786v3.pdfruns againLLM call
- 2502.20346v1.pdfmemo hit
- paper_metadatano writes
- author_papersno writes
- metadata_embeddings−5 +5
extract_metadata is not memoized, so the same page 1 is sent again. The 5 vectors come from the embed() memo, but uuid4() gives each row a new id: 5 deletes, 5 inserts.
- LLM calls
- 0 · 4 skipped
- embeddings
- 0 computed
- 1706.03762v7.pdfmemo hit
- 1810.04805v2.pdfmemo hit
- 2502.06786v3.pdfruns againLLM skipped (memo)
- 2502.20346v1.pdfmemo hit
- paper_metadatano writes
- author_papersno writes
- metadata_embeddingsno writes
The extract_metadata memo hits on the unchanged page-1 text. Stable ids match the old rows, so nothing is written.
Fix an author affiliation on page 1 of 1706.03762v7.pdf (Attention Is All You Need). The text the LLM sees changed, so this paper needs one new LLM call in both versions. Its title and abstract did not change.
- LLM calls
- 1 · 3 skipped
- embeddings
- 0 computed
- 1706.03762v7.pdfruns againLLM call
- 1810.04805v2.pdfmemo hit
- 2502.06786v3.pdfmemo hit
- 2502.20346v1.pdfmemo hit
- paper_metadata~1
- author_papersno writes
- metadata_embeddings−4 +4
The metadata row is updated. Author names are the same, so author_papers is untouched. The 4 embedding rows get new uuid4() ids.
- LLM calls
- 1 · 3 skipped
- embeddings
- 0 computed
- 1706.03762v7.pdfruns againLLM call
- 1810.04805v2.pdfmemo hit
- 2502.06786v3.pdfmemo hit
- 2502.20346v1.pdfmemo hit
- paper_metadata~1
- author_papersno writes
- metadata_embeddingsno writes
Only the metadata row is updated.
In the test run, the stub returned the original fields with one affiliation changed.
Delete 1810.04805v2.pdf (BERT). The file is gone, so its component is no longer mounted and every row it declared is deleted. No LLM call is needed.
- LLM calls
- 0 · 3 skipped
- embeddings
- 0 computed
- 1706.03762v7.pdfmemo hit
- 1810.04805v2.pdfdeleted
- 2502.06786v3.pdfmemo hit
- 2502.20346v1.pdfmemo hit
- paper_metadata−1
- author_papers−4
- metadata_embeddings−4
- LLM calls
- 0 · 3 skipped
- embeddings
- 0 computed
- 1706.03762v7.pdfmemo hit
- 1810.04805v2.pdfdeleted
- 2502.06786v3.pdfmemo hit
- 2502.20346v1.pdfmemo hit
- paper_metadata−1
- author_papers−4
- metadata_embeddings−4
Edit the system prompt. It is a literal inside the body of extract_metadata, so the edit changes its logic fingerprint. Every paper that called it must run again.
- LLM calls
- 4
- embeddings
- 0 computed
- 1706.03762v7.pdfruns againLLM call
- 1810.04805v2.pdfruns againLLM call
- 2502.06786v3.pdfruns againLLM call
- 2502.20346v1.pdfruns againLLM call
- paper_metadatano writes
- author_papersno writes
- metadata_embeddings−17 +17
All 17 embedding rows get new ids, even when the text is the same.
- LLM calls
- 4
- embeddings
- 0 computed
- 1706.03762v7.pdfruns againLLM call
- 1810.04805v2.pdfruns againLLM call
- 2502.06786v3.pdfruns againLLM call
- 2502.20346v1.pdfruns againLLM call
- paper_metadatano writes
- author_papersno writes
- metadata_embeddingsno writes
Rows are written only where the new output differs.
Counts for the prompt and model edits assume the model returns the same fields. A field that changes updates its row; a changed title or chunk is embedded again.
Set LLM_MODEL = "gpt-4.1". LLM_MODEL is a module constant. The logic fingerprint covers the function body, which names LLM_MODEL but does not contain its value.
- LLM calls
- 0 · 4 skipped
- embeddings
- 0 computed
- 1706.03762v7.pdfmemo hit
- 1810.04805v2.pdfmemo hit
- 2502.06786v3.pdfmemo hit
- 2502.20346v1.pdfmemo hit
- paper_metadatano writes
- author_papersno writes
- metadata_embeddingsno writes
Nothing re-runs. The 4 indexed papers keep the gpt-4o output, and only new or edited papers use gpt-4.1.
- LLM calls
- 4
- embeddings
- 0 computed
- 1706.03762v7.pdfruns againLLM call
- 1810.04805v2.pdfruns againLLM call
- 2502.06786v3.pdfruns againLLM call
- 2502.20346v1.pdfruns againLLM call
- paper_metadatano writes
- author_papersno writes
- metadata_embeddingsno writes
deps=LLM_MODEL makes the value part of the logic, so every paper is extracted again with the new model.
Counts for the prompt and model edits assume the model returns the same fields. A field that changes updates its row; a changed title or chunk is embedded again.
Set EMBED_MODEL to sentence-transformers/all-MiniLM-L12-v2. EMBEDDER is a context key with detect_change=True, and process_file reads it, so a new model invalidates every process_file memo.
- LLM calls
- 4
- embeddings
- 17 computed
- 1706.03762v7.pdfruns againLLM call
- 1810.04805v2.pdfruns againLLM call
- 2502.06786v3.pdfruns againLLM call
- 2502.20346v1.pdfruns againLLM call
- paper_metadatano writes
- author_papersno writes
- metadata_embeddings−17 +17
To get new vectors, the example also makes 4 LLM calls whose output it already has.
- LLM calls
- 0 · 4 skipped
- embeddings
- 17 computed
- 1706.03762v7.pdfruns againLLM skipped (memo)
- 1810.04805v2.pdfruns againLLM skipped (memo)
- 2502.06786v3.pdfruns againLLM skipped (memo)
- 2502.20346v1.pdfruns againLLM skipped (memo)
- paper_metadatano writes
- author_papersno writes
- metadata_embeddings~17
The extract_metadata memo hits for all 4 papers. Only the vectors are computed again, and the 17 rows are updated in place.
+ 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_MODELre-runs nothing. The logic fingerprint is computed from the function’s source code, and the body ofextract_metadatanamesLLM_MODELbut 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:
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),
...
),
)
memo=Trueonextract_metadatacaches the LLM result per paper, keyed by its page-1 text. Whenprocess_fileruns 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.deps=LLM_MODELmakes the model name part of the function’s logic. Changing it re-extracts every paper with the new model.UuidGeneratorgives 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.


