LLM Application/LangChain

LangChain - RAG + Ollama + gemma3

carrotweb 2026. 7. 24. 18:06
728x90
반응형

LangChain에서 Ollama 연동하기

LangChain에서 Ollama와 연동하는 방법을 제공하고 있습니다.

(https://docs.langchain.com/oss/python/integrations/providers/ollama)

 

Ollama를 사용하면 Llama3.1과 같은 오픈 소스 대규모 언어 모델을 로컬에서 실행할 수 있습니다.

Ollama는 모델 가중치, 구성 그리고 데이터를 Modelfile로 정의된 단일 패키지로 묶습니다. GPU 사용량을 포함한 설정 및 구성 세부 정보를 최적화합니다. 지원되는 모델 및 모델 변형의 전체 목록은 Ollama 모델 라이브러리를 참조하세요.

OllamaLLM은 LangChain에서 Ollama 모델과 상호 작용하는 방법을 설명합니다.

(https://docs.langchain.com/oss/python/integrations/llms/ollama)

 

Ollama 실행하기

1. project3QnA2.ipynb 파일에 Ollama 코드를 추가합니다.

[Markdown]
Ollama Gemma3:4b

[Code]
from langchain_community.llms import Ollama
from langchain_core.prompts import ChatPromptTemplate

model = Ollama(model="gemma3:1b")

system_template = "너는 천문학 전문가로 천문학 질문에 친절하게 답변해 주십시오."

prompt_template = ChatPromptTemplate.from_messages([
    ("system", system_template),
    ("user", "{text}")
])

prompt = prompt_template.invoke({"text": "태양계에서 가장 큰 행성은 무엇인가요?"})

response = model.invoke(prompt)
response

 

2. Ollama 코드를 실행합니다.

 

Ollama 코드 실행 결과입니다.

'안녕하세요! 천문학 전문가로서 태양계 행성에서 가장 큰 행성은 **목성**입니다. \n\n목성은 태양을 중심으로 하는 역전 운동 시스템의 중력으로 인해 엄청난 크기를 가지고 있습니다. 이는 태양의 중력에 비해 훨씬 크기 때문에, 목성은 태양계의 가장 큰 행성이 됩니다.\n\n혹시 더 궁금한 점이 있으신가요? 예를 들어, 목성의 특징이나 행성 간의 상대적인 크기 등에 대해 더 자세히 알려드릴 수 있습니다.'

 

 

 

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

1. project3에 QnA2.ipynb 파일에 Ollama로 프롬프트 실행 코드를 추가합니다.

[Code]
%pip install langchain-ollama

[Code]
from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

model = ChatOllama(
    model="gemma3:1b",
    temperature=0
)

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)

 

위 방식은 chain 방식입니다.

do_prompt = prompt.invoke({"context" : texts, "question": "중학생의 수학 기초학력 미달률은?"})

ai_msg = model.invoke(do_prompt)
print(ai_msg.content)

 

2. 첫번째 [Code]를 실행하여 langchain-ollama를 설치합니다.

 

3. Ollama로 프롬프트 실행 코드를 실행합니다.

 

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

The 기초학력 미달률은 9.1%입니다. 특히 수학의 기초학력 부진이 가장 높습니다. 테크빌교육은 기초학력 향상 코스웨어 기획전을 진행하고 있습니다.

 

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

The provided context does not contain information about the math 기초학력 미달률. (제공된 컨텍스트에는 수학 기초학력 미달률에 대한 정보가 포함되어 있지 않습니다.)

 

 

Ollama에서 gemma3n 다운로드 하기
1. Ollama Models Search (https://ollama.com/library/gemma3n)에서 gemma3n를 검색합니다.

 

2. 콘솔에서 ollama pull 명령어를 사용하여 gemma3n:e4b를 다운로드합니다.

ollama pull gemma3n:e4b

 

3. project3에 QnA2.ipynb 파일에 Ollama로 프롬프트 실행 코드를 수정합니다.

[Code]
from langchain_ollama import ChatOllama
from langchain_core.output_parsers import StrOutputParser

model = ChatOllama(
    model="gemma3n:e4b",
    temperature=0
)

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)

 

4. Ollama로 프롬프트 실행 코드를 실행합니다.

 

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

교육부의 '2023 국가수준 학업성취도평가' 결과, 중학생의 수학 기초학력 미달률은 13.0%로 나타났습니다. 이는 영어 6.0%보다 높은 수치이며, 특히 수학의 기초학력 부진이 심각한 상황입니다. 따라서 학습 격차 해소를 위한 지원이 필요합니다.

 

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

I am sorry, but I cannot answer the question about the percentage of middle school students with insufficient basic math skills. The provided context is empty, so I do not have the information needed to answer. Therefore, I don't know the answer. (죄송하지만, 중학생 중 기초 수학 능력이 부족한 학생의 비율에 대한 질문에는 답변해 드릴 수 없습니다. 제공된 정보가 부족하여 답변에 필요한 정보를 얻을 수 없습니다. 따라서 답변을 드릴 수 없습니다.)

 

 

728x90
반응형