← Back to articles
Tutorials

Free Machine Reading Comprehension (MRC) API: A Complete Tutorial (2026-11-12 Verified)

Free Machine Reading Comprehension (MRC) API: A Complete Tutorial

Last verified: 2026-11-12

Introduction

Machine Reading Comprehension (MRC) is a core task in Natural Language Processing (NLP) where a computer system reads a given context passage and answers questions about its content. Unlike traditional keyword-based search engines that merely match terms, MRC systems are designed to understand semantics, grasp context, and even perform multi-step reasoning to produce accurate answers.

MRC matters because it bridges the gap between unstructured text and actionable knowledge. Organizations accumulate massive amounts of textual data — FAQs, manuals, contracts, research papers — but extracting specific information manually is slow and costly. MRC automates this process, enabling machines to read and comprehend at scale, dramatically reducing the time from question to answer.

Common use cases include:

  • Customer support: Automatically answering user questions from knowledge bases and FAQ documents
  • Legal document analysis: Finding specific clauses, obligations, or terms in lengthy contracts
  • Medical literature mining: Extracting findings, dosages, or contraindications from clinical studies
  • Educational tutoring: Helping students find precise answers in textbooks and lecture notes
  • Enterprise search: Powering internal knowledge management systems with natural language queries

In this tutorial, we explore four free, open-source MRC solutions, compare their performance, walk through a practical customer-service case, and show how to access MRC APIs through the APIShare platform.


Solution 1: HuggingFace Transformers (BERT/RoBERTa Extractive MRC)

Principle

HuggingFace Transformers provides pre-trained models like BERT and RoBERTa that are fine-tuned on SQuAD (Stanford Question Answering Dataset). These models perform extractive MRC, meaning they identify the exact span of text within the passage that best answers the question. The model takes a question-context pair as input and outputs start and end token positions marking the answer span. This approach is highly effective for factoid questions where the answer explicitly appears in the text.

Code Example

from transformers import pipeline

# Load the extractive QA pipeline with a RoBERTa model fine-tuned on SQuAD2
qa_pipeline = pipeline(
    "question-answering",
    model="deepset/roberta-base-squad2",
    tokenizer="deepset/roberta-base-squad2"
)

# Define context passage and question
context = """
Machine Reading Comprehension is a task in natural language processing where a model reads a text passage and answers questions about it. Extractive models identify the answer span within the passage, while generative models produce the answer in free-form text. BERT-based models are among the most popular extractive approaches due to their strong performance on benchmark datasets.
"""

question = "What do extractive models do?"

# Get the answer
result = qa_pipeline(question=question, context=context)

print(f"Question: {question}")
print(f"Answer: {result['answer']}")
print(f"Confidence score: {result['score']:.4f}")
print(f"Start position: {result['start']}, End position: {result['end']}")

Pros and Cons

Pros:

  • State-of-the-art accuracy on benchmark datasets like SQuAD
  • Huge model hub with hundreds of pre-trained MRC models
  • Supports multilingual models (e.g., bert-base-multilingual-cased)
  • Active community and extensive documentation

Cons:

  • Requires GPU for fast inference on large-scale deployments
  • Models can be large (400MB+), increasing deployment footprint
  • Extractive approach cannot synthesize answers not present in the source text

Solution 2: Haystack Framework (End-to-End QA Pipeline)

Principle

Haystack by deepset is an end-to-end framework that combines document retrieval with MRC. It uses a two-stage architecture: first, a retriever (e.g., BM25 or dense embedding) finds relevant documents from a large corpus; second, a reader (e.g., a BERT-based MRC model) extracts precise answers from those documents. This design scales MRC to large knowledge bases where feeding all documents to the reader at once is infeasible.

Code Example

from haystack.document_stores import InMemoryDocumentStore
from haystack.nodes import BM25Retriever, FARMReader
from haystack.pipelines import ExtractiveQAPipeline

# Step 1: Create an in-memory document store
document_store = InMemoryDocumentStore()

# Step 2: Index some documents
documents = [
    {"content": "Haystack is an open-source NLP framework by deepset for building search pipelines and QA systems."},
    {"content": "The retriever filters documents from the document store based on relevance to the query."},
    {"content": "The reader model extracts exact answer spans from the retrieved documents using BERT-based architectures."}
]
document_store.write_documents(documents)

