Your PDF parser gets HTML, and the ingestion job still looks successful. Somewhere upstream, bestOaUrl became shorthand for “download the paper.”

That shortcut is tempting when you're turning scholarly search results into a reading pipeline. The catch: the Actor returns records and links, not fetched article bodies. URL availability and extraction quality are untested here.

Lab note 179: can we choose an acquisition path from these fields without guessing what a URL serves? Our bet is that preserving their distinctions gives the fetcher enough information to make a sensible attempt.

Which URL belongs in the text fetcher?

A free copy, a landing page, and machine-readable text describe different acquisition responsibilities.

For our worked example, the Actor exposes contentUrls.pdf and contentUrls.grobidXml for OpenAlex's cached copies when hasFulltext is true. Its oaLocations describes publisher and repository copies, including license, version, and source evidence.

An open-access URL is a discovery clue, not a parser contract.

This routing sketch keeps that distinction visible:

work record ├─ cached TEI link ────────> fetch and validate TEI ├─ cached PDF link ────────> fetch and validate PDF └─ discovered OA location > resolve and classify response | selected copy | extract, then chunk 

These are candidates, not instructions to ingest every copy.

For a section-aware corpus, we'd prefer validated TEI when available. Structured sections give the chunker boundaries it otherwise has to infer from PDF extraction. That's an engineering preference, not a claim that every TEI file is clean.

The fields that earn their place

The task is narrow: acquire readable text, preserve the selected copy's provenance, and prepare grounded chunks. Citation ranking and author analysis can wait.

Field or input Decision it supports Treatment
openAccessOnly Restrict discovery to works with a free, legal full-text copy Use for OA discovery
hasFulltextOnly Restrict discovery to works where OpenAlex has machine-readable full text Use when cached-text coverage is the goal
includeOpenAccessLocations Include OA copies and available cached full-text links Keep enabled
isOa, hasFulltext Describe work-level availability Retain as context, never as fetch validation
contentUrls.grobidXml Identify a cached TEI candidate Keep in the TEI lane
contentUrls.pdf Identify a cached PDF candidate Keep in the PDF lane
oaLocations Preserve discovered copies and their license, version, and source evidence Keep each location intact
bestOaUrl, openAccessOaUrl Supply convenient discovery URLs Keep as unresolved hints
openalexId Anchor acquisition and chunks to a work Carry through the pipeline

The discovery filters answer different questions. Restricting a corpus to cached machine-readable text can exclude works that still have accessible copies elsewhere.

Choose that restriction deliberately. Otherwise, acquisition convenience quietly becomes a corpus inclusion policy.

Keep acquisition evidence out of the reading prompt

Your fetcher needs alternatives. Your answering model needs the text you actually selected.

Keep the acquisition plan in storage, including unsuccessful candidates. Send the model the chosen chunk and enough provenance to trace it back. A pile of alternative URLs makes poor supporting evidence.

For this task, we'd drop citation metrics, author affiliations, topic hierarchies, and cost metadata from the prompt projection. They can remain useful elsewhere in the system without consuming the reading budget.

We'd also keep the abstract separate from full-text chunks. An abstract can support screening, but silently substituting it after a failed download changes what “read the paper” means.

Deduplication needs the same restraint. A shared work identifier groups candidates; it doesn't establish that a preprint and a published version contain identical text. Group by work, compare content, and preserve the copy you chose.

Build a plan without guessing location keys

This planner separates cached format candidates from intact OA location records and scalar URL hints.

import hashlib import json def acquisition_plan(record): content = record.get("contentUrls") cached = content if isinstance(content, dict) else {} candidates = [] for lane, field in (("tei", "grobidXml"), ("pdf", "pdf")): url = cached.get(field) if isinstance(url, str) and url.strip(): candidates.append({ "lane": lane, "url": url, "oa_location": None, }) locations = record.get("oaLocations") locations = locations if isinstance(locations, list) else [] hints = [] for field in ("bestOaUrl", "openAccessOaUrl"): url = record.get(field) if isinstance(url, str) and url.strip(): hints.append({"field": field, "url": url}) return { "work_id": record.get("openalexId"), "availability": { "isOa": record.get("isOa"), "hasFulltext": record.get("hasFulltext"), }, "cached_candidates": candidates, "oa_locations": locations, "unresolved_hints": hints, "unparsed_content_urls": ( content if content is not None and not isinstance(content, dict) else None ), } 

Location entries stay intact instead of being flattened into guessed properties. Your location adapter needs to resolve those entries against the returned structure before producing fetch candidates.

We'd rather leave a candidate unresolved than invent a convenient field.

Example synthetic metadata illustrates the split without making any network requests.

example_record = { "openalexId": "Example work", "isOa": True, "hasFulltext": True, "bestOaUrl": "https://example.org/article", "contentUrls": { "pdf": "https://example.org/cached.pdf", "grobidXml": "https://example.org/cached.tei", }, "oaLocations": [], } example_plan = acquisition_plan(example_record) 

