Lang Chain 개요

Kkoaa·2024년 11월 19일

Langchain이란?

LLM을 쉽게 다룰 수 있게 해주는 프레임워크

마치 tensorflow를 쓰듯이 LLM을 사용하는 일련의 과정을 정의하여 파이프라인으로 실행하는 형태로 정의하면 우리가 원하는 LLM 어플리케이션을 쉽게 만들고 배포할 수 있다.

Langchain 프레임워크 구성

  1. 랭체인 라이브러리(LangChain Libraries): 파이썬과 자바스크립트 라이브러리를 포함하며, 다양한 컴포넌트의 인터페이스와 통합, 이 컴포넌트들을 체인과 에이전트로 결합할 수 있는 기본 런타임, 그리고 체인과 에이전트의 사용 가능한 구현이 가능합니다.
  2. 랭체인 템플릿(LangChain Templates): 다양한 작업을 위한 쉽게 배포할 수 있는 참조 아키텍처 모음입니다. 이 템플릿은 개발자들이 특정 작업에 맞춰 빠르게 애플리케이션을 구축할 수 있도록 돕습니다.
  3. 랭서브(LangServe): 랭체인 체인을 REST API로 배포할 수 있게 하는 라이브러리입니다. 이를 통해 개발자들은 자신의 애플리케이션을 외부 시스템과 쉽게 통합할 수 있습니다.
  4. 랭스미스(LangSmith): 개발자 플랫폼으로, LLM 프레임워크에서 구축된 체인을 디버깅, 테스트, 평가, 모니터링할 수 있으며, 랭체인과의 원활한 통합을 지원합니다.

Premilaries

  • 패키지 관리자로 langchain 설치
  • 각 llm 종류별로 필요한 의존성을 설치
  • 각 llm 종류별 api key
pip install langchain
pip install langchain-openai

모델을 바로 사용하는 법

원하는 모델을 정의하고 invoke() 메서드를 통해 메세지를 전달한다.

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage, SystemMessage
import os

os.environ['OPENAI_API_KEY'] = 'API-Key'
# model 

model = ChatOpenAI(model="gpt-4o-mini")

messages = [
    SystemMessage(content="Translate the following from English into Korean"),
    HumanMessage(content="Love")
]

model.invoke(messages)

Langchain에서의 메세지

  • SystemMessage : 시스템 컴포넌트로부터의 메시지로, ChatModel에게 페르소나, 역할 설정 → ex) 너는 초등학교 교사야 or 너는 대학교 교수야
  • HumanMessage : 사용자로부터의 메시지로, ChatModel에게 작업을 시키는 인풋 메시지
  • AIMessage : LLM의 반환된 메세지, 즉 아웃풋

Prompt Template

application logic usually takes the raw user input and transforms it into a list of messages ready to pass to the language model

일반적으로 application logic에서 user input을 받고 변환을 하는 등 다양한 작업을 한 뒤의 메세지를 llm에 던짐.

https://python.langchain.com/docs/tutorials/llm_chain/

prompt와 LLM 모델을 연결하여 chain을 구성

pipe operator ‘|’ 를 이용한다.

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage, SystemMessage
import os

os.environ['OPENAI_API_KEY'] = 'API-Key'
# model 

model = ChatOpenAI(model="gpt-4o-mini")

system_template = "Translate the following from English into {language}"

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

chain = prompt_template | model
result = chain.invoke({"language": "German", "text": "Good Morning"})

print(result)

여러 chain을 연결하는 방법

chain1에서 출력한 값을 입력값으로 받아서, 이 번역된 단어를 english_word 변수에 저장한다.

다음으로, 이 변수를 사용하여 두 번째 체인의 입력으로 제공하고, 영어 단어의 뜻을 설명하는 작업을 수행한다.


from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.output_parsers import StrOutputParser
import os

os.environ['OPENAI_API_KEY'] = 'API-Key'

# model 
model = ChatOpenAI(model="gpt-4o-mini")

prompt1 = ChatPromptTemplate.from_template("translates {korean_word} to English.")
prompt2 = ChatPromptTemplate.from_template(
    "explain {english_word} using oxford dictionary to me in Korean."
)

chain1 = prompt1 | model | StrOutputParser()
chain2 = (
    {"english_word": chain1}
    | prompt2
    | model
    | StrOutputParser()
)
# result1 = chain1.invoke({"korean_word" : "사과"})
# print("chain 1 result >> ", result1)
result2 = chain2.invoke({"korean_word":"사과"})
print("chain 2 result >> ", result2)

Runnable

langchain에서 사용자 정의 체인을 쉽게 생성하고 관리할 수 있도록 정의한 프로토콜
마치 REST API에서 CRUD, GET Post GetData 처럼

Runnable 주요 메서드

  • invoke: 주어진 입력에 대해 체인을 호출하고, 결과를 반환, 단일 입력에 대해 동기적으로 작동
  • batch: 입력 리스트에 대해 체인을 호출하고, 각 입력에 대한 결과를 리스트로 반환. 여러 입력에 대해 동기적으로 작동하며, 효율적인 배치 처리 가능
  • stream: 입력에 대해 체인을 호출하고, 결과의 조각들을 스트리밍, 대용량 데이터 처리나 실시간 데이터 처리에 유용(chatgpt 응답이 한 번에 응답 문장을 던지는 게 아니라 응답을 한 글자 한 글자 생성하듯이)
  • 비동기 버전ainvokeabatchastream 등의 메소드는 각각의 동기 버전에 대한 비동기 실행을 지원. 비동기 프로그래밍 패러다임을 사용하여 더 높은 처리 성능과 효율을 달성

Reference

profile
냠냠

0개의 댓글