# Step 3: Initialize retriever and reader
retriever = BM25Retriever(document_store=document_store)
reader = FARMReader(model_name_or_path="deepset/roberta-base-squad2", use_gpu=False)

# Step 4: Build the QA pipeline
pipe = ExtractiveQAPipeline(reader, retriever)

# Step 5: Ask a question
prediction = pipe.run(
    query="What does the reader model do?",
    params={"Retriever": {"top_k": 3}, "Reader": {"top_k": 2}}
)

for answer in prediction["answers"]:
    print(f"Answer: {answer.answer}")
    print(f"Score: {answer.score:.4f}")
    print(f"Context: {answer.context[:100]}...")
    print("---")

Pros and Cons

Pros:

  • End-to-end pipeline handles retrieval and reading in one framework
  • Scales to millions of documents with Elasticsearch or FAISS backends
  • Supports both extractive and generative QA
  • Built-in evaluation and labeling tools

Cons:

  • Steeper learning curve than a single model pipeline
  • More dependencies and setup complexity
  • Heavier resource requirements for full production deployment

Solution 3: DeepPavlov (Open-Source NLP Library with MRC Models)

Principle

DeepPavlov is an open-source conversational AI and NLP library developed by the Neural Networks and Deep Learning Lab at MIPT. It provides pre-configured MRC models based on architectures like BERT, using a config-driven approach. Users specify a JSON config file that defines the entire pipeline — from tokenization to model inference — and DeepPavlov handles the rest. It also supports Russian and other languages natively, making it a strong choice for multilingual applications.

Code Example

from deeppavlov import build_model

# Build a pre-configured SQuAD BERT model
# This downloads model weights on first run
model = build_model("squad_bert", download=True)

# Define context and question
context = "DeepPavlov is an open-source library for building conversational AI systems. It supports tasks like named entity recognition, question answering, and intent classification across multiple languages."

question = "What tasks does DeepPavlov support?"

# Get prediction — returns [answer_text, start_char, logit_score]
result = model([context], [question])

print(f"Question: {question}")
print(f"Answer: {result[0][0]}")
print(f"Start character: {result[1][0]}")
print(f"Logit score: {result[2][0]:.4f}")

Pros and Cons

Pros:

  • Config-driven architecture makes experimentation and customization easy
  • Strong multilingual support, especially for Russian and Slavic languages
  • Integrates seamlessly with conversational AI components
  • Well-structured modular design for pipeline composition

Cons:

  • Smaller community compared to HuggingFace ecosystem
  • Documentation can be sparse for advanced or non-standard use cases
  • Installation can have complex dependency requirements on some systems

Solution 4: spaCy + Custom Rules (Lightweight Keyword Matching + Passage Extraction)

Principle

For scenarios where deploying a large neural model is impractical, a lightweight approach using spaCy's linguistic features combined with custom rules can provide reasonable MRC results. This method uses tokenization, part-of-speech tagging, and named entity recognition to identify relevant sentences in a passage based on keyword overlap and semantic similarity. While not as accurate as transformer-based models, it is extremely fast and requires minimal computational resources, making it ideal for edge devices or low-latency applications.

Code Example

import spacy

# Load a small English model
nlp = spacy.load("en_core_web_sm")

def lightweight_mrc(context, question, top_k=1):
    """
    A simple extractive MRC approach using sentence similarity
    based on keyword overlap and named entity matching.
    """
    # Process context and split into sentences
    context_doc = nlp(context)
    sentences = list(context_doc.sents)

    # Process question and extract keywords (nouns, proper nouns, verbs)
    question_doc = nlp(question)
    question_keywords = set(
        token.lemma_.lower()
        for token in question_doc
        if token.pos_ in ("NOUN", "PROPN", "VERB")
    )

    # Score each sentence by keyword overlap
    scored_sentences = []
    for sent in sentences:
        sent_keywords = set(
            token.lemma_.lower()
            for token in sent
            if token.pos_ in ("NOUN", "PROPN", "VERB")
        )
        overlap = len(question_keywords & sent_keywords)
        scored_sentences.append((sent, overlap))

    # Sort by score and return top-k sentences
    scored_sentences.sort(key=lambda x: x[1], reverse=True)
    return scored_sentences[:top_k]