The cached candidates receive format hints from their fields. The scalar URL remains unresolved, even though its spelling looks harmless.

No filename extension gets promoted to evidence.

Let the response choose the parser

This fetch stage bounds the response body, follows a bounded redirect chain, checks status, and preserves headers for classification.

import httpx def fetch_candidate(url, max_bytes=8_000_000): if httpx.URL(url).scheme not in {"http", "https"}: raise ValueError("Expected an HTTP URL") with httpx.Client( timeout=30.0, follow_redirects=True, max_redirects=5, ) as client: with client.stream("GET", url) as response: response.raise_for_status() body = bytearray() for part in response.iter_bytes(chunk_size=65_536): if len(body) + len(part) > max_bytes: raise ValueError("Download exceeds the byte budget") body.extend(part) return { "requested_url": url, "final_url": str(response.url), "redirects": [ str(hop.url) for hop in response.history ], "response_headers": list( response.headers.multi_items() ), "body": bytes(body), } 

The function is defined here without fetching the synthetic URLs.

Before dispatching a parser, compare the media type declared in the response headers with the body. Check a PDF signature before PDF extraction; parse XML and verify the TEI root before treating it as TEI.

HTML belongs back in discovery or in a review queue. Giving a landing page to a document parser doesn't become correct because the request returned successfully. HTTP has a limited sense of achievement.

At corpus scale, reuse a client across fetches and record failures per candidate. A failed cached download can trigger another acquisition attempt; it shouldn't silently turn an abstract into full text.

Give each chunk a copy identity

This serializer attaches the selected acquisition evidence to extracted text and rejects oversized chunks instead of silently clipping them.

def serialize_chunk( plan, candidate, final_url, parser, text, max_chars=8_000 ): if not plan["work_id"]: raise ValueError("A work identity is required") if not text.strip(): raise ValueError("Empty text is not a reading chunk") if len(text) > max_chars: raise ValueError("Split the text before serialization") envelope = { "work_id": plan["work_id"], "requested_url": candidate["url"], "source_url": final_url, "selected_format": parser, "oa_location": candidate.get("oa_location"), "text_sha256": hashlib.sha256( text.encode("utf-8") ).hexdigest(), "text": text, } return json.dumps({ "instruction": ( "Answer from the supplied text. Cite work_id and source_url." ), "chunk": envelope, }, ensure_ascii=False) 

For a discovered copy, the adapter should attach its original location entry as oa_location. That preserves available license, version, and source evidence without inventing normalized fields.

For a cached candidate, that value remains empty unless you've evidence connecting it to a particular location. Don't borrow a repository copy's license merely because both URLs belong to the same work.

The hash flags identical chunk text for comparison. It isn't permission to erase provenance, and it won't detect near-duplicate versions.

The character guard is a transport limit, not a token count. Split text upstream using your tokenizer budget and document boundaries; preserve headings with their following content where possible.

Where the shortcut breaks

The OpenAlex Citation & Open-Access Works Explorer gives us enough separation to build an acquisition plan. It doesn't supply extracted article bodies or establish that a candidate will download successfully.

Flattening everything into bestOaUrl doesn't work as an ingestion contract. It discards the distinction between a cached format candidate and a discovered destination before the fetcher can use it.

A work-level availability flag also can't validate a particular response. Neither can it settle downstream reuse policy: retain copy-specific license evidence for the system making that decision.

Our verdict is plain: the schema supports separate acquisition lanes. Parser selection still belongs after fetching, and provenance belongs beside the resulting text.

Reproduce the routing decision

Use a discovery input that permits OA copies beyond cached full text, then inspect the plans before adding extraction.

  1. Set APIFY_TOKEN in your environment.
  2. Run the following cell after the function definitions.
  3. Inspect plans, resolve location entries, and validate fetched responses before calling serialize_chunk.

This cell acquires records and builds plans; it doesn't download article bodies.

import os from apify_client import ApifyClient run_input = { "mode": "searchWorks", "searchQuery": "large language models", "openAccessOnly": True, "hasFulltextOnly": False, "includeOpenAccessLocations": True, "perPage": 3, "maxItems": 3, } client = ApifyClient(os.environ["APIFY_TOKEN"]) run = client.actor( "vexaloom-labs/openalex-citation-and-open-access-works-explorer" ).call(run_input=run_input) items = client.dataset(run["defaultDatasetId"]).list_items().items plans = [acquisition_plan(item) for item in items] 

Keep cached-text filtering off for this inspection so it doesn't decide which OA copies your fetcher gets to consider. Paste this exact discovery request into the input editor:

{ "mode": "searchWorks", "searchQuery": "large language models", "openAccessOnly": true, "hasFulltextOnly": false, "includeOpenAccessLocations": true, "perPage": 3, "maxItems": 3 } 

Drafted with AI assistance and reviewed for accuracy.