본문 바로가기
📚도서 공부/LangChain으로 구현하는 LLM

4-2-3(정보요약, 맵 리듀스 파이프라인) Langchain 비서 구축

by Majestyblue 2024. 4. 22.

2. 정보 요약

빠르게 변화하는 요즘 환경에서는 지속적으로 증가하는 정보 양에 대응하는 것이 어렵다. 특히 컴퓨터 과학 및 AI 분야는 더욱 그렇다. 수 많은 논문을 읽고 이해하는 것에 시간이 너무 많이 소요된다. 이 때 자동화가 중요한 역할을 한다. LLM은 강력한 언어 이해 능력을 통해 텍스트를 간추리는 데 뛰어나다. LangChain을 사용해 요약 기술을 더욱 정교한 수준으로 탐색해 보자.

 

4. 맵 리듀스 파이프라인

Langchain은 맵 리듀스 접근방식을 지원한다. 긴 문서를 요약하기 위해 먼저 문서를 LLM의 토큰 컨텍스트 길이에 적합한 작은 부분(청크 chunk)으로 나눈 다음, 맵 리듀스 체인이 이러한 청크를 독립적으로 요약한 후 재결합할 수 있다. 이렇게 하면 어떤 길이로도 요약을 확장할 수 있으며 청크 크기를 제어할 수 있다.

주요 단계는 아래와 같다.

  • 맵(Map): 문서는 요약 체인(LLM 체인)을 통과한다.
  • 콜랩스(Collapse): 문서가 여러개라면, 요약된 문서를 단일 문서로 결합한다.
  • 리듀스(Reduce): 축소된 문서는 최종 LLM 체인을 통과해 결과를 생성한다.

이는 문서를 병렬로 처리하고 개별 문서를 추론, 생성 또는 분석하고 그 출력을 결합하는데 LLM을 사용할 수 있다.

PDF 문서를 로드하고 요약하는 간단한 예제다.

%%time
from langchain.chains.summarize import load_summarize_chain
from langchain.document_loaders import PyPDFLoader
#위에서 선언하였음.
# from langchain.llms import GPT4All
#model = "E:\\GPT4ALL\\Download Models\\mistral-7b-instruct-v0.2.Q4_0.gguf"
#llm = GPT4All(model=model, device='gpu')

pdf_file_path = "E:\\GPT4ALL\\Download Models\\what_is_prediabetes.pdf" # 2page
pdf_loader = PyPDFLoader(pdf_file_path)
docs = pdf_loader.load_and_split()
chain = load_summarize_chain(llm, chain_type = "map_reduce")
chain.run(docs)
CPU times: total: 3.11 s
Wall time: 58.4 s
"\\nPrediabetes is a condition with elevated blood glucose levels, increasing heart disease/stroke risks and leading to type 2 diabetes. Symptoms are absent; regular check-ups are essential. Prevention includes daily physical activity (30 minutes walk five days weekly), weight loss, medication if prescribed. Healthy habits: avoid sugary drinks, lower-calorie snacks, veggies in meals, limit processed meats, use healthy oils, reduce dessert portions, track food intake, and get tested for diabetes risk via the American Diabetes Association's resources."

"\\n당뇨병 전단계는 혈당 수치가 상승하여 심장병/뇌졸중 위험이 증가하고 제2형 당뇨병을 초래하는 질환입니다. 증상은 없으며 정기적인 검진이 필수적입니다. 예방에는 매일 신체 활동(주 5일 30분 걷기), 체중 감량, 처방된 경우 약물 복용 등이 포함됩니다. 건강한 습관: 설탕이 든 음료, 저칼로리 간식, 식사 중 채소, 가공육 제한, 건강한 기름 사용, 디저트 양 줄이기, 음식 섭취 추적, 미국 당뇨병 협회 자원을 통한 당뇨병 위험 검사 받기"

만약 문서가 모델이 허용하는 토큰 수를 넘어버리면(20pg, 8pg이지만 토큰이 많은 경우 등)

ERROR: The prompt size exceeds the context window size and cannot be processed.

오류: 프롬프트 크기가 컨텍스트 창 크기를 초과하여 처리할 수 없습니다.

