LLM Application/LangChain

LangChain – Advanced RAG, Pre-Retrieval(한국어 LLM 사용)

carrotweb 2026. 7. 30. 18:23
728x90
반응형

이번에는 한국어 LLM인 exaone3.5:7.8b를 사용하여 답변을 생성해보고 MultiQueryRetriever에 적용해보겠습니다.

 

Exaone 3.5 (https://www.lgresearch.ai/exaone)

현배 버전은 4.5입니다.

 

 

Ollama에서 Exaone 3.5 다운로드 하기
1. Ollama Models Search (https://ollama.com/search?q=exaone) 에서 Exaone 3.5를 검색합니다.

 

Exaone 3.5(https://ollama.com/library/exaone3.5)를 클릭하면 다양한 모델이 있습니다.
PC에서 사용할거라 용량이 작은 모델인 Exaone 3.5를 사용할 겁니다.

 

exaone3.5:7.8b를 클릭하면 모델에 대한 정보를 확인할 수 있습니다.

 

2. 콘솔에서 ollama pull 명령어를 사용하여 exaone3.5:7.8b를 다운로드합니다.

ollama pull exaone3.5:7.8b

콘솔에서 ollama list 명령어를 사용하여 다운로드된 모델들을 확인할 수 있습니다.

 

 

Generation (생성) – LLM (답변 생성)

1. project3에 QnA3.ipynb 파일에 Exaone으로 실행 코드를 추가합니다.

[Code]
from langchain_ollama import ChatOllama

model = ChatOllama(
    model="exaone3.5:7.8b",
    temperature=0
)

[Code]
from langchain import hub

prompt = hub.pull("rlm/rag-prompt")
print(prompt)

[Code]
retriever = loaded_vector_store.as_retriever(search_kwargs={"k": 5})

result_texts = retriever.invoke("중학생의 수학 기초학력 미달률은?")
print(result_texts)

[Code]
from langchain_core.output_parsers import StrOutputParser

texts = "\n\n".join(result_text.page_content for result_text in result_texts)

chain = prompt | model | StrOutputParser()
response = chain.invoke({"context" : texts, "question": "중학생의 수학 기초학력 미달률은?"})
print(response)

 

2. Exaone으로 실행 코드를 실행합니다.

 

Ollama 프롬프트 실행 결과입니다.

중학생의 수학 기초학력 미달률은 13.0%입니다. 이는 전체 기초학력 미달률 중 수학 분야에서 가장 높은 비율을 보입니다. 학습 격차 해소를 위한 추가적인 지원이 필요한 상황입니다.

 

Context가 없을 경우 실행 결과입니다.

제공된 맥락에는 중학생의 수학 기초학력 미달률에 대한 구체적인 통계나 데이터가 포함되어 있지 않습니다. 정확한 비율을 말씀드리기 위해서는 해당 연도와 지역의 공식 교육 통계 자료가 필요합니다. 따라서 현재 정보로는 해당률을 알려드리지 못합니다.

 

 

만약, Exaone3.5:32b를 다운로드하여 사용하고자 할 경우에는 시스템 사양이 낮을 경우 응답시간이 느려 사용할 수 없습니다.

 

용량이 크기 때문에 작동이 되지 않습니다.

 

그럴 경우, 시스템 속성(Windows + R)에서 가상메모리의 페이징 파일 크기를 변경하시면 사용이 가능합니다.

 

 

한국어 LLM 사용시 Multi-Query Retriever의 문제점

 

한국어 LLM를 Multi-Query Retriever에 사용할 경우에 문제점있습니다.

 

1. project3에 QnA3.ipynb 파일에 테스트 실행 코드를 추가합니다.

[Code]
question = "대출?"

result_texts = multi_query_retriever.invoke(input=question)
result_texts

 

2. 테스트 실행 코드를 실행합니다.

 

Multi-Query Retriever가 생성한 질문이 영문으로 생성되는 문제점있습니다.

 

INFO:langchain.retrievers.multi_query:Generated queries: ['1. What loan options are available for borrowers with my current financial profile?', '2. Could you recommend details on loan terms and interest rates for similar financial situations?', '3. How do different loan products compare in terms of eligibility criteria and repayment options?']

 

[번역]

1. 현재 제 재정 상황에 맞는 대출 옵션은 무엇인가요?

2. 비슷한 재정 상황에 맞는 대출 조건과 금리를 자세히 설명해 주시겠어요?

3. 자격 기준과 상환 옵션 측면에서 다양한 대출 상품을 비교하면 어떤가요?

 

 

프롬프트를 이용하여 한글 질문 생성하기

1. project3에 QnA3.ipynb 파일에 테스트 실행 코드를 추가합니다.

[Code]
from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser

# 프롬프트 (영어)
prompt_template = PromptTemplate.from_template(
"""You are an AI language model assistant. 
Your task is to generate three different versions of the given user question to retrieve relevant documents from a vector database. 
By generating multiple perspectives on the user question, your goal is to help the user overcome some of the limitations of the distance-based similarity search. 
Your response should be a list of values separated by new lines

#ORIGINAL QUESTION: 
{question}

#Answer in Korean:
"""
)

question = "대출?"

#chain = prompt | model | StrOutputParser()

#response = chain.invoke({"question": question})
#print(response)

chain = (
    {"question": RunnablePassthrough()}
    | prompt_template
    | model
    | StrOutputParser()
)

response = chain.invoke(question)
response

RunnablePassthrough() 는 데이터를 전달하는 역할을 합니다. invoke() 메서드를 통해 입력된 데이터를 그대로 반환 합니다.

 

2. 테스트 실행 코드를 실행합니다.

 

프롬프트가 생성한 결과입니다.

'대출 관련 정보 찾기  \n대출 조건 문의  \n금융 대출 옵션 탐색'

 

프롬프트가 한글이면 좀 더 나은 질문을 생성할 수 있습니다.

 

3. 프롬프트를 한글로 변경합니다.

[Code]
from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser

# 프롬프트 (한국어)
prompt_template = PromptTemplate.from_template(
"""당신은 AI 언어 모델 어시스턴트입니다.
당신의 임무는 주어진 사용자 질문의 세 가지 다른 버전을 생성하여 벡터 데이터베이스에서 관련 문서를 검색하는 것입니다.
사용자 질문에 대한 다양한 관점을 생성함으로써, 사용자가 거리 기반 유사도 검색의 한계를 극복하도록 돕는 것이 당신의 목표입니다.

너의 응답 결과는 줄바꿈으로 구분하여 리스트로 제공합니다.

#원본 질문
{question}
"""
)

question = "대출?"
chain = (
    {"question": RunnablePassthrough()}
    | prompt_template
    | model
    | StrOutputParser()
)
response = chain.invoke(question)
response

 

4. 테스트 실행 코드를 실행합니다.

 

프롬프트가 생성한 결과입니다.

'```\n# 버전 1\n대출 조건과 이자율에 대해 자세히 알려주시겠어요?\n\n# 버전 2\n현재 이용 가능한 대출 상품의 종류와 장단점은 무엇인가요?\n\n# 버전 3\n대출 신청 과정과 필요 서류는 무엇인가요? \n```'

 

 

 

 

 

728x90
반응형