로컬 환경에서 대규모 언어 모델을 실행하면 클라우드 API에 의존하지 않고도 강력한 AI 애플리케이션을 구축할 수 있습니다.
이 글에서는 LangChain과 Ollama를 활용하여 로컬 LLM을 효과적으로 구현하는 방법을 알아보겠습니다.
로컬 LLM을 사용하는 것은 여러 장점이 있습니다.
Ollama는 로컬 환경에서 LLM을 쉽게 실행할 수 있게 해주는 도구입니다.
ollama pull llama2
터미널에서 다음 명령어로 모델을 실행할 수 있습니다.
ollama run llama2
이제 터미널에서 직접 모델과 대화할 수 있습니다.
>>> hi
Hello! It's nice to meet you. Is there something I can help you with or would you like to chat?
LangChain은 대규모 언어 모델로 구동되는 애플리케이션을 개발하기 위한 오픈소스 프레임워크입니다. LangChain을 사용하면 로컬 LLM을 쉽게 통합하여 더 복잡한 애플리케이션을 구축할 수 있습니다.
pip install langchain
from langchain_community.llms import Ollama
# Ollama 모델 초기화
llm = Ollama(model="llama2")
# 간단한 질의 실행
response = llm.invoke("Hi")
print(response)
Streamlit을 활용하여 간단한 대화형 애플리케이션을 만들 수 있습니다.
from langchain_community.llms import Ollama
import streamlit as st
# 모델 초기화
llm = Ollama(model="llama2")
# 세션 상태 초기화
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
def add_to_chat_history(user_input, bot_response):
st.session_state.chat_history.append("사용자: " + user_input)
st.session_state.chat_history.append("봇: " + bot_response)
def display_chat_history():
for message in st.session_state.chat_history:
st.write(message)
# 사용자 입력 필드
user_input = st.text_input("사용자 입력")
# 사용자가 입력을 제출했을 때
if user_input:
# LLM으로부터 응답받기
bot_response = llm(user_input)
# 대화 기록에 추가
add_to_chat_history(user_input, bot_response)
# 입력 필드 초기화
st.session_state.user_input = ""
# 대화 기록 표시
display_chat_history()
streamlit run app.py
Ollama 외에도 다양한 방법으로 로컬 LLM을 실행할 수 있습니다.
from langchain_huggingface.llms import HuggingFacePipeline
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
model_id = "gpt2"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=100)
hf = HuggingFacePipeline(pipeline=pipe)
LM Studio를 사용하면 다양한 로컬 LLM을 실행하고 관리할 수 있습니다.
Docker와 Docker Compose를 설치한 후 LM Studio를 설정하여 사용할 수 있습니다.
Google Cloud 환경 내에서 GPU 없이도 CPU와 메모리만으로 로컬에서 LLM을 실행할 수 있는 도구입니다.
특히 Cloud Workstations과 결합하여 사용할 때 효과적입니다.
Ollama, HuggingFace, LM Studio 등 다양한 도구를 활용하여 로컬 LLM을 실행하고 LangChain과 통합할 수 있습니다.
LangChain과 로컬 LLM을 활용하면 클라우드 API에 의존하지 않고도 강력한 AI 애플리케이션을 구축할 수 있습니다.
비용 절감, 데이터 보안, 안정성 등 여러 장점이 있어 특히 기업 환경이나 특정 도메인에 특화된 애플리케이션을 개발할 때 유용합니다.