의료 QA를 위한 Long Context RAG에서 Lost-in-the-Middle 극복하기
Leveraging long context in retrieval augmented language models for medical question answering
TL;DR Highlight
Map-reduce 전략을 적용한 RAG 시스템이 의료 도메인에서 긴 문서 중간의 핵심 정보 무시 문제를 해결하고 정보 검색 정확도를 향상시킨다.
Who Should Read
의료/헬스케어 서비스에 RAG 파이프라인을 적용 중인 백엔드 개발자나 AI 엔지니어. 특히 검색 결과가 길어질수록 답변 품질이 들쭉날쭉한 문제를 겪고 있는 경우.
Core Mechanics
- RAG에서 검색된 문서가 많아질수록 중간에 위치한 핵심 정보를 LLM이 놓치는 'Lost-in-the-Middle' 현상이 의료 QA에서 특히 위험함
- BriefContext라는 map-reduce 전략 제안: 각 문서를 개별 요약(map)한 뒤 합쳐서 최종 답변 생성(reduce) — 모델 가중치 수정 없이 적용 가능
- GPT-4, Llama 등 여러 LLM 백본에서 모두 효과를 확인했고, 특정 모델에 종속되지 않음
- 의료 QA, 임상 의사결정 지원, 환자 대면 앱 등 고위험 도메인에서 오정보 리스크를 줄이는 데 초점
- 검색 결과의 rank(순위)와 density(밀도)가 RAG 응답 품질에 큰 영향을 미친다는 걸 실험으로 검증
Evidence
- 여러 의료 QA 데이터셋에서 다양한 LLM 백본으로 실험해 BriefContext의 일관된 성능 향상을 확인 (구체적 수치는 abstract에 미기재, 본문 참조 필요)
- Lost-in-the-Middle 문제를 모델 재학습 없이(zero weight modification) 워크플로우 변경만으로 해결했다는 점이 실용적 기여
How to Apply
- 기존 RAG 파이프라인에서 검색된 N개 문서를 한 번에 LLM에 넣는 대신, 각 문서별로 '이 문서에서 질문과 관련된 핵심만 요약해줘'를 개별 호출(map)한 뒤, 요약본만 모아서 최종 답변 생성(reduce)으로 교체
- 의료처럼 오답이 치명적인 도메인에서 검색 결과가 5개 이상 넘어갈 때부터 BriefContext 방식을 적용하면 중간 문서 누락 리스크를 줄일 수 있음
- map 단계의 요약 프롬프트에 '임상적으로 중요한 수치, 용량, 금기사항을 반드시 포함해'처럼 도메인 특화 지시를 추가하면 의료 정확도를 더 높일 수 있음
Code Example
# BriefContext map-reduce RAG 패턴 예시
from openai import OpenAI
client = OpenAI()
def map_summarize(doc: str, question: str) -> str:
"""각 문서를 질문 기준으로 개별 요약 (map 단계)"""
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "의료 전문 요약가입니다. 질문과 관련된 핵심 임상 정보만 3문장 이내로 요약하세요."},
{"role": "user", "content": f"질문: {question}\n\n문서:\n{doc}"}
]
)
return response.choices[0].message.content
def reduce_answer(summaries: list[str], question: str) -> str:
"""요약본을 합쳐 최종 답변 생성 (reduce 단계)"""
combined = "\n\n---\n\n".join(summaries)
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "의료 QA 전문가입니다. 아래 요약된 근거들을 바탕으로 정확하고 안전한 답변을 작성하세요."},
{"role": "user", "content": f"질문: {question}\n\n근거 요약:\n{combined}"}
]
)
return response.choices[0].message.content
# 실제 사용
question = "메트포르민의 신장 기능 저하 환자 금기 기준은?"
docs = retrieve_documents(question) # 기존 검색 단계
# map: 병렬 처리 가능
summaries = [map_summarize(doc, question) for doc in docs]
# reduce
final_answer = reduce_answer(summaries, question)
print(final_answer)Terminology
관련 논문
Airbyte Agents – 여러 데이터 소스를 아우르는 Agent용 Context Layer
Airbyte가 Slack, Salesforce, Linear 등 여러 SaaS 시스템의 데이터를 미리 인덱싱해서 Agent가 API를 일일이 뒤지지 않아도 되는 Context Store를 출시했다. 기존 MCP 방식보다 토큰을 최대 90%까지 줄이는 효과를 확인했다.
Polynomial Autoencoder가 Transformer Embedding에서 PCA를 능가하는 방법
PCA 인코더에 2차 다항식 디코더를 붙여서 닫힌 형태(closed-form)로 embedding 압축 품질을 크게 개선하는 기법으로, SGD 없이 numpy만으로 구현 가능하다.
비정형 Recall에서 Schema 기반 Memory로: 반복적 Schema-Aware Extraction을 통한 신뢰할 수 있는 AI Memory
RAG 스타일 텍스트 검색 대신 Schema로 정의된 구조화 레코드에 메모리를 저장하면, 정확한 사실 조회·상태 추적·집계 쿼리에서 압도적으로 높은 정확도를 얻을 수 있다.
Atomic – Local-first, AI 기반 개인 지식 그래프 앱
노트, 웹 클립, RSS 피드를 자동으로 임베딩·태깅·연결해주는 오픈소스 개인 지식 그래프 앱으로, 시맨틱 검색과 LLM 기반 위키 합성, MCP 통합까지 지원한다.
RAG 대신 Virtual Filesystem으로 AI 문서 어시스턴트 만든 이야기
Mintlify의 ChromaFs(Chroma DB 위의 UNIX 명령어 흉내 가상 파일시스템)가 RAG 청킹 한계를 극복해 세션 부팅 시간을 46초에서 100ms로 단축한다.
Chroma Context-1: Self-Editing 기능을 갖춘 검색 에이전트 학습 방법
Chroma의 20B 파라미터 agentic search 모델이 프론티어급 LLM 수준의 검색 성능을 1/10의 비용과 10배 빠른 속도로 달성한다.
Original Abstract (Expand)
While holding great promise for improving and facilitating healthcare through applications of medical literature summarization, large language models (LLMs) struggle to produce up-to-date responses on evolving topics due to outdated knowledge or hallucination. Retrieval-augmented generation (RAG) is a pivotal innovation that improves the accuracy and relevance of LLM responses by integrating LLMs with a search engine and external sources of knowledge. However, the quality of RAG responses can be largely impacted by the rank and density of key information in the retrieval results, such as the “lost-in-the-middle” problem. In this work, we aim to improve the robustness and reliability of the RAG workflow in the medical domain. Specifically, we propose a map-reduce strategy, BriefContext, to combat the “lost-in-the-middle” issue without modifying the model weights. We demonstrated the advantage of the workflow with various LLM backbones and on multiple QA datasets. This method promises to improve the safety and reliability of LLMs deployed in healthcare domains by reducing the risk of misinformation, ensuring critical clinical content is retained in generated responses, and enabling more trustworthy use of LLMs in critical tasks such as medical question answering, clinical decision support, and patient-facing applications.