Upload, extract, summarize: building the pipeline behind the button

Builders using AI app generators and no-code platforms often hit the same wall. The interface comes together quickly, but the core feature, letting a user upload a document and having an AI analyse it, parse it and extract structured information, refuses to work. Files are too large, the API key is exposed in the browser, the model cannot read PDFs directly, or answers come back as unparseable prose.
This guide walks through the pipeline behind that upload button, step by step. It is written for people building on visual or low-code platforms who can add a small backend function, and for developers helping them. You will get a clear architecture, working code for the key steps, and a list of limits to respect.
The examples call the keyless free-ai endpoint so you can prototype without a key; swap the base URL and model when you move to a paid provider. This site is not affiliated with OpenAI. Note that free-ai is text only, so documents must be converted to text before analysis.
Frequently asked questions
Can a language model read a PDF directly?
Some commercial APIs accept files or images and extract text for you. Text-only endpoints, including the free one here, need plain text. Converting the document yourself also gives you more control over what is sent and how much it costs.
What is chunking?
Splitting a long document into smaller pieces that each fit within the model's context window. Each chunk is analysed separately and the results are combined. Good chunking follows natural boundaries such as headings or paragraphs.
How does extraction differ from summarization?
Extraction pulls specific fields, such as dates, names, totals or clauses, into a fixed structure. Summarization condenses content into shorter prose. Extraction is easier to validate and to use in an app; summaries are better for human reading.
Why not call the API directly from the browser?
With a paid provider, a browser call exposes your key to anyone who opens developer tools. A small backend function keeps the key secret, enforces limits per user and lets you validate files before they reach the model.
Which is better for scanned documents, OCR or a vision model?
Dedicated OCR is cheaper and predictable for clean scans. Vision-capable commercial models handle messy layouts, handwriting and tables better. A text-only model like free-ai needs an OCR step first and cannot see images itself.
How large a document can free-ai handle?
The context window is 32,000 tokens, shared between your prompt and the answer, and answers can be up to 16,000 tokens. Longer documents must be chunked. In practice, chunks of a few thousand tokens give more reliable extraction than filling the window.
Is it safe to send user documents to an AI API?
Only if your users know and agree, and if the provider's data terms fit your obligations. Remove personal data you do not need before sending. The free endpoint keeps a technical log per request but no conversation content between calls.
What does stateless mean for document chat?
The API does not remember previous requests. If users ask follow-up questions about a document, your backend must resend the relevant text or extracted data with each question.
Step by step
- Add a backend function — Create a serverless or webhook endpoint on your platform that accepts a file upload and returns JSON.
- Convert the file to text — Use a PDF or Word library for text documents and route scanned files to OCR; clean headers, footers and whitespace.
- Split into chunks — Break the text on paragraph boundaries into pieces of a few thousand words with a small overlap.
- Extract with a strict prompt — Send each chunk with a system prompt that defines an exact JSON schema, at low temperature, and validate the reply.
- Merge and store — Combine chunk results, remove duplicates, optionally summarize, and save the output in your app's database.
- Wire up the interface — Connect the upload widget to the endpoint, show progress, and bind the stored fields to your display components.
The architecture in one picture
A reliable document feature has four stages. The browser uploads a file to your backend. The backend converts it to plain text and splits it into chunks. Each chunk goes to the model with a precise extraction prompt. The backend merges the results, validates them and stores them for the interface to display.
No-code platforms usually provide the first and last stages: file upload widgets and a database. The middle two belong in a backend function, which most platforms support through serverless functions, edge functions or an external webhook.
Why a backend function
Conversion libraries, chunking logic and API calls are easier to write and test in a few dozen lines of code than in visual workflow blocks, and they keep any keys off the client.
Keep the browser thin
The browser should upload, show progress and render results. Every decision about what to send to the model lives on the server.
Converting documents to text
Start by turning each upload into clean text. Text-based PDFs can be read with a library such as pypdf; Word files with python-docx; plain text and Markdown need nothing. Scanned PDFs and photos need OCR first, since there is no text layer to read.
Clean the result before sending it anywhere. Remove repeated headers and footers, page numbers and long runs of whitespace. These add tokens and confuse extraction without carrying meaning.
Detect empty extractions
If a PDF yields almost no text, it is probably scanned. Tell the user or route it to OCR instead of sending an empty prompt.
from pypdf import PdfReader
import re
def pdf_to_text(path: str) -> str:
reader = PdfReader(path)
pages = [page.extract_text() or "" for page in reader.pages]
text = "\n".join(pages)
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
print(pdf_to_text("sample.pdf")[:500])
Chunking long documents sensibly
Even when a document technically fits in the context window, extraction is more accurate on smaller pieces. Split on headings or blank lines and aim for chunks of roughly a few thousand words, with a small overlap so that a sentence cut at a boundary appears in both chunks.
A rough rule is that one token is about three quarters of an English word, so a 3,000-word chunk is around 4,000 tokens. That leaves plenty of room in a 32,000-token window for instructions and the answer.
Very long paragraphs
If a single paragraph exceeds the chunk size, split it by sentences. Tables extracted from PDFs often arrive as one giant paragraph and need this treatment.
def chunk_text(text: str, max_words: int = 2500, overlap: int = 150) -> list[str]:
paras = [p for p in text.split("\n\n") if p.strip()]
chunks, current = [], []
for p in paras:
words = p.split()
if current and len(current) + len(words) > max_words:
chunks.append(" ".join(current))
current = current[-overlap:]
current.extend(words)
if current:
chunks.append(" ".join(current))
return chunksWriting the extraction prompt
Ask for exactly the fields you need, in a fixed JSON shape, and say what to do when a field is missing. Vague requests like analyse this document produce essays that your app cannot use. Specific requests produce data.
Include a short description of the document type if you know it. A model extracts invoice totals far more reliably when told it is reading an invoice.
Validate every result
Parse the JSON, check required keys and types, and retry once with the error message if it fails. Our article on reliable JSON output covers this loop in depth.
Low temperature for extraction
Extraction is not a creative task. A temperature near zero makes answers more consistent across chunks and reruns.
import json
from openai import OpenAI
client = OpenAI(base_url="https://api.apifreekeyopenai.com/v1", api_key="not-needed")
SYSTEM = (
"You extract data from business documents. Reply with JSON only, no prose. "
'Schema: {"parties": [string], "dates": [string], "amounts": [string], '
'"key_points": [string]}. Use empty lists when nothing is found.'
)
def extract(chunk: str) -> dict:
r = client.chat.completions.create(
model="free-ai",
messages=[{"role": "system", "content": SYSTEM},
{"role": "user", "content": chunk}],
temperature=0,
max_tokens=800,
)
raw = r.choices[0].message.content.strip()
raw = raw.removeprefix("```json").removeprefix("```").removesuffix("```").strip()
return json.loads(raw)
Merging results across chunks
Each chunk returns its own partial result. Merge lists by concatenating and removing duplicates, and for single-value fields such as a document date, prefer the first confident value or ask the model to reconcile conflicts in a final short call.
For a human-readable overview, run one more request that takes the merged data, not the original text, and writes a short summary. This keeps the final call small and cheap.
Deduplicate loosely
The same party may appear as a full company name in one chunk and an abbreviation in another. Normalize case and whitespace, and consider a final reconciliation prompt for names.
Connecting it to a no-code front end
Expose the pipeline as a single HTTP endpoint on your backend that accepts a file and returns JSON. In the no-code builder, wire the upload widget to that endpoint and bind the response fields to your display components. Store the result in the platform's database so users do not re-run analysis every time they open a page.
If the platform's AI generator writes the backend for you, give it precise instructions: the base URL, the model name, the limits and the response schema. The text at /prompt.txt is written for exactly that purpose and can be pasted into a coding assistant as context.
Show progress
Analysis of a long document takes many seconds. Return a job ID immediately and let the front end poll for status, or stream progress, so users do not think the app froze.
Limit file size
Reject files above a sensible size in the backend before any conversion. It protects your budget and the free endpoint's per-IP allowance.

