의료 QA를 위한 Long Context RAG에서 Lost-in-the-Middle 극복하기
Leveraging long context in retrieval augmented language models for medical question answering
TL;DR Highlight
RAG에서 긴 문서 중간에 있는 핵심 정보가 무시되는 문제를 map-reduce 전략으로 해결한 의료 도메인 논문.
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
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.