1. LangChain 소개

LangChain은 대규모 언어 모델(LLM)을 활용한 애플리케이션 개발을 위한 프레임워크입니다. 다양한 LLM과 외부 데이터 소스를 연결하고, 복잡한 작업을 체인(Chain) 형태로 구성할 수 있게 해줍니다.

LangChain의 주요 특징

  • 다양한 LLM과의 통합 (OpenAI, Anthropic, HuggingFace 등)
  • 외부 데이터 소스 연결 가능
  • 복잡한 작업 흐름을 체인으로 구성
  • 메모리 기능으로 대화 컨텍스트 유지
  • 에이전트 기능으로 도구 사용 가능

2. 설치 및 환경 설정

LangChain 설치

# pip로 LangChain 설치하기
pip install langchain
pip install langchain-openai# OpenAI 모델 사용 시

API 키 설정

# 환경 변수로 API 키 설정하기
import os
os.environ["OPENAI_API_KEY"] = "your-api-key-here"

# 또는 코드에서 직접 설정
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(api_key="your-api-key-here")

3. LangChain의 핵심 구성 요소

1) 모델 (LLMs / Chat Models)

from langchain_openai import OpenAI, ChatOpenAI

# 텍스트 완성 모델
llm = OpenAI(temperature=0.7)
response = llm.predict("머신러닝이란 무엇인가요?")
print(response)

# 채팅 모델
chat_model = ChatOpenAI(temperature=0.2)
from langchain_core.messages import HumanMessage
response = chat_model.invoke([HumanMessage(content="안녕하세요! 오늘 날씨가 어떤가요?")])
print(response.content)

2) 프롬프트 템플릿 (Prompt Templates)

from langchain_core.prompts import PromptTemplate

# 단순 프롬프트 템플릿
prompt_template = PromptTemplate.from_template(
    "다음 주제에 대해 500자로 설명해주세요: {topic}"
)
prompt = prompt_template.format(topic="인공지능의 미래")
print(prompt)

# 채팅 프롬프트 템플릿
from langchain_core.prompts import ChatPromptTemplate
chat_template = ChatPromptTemplate.from_messages([
    ("system", "당신은 {subject} 전문가입니다."),
    ("human", "{question}")
])
chat_prompt = chat_template.format_messages(
    subject="파이썬 프로그래밍",
    question="데코레이터란 무엇인가요?"
)
print(chat_prompt)

3) 출력 파서 (Output Parsers)

from langchain_core.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field
from typing import List

# Pydantic 모델 정의
class Movie(BaseModel):
    title: str = Field(description="영화 제목")
    director: str = Field(description="영화 감독")
    year: int = Field(description="개봉 연도")

class MovieList(BaseModel):
    movies: List[Movie] = Field(description="영화 목록")

# 출력 파서 설정
parser = PydanticOutputParser(pydantic_object=MovieList)

# 프롬프트 템플릿에 파서 포맷 지침 추가
prompt = PromptTemplate(
    template="다음 장르의 영화 3개를 추천해주세요: {genre}\n{format_instructions}",
    input_variables=["genre"],
    partial_variables={"format_instructions": parser.get_format_instructions()}
)

# 전체 체인 구성
chain = prompt | chat_model | parser

# 결과 실행
result = chain.invoke({"genre": "SF"})
print(result)

4) 체인 (Chains)

from langchain_core.runnables import RunnablePassthrough

# 간단한 체인 구성
simple_chain = (
    {"topic": RunnablePassthrough()} |
    prompt_template |
    llm
)

result = simple_chain.invoke("양자 컴퓨팅")
print(result)

4. 실습 예제: 기본 체인 만들기

간단한 질의응답 체인

from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser

# 1. 프롬프트 템플릿 정의
prompt = ChatPromptTemplate.from_template("""
다음 질문에 대해 자세히 답변해주세요.
질문: {question}
""")

# 2. 모델 정의
model = ChatOpenAI(temperature=0.2)

# 3. 출력 파서 정의
output_parser = StrOutputParser()

# 4. 체인 구성
chain = prompt | model | output_parser

# 5. 체인 실행
result = chain.invoke({"question": "인공지능이 사회에 미치는 영향은 무엇인가요?"})
print(result)

LCEL(LangChain Expression Language)을 활용한 체인

from langchain_core.runnables import RunnablePassthrough
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

# 함수 정의
def get_weather(location):
# 실제로는 날씨 API를 호출하겠지만, 여기서는 예시로 대체
    weather_info = {
        "서울": "맑음, 기온 22도",
        "부산": "흐림, 기온 25도",
        "제주": "비, 기온 20도"
    }
    return weather_info.get(location, "날씨 정보 없음")

# 체인 구성
chain = (
    {
        "location": RunnablePassthrough(),
        "weather": lambda x: get_weather(x)
    }
    | ChatPromptTemplate.from_template(
        "{location}의 날씨는 {weather}입니다. 이런 날씨에 어울리는 활동을 추천해주세요."
    )
    | ChatOpenAI(temperature=0.7)
    | StrOutputParser()
)

# 체인 실행
result = chain.invoke("서울")
print(result)
profile
개발자 지망생. 일단 하고보자

0개의 댓글