ContextGem is a free, open-source LLM framework for easier, faster extraction of structured data and insights from documents through powerful abstractions.
Most popular LLM frameworks for extracting structured data from documents require extensive boilerplate code to extract even basic information. This significantly increases development time and complexity.
ContextGem addresses this challenge by providing a flexible, intuitive framework that extracts structured data and insights from documents with minimal effort. Complex, most time-consuming parts are handled with powerful abstractions, eliminating boilerplate code and reducing development overhead.
Read more on the project motivation in the documentation.
- Extract structured data from documents (text, images) with minimal code
- Identify and analyze key aspects (topics, themes, categories) within documents
- Extract specific concepts (entities, facts, conclusions, assessments) from documents
- Build complex extraction workflows through a simple, intuitive API
- Create multi-level extraction pipelines (aspects containing concepts, hierarchical aspects)
Built-in abstractions | ContextGem | Other LLM frameworks* |
---|---|---|
Automated dynamic prompts | β | β |
Automated data modelling and validators | β | β |
Precise granular reference mapping (paragraphs & sentences) | β | β |
Justifications (reasoning backing the extraction) | β | β |
Neural segmentation (SaT) | β | β |
Multilingual support (I/O without prompting) | β | β |
Single, unified extraction pipeline (declarative, reusable, fully serializable) | β | |
Grouped LLMs with role-specific tasks | β | |
Nested context extraction | β | |
Unified, fully serializable results storage model (document) | β | |
Extraction task calibration with examples | β | |
Built-in concurrent I/O processing | β | |
Automated usage & costs tracking | β | |
Fallback and retry logic | β | β |
Multiple LLM providers | β | β |
β
- fully supported - no additional setup required
β - not supported - requires custom logic
* See descriptions of ContextGem abstractions and comparisons of specific implementation examples using ContextGem and other popular open-source LLM frameworks.
pip install -U contextgem
Aspect is a defined area or topic within a document (or another aspect). Each aspect reflects a specific subject or theme.
# Quick Start Example - Extracting payment terms from a document
import os
from contextgem import Aspect, Document, DocumentLLM
# Sample document text (shortened for brevity)
doc = Document(
raw_text=(
"SERVICE AGREEMENT\n"
"SERVICES. Provider agrees to provide the following services to Client: "
"Cloud-based data analytics platform access and maintenance...\n"
"PAYMENT. Client agrees to pay $5,000 per month for the services. "
"Payment is due on the 1st of each month. Late payments will incur a 2% fee per month...\n"
"CONFIDENTIALITY. Both parties agree to keep all proprietary information confidential "
"for a period of 5 years following termination of this Agreement..."
),
)
# Define the aspects to extract
doc.aspects = [
Aspect(
name="Payment Terms",
description="Payment terms and conditions in the contract",
# see the docs for more configuration options, e.g. sub-aspects, concepts, etc.
),
# Add more aspects as needed
]
# Or use `doc.add_aspects([...])`
# Define an LLM for extracting information from the document
llm = DocumentLLM(
model="openai/gpt-4o-mini", # or any other LLM from e.g. Anthropic, etc.
api_key=os.environ.get(
"CONTEXTGEM_OPENAI_API_KEY"
), # your API key for the LLM provider, e.g. OpenAI, Anthropic, etc.
# see the docs for more configuration options
)
# Extract information from the document
doc = llm.extract_all(doc) # or use async version `await llm.extract_all_async(doc)`
# Access extracted information in the document object
for item in doc.aspects[0].extracted_items:
print(f"β’ {item.value}")
# or `doc.get_aspect_by_name("Payment Terms").extracted_items`
Concept is a unit of information or an entity, derived from an aspect or the broader document context.
# Quick Start Example - Extracting anomalies from a document, with source references and justifications
import os
from contextgem import Document, DocumentLLM, StringConcept
# Sample document text (shortened for brevity)
doc = Document(
raw_text=(
"Consultancy Agreement\n"
"This agreement between Company A (Supplier) and Company B (Customer)...\n"
"The term of the agreement is 1 year from the Effective Date...\n"
"The Supplier shall provide consultancy services as described in Annex 2...\n"
"The Customer shall pay the Supplier within 30 calendar days of receiving an invoice...\n"
"The purple elephant danced gracefully on the moon while eating ice cream.\n" # π anomaly
"This agreement is governed by the laws of Norway...\n"
),
)
# Attach a document-level concept
doc.concepts = [
StringConcept(
name="Anomalies", # in longer contexts, this concept is hard to capture with RAG
description="Anomalies in the document",
add_references=True,
reference_depth="sentences",
add_justifications=True,
justification_depth="brief",
# see the docs for more configuration options
)
# add more concepts to the document, if needed
# see the docs for available concepts: StringConcept, JsonObjectConcept, etc.
]
# Or use `doc.add_concepts([...])`
# Define an LLM for extracting information from the document
llm = DocumentLLM(
model="openai/gpt-4o-mini", # or any other LLM from e.g. Anthropic, etc.
api_key=os.environ.get(
"CONTEXTGEM_OPENAI_API_KEY"
), # your API key for the LLM provider, e.g. OpenAI, Anthropic, etc.
# see the docs for more configuration options
)
# Extract information from the document
doc = llm.extract_all(doc) # or use async version `await llm.extract_all_async(doc)`
# Access extracted information in the document object
print(
doc.concepts[0].extracted_items
) # extracted items with references & justifications
# or `doc.get_concept_by_name("Anomalies").extracted_items`
See more examples in the documentation:
- Aspect Extraction from Document
- Extracting Aspect with Sub-Aspects
- Concept Extraction from Aspect
- Concept Extraction from Document (text)
- Concept Extraction from Document (vision)
- Extracting Aspects Containing Concepts
- Extracting Aspects and Concepts from a Document
- Using a Multi-LLM Pipeline to Extract Data from Several Documents
ContextGem leverages LLMs' long context windows to deliver superior extraction accuracy from individual documents. Unlike RAG approaches that often struggle with complex concepts and nuanced insights, ContextGem capitalizes on continuously expanding context capacity, evolving LLM capabilities, and decreasing costs. This focused approach enables direct information extraction from complete documents, eliminating retrieval inconsistencies while optimizing for in-depth single-document analysis. While this delivers maximum accuracy for individual documents, ContextGem does not currently support cross-document querying or corpus-wide retrieval - for these use cases, traditional RAG systems (e.g., LlamaIndex, Haystack) remain more appropriate.
Read more on how it works in the documentation.
ContextGem supports both cloud-based and local LLMs through LiteLLM integration:
- Cloud LLMs: OpenAI, Anthropic, Google, Azure OpenAI, and more
- Local LLMs: Run models locally using providers like Ollama, LM Studio, etc.
- Simple API: Unified interface for all LLMs with easy provider switching
ContextGem documentation offers guidance on optimization strategies to maximize performance, minimize costs, and enhance extraction accuracy:
- Optimizing for Accuracy
- Optimizing for Speed
- Optimizing for Cost
- Dealing with Long Documents
- Choosing the Right LLM(s)
Full documentation is available at contextgem.dev.
A raw text version of the full documentation is available at docs/docs-raw-for-llm.txt
. This file is automatically generated and contains all documentation in a format optimized for LLM ingestion (e.g. for Q&A).
If you have a feature request or a bug report, feel free to open an issue on GitHub. If you'd like to discuss a topic or get general advice on using ContextGem for your project, start a thread in GitHub Discussions.
We welcome contributions from the community - whether it's fixing a typo or developing a completely new feature! To get started, please check out our Contributor Guidelines.
ContextGem is at an early stage. Our development roadmap includes:
- Enhanced Analytical Abstractions: Building more sophisticated analytical layers on top of the core extraction workflow to enable deeper insights and more complex document understanding
- API Simplification: Continuing to refine and streamline the API surface to make document analysis more intuitive and accessible
- Terminology Refinement: Improving consistency and clarity of terminology throughout the framework to enhance developer experience
We are committed to making ContextGem the most effective tool for extracting structured information from documents.
This project is automatically scanned for security vulnerabilities using CodeQL. We also use Snyk as needed for supplementary dependency checks.
See SECURITY file for details.
ContextGem relies on these excellent open-source packages:
- pydantic: The gold standard for data validation
- Jinja2: Fast, expressive template engine that powers our dynamic prompt rendering
- litellm: Unified interface to multiple LLM providers with seamless provider switching
- wtpsplit: State-of-the-art text segmentation tool
- loguru: Simple yet powerful logging that enhances debugging and observability
- python-ulid: Efficient ULID generation
- PyTorch: Industry-standard machine learning framework
- aiolimiter: Powerful rate limiting for async operations
This project is licensed under the Apache 2.0 License - see the LICENSE and NOTICE files for details.
Copyright Β© 2025 Shcherbak AI AS, an AI engineering company building tools for AI/ML/NLP developers.
Shcherbak AI is now part of Microsoft for Startups.
Connect with us on LinkedIn for questions or collaboration ideas.
Built with β€οΈ in Oslo, Norway.