[문헌 세미나] 5장. LangChain 프레임워크 LLM 활용 실습

2025. 1. 20. 13:42Project Log/학부 졸업프로젝트

현재 프로젝트 이슈

지난 3주 동안 GPT, Whisper, Lex, Flutter, Django, Lambda 등 여러 가지를 돌아가며 건드리고 있었다. 교수님께서 핵심 서비스 코드에 집중할 수 있는 서버리스 아키텍처를 추천하셔서, 기존의 서버 기반 아키텍처를 서버 리스 아키텍처로 수정하는 시간을 가졌다. 우선 팀원들과 교수님께 아키텍처를 공유한 상태이다.

 

서버 리스 아키텍처와 Lex 사용 여부에 관한 컨펌이 나면, Django를 비롯한 서버 관련 컴포넌트를 버리고 기존 Whisper 관련 코드도 고쳐야 한다. Lex를 쓰느냐 GPT만 쓰느냐에 따라서도 매우 달라질 것이다.

 

Flutter 앱 또한 와이어프레임은 구성했지만, 디자인 시안이 나오지 않아서 개발을 곧바로 시작하기는 어렵다. 월요일 교수님 줌 면담에서 위의 문제들을 명확하게 풀어낸 후에 개발을 진행하는 편이 좋겠다고 생각했다.

 

 

이슈와 무관하게 할 수 있는 작업

그래서 일단 위의 문제들에 영향을 받지 않고, 알아두면 나중에 도움이 될 것을 추려보았다.

 

첫 번째는 GPT 관련 공부. (with 문헌 OR 공식 docs)

두 번째는 Flutter 기본 개발 공부. (with 공식 docs OR 유튜브 강의)

세 번째는 람다 함수 활용 공부. (with 공식 docs OR 유튜브 강의)

 

랭체인 프레임워크

벌써 5장 내용을 다룬다. 랭체인 프레임워크와 GPT-4 플러그인이 주된 내용이다.

 

랭체인(LangChain)은 LLM 기반 애플리케이션 개발을 위한 새로운 프레임워크이다. 

 

아래 커맨드로 랭체인을 설치한다.

pip install langchain

 

랭체인의 주요 기능 6가지가 있다.

 

1. 모델: 랭체인에서 제공하는 표준 인터페이스이다. 모델을 통해 OpenAI, HuggingFace, Cohere, GPT4All 등 여러 업체의 다양한 LLM과 상호작용을 할 수 있다. 

 

2. 프롬프트: 프롬프트는 LLM 프로그래밍의 표준이 되고 있다. 프롬프트 모듈에는 관리는 돕는 다양한 도구가 포함된다.

 

3. 인덱스: 인덱스 모듈을 사용해 LLM을 데이터와 결합할 수 있다.

 

4. 체인: 체인 인터페이스는 여러 모델이나 프롬프트를 결합하기 위한 호출을 생성한다.

 

5. 에이전트: 사용자 입력 처리, 의사 결정, 작업을 수행할 적절한 도구 선택을 할 수 있는 인터페이스이다. 목적에 맞게 반복해 조정 작업을 할 수 있다.

 

6. 메모리: 메모리 모듈을 사용해 체인이나 에이전트 호출 간의 상태를 유지한다. 체인과 에이전트는 상태 비저장형이므로 메모리 기능이 없다면 입력값을 독립적으로 처리해 앞선 대화를 감안한 출력값을 생성하지 못한다.

 

랭체인 모듈

 

  • PromptTemplate은 모델을 위한 입력을 구성하는 역할을 한다. input_variables를 통해 값을 지정할 수 있는 template가 포함되어 있다.
  • ChatOpenAI 함수의 model_name 파라미터에 모델명을 적는다.
  • LLMChain 함수는 프롬프트와 모델을 연결한다.
  • load_tools 함수는 wikipedia와 llm-math, 그리고 모델을 설정한다.
  • ConversationChain을 활용하여 앞선 입력과 출력값을 기억하는 채팅 도구를 구축한다.

아래 커맨드로 requirements.txt에 있는 패키지를 설치한다.

pip install -r requirements.txt
langchain==0.1.12 
langchain_openai==0.1.1
langchain-community==0.0.38
bs4==0.0.1
wikipedia==1.4.0
langchainhub==0.1.15

 

아래 파이썬 코드 파일명을 langchain.py로 설정하면 안 된다. 오랫동안 langchain.chains에서 ModuleNotFound 에러가 나서 이상하다고 생각했는데, 아래 파일을 langchain 모듈로 인식해서 오류가 난 것이었다. 파일명을 바꿔주니 해결되었다.

 

Deprecated 모듈은 langchain 대신 langchain_community를 임포트하여 에러를 해결했다. 업데이트로 인해 공식 코드에서 수정할 부분들이 조금 있었다.

from dotenv import load_dotenv
load_dotenv()
from openai import OpenAI

import os
from langchain_openai import ChatOpenAI
from langchain.chains import ConversationChain, LLMChain
from langchain.prompts import PromptTemplate
from langchain import hub
from langchain_community.agent_toolkits.load_tools import load_tools
from langchain.agents import create_react_agent, AgentExecutor

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

