Ask your PDFs and notes questions through a small Python backend

APIFreeGroqKey · Updated 2026-11-22 · 8 min read

Stack of documents and binders beside a laptop
A small backend can answer questions about a pile of documents.

Document intelligence projects are everywhere: upload contracts, manuals or research notes, then ask questions and get answers with references. Many tutorials reach for an agent framework, a vector database and an embedding service on day one. For a first version, you need far less. A web framework, a text chunker, a simple keyword ranker and one chat model will answer most questions about a modest collection of documents, and every part stays easy to understand and debug.

This guide walks through building that minimal service with FastAPI. It is for Python developers who want a working backend they can extend later with embeddings, user accounts or long-term memory. The model calls go to the keyless free-ai endpoint on this site, which needs no account, and the same code runs against Groq or any other OpenAI-compatible provider by changing three settings.

Frequently asked questions

Do I need a vector database for document Q&A?

Not for small and medium collections. Keyword ranking such as BM25 works well when questions share words with the answer passages, which is common for manuals and policies. Add embeddings when users phrase questions very differently from the text or when the collection grows large.

Does the keyless endpoint provide embeddings?

No. It offers chat completions, text completions, a model list, a health check and a simple ask endpoint. For embeddings, use a local embedding model or a provider that offers an embeddings API, and keep using free-ai for answers.

How does retrieval-augmented answering differ from fine-tuning?

Retrieval puts relevant passages into the prompt at question time, so the model answers from your current documents. Fine-tuning changes the model's weights and is poor at storing facts reliably. For document Q&A, retrieval is almost always the right choice.

How big can my documents be?

The collection can be as large as your storage allows, because only a few chunks go into each prompt. The prompt itself must fit the context window; the keyless model accepts 32,000 tokens, which leaves room for several long passages plus the question.

How do I stop the model from making up answers?

Tell it to answer only from the supplied passages, to cite passage numbers and to say when the passages do not contain the answer. Then check that cited numbers exist. This does not eliminate errors but makes them visible.

Can it read scanned PDFs or images?

Not directly. The model is text only. Extract text first with a PDF text extractor, and run OCR on scanned pages. Vision-capable models from other providers can read images, but that is a separate integration.

Is it safe to upload confidential documents?

Only the retrieved passages are sent to the model, but they leave your server. Every request to the keyless endpoint creates a technical log entry, although the API stores no conversations. For confidential material, consider a local model or a provider with suitable contractual terms.

Step by step

  1. Set up the project — Create a virtual environment and install fastapi, uvicorn, openai and rank-bm25.
  2. Chunk the documents — Split each text into overlapping chunks of a few hundred words and keep the source name with every chunk.
  3. Build the ranker — Tokenize chunks and build a BM25 index that scores chunks against a question.
  4. Write the answer endpoint — Retrieve the top chunks, build a prompt with numbered passages and call the chat completions API.
  5. Return citations — Send back the answer together with the source names and passage numbers it used.
  6. Run and test — Start the server with uvicorn and ask real questions from your users, checking the citations.

Architecture in one picture

The service has two paths. Ingestion reads documents, splits them into chunks and adds them to an index. Answering takes a question, finds the best chunks, sends them with the question to the model and returns the answer with references. Both paths live in one small FastAPI app, with the index kept in memory for simplicity.

This design leaves obvious upgrade points: swap the in-memory index for a database, replace BM25 with hybrid keyword and embedding search, add user authentication, or keep conversation history. None of these change the basic flow, so you can start simple without painting yourself into a corner.

Why start without an agent framework

Frameworks add abstractions that are helpful at scale and confusing at the start. Writing the twenty lines of retrieval and prompting yourself teaches you exactly what the model sees, which is the key to fixing bad answers later. Our comparison of LangChain and the plain SDK discusses when a framework earns its place.

Chunking documents sensibly

Chunks should be large enough to contain a complete idea and small enough that several fit in a prompt. A few hundred words with some overlap between neighbours is a solid default. Overlap prevents an answer from being cut in half at a chunk boundary.

Keep metadata with each chunk: the source file name, the chunk number and, if you can, the heading it falls under. The metadata goes into the prompt and into the citations, so users can find the original text.

Split on structure where possible

Splitting on headings and paragraphs gives cleaner chunks than cutting at a fixed word count. Fall back to word counts only for long unstructured passages.

Clean extracted text

PDF extraction often leaves page numbers, headers and broken hyphenation. Removing repeated headers and joining hyphenated words improves both retrieval and answers.

Paper cutter slicing a long scroll into strips
Chunking splits documents into pieces that fit in a prompt.

Keyword ranking with BM25

BM25 scores chunks by how often question words appear in them, adjusted for word rarity and chunk length. It is fast, needs no model and is surprisingly strong for documents with consistent terminology. The rank-bm25 package implements it in a few lines. Lowercasing and stripping punctuation is enough tokenization for a first version.

When keyword ranking fails

If users ask about "cancelling" while the document says "termination", BM25 misses the match. Adding a short synonym list, or later an embedding model, fixes this. Log questions where no chunk scores well to see how often it happens.

The complete FastAPI service

Here is the whole service. It accepts plain text documents through one endpoint, indexes them and answers questions through another. Install the dependencies with pip install fastapi uvicorn openai rank-bm25, save the file as app.py and run uvicorn app:app --reload.

Configuration through environment variables

The base URL, key and model come from environment variables with keyless defaults. To switch to Groq, set them to its OpenAI-compatible URL, your own key and a model from its catalog. The code does not change.

Rebuilding the index

For simplicity the index is rebuilt after every upload, which is fine for hundreds of chunks. For larger collections, build it once after a batch of uploads or move to a persistent search engine.