# Test data
context = """
Return policies vary by store. Most retail stores allow returns within 30 days of purchase with a valid receipt. Electronics may have a shorter return window of 14 days. Items must be in original packaging and unused condition. Refunds are typically processed to the original payment method within 5 to 7 business days.
"""

question = "How long do I have to return an item?"

results = lightweight_mrc(context, question, top_k=2)

print(f"Question: {question}\n")
for sent, score in results:
    print(f"[Score: {score}] {sent.text.strip()}")

Pros and Cons

Pros:

  • Extremely lightweight — runs on CPU with minimal memory footprint
  • No large model download or GPU required
  • Fast inference suitable for real-time and edge applications
  • Easy to customize, debug, and extend with domain-specific rules

Cons:

  • Significantly lower accuracy than neural models
  • Cannot understand complex semantics or multi-hop reasoning
  • Requires manual rule engineering for different domains
  • Not suitable for complex questions spanning multiple sentences

Performance Comparison

The radar chart below compares the four solutions across five dimensions: accuracy, inference speed, ease of use, multilingual support, and deployment flexibility. Scores are on a scale of 1 to 10, based on typical real-world usage patterns.

option = {
  title: {
    text: 'MRC Solutions Performance Comparison',
    subtext: 'Scale: 1-10 (higher is better)',
    left: 'center',
    textStyle: { fontSize: 18 }
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    data: ['HuggingFace Transformers', 'Haystack', 'DeepPavlov', 'spaCy + Rules'],
    bottom: 0,
    textStyle: { fontSize: 12 }
  },
  radar: {
    indicator: [
      { name: 'Accuracy', max: 10 },
      { name: 'Speed', max: 10 },
      { name: 'Ease of Use', max: 10 },
      { name: 'Multilingual', max: 10 },
      { name: 'Deployment', max: 10 }
    ],
    radius: '65%',
    axisName: { fontSize: 13 }
  },
  series: [
    {
      name: 'MRC Comparison',
      type: 'radar',
      data: [
        {
          value: [9, 5, 8, 9, 7],
          name: 'HuggingFace Transformers',
          itemStyle: { color: '#5470c6' },
          areaStyle: { opacity: 0.15 }
        },
        {
          value: [8.5, 6, 6, 8, 6],
          name: 'Haystack',
          itemStyle: { color: '#91cc75' },
          areaStyle: { opacity: 0.15 }
        },
        {
          value: [8, 6, 7, 8.5, 6.5],
          name: 'DeepPavlov',
          itemStyle: { color: '#fac858' },
          areaStyle: { opacity: 0.15 }
        },
        {
          value: [5, 9.5, 9, 5, 9],
          name: 'spaCy + Rules',
          itemStyle: { color: '#ee6666' },
          areaStyle: { opacity: 0.15 }
        }
      ]
    }
  ]
}

From the radar chart, we can observe that HuggingFace Transformers leads in accuracy and multilingual support but has moderate speed. Haystack offers a balanced enterprise-grade solution. DeepPavlov excels in multilingual scenarios with a config-driven approach. spaCy + Rules is the fastest and easiest to deploy, ideal for resource-constrained environments where approximate answers suffice.


Practical Case: Smart Customer Service FAQ Auto-Answering

In a smart customer service scenario, users frequently ask questions about product usage. We can leverage MRC technology to extract precise answers directly from lengthy FAQ documents, rather than returning the entire document.

Assume we have an API usage guide, and a user asks: "Where can I find my API key?" We will use the HuggingFace solution to build a customer service QA function.

from transformers import pipeline

class SmartCustomerService:
    def __init__(self):
        # Load the MRC model optimized for QA tasks
        self.qa_model = pipeline("question-answering", model="deepset/roberta-base-squad2")
        
    def answer_query(self, faq_context: str, user_question: str) -> dict:
        """
        Extract answer from FAQ context based on user question.
        """
        if not faq_context or not user_question:
            return {"answer": "Sorry, I cannot find the answer.", "confidence": 0.0}
            
        try:
            result = self.qa_model(question=user_question, context=faq_context)
            return {
                "answer": result['answer'],
                "confidence": round(result['score'], 4),
                "raw_context": faq_context[result['start']:result['end']]
            }
        except Exception as e:
            return {"answer": f"Error processing request: {str(e)}", "confidence": 0.0}