# Task 1. LLM Chain
template = """Question: {question}
Let's think step by step.
Answer: """
prompt = PromptTemplate(template=template, input_variables=["question"])

llm = ChatOpenAI(model_name="gpt-3.5-turbo")
llm_chain = LLMChain(prompt=prompt, llm=llm)

question = """What is the population of the capital of the country where the
Olympic Games were held in 2016? """
llm_chain.invoke(question)

# Task 2. Calculation
tools = load_tools(["wikipedia", "llm-math"], llm=llm)
agent = create_react_agent(
    tools=tools,
    llm=llm,
    prompt=hub.pull("hwchase17/react")
)

question = """What is the square root of the population of the capital of the
country where the Olympic Games were held in 2016 ?"""
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input": question})


# Task 3. Chat Tool
chatbot_llm = ChatOpenAI(model_name='gpt-3.5-turbo')
chatbot = ConversationChain(llm=chatbot_llm, verbose=True)
chatbot.predict(input='Hello')
chatbot.predict(input='Can I ask you a question? Are you an AI?')

 

[ 실행 결과 ]

Task 1 & Task 2
Task 3

 

랭체인 프레임워크와 임베딩

언어 모델에 자체 데이터를 결합하여, 애플리케이션에서 사용하는 컨텍스트와 정보를 확장할 수 있다. document_loaders 모듈로 다양한 소스의 텍스트 데이터를 애플리케이션으로 빠르게 불러올 수 있다. 정보 검색이 되려면 로드된 각 페이지를 임베딩해야 한다. 임베딩은 정보 검색에서 단어, 토큰, 문장 등 수치형이 아닌 항목을 벡터로 변환하는 과정이다.

 

  • similarity_search로 유사한 항목을 검색한다.
  • RetrievalQA로 임베딩을 활용해 정보를 검색하고 질문에 답변하도록 한다.

requirements.txt

pip install -r requirements.txt
pypdf==3.11.0
tiktoken==0.4.0
faiss-cpu==1.7.4

 

tiktoken과 faiss-cpu를 설치하기에 앞서 추가로 설치할 것이 있다. swig와 rust를 설치해야 한다.

// swig 설치
brew install swig

 

Rust에서 기본으로 제공하는 명령어를 사용하면 sudo를 붙여도 Permission Denied 에러가 나왔다. 아래 과정으로 설치를 진행하면 된다. (참고 사이트: https://velog.io/@juheesvt/MacOS에서-Rust-설치하기)

Permission Denied 에러

 

// --no-modify-path 옵션 추가
curl https://sh.rustup.rs -sSf | bash -s -- -y --no-modify-path

// ~/.zshrc 파일에 아래 코드 추가
export PATH="$HOME/.cargo/bin:$PATH"

// 변경 사항 적용
source ~/.zshrc

// Rust 버전 확인
rustup --version

 

swig와 rust를 설치하고 requirements.txt를 설치하면, tiktoken은 정상적으로 설치된다. 하지만 faiss-cpu는 다른 에러가 나온다. 아래 사이트에서 다른 설치 방법을 찾았다.

 

- Fail to install faiss-cpu 1.8.0: https://github.com/facebookresearch/faiss/issues/3314

- facebookresearch/faiss: https://github.com/facebookresearch/faiss/blob/main/INSTALL.md

conda install -c pytorch faiss-cpu=1.9.0

 

아래 코드의 주요 사항은 PDF에서 질문과 유사한 내용을 검색하고, 그에 대한 답을 하는 것이다. ExplorersGuide.pdf는 (https://oreil.ly/ZGu3z) 사이트에서 다운로드했다. 

from dotenv import load_dotenv
load_dotenv()
from openai import OpenAI
import os
from langchain_community.document_loaders.pdf import PyPDFLoader
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores.faiss import FAISS
from langchain.chains.retrieval_qa.base import RetrievalQA
from langchain_openai import OpenAI

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

loader = PyPDFLoader("./chapter5/ExplorersGuide.pdf")
pages = loader.load_and_split()

embeddings = OpenAIEmbeddings()

db = FAISS.from_documents(pages, embeddings)

q = "What is Link's traditional outfit color?"
content = db.similarity_search(q)[0]

print("Similarity Search: \n", content)
print("\n")

llm = OpenAI()
chain = RetrievalQA.from_llm(llm=llm, retriever=db.as_retriever())
q = "What is Link's traditional outfit color?"
response = chain.invoke(q, return_only_outputs=True)

print("Answer: \n", response)

 

[ 실행 결과 ]

질문과 유사한 내용을 PDF에서 검색하고, 파일명과 페이지 수를 알려준다. PDF 내용을 바탕으로 질문에 대한 응답도 적절하게 생성했다.

 

 

* 참고 문헌

 

CAELEN, Olivier; BLETE, Marie-Alice. Developing Apps with GPT-4 and ChatGPT: Build Intelligent Chatbots, Content Generators, and More. " O'Reilly Media, Inc.", 2024.