import os
import re
from fastapi import FastAPI
from pydantic import BaseModel
from rank_bm25 import BM25Okapi
from openai import OpenAI

client = OpenAI(
    base_url=os.environ.get("LLM_BASE_URL", "https://api.apifreegroqkey.com/v1"),
    api_key=os.environ.get("LLM_API_KEY", "free"),
)
MODEL = os.environ.get("LLM_MODEL", "free-ai")

app = FastAPI()
chunks = []   # list of dicts: {"source": str, "text": str}
index = None

def tokens(text):
    return re.findall(r"\w+", text.lower())

def split(text, size=250, overlap=50):
    words = text.split()
    step = size - overlap
    return [" ".join(words[i:i + size]) for i in range(0, max(len(words), 1), step)]

class Doc(BaseModel):
    source: str
    text: str

class Question(BaseModel):
    question: str
    k: int = 4

@app.post("/documents")
def add_document(doc: Doc):
    global index
    for part in split(doc.text):
        if part.strip():
            chunks.append({"source": doc.source, "text": part})
    index = BM25Okapi([tokens(c["text"]) for c in chunks])
    return {"chunks": len(chunks)}

@app.post("/ask")
def ask(q: Question):
    if index is None:
        return {"answer": "No documents loaded yet.", "sources": []}
    scores = index.get_scores(tokens(q.question))
    top = sorted(range(len(chunks)), key=lambda i: scores[i], reverse=True)[:q.k]
    passages = "\n\n".join(f"[{n + 1}] ({chunks[i]['source']}) {chunks[i]['text']}" for n, i in enumerate(top))
    system = ("Answer only from the numbered passages. Cite passage numbers like [2]. "
              "If the passages do not contain the answer, say so plainly.")
    r = client.chat.completions.create(
        model=MODEL,
        messages=[{"role": "system", "content": system},
                  {"role": "user", "content": f"{passages}\n\nQuestion: {q.question}"}],
        temperature=0.2,
        max_tokens=600,
    )
    answer = r.choices[0].message.content
    cited = sorted({int(n) for n in re.findall(r"\[(\d+)\]", answer) if 0 < int(n) <= len(top)})
    return {"answer": answer, "sources": [{"n": n, "source": chunks[top[n - 1]]["source"]} for n in cited]}
Library card catalogue with a drawer pulled out
Keyword ranking picks the most relevant chunks for each question.

Prompting for grounded answers

The system prompt does three jobs: restrict the model to the passages, require citations and allow it to say the answer is missing. The third is the most important. Without explicit permission, models tend to answer anyway from general knowledge, which looks fine and may be wrong for your specific documents.

Citation checks in the code drop references to passage numbers that do not exist. You can go further and verify that a quoted phrase appears in the cited passage. These checks catch a share of mistakes automatically and make the rest easier to spot.

Allow an honest no

A reply such as "The documents do not say" is a success, not a failure. Count these replies in your tests; if they are frequent for questions that do have answers, retrieval is missing the right chunks.

Show the passages to users

Let users expand each citation to read the passage itself. People trust answers they can verify, and they report errors much faster when the source text is one click away.

  • Number passages and include the source name with each
  • Ask for citations after each claim, not only at the end
  • Lower temperature for factual answers
  • Return sources separately so the interface can link them

Testing with real questions

Collect twenty to thirty questions that real users would ask, with the expected answer and source for each. Run them after every change to chunking, ranking or prompt. Note three outcomes per question: correct with the right citation, correct but poorly cited, and wrong or unanswered. This small evaluation set is worth more than any general benchmark.

Watch for questions where the right chunk was never retrieved. Those are ranking problems, not model problems, and no amount of prompt tuning will fix them. Our explainer on graph RAG covers questions that need relationships across many documents, a case where simple retrieval struggles.

Check retrieval separately

Log which chunks were retrieved for each test question. If the correct passage is in the top four, retrieval works and any error is in answering; if not, fix ranking first.

Open book with numbered sticky tabs
Numbered passages make citations easy to check.

Limits, latency and costs

Each question is one model call, so throughput depends on your provider's limits. The keyless endpoint allows one request per second per IP, two in parallel, and 10,000 requests or 10 million tokens a day. For an internal tool used by a small team, that is often enough. For a public product, your server's IP becomes the bottleneck and a paid plan is needed.

Groq's API is popular for this kind of service because fast answers make Q&A feel interactive; its free-tier limits differ by model, so check the current limits page. This site is not affiliated with Groq, and free-ai, an independent open-weight model of roughly 35B parameters, is not one of the models Groq hosts. A strong commercial model will usually write more precise answers from complex legal or technical text.

Handle busy responses

Wrap the model call so that a 429 waits for the Retry-After value and a 503 retries after two to five seconds. Return a friendly message to the user if retries run out instead of a server error.

Where to go next

Once the basic service answers well, the usual next steps are authentication, persistence and better retrieval. Store chunks in a database with full-text search, add a hybrid ranker that combines keywords with embeddings from a local model, and protect the endpoints with API keys or user logins. If you want the service to remember facts about each user between sessions, store them yourself; the model API is stateless and forgets everything after each request.

If you plan to send some questions to a cheaper model and harder ones to a stronger model, read our guide to routing requests between models.

Protect the endpoints

An open Q&A endpoint on the internet will be found and used by others, consuming your quota. Add authentication before deploying anywhere public, even for a demo.

Small server rack in a locked cabinet
Protect the service before you put it on the internet.
Try the free API

Send a request to the keyless free-ai endpoint from the home page and see how it fits your project, no sign-up needed.

Read also