# Example Usage
faq_document = """
To use our API, you first need to register an account on the platform. 
After logging in, navigate to the 'Dashboard' section. 
You will find your unique API key under the 'API Settings' tab. 
Keep this key secure and do not share it publicly.
"""

service_bot = SmartCustomerService()
user_question = "Where can I find my API key?"
response = service_bot.answer_query(faq_document, user_question)

print(f"User Question: {user_question}")
print(f"Bot Answer: {response['answer']}")
print(f"Confidence: {response['confidence']}")

In this case, the MRC model accurately extracted "the 'API Settings' tab" as the answer from the document, saving the user from reading the entire text. This demonstrates how MRC can dramatically improve customer service efficiency by providing instant, precise answers.


How to Use MRC API via APIShare Platform

While local deployment of open-source models offers maximum flexibility, the cost of configuring GPU servers and maintaining model inference services remains high for many startups and individual developers. Using cloud APIs is the optimal alternative.

The APIShare platform provides a rich collection of free LLM and NLP API endpoints, including high-performance machine reading comprehension services. With APIShare, you do not need to worry about underlying hardware or model deployment — just a few lines of code to integrate powerful MRC capabilities.

Step 1: Register and Get Your API Key

First, visit the APIShare registration page to create your free account. After registration, generate your dedicated API Key in the "API Management" section of the dashboard.

Step 2: Find MRC APIs

In the APIShare Free API marketplace, search for "Machine Reading Comprehension" or "Question Answering" to find available MRC endpoints. These APIs typically support standard JSON input and output.

Step 3: Call the API

Here is a Python example using the requests library to call the APIShare MRC API:

import requests
import json

# API Endpoint and Key
api_url = "https://api.apishare.cc/v1/mrc/extract"
api_key = "YOUR_APISHARE_API_KEY" # Replace with your actual key

# Payload
payload = {
    "context": "The Great Wall of China is a series of fortifications that was built across the historical northern borders of ancient Chinese states.",
    "question": "What is the Great Wall of China?"
}

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

# Send POST request
response = requests.post(api_url, headers=headers, json=payload)

if response.status_code == 200:
    result = response.json()
    print(f"Extracted Answer: {result.get('answer')}")
    print(f"Confidence Score: {result.get('score')}")
else:
    print(f"Error: {response.status_code} - {response.text}")

Through the APIShare Free API marketplace, developers can not only test MRC functionality for free but also seamlessly scale to larger commercial models as business needs grow, without modifying their code architecture.


Summary and Recommendations

Machine Reading Comprehension technology is reshaping how we retrieve information. This tutorial introduced four free MRC solutions:

  1. HuggingFace Transformers — Best for developers seeking maximum accuracy with adequate computing resources. The mainstream choice in academia and industry.
  2. Haystack — Ideal for teams building enterprise-grade knowledge base QA systems with large document collections.
  3. DeepPavlov — Suitable for researchers wanting to quickly experiment with different MRC academic models.
  4. spaCy + Rules — Perfect for edge scenarios with extreme resource constraints, fixed text structures, and strict latency requirements.

For users who want to launch products quickly without heavy operational costs, we strongly recommend using cloud API services. Visit the APIShare Free API marketplace now to explore more powerful NLP endpoints.

Ready to build your intelligent QA system? Click APIShare registration to get your free API credits and start your machine reading comprehension journey today!

This article was verified and updated on 2026-11-12 to ensure all code examples and API information are accurate and effective.

More in this category

Free Knowledge Distillation API Complete Tutorial: Compress BERT Models from Principle to Practice (2026-11-17 Verified)Free Vector Database API Complete Tutorial: Zero-Cost RAG Semantic Search Engine (2026-10-22 Verified)Free Speech Recognition (ASR) API Complete Tutorial: Convert Voice to Text at Zero Cost (2026-10-20 Verified)Best Practices for Publishing APIs on APIShare (2026-10-19 Complete Guide)Free Sentiment Analysis API Tutorial: Zero-Cost Detect Positive vs Negative Text (2026-10-19 Verified)

Ready to use free LLM APIs?

APIShare aggregates free AI APIs worldwide — sign up and get bonus credits.