반나절 만에 만드는
작동하는 RAGBuild a Working RAG
in Half a Day
답변마다 가 따라붙는 파이프라인을 손으로 짓다Hand-building a pipeline on UN policy reports with LangChain,
where every answer carries its
GitHub · 참고자료GitHub · resources
모든 코드는 셀 단위로 공개돼 있다. 각 블록은 Colab 셀 하나에 대응한다.All the code is published cell by cell. Each block corresponds to one Colab cell.
DH2026 · Build a Working RAG in Half a Day · UN Policy Reports with LangChain
이 답변을 믿으시겠습니까?Would you trust this answer?
2025년 기준 전 세계 극빈 인구는 약 6억 9,200만 명으로 추산됩니다.1 이는 팬데믹 이전 추세로의 회복이 지연된 결과이며, 사하라 이남 아프리카가 전체의 절반 이상을 차지합니다.2 현재 감소 속도가 유지될 경우 2030년 목표 달성은 어려울 것으로 전망됩니다.3
As of 2025, roughly 692 million people worldwide are estimated to live in extreme poverty.1 This reflects a delayed recovery to pre-pandemic trends, with sub-Saharan Africa accounting for more than half of the total.2 At the current rate of decline, the 2030 target is projected to be out of reach.3
같은 질문, 두 개의 경로One question, two paths
이 불안에 대한 기술적 응답이 RAG다. 2020년 Lewis와 동료들이 이 개념을 본격적으로 제시한The technical response to this unease is RAG. After Lewis and colleagues set out the concept in earnest in 2020,1Retrieval-Augmented Generation for Knowledge-Intensive NLP TasksLewis, Perez, Piktus et al. · NeurIPS 2020검색기(retriever)와 생성기(generator)를 결합한 구조를 제안하고, 모수(parametric) 기억에만 의존하는 모델보다 사실성이 개선됨을 보였다. RAG라는 이름이 자리 잡은 출발점.Proposed an architecture combining a retriever with a generator, and showed improved factuality over models relying on parametric memory alone. The point at which the name RAG took hold.arXiv:2005.11401 이후, RAG는 빠르게 확산해 생성형 AI의 약점을 보완하는 핵심 기술로 자리 잡았다. RAG spread quickly and became a core technique for shoring up the weaknesses of generative AI.2Retrieval-Augmented Generation for Large Language Models: A SurveyGao, Xiong, Gao et al. · arXiv 2023 (rev. 2024)RAG 연구를 Naive → Advanced → Modular 세 세대로 정리한 대표 서베이. 이 계보가 존재한다는 사실 자체가, 초기 RAG의 문제가 모델 성능이 아니라 구조에 있었음을 보여준다.The standard survey, organising RAG research into three generations — Naive → Advanced → Modular. That this lineage exists at all shows the problem with early RAG lay in structure, not model performance.arXiv:2312.10997
근거를 찾은 뒤에 말한다.We do not look for grounds after speaking.
We speak after finding the grounds.
그렇다면 RAG가 다 해결해 주는가So does RAG solve everything?
전혀 그렇지 않다. 오히려 최근 보고되는 연구들은 RAG가 기대만큼 튼튼하지 않다고 말한다.Not at all. Recent studies report the opposite — that RAG is not as robust as we hoped.3Seven Failure Points When Engineering a Retrieval Augmented Generation SystemBarnett, Kurniawan, Thudumu et al. · CAIN 2024연구·교육·생의학 세 분야의 실제 구축 사례에서 실패 지점 일곱 개를 도출했다. 결정적인 것은 그 일곱 개가 모두 모델 가중치가 아니라 파이프라인 단계에 자리한다는 점이다.Derived seven failure points from real deployments across research, education and biomedicine. Decisively, all seven sit in pipeline stages, not model weights.arXiv:2401.05856 · DOI 10.1145/3644815.36449454A Systematic Literature Review of Retrieval-Augmented Generation: Techniques, Metrics, and ChallengesBrown, Roman, Devereux · arXiv 20252020년부터 2025년 5월까지 피인용 상위 128편을 PRISMA 방식으로 검토해, 평가 관행과 방법론의 공백을 정리했다. 가장 최신의 체계적 문헌고찰.A PRISMA review of the 128 most-cited papers from 2020 to May 2025, mapping gaps in evaluation practice and methodology. The most recent systematic review.arXiv:2508.06401 검색을 붙였는데도 환각이 사라지지 않는 사례가 축적되고 있고 Cases keep accumulating where hallucination survives even with retrieval attached,5RAGTruth: A Hallucination Corpus for Developing Trustworthy Retrieval-Augmented Language ModelsNiu, Wu, Zhu et al. · ACL 2024검색해 온 근거와 어긋나거나 근거가 없는 주장을 단어 단위로 주석한 코퍼스. 검색을 붙여도 환각은 살아남는다는 사실을 실증했다.A corpus annotating, word by word, claims that contradict or lack the retrieved evidence. Demonstrated empirically that hallucination survives retrieval.arXiv:2401.00396 · ACL 2024.acl-long.585, 그 원인은 RAG 바깥이 아니라 RAG의 설계 그 자체에 있다. and the cause lies not outside RAG but in the design of RAG itself.
재순위 역효과reranking backfires11Drowning in Documents: Consequences of Scaling Reranker InferenceJacob et al. · ReNeuIR @ SIGIR 2025재순위 모델은 일정 지점까지는 결과를 개선하지만, 더 많은 문서를 채점하게 하면 1차 검색기보다도 성능이 떨어진다. 단일 단계가 품질을 적극적으로 해칠 수 있음을 보여주는 사례.Rerankers improve results up to a point, but when made to score more documents they fall below the first-stage retriever. A case where a single stage actively harms quality.arXiv:2411.11767
모델과 모델 사이에 놓인 파이프라인이다.What determines quality is not the model, but
the pipeline laid between the models.
무엇을 만드는가What we build
① 에서 무너졌던 그 카드를, 근거가 붙은 형태로 다시 세운다.We rebuild the card that collapsed in ①, this time with its grounds attached.
보고서가 제시한 극빈 인구 규모와 감소 추세를 아래 근거 문단에 있는 내용만으로 정리해 답한다.Answers with the report's figures for the extreme-poverty population and its trend, using only what appears in the source passages below.
전거는 따라오지 않는다Provenance does not follow
인용을 붙이도록 설계된 최신 모델조차 절반 가까운 경우에 근거가 불완전했다.Even recent models designed to attach citations left the grounds incomplete in nearly half of cases.13Enabling Large Language Models to Generate Text with CitationsGao, Yen, Yu, Chen (Princeton NLP) · EMNLP 2023인용 품질을 재는 최초의 벤치마크 ALCE를 제안했다. ELI5 과제에서 최고 성능 모델조차 약 절반의 경우 인용 근거가 온전하지 않았다. 전거는 모델에 맡겨 두면 확보되지 않는다.Proposed ALCE, the first benchmark for citation quality. On the ELI5 task, even the best-performing model had incomplete citation support in roughly half of cases. Provenance is not secured by leaving it to the model.arXiv:2305.14627 · ACL 2023.emnlp-main.398 아카이브 자료에서도 기성 파이프라인만으로는 부족했다. With archival material too, an off-the-shelf pipeline was not enough.14FolkRAG: a retrieval-augmented generation system for cultural heritage materialsKelly, Schild, Jafari · Neural Computing and Applications, 2025미국 의회도서관 American Folklife Center 소장 자료를 대상으로 한 RAG. 파편화된 아카이브 메타데이터 탓에 기성 구성으로는 작동하지 않아 문장 단위 검색·HyDE·재순위·벡터저장소 조정을 모두 거쳐야 했다.
확인 범위: 유료 접근이라 초록 수준까지만 검증함.A RAG system over holdings of the American Folklife Center at the Library of Congress. Fragmented archival metadata meant an off-the-shelf configuration would not work; sentence-level retrieval, HyDE, reranking and vector-store tuning were all required.
Extent verified: paywalled — checked to abstract level only.DOI 10.1007/s00521-025-11455-4
전거는 설계해서 얻는다Provenance is obtained by design
메타데이터를 짜고, 청크마다 출처를 붙이고, 검색 결과에 실어 나르고, 답변 끝에 다시 꺼내 놓는다. 그 설계가 오늘 손으로 짓는 것이다.You compose the metadata, attach a source to every chunk, carry it through the retrieval results, and lay it out again at the end of the answer. That design is what we build by hand today.
출처(典據)를 갖춘 RAG 파이프라인이다.What we build is not a chatbot, but
a RAG pipeline that carries its provenance.
무엇으로 만드는가What we build it with
- 가장 널리 알려진 국제 보고서다. 내용을 몰라도 무엇을 묻고 싶은지는 안다.The best-known international report there is. Even without knowing its contents, you know what you want to ask it.
- 목표·절·쪽이 뚜렷해 구조화가 가능하다. 실습 자료로서 이 점이 결정적이다.Goals, sections and pages are clearly marked, so it can be structured. For a hands-on corpus, that is decisive.
- RAG 파이프라인을 가장 간단하게 조립할 수 있는 코드다.It is the code that lets you assemble a RAG pipeline most simply.
- 단계가 코드로 분리돼 있어 한 마디씩 열어 볼 수 있다. 오늘의 목적에 맞는다.The stages are separated in code, so you can open them one link at a time. That suits today's purpose.
인용에 출처를 달고 검색된 근거 위에서만 진술하는 태도는 인문학이 오래 지켜 온 자료 비판의 규율 그 자체다. 실록이든 관보든 문학 텍스트든 — 다루는 자료는 달라도 규율은 같다. 오늘 하는 일은 그 규율을 기계에 이식하는 작업이다.Citing your sources and asserting only on retrieved grounds is the discipline of source criticism the humanities have long kept. Veritable records, official gazettes, literary texts — the material differs, the discipline does not. What we do today is transplant that discipline into a machine.
RAG란 무엇인가 — 두 국면의 흐름What RAG is — a flow in two phases
RAG는 성격이 다른 두 국면으로 나뉜다. A. 자료 준비는 한 번만 하는 오프라인 작업이고, B. 질문·검색·답변은 질문할 때마다 반복되는 온라인 작업이다.RAG divides into two phases of different character. A. Preparing the material is offline work done once; B. Question, retrieval, answer is online work repeated with every question.
A의 종착점이자 B의 진입점. 임베딩된 자료를 좌표로 정리해 둔 색인이다. 질문이 들어오면 이 색인을 뒤져 가장 가까운 항목을 찾는다 — 방대한 자료를 매번 처음부터 훑지 않고, 뒤에 붙은 색인으로 곧장 찾아가는 것과 같다.The terminus of A and the entrance to B. An index that arranges the embedded material by coordinates. When a question arrives, it searches this index for the nearest entries — like going straight to the index at the back of a book instead of reading a vast work from the beginning every time.
오늘의 여정 — STEP 1에서 10까지Today's journey — STEP 1 to 10
앞의 A/B 흐름을 열 단계로 해체한다. STEP 1에서 준비를 끝내면, 이후는 네트워크가 끊겨도 돌아간다. 가 오늘의 무게중심이다.We take the A/B flow apart into ten steps. Once STEP 1 finishes the preparation, everything after it runs even with the network cut. is today's centre of gravity.
끝나고 나면 무엇이 남는가What remains when this is over
반나절 뒤에 손에 쥐고 나가는 것은 셋이다. 각각이 무엇을 뜻하는지가 더 중요하다.Three things go home with you after half a day. What each of them means matters more.
환경설정 · 자산준비Setup · asset preparation
- 공유 Google Drive 폴더를
내 드라이브에 바로가기 추가 (다운로드 아님, 포인터만)Add a shortcut to the shared Google Drive folder inMy Drive(not a download — just a pointer) → 구글 드라이브 추가 방법How to add the Google Drive shortcutgithub.com/littlekg87/DH2026/…/Workshop_procedure.md - Colab 런타임을
T4 GPU로 설정 — 생성 모델 Qwen3에 필요Set the Colab runtime toT4 GPU— required by the Qwen3 generation model
버전을 고정(pin)해 참가자 20명이 완전히 같은 환경에서 실행하도록 한다. Hugging Face Hub를 오프라인으로 봉인(HF_HUB_OFFLINE)해, 이후 어떤 셀도 몰래 인터넷에 나가지 않도록 못 박는다. 모델은 모두 공유 드라이브에서 로컬로 읽는다.Versions are pinned so all 20 participants run in exactly the same environment. The Hugging Face Hub is sealed offline (HF_HUB_OFFLINE), nailing down that no later cell quietly reaches for the internet. Every model is read locally from the shared Drive.
# Hugging Face Hub 봉인 — 모든 자산은 이미 로컬에 있다seal the Hugging Face Hub — every asset is already local os.environ["HF_HUB_OFFLINE"] = "1" os.environ["TRANSFORMERS_OFFLINE"] = "1" # Qwen3에는 GPU가 필요하다. 없으면 여기서 멈춘다.Qwen3 needs a GPU. Without one, stop here. assert torch.cuda.is_available(), "No GPU detected..." print("GPU:", torch.cuda.get_device_name(0)) drive.mount("/content/drive") BASE = "/content/drive/MyDrive/DH2026_Workshop" ENCODER_DIR = f"{BASE}/Encoder" LLM_DIR = f"{BASE}/LLM"
본격적인 작업 전에 라이브러리·모델·데이터를 한자리에 모아 둔다. 이후 중간에 다시 자료를 찾으러 나가지 않도록 — 네트워크 봉인은 "이 자리에 있는 것만으로 끝까지 간다"는 약속이다.Before the real work begins, gather libraries, models and data in one place, so you never have to go looking for material mid-task. Sealing the network is a promise: we finish with what is on this desk.
naive chunk 실패 목격Witness naive chunking fail
500자마다 눈 감고 자르고 50자를 겹친다. 구조도, 소제목도, 전거도 없다. 실행해 보면 왜 이것이 실패인지 눈으로 확인된다.Cut blind every 500 characters with a 50-character overlap. No structure, no headings, no provenance. Run it and you see with your own eyes why it fails.
# 눈 감고 500자씩 절단, 50자 겹침 — 나이브 기준선cut blind every 500 chars, 50-char overlap — the naive baseline splitter = RecursiveCharacterTextSplitter( chunk_size=500, chunk_overlap=50) naive_chunks = splitter.split_text(raw_text)
글자 수는 의미 경계를 모른다Character counts know nothing of meaning
문장이 중간에서 잘리고, 조판 지시문이 본문에 섞이며, 숫자 부스러기만 남은 청크가 생기고, Goal 경계가 뒤섞인다.Sentences are severed mid-way, typesetting instructions bleed into the body, chunks survive holding nothing but scraps of numbers, and Goal boundaries are jumbled together.
두 가지가 동시에 무너졌다Two things collapsed at once
① 원천 오염 — 조판 지시문·표 부스러기가 섞여 있다.
② 구조 무지 — 글자 수로 자르니 의미 단위를 모른다.① Contaminated at source — typesetting instructions and table debris are mixed in.
② Blind to structure — cutting by character count knows no unit of meaning.
두 문제 다 구조를 모르기 때문이다. 구조를 명시하면 둘 다 풀린다 → XML(STEP 3)Both problems come from not knowing the structure. Make the structure explicit and both dissolve → XML (STEP 3)
글을 내용과 무관하게 일정 길이로 잘라 버리면, 한 문장이 두 조각으로 흩어지고 앞뒤 맥락을 잃는다. 어디서 끊을지는 글자 수가 아니라 의미의 단위가 정해야 하고, 그 단위를 아는 건 자료를 읽은 사람이다.Cut text to a fixed length regardless of content and a single sentence scatters into two pieces, losing the context on either side. Where to break should be decided by the unit of meaning, not the character count — and the person who knows that unit is the one who has read the material.
PDF → XML ★ 무게중심★ centre of gravity
편집자는 소제목을 굵은 11포인트로, 본문을 9포인트로 지정해 두었다. 조판이 곧 구조다. 그러니 "이 줄이 소제목인가"를 글자만 보고 추측할 필요가 없다. 문서가 이미 선언해 둔 것을 읽으면 된다.The editor set subheadings in bold 11-point and body text in 9-point. The typesetting is the structure. So there is no need to guess from the words alone whether a line is a subheading. Just read what the document has already declared.
def classify(spans): font, size = spans[0]["font"], round(spans[0]["size"], 1) if "Gotham-Black" in font and 15 <= size <= 17: return "goal_title" if all("GothamBold" in s["font"] and 10.5 <= s["size"] <= 11.5 for s in spans): return "heading" # ← 소제목subheading if font.startswith("Whitney-") and 8.8 <= size <= 9.2: return "body" # ← 본문body text return "ignore" # 나머지는 전부 버린다discard everything else
조판을 읽는다.Do not read the letters —
read the typesetting.
# build_xml.py : [입력 PDF] [출력 XML][input PDF] [output XML] !python "{BUILD_SCRIPT}" "{PDF_PATH}" sdg_report_2025.xml
서지학은 활자와 행관(行款), 판식을 보고 판본을 가려낸다. 본문을 다 읽기 전에 형태가 먼저 말해 주기 때문이다. 여기서 하는 일도 같다 — 이 문서에서는 서체가 그 형태였다. 자료마다 구조를 담고 있는 자리는 다르고, 그 자리를 찾아내는 것이 연구자의 몫이다.Bibliography distinguishes editions by their type, line rulings and page format, because the form speaks first, before you have read the text through. What we do here is the same — in this document, the form was the typeface. Where the structure lives differs from source to source, and finding that place is the researcher's part of the work.
XML → chunk
정본 XML은 드라이브에서 읽기 전용으로 불러오므로, 참가자 전원이 완전히 같은 판본에서 출발한다. 검색 대상이 되는 것은 소제목 + 본문이고, Goal 번호·이름·쪽수는 검색되지 않고 전거로만 실린다.The canonical XML is loaded read-only from the Drive, so every participant starts from exactly the same edition. What becomes searchable is subheading + body; the Goal number, name and pages are never searched — they ride only as provenance.
인코더의 입력 한도는 256토큰이다. 넘으면 뒷부분이 잘린 채 벡터가 되어 검색에서 빠진다. 그래서 172단어(제목 포함)를 넘으면 문단 경계에서, 문단 하나가 그보다 길면 문장 경계에서 나눈다 — 문장은 자르지 않는다.The encoder's input limit is 256 tokens. Go over and the tail is truncated before it becomes a vector, dropping out of retrieval entirely. So beyond 172 words (title included) we split at a paragraph boundary, and if a single paragraph is longer than that, at a sentence boundary — we never cut a sentence.
47 / 108 소제목47 / 108 subheadings
한도 안에 들어오므로 1 소제목 = 1 청크 그대로.They fit within the limit, so one subheading stays one chunk.
나머지 61 소제목The remaining 61 subheadings
문단·문장 경계에서 분할. part: "1/2"가 붙지만 heading·goal·pages는 동일하므로 전거는 그대로다.Split at paragraph and sentence boundaries. A part: "1/2" is attached, but heading, goal and pages stay identical, so the provenance is unchanged.
chunks.append({
"metadata": { # 전거. 절대 임베딩 안 함provenance. never embedded
"id": f"G{g_num:02d}-S{i+1:02d}",
"goal": g_num,
"goal_name": g_name,
"pages": g_pages,
"heading": heading,
},
"text": f"{heading}\n{body}", # 본문. 이것만 임베딩body. only this is embedded
})
LangChain Document는 출처가 적힌 색인 카드다. 앞면(page_content)엔 검색될 본문을, 뒷면(metadata)엔 출처를 적는다. 뒷면은 검색되지 않지만, 카드가 뽑힐 때 늘 함께 딸려 나온다 — 그것이 전거(典據, 출처 근거)다.A LangChain Document is an index card with its source written on it. The front (page_content) holds the text to be searched; the back (metadata) holds the source. The back is never searched, but it always comes out with the card when the card is drawn — that is provenance.
소제목만은 양면에 모두 적는다. 앞면에 두는 이유는 나뉜 조각 때문이다 — part 2/2는 본문 중간 문단들만 갖고 있어서, 소제목이 없으면 무슨 주제인지 알 수 없는 고아 문단이 된다. 제목을 붙여야 검색이 그 조각을 찾아낸다.The subheading alone is written on both faces. It goes on the front because of the split pieces — a part 2/2 holds only middle paragraphs, and without the subheading it is an orphan passage whose subject cannot be told. Attach the title and retrieval can find that piece.
Chunk → Vector
인코더는 드라이브에서 로컬로 불러오고(허브가 봉인돼 있으므로), normalize_embeddings=True로 정규화한다. 정규화된 벡터에서는 L2거리² = 2 − 2·코사인유사도 — L2와 코사인이 순위상 동치가 되어, 화면 숫자와 설명이 일치한다.The encoder is loaded locally from the Drive (the Hub is sealed) and normalised with normalize_embeddings=True. For normalised vectors, L2 distance² = 2 − 2·cosine similarity — L2 and cosine rank identically, so the numbers on screen match the explanation.
embeddings = HuggingFaceEmbeddings( model_name=ENCODER_DIR, model_kwargs={"device": "cuda"}, encode_kwargs={"normalize_embeddings": True}, ) # 각 문장 → 384개의 숫자each passage → 384 numbers vectors = embeddings.embed_documents([c["text"] for c in chunks])
글의 뜻을 384개 축 위의 한 지점으로 옮긴다. 비슷한 뜻은 가까이, 다른 뜻은 멀리 놓인다. 주제별로 자료의 자리를 정해 두는 분류 체계와 같되, 그 자리를 사람이 아니라 의미의 근접성이 결정한다.The sense of a passage is moved to a single point on 384 axes. Similar meanings land near each other, different ones far apart. It is like a classification scheme assigning each item a place by subject — except the place is decided not by a person but by proximity of meaning.
Vector DB(FAISS) 구축Building the Vector DB (FAISS)
여기서 A(자료 준비)가 끝나고 B(질문·검색)가 시작된다. 앞의 흐름도에서 청록으로 강조된 경첩이 바로 이 색인집이다. FAISS는 벡터, 원문, id 테이블 세 저장소를 나란히 두고, 색인 번호로 즉시 맞물린다.Here A (preparing the material) ends and B (question and retrieval) begins. The hinge picked out in teal in the earlier diagram is exactly this index. FAISS keeps three stores side by side — vectors, source text, and an id table — meshed instantly by index number.
store = FAISS.from_embeddings( text_embeddings=list(zip( [c["text"] for c in chunks], vectors)), embedding=embeddings, metadatas=[c["metadata"] for c in chunks], ids=[c["metadata"]["id"] for c in chunks], ) # 벡터 저장소 · id 테이블 · 원문 저장소가 색인 번호로 맞물린다vector store · id table · document store mesh by index number
수천 항목을 좌표로 정리해 둔 색인. 이제 어떤 질문이 와도 전체 원문을 처음부터 읽지 않고, 색인만 뒤져 가장 가까운 항목으로 곧장 간다. 메타데이터(전거)가 함께 저장되어, 찾은 항목마다 출처가 딸려 나온다.An index arranging thousands of entries by coordinate. Whatever question arrives, we no longer read the whole text from the start — we search the index alone and go straight to the nearest entries. The metadata (the provenance) is stored alongside, so every entry found brings its source with it.
Query → Vector
질문과 청크가 같은 좌표계에 놓여야 거리를 잴 수 있다. 다른 자로 잰 길이는 비교할 수 없듯, 같은 인코더로 임베딩해야 한다. 여기서 B 국면(온라인)이 실제로 돌기 시작한다.Question and chunks must sit in the same coordinate system before a distance can be measured. Just as lengths taken with different rulers cannot be compared, both must be embedded by the same encoder. This is where phase B (online) actually starts running.
query = "How many people still live in extreme poverty?" # 청크와 같은 인코더 · 같은 384차원 좌표계same encoder as the chunks · same 384-dim coordinate system qv = embeddings.embed_query(query) print(f"vector: {len(qv)} dims") # → 384
질문과 자료를 비교하려면 같은 척도가 필요하다. 청크를 잰 그 인코더로 질문도 재야, 둘 사이의 거리가 의미를 갖는다. 서로 다른 도량형으로 잰 값은 나란히 둘 수 없다.Comparing a question with the material requires one scale. Only if the question is measured by the encoder that measured the chunks does the distance between them mean anything. Values taken in different systems of measure cannot be set side by side.
Distance 계산Distance, by hand
쿼리 벡터와 모든 청크 벡터의 차이를 제곱해 더하고 제곱근을 취한다 — 그게 L2 거리다. 정렬하면 가장 가까운 청크가 위로 온다. 다음 단계에서 FAISS 결과와 완전히 같음을 확인한다.Take the difference between the query vector and every chunk vector, square it, sum, and take the square root — that is L2 distance. Sort, and the nearest chunk rises to the top. In the next step we confirm this is exactly identical to what FAISS returns.
V = store.index.reconstruct_n(0, store.index.ntotal) # 모든 청크every chunk Q = np.array(qv) # 질문 하나one question distances = [] for v in V: diff = v - Q # 384개의 차이384 differences dist = np.sqrt((diff ** 2).sum()) # 제곱→합→제곱근square→sum→root distances.append(dist) order = np.argsort(distances) # 가까운 순 정렬sort nearest first
검색이 마법처럼 보이지만, 실은 손으로 잴 수 있는 산술이다. 원리를 직접 계산해 보는 것은, 도구가 내놓은 결과를 그대로 믿기 전에 그 결과가 어떻게 나왔는지 스스로 확인하는 태도다 — 인문학 연구가 근거를 손수 대조해 온 방식 그대로.Retrieval looks like magic, but it is arithmetic you can do by hand. Working the principle out yourself is the habit of checking how a result was arrived at before trusting what a tool hands you — exactly how humanities scholarship has always collated its evidence.
FAISS 검색 + 전거FAISS retrieval + provenance
"방금 손으로 한 게 이거였다." 손계산과 FAISS의 상위 3개가 정확히 일치함을 보여주고, 메타데이터로 전거를 표시한다 — 메타데이터는 검색되지 않지만 결과에 늘 딸려 나온다.“That is what we just did by hand.” We show the top 3 from the hand computation and from FAISS agreeing exactly, then display the provenance from the metadata — which is never searched, yet always comes out with the result.
results = store.similarity_search_with_score(query, k=3) print("STEP 8 (by hand):", hand_top3) print("STEP 9 (FAISS) :", faiss_top3) print("match :", hand_top3 == faiss_top3) # True # 각 결과에 전거를 붙인다attach the provenance to each result print(f"{m['id']} · Goal {m['goal']} {m['goal_name']} · pp. {m['pages']}")
찾은 대목마다 "어느 목표, 어느 절, 몇 쪽"을 명기한다. 인용에 반드시 출처를 다는 인문학의 규율 그대로다. 근거를 댈 수 없는 검색 결과는 신뢰할 수 없다.For every passage found, state which Goal, which section, which pages. It is the humanities' own discipline of always citing a source. A retrieval result whose grounds cannot be given is not trustworthy.
생성 + 전거Generation + provenance
Qwen3는 causal 모델(AutoModelForCausalLM)이자 chat 모델이라, 입력을 chat 템플릿으로 감싸고 답변만 잘라낸다. 핵심은 before/after 대비다.Qwen3 is a causal model (AutoModelForCausalLM) and a chat model, so we wrap the input in a chat template and slice out just the answer. The point is the before/after contrast.
기억만으로 답한다Answering from memory alone
검색도 근거도 없이 모델의 기억에서 답을 꺼낸다. 그럴듯하지만 낡았을 수 있고, 틀렸을 수 있고, 확인할 출처가 없다.The answer is drawn from the model's memory, with no retrieval and no grounds. It is plausible, but it may be stale, it may be wrong, and there is no source to check.
보고서에 딛고 선 답An answer standing on the report
근거를 검색해 LLM에 넣고, 답변을 출처와 함께 보여준다. 이제 모든 진술이 열어 확인할 수 있는 named source 위에 선다.The grounds are retrieved, fed to the LLM, and the answer is shown together with its sources. Now every statement stands on a named source you can open and check.
def ask_with_sources(q, k=3): results = store.similarity_search_with_score(q, k=k) # 1. 검색retrieve context = "\n\n".join(doc.page_content for doc, _ in results) prompt = f"Use only the following sources... {context}\n\nQuestion: {q}" answer = llm.invoke(prompt) # 3. 생성generate print(answer) print("\nSources") # 4. 전거provenance for doc, _ in results: m = doc.metadata print(f" [{m['id']}] Goal {m['goal']} · pp. {m['pages']}")
구조를 먼저 이해하고, 정제는 거기에 맞춘다Understand the structure first, then fit the cleaning to it
검색 단위가 답변의 전거(典據) 단위를 정한다.The structure of the material sets the unit of retrieval,
and the unit of retrieval sets the unit of provenance in the answer.
무엇이 본문인가what is heading
and what is body
버린다what the structure
omits, discard
검색 단위the boundary is
the unit of retrieval
출처 주소the structure is
the source address
오늘 우리는 STEP 2에서 구조를 모른 채 글자 수로 자르는 실패를 고의로 경험했다. 이렇게 할 경우 실패의 원인은 명확하다 — 자료의 구조를 먼저 확정하지 않았다는 것.Today, in STEP 2, we deliberately went through the failure of cutting by character count without knowing the structure. When you do that, the cause of the failure is clear — the structure of the material was not established first.
구조를 확정하고 나면 나머지는 따라온다. 무엇을 버릴지가 분명해지고, 어디서 자를지가 분명해지고, 잘린 조각마다 제 주소가 붙는다. 전거는 마지막에 덧붙이는 장식이 아니라, 구조를 지킨 결과로 저절로 남는 것이다.Once the structure is settled, the rest follows. What to discard becomes clear, where to cut becomes clear, and every piece cut carries its own address. Provenance is not an ornament added at the end — it is what remains of its own accord when the structure has been kept.
이 워크샵이 남기는 것은 챗봇 한 개가 아니라, 여러분의 자료에 그대로 옮겨 쓸 수 있는 방법이다. 실록이든 관보든 문학 텍스트든 철학 원전이든 — 자료마다 구조가 놓인 자리는 다르지만, 구조를 먼저 읽고 거기에 정제를 맞춘다는 순서는 같다. 그 순서를 세우는 자리에서 오늘의 작업이 다시 쓰인다.What this workshop leaves you is not one chatbot but a method you can carry straight over to your own material. Veritable records, official gazettes, literary texts, philosophical originals — where the structure sits differs with every source, but the order is the same: read the structure first, then fit the cleaning to it. Wherever you set that order, today's work is written again.
그래서, 가장 먼저 보아야 할 것So, what to look at first
오히려 인문학, 특히 역사학에서 오랫동안 강조해온 것, 그리고 다소 지루한 것.It is, rather, what the humanities — history above all — have long insisted on, and what sounds rather dull.
어떻게 구조화되어 있는지 아는 것이다.Namely, knowing what your material actually says,
and how it is structured.
오늘의 원칙으로, 저도 만들고 있습니다Built on the very principles we practiced today
반나절을 끝까지 함께해 주셔서 고맙습니다. 오늘 실습한 그 원칙 그대로, 저는 제 자료 위에 RAG를 짓고 있습니다. QR이나 링크로 직접 만나 보세요.Thank you for staying through the whole half-day. On the very principles we practiced today, I build RAG systems on my own material. Meet them by QR or link.
시간이 되신다면, 제 발표에도 와 주세요If you have the time, come to my talks
이번 DH2026에서 두 편을 발표합니다. 특히 수요일 발표는 오늘 이야기한 정교한 RAG 파이프라인 구축 전략을 다룹니다.I'm presenting two papers at DH2026. The Wednesday talk in particular is about strategies for building a well-crafted RAG pipeline — exactly today's theme.