이런 식으로 오류를 뿜으면서 이상한 요약본을 출력한다.

 

위 코드에서 맵 및 리듀스의 기본 프롬프트는 다음과 같다.

langchain/libs/langchain/langchain/chains/summarize/map_reduce_prompt.py at master · langchain-ai/langchain · GitHub

 

langchain/libs/langchain/langchain/chains/summarize/map_reduce_prompt.py at master · langchain-ai/langchain

🦜🔗 Build context-aware reasoning applications. Contribute to langchain-ai/langchain development by creating an account on GitHub.

github.com

from langchain_core.prompts import PromptTemplate

prompt_template = """Write a concise summary of the following:

"{text}"

CONCISE SUMMARY:"""
PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])

각 단계에 원하는 프롬프트를 PromptTemplate로 아래와 같이 지정해 줄 수 있다.

SUMMARY = (
    "Summarize this text in as much detail as possible. Give a clear explanation of the objectives, core assertions, implications, "
    "and mechanics elucidated in this text - remove citations! \\n"
    "I want to highlight the main points starting from their importance and impact, mechanics, available tools, and potential extensions that impact dimensions such as privacy, safety flexibility, competitive performance, ease of use."
    "Text: {text} \\n"
)

SUMMERY = (
"이 텍스트를 가능한 한 자세히 요약하십시오. 목표, 핵심 주장, 시사점에 대해 명확하게 설명하십시오."
"그리고 이 본문에서 설명된 역학 - 인용을 제거합니다!\\n"
"개인정보 보호, 안전 유연성, 경쟁 성능, 사용 편의성과 같은 차원에 영향을 미치는 중요성과 영향, 역학, 사용 가능한 도구 및 잠재적 확장에서 시작하는 주요 사항을 강조하고 싶습니다."
"텍스트: {text} \\n"
)
%%time
from langchain_core.prompts import PromptTemplate
SUMMARY = (
    "Summarize this text in as much detail as possible. Give a clear explanation of the objectives, core assertions, implications, "
    "and mechanics elucidated in this text - remove citations! \\n"
    "I want to highlight the main points starting from their importance and impact, mechanics, available tools, and potential extensions that impact dimensions such as privacy, safety flexibility, competitive performance, ease of use."
    "Text: {text} \\n"
)
prompt = PromptTemplate.from_template(SUMMARY)

pdf_file_path = "E:\\GPT4ALL\\Download Models\\what_is_prediabetes.pdf" # 2page
pdf_loader = PyPDFLoader(pdf_file_path)
docs = pdf_loader.load_and_split()
chain = load_summarize_chain(llm, chain_type = "map_reduce", map_prompt=prompt)
chain.run(docs)
CPU times: total: 3.66 s
Wall time: 1min 9s
'\\nThe text discusses prediabetes, its implications, and ways to delay or prevent type 2 diabetes through daily physical activity, weight management, and medication. The small changes in diet suggested include avoiding sugary drinks, reducing portion sizes, and making mindful food choices. These healthy habits can reduce the risk of developing type 2 diabetes and contribute to overall improved health.'

'\\n본문에서는 당뇨병 전단계, 그 영향 및 매일의 신체 활동, 체중 관리 및 약물 치료를 통해 제2형 당뇨병을 지연시키거나 예방하는 방법에 대해 설명합니다. 제안된 식단의 작은 변화에는 설탕이 든 음료를 피하는 것, 부분 크기를 줄이는 것, 염두에 둔 음식 선택을 하는 것이 포함됩니다. 이러한 건강한 습관은 제2형 당뇨병 발병 위험을 줄이고 전반적인 건강 개선에 기여할 수 있습니다.'

LangChain을 사용한 프롬프트 엔지니어링은 LLM을 활용한 smmarization 기능을 제공한다. 몇 가지 팁은 아래와 같다.

  • 더 간단한 접근법으로 시작하고 필요한 경우 맵 리듀스를 사용한다.
  • 컨텍스트 제한과 병렬성을 균형잡기 위해 청크 크기를 조절한다.
  • 최상의 결과를 위해 맵과 리듀스 프롬프트를 정의한다.
  • 컨텍스트 제한헤 맞게 청크를 압축하거나 재귀적으로 압축한다.