280개 이상의 piece를 MCP 서버로 노출하는 오픈소스 AI 워크플로 자동화.
한국어는 runchr 제공 번역입니다. 원문 README는 English tool page.
contextgem
ContextGem은 LLM과 의사결정 모델을 사용하여 문서에서 구조화된 데이터와 인사이트를 추출하는 오픈소스 Python 프레임워크이며, 출처
- Install
- pip install contextgem
프로젝트 README (번역)
GitHub ↗Written by the project's own authors, not by runchr. Snapshot taken 2026-10-29.
LLM과 의사결정 모델을 사용해 문서에서 구조화된 데이터와 인사이트 추출
프롬프트를 작성하지 말고, 설명하세요.
Quickstart ·
작동 방식 ·
에이전트 워크플로 ·
변경 로그 ·
보안 ·
문서
예시 계약서. 추출된 모든 사실은 출처로 추적됩니다.
참고
1.0의 새로운 기능: 의사결정 모델. LLM과 더불어 ContextGem은 이제 의사결정 모델과도 함께 작동합니다. 의사결정 모델은 폐쇄형 질문(예/아니오, 사용자의 레이블 중 하나, 척도의 한 단계)에 각 가능한 답변의 확률과 함께 빠르고 저렴한 비용으로 답합니다. 모델 그룹은 각 aspect와 concept을 그에 맞는 모델로 보내며, 어떤 모델이든 다른 모델로 폴백할 수 있습니다: LLM과 의사결정 모델을 참고하세요.
0.x에서 업그레이드하시나요? 일부 클래스와 매개변수가 이름이 바뀌거나 제거되었고, 일부 기본값이 변경되었으며, Python 3.10은 더 이상 지원되지 않습니다. 마이그레이션 가이드를 따르거나, 코딩 에이전트를 문서 색인인 llms.txt로 안내하세요.
ContextGem은 모델 주변의 작업을 대신 처리해 주는 무료 오픈소스 프레임워크입니다: 프롬프트, 데이터 모델, 소스 참조, 근거를 최소한의 코드로 처리합니다.
ContextGem을 쓰는 이유
문서에서 신뢰할 수 있는 추출을 하려면 보통 프롬프트 작성, 검증 모델 설계, 출력을 소스로 다시 매핑, 다단계 파이프라인 오케스트레이션, 모델 전반의 사용량 추적이 필요합니다. ContextGem은 이 모든 것을 재사용하고 직렬화할 수 있는 하나의 선언적 파이프라인에 내장하고 있습니다.
작성할 프롬프트 없음
프롬프트는 추출할 내용에 대한 설명으로부터 생성됩니다.
타입이 지정되고 검증된 출력
텍스트, 숫자, 날짜, 불리언, 레이블, 평점, JSON 객체.
모든 사실이 출처로 추적됨
항목은 문단이나 문장으로 매핑되며, 요청 시 추론 근거도 제공됩니다.
중첩 컨텍스트
Aspect, 하위 aspect, concept이 모델을 중요한 텍스트에 집중시킵니다.
각 질문에 맞는 모델
추론이 필요한 곳에는 LLM, 빠르고 저렴한 답변으로 충분한 곳에는 의사결정 모델.
확률이 포함된 답변
의사결정 모델은 각 가능한 답변의 확률을 제공하며, 임계값은 사용자가 설정합니다.
ContextGem의 동기에 대해 더 읽어보세요.
LLM과 의사결정 모델
ContextGem은 두 종류의 모델과 함께 작동합니다. 추출할 내용을 두 경우 모두 동일한 방식으로 설명하며, 각 aspect와 concept은 그에 맞는 모델로 전달됩니다.
예시 서비스 계약서: 개방형 질문은 LLM으로, 폐쇄형 질문은 의사결정 모델로.
LLM
의사결정 모델
답변 방식
답변을 작성하며, ContextGem이 이를 타입이 지정된 항목으로 검증
각 가능한 답변의 확률을 제공하며, 텍스트를 작성하지 않음
추출 대상
텍스트와 이미지로부터의 aspect 및 모든 유형의 concept
텍스트로부터의 aspect, 그리고 Boolean, 레이블, 평점 concept
각 항목과 함께
문단이나 문장에 대한 참조, 요청 시 근거
모든 가능한 답변의 확률, 그리고 모델에 대해 또는 각 aspect와 concept에 대해 사용자가 설정하는 결정 임계값
사용 용도
개방형 값, 추론이 필요한 답변
대량의 폐쇄형 질문, 빠르고 저렴한 답변으로 충분한 경우
모델
LiteLLM을 통한 모든 클라우드 또는 로컬 LLM: OpenAI, Anthropic, Google, Azure OpenAI, xAI, Ollama, LM Studio 등
TypeSafe Jev, OpenAI Decisions API, Microsoft Foundry 등, 클라우드 또는 로컬
더 읽기
지원되는 LLM, 구성, 추출 방법
의사결정 모델
모델 선택. ContextGem은 gpt-6-luna(OpenAI), claude-haiku-5-5(Anthropic) 같은 호스팅 LLM과 Jev(TypeSafe) 같은 의사결정 모델로 테스트되었습니다. 로컬에서 실행되는 많은 모델처럼 더 작은 LLM은 상세한 추출 지침을 따르지 못할 수 있습니다: 문서 샘플로 확인하고, 부족할 경우 문제 해결 가이드를 참고하세요. 의사결정 모델에 질문을 주기 전에, 문서 샘플에서 LLM과 비교해 보세요: 의사결정 모델을 언제 사용할지 참고하세요.
빠른 시작
uv add contextgem # 또는: pip install -U contextgem
uv add " contextgem[docling] " # Docling과 함께, PDF, DOCX 및 기타 파일 변환용
LLM으로 추출하기
LLM은 모든 유형의 aspect와 값을 추출합니다. 아래에서는 계약서에서 두 가지를 추출합니다: aspect인 payment terms는 결제에 관한 문단으로 반환되고, concept인 anomalies는 문서 전체에 걸쳐 있으며 검색 기반 접근 방식이 놓칠 수 있는 항목입니다. 각 anomaly는 근거와 발견된 문장과 함께 제공됩니다.
import os
from contextgem import Aspect , Document , DocumentLLM , StringConcept
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
"Time-traveling dinosaurs will review all deliverables before acceptance. \n " # 💎 another anomaly
"This agreement is governed by the laws of Norway... \n "
),
)
doc . add_aspects (
[
Aspect (
name = "Payment terms" ,
description = "Clauses on payments, fees and invoices" ,
)
]
)
doc . add_concepts (
[
StringConcept (
name = "Anomalies" ,
description = "Anomalies in the document" ,
add_references = True ,
reference_depth = "sentences" ,
add_justifications = True ,
justification_depth = "brief" ,
)
]
)
llm = DocumentLLM (
model = "openai/gpt-6-luna" , # 또는 다른 LLM, 클라우드 또는 로컬
api_key = os . environ . get ( "CONTEXTGEM_OPENAI_API_KEY" ),
)
doc = llm . extract_all ( doc )
payment_terms = doc . get_aspect_by_name ( "Payment terms" ). extracted_items
# 1개 항목, 문단: "The Customer shall pay the Supplier within 30 calendar
# days of receiving an invoice..."
anomalies = doc . get_concept_by_name ( "Anomalies" ). extracted_items
# 2개 항목. 첫 번째:
# .value: "The statement that a purple elephant danced on the moon while eating
# ice cream is anomalous and unrelated to the consultancy agreement."
# .justification: "It is an implausible, fantastical statement in an otherwise
# contractual document."
# .reference_sentences: 보라색 코끼리에 관한 문장
위 예시가 추출하는 것: aspect는 문서 자체의 텍스트를 반환하고, concept은 출처와 함께 새로운 값을 반환합니다.
의사결정 모델로 추출하기
의사결정 모델은 폐쇄형 질문(예/아니오, 사용자의 레이블 중 하나, 척도의 한 단계)에 각 가능한 답변의 확률과 함께 답합니다. 아래에서는 계약서에서 aspect인 termination clauses를 각 문단이 해당하는지 여부를 결정하여 추출하고, 계약서에 관한 두 가지 질문(concept)에 하나의 요청으로 답합니다.
import os
from contextgem import (
Aspect ,
BooleanConcept ,
Document ,
DocumentDecisionModel ,
LabelConcept ,
)
doc = Document (
raw_text = (
"Service Agreement \n "
"Either party may terminate this Agreement for any reason by giving 30 days' "
"written notice to the other party. \n "
"This Agreement is governed by the laws of the State of New York. \n "
),
)
doc . add_aspects (
[
Aspect (
name = "Termination" ,
description = "Clauses on termination of the agreement" ,
)
]
)
doc . add_concepts (
[
BooleanConcept (
name = "Termination for convenience" ,
description = "Either party may terminate the agreement without cause" ,
),
LabelConcept (
name = "Notice form" ,
description = "Required form of the termination notice" ,
labels = [ "Written" , "Email" , "Any form" , "Not specified" ],
classification_type = "multi_class" ,
),
]
)
decision_model = DocumentDecisionModel (
model = "typesafe/jev-latest" , # 또는 다른 의사결정 모델, 클라우드 또는 로컬
api_key = os . environ . get ( "CONTEXTGEM_TYPESAFE_API_KEY" ),
)
# aspect: 각 문단에 대한 예/아니오 질문. concept: 둘 다 하나의 요청으로.
doc = decision_model . extract_all ( doc )
termination_clauses = doc . get_aspect_by_name ( "Termination" ). extracted_items
# 1개 항목, 문단: "Either party may terminate this Agreement for any reason..."
# .probabilities: {True: 0.99, False: 0.01} (반올림); 나머지 두 문단은
# 0.26과 0.03으로, 결정 임계값 0.5 미만
convenience = doc . get_concept_by_name ( "Termination for convenience" ). extracted_items [ 0 ]
# .value: True
# .probabilities: {True: 0.98, False: 0.02} (반올림)
notice_form = doc . get_concept_by_name ( "Notice form" ). extracted_items [ 0 ]
# .value: ["Written"]
# .probabilities: {"Written": 1.0, "Email": 0.0, "Any form": 0.0, "Not specified": 0.0}
위 예시가 추출하는 것: 각 문단에 대한 예 또는 아니오, 그리고 각 concept에 대한 답변으로, 각각 확률과 함께 제공됩니다.
Docling으로 파일에서 시작하기
문서는 파일입니다. Docling이 이를 변환하고, Document.from_docling()이 그 결과로 문서를 만들며, 여기서 각 문단은 파일 구조 내에서의 위치(예: 표 행의 열 헤더)와 해당 페이지를 유지합니다. ContextGem은 다음 형식의 파일을 지원합니다:
DOCX, DOC, RTF,
ODT, Pages
PPTX, PPT,
ODP, Keynote
XLSX, XLS,
ODS, Numbers
CSV
EPUB
Box Notes
이미지
오디오
비디오
WebVTT
HTML, MHTML
Markdown
AsciiDoc
LaTeX
XBRL
JATS XML
USPTO XML
DocLang
Docling JSON
METS GBS
EBCDIC
AFP
각 형식은 자체 파일로 테스트됩니다. 지원되는 형식은 확장자를 제공하며, 일부 형식에 필요한 것(예: DOC, PPT, XLS, RTF용 LibreOffice)도 제공합니다.
아래에서는 LLM이 2페이지 서비스 계약서에서 aspect와 concept을 추출하며, 각 항목은 해당 페이지로 인용됩니다.
import os
from docling . document_converter import DocumentConverter
from contextgem import Aspect , Document , DocumentLLM , JsonObjectConcept
# Docling으로 파일 변환, 예: PDF, DOCX, PPTX, XLSX 또는 HTML
result = DocumentConverter (). convert ( "service_agreement.pdf" )
# 문단은 파일 구조 내에서의 위치와 페이지를 유지
doc = Document . from_docling ( result . document )
doc . add_aspects (
[
Aspect (
name = "Termination" ,
description = "Clauses on the term of the agreement and its termination" ,
)
]
)
doc . add_concepts (
[
JsonObjectConcept (
name = "Fees" ,
description = "The monthly fee of each service" ,
structure = { "service" : str , "monthly_fee_eur" : float , "billing" : str },
add_references = True ,
)
]
)
llm = DocumentLLM (
model = "openai/gpt-6-luna" , # 또는 다른 LLM, 클라우드 또는 로컬
api_key = os . environ . get ( "CONTEXTGEM_OPENAI_API_KEY" ),
)
doc = llm . extract_all ( doc )
termination = doc . get_aspect_by_name ( "Termination" )
# .extracted_items: 3개 항목, 섹션 3의 제목과 조항 3.1 및 3.2
# .reference_page_numbers: [2]
fees = doc . get_concept_by_name ( "Fees" ). extracted_items
# 3개 항목, 요금 표의 각 행에 하나씩. 첫 번째:
# .value: {"service": "Hosting", "monthly_fee_eur": 1200.0,
# "billing": "In advance"}
# .reference_paragraphs: 표 행, 각 열의 헤더 포함:
# "Service: Hosting; Monthly fee: 1,200 EUR; Billing: In advance"
# .reference_page_numbers: [1]
위 예시가 추출하는 것: 표의 각 행에서 각 요금, 그리고 종료 조항으로, 각각 해당 페이지로 인용됩니다.
더 많은 예시
문서
이미지 · Docling의 파일 · 문단 컨텍스트 · 저장 및 불러오기
Aspect와 concept
Aspect · 하위 aspect · 문서의 concept · aspect의 concept · concept이 있는 aspect · JSON 객체 · 분류 · 참조 · 근거 · 재사용 가능한 파이프라인
LLM
클라우드 모델 · 로컬 모델 · 추출 방법 · 추론 노력 · 폴백 · 사용량 및 비용 · 채팅 · 도구를 사용한 채팅
의사결정 모델
클라우드 모델 · 로컬 모델 · Concept · Aspect · 결정 임계값 · 폴백 · 사용량 및 비용
모델 그룹
역할이 있는 LLM · LLM과 의사결정 모델 · 여러 문서
에이전트 워크플로
수집 시 메타데이터 · 도구에서의 추출 · MCP를 통한 도구 · 의사결정 지점 · 도구 선택
작동 방식
예시 계약서: 사용자가 정의하는 것과 추출되는 것.
콘텐츠를 …로 감싸세요
No comments yet.
to comment.