Respecting limits and costs
Every chunk is one request. A fifty-page document might be fifteen chunks plus a summary call. On the free endpoint, that is fine for a prototype but subject to about one request per second per IP, two concurrent requests, and 503 responses when the server is busy. Queue chunks rather than firing them all at once.
On a paid provider, estimate tokens per document and multiply by expected uploads before launching. Check the provider's current pricing page; large documents can be costly if processed repeatedly. Caching results per file hash avoids paying twice for the same upload.
Where a commercial model wins
For complex contracts, messy scans, handwriting or documents mixing tables and images, a strong commercial model with file and vision support will produce noticeably better results than a mid-sized text model.
Process uploads in a queue
A simple job queue, even a database table with a status column, keeps uploads from overwhelming the API. A worker picks up one document at a time, processes its chunks in order and marks it done. If the worker crashes, unfinished jobs stay in the queue and resume later. This structure also makes it easy to show users an honest position in line during busy periods.
- Process chunks sequentially or with at most two in parallel on the free endpoint.
- Retry on 429 after Retry-After and on 503 after a few seconds.
- Cache results by file hash.
- Set a per-user daily upload limit.
Privacy and user trust
Users uploading documents are trusting you with them. Say clearly which service processes the content, how long you keep results and how to delete them. Strip personal data you do not need before sending chunks to any model; the redaction approach in keeping secrets out of prompts works for documents too.
For sensitive material such as medical, legal or financial records, check the provider's data processing terms and your own legal obligations before going live. A prototype on test documents is a very different thing from production with real customer files.
Delete originals
If you only need the extracted data, delete the uploaded file after processing. Less stored data means less to protect.

Send a prompt to the keyless free-ai endpoint from the home page and see a reply in seconds, no sign-up needed.
Read also
- Is there a free OpenAI-compatible API you can use for testing?
- API gateway vs direct OpenAI API: which is better for builders?
- Hosted LLM API vs self-hosted open-weight model: which fits you?
- Navigating the Retirement of Your Favorite AI Model
- How do you stop an autonomous agent loop from burning your API budget?