LangChain example 01

Kitkat·2025년 1월 13일

LangChain 공식 문서 :
https://python.langchain.com/docs/introduction/

LangChain은 LLM과 Chat model 두가지를 모두 지원

from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI

입출력 형식의 차이

  • LLM
    단일 문자열을 입력으로 받고 단일 문자열을 출력으로 반환
    주로 단일 요청에 대한 복잡한 출력 생성에 적합
  • Chat Model
    메시지 리스트를 입력으로 받고 메시지 형태로 출력 반환
    대화의 맥락을 포함한 메시지를 처리하여 자연스러운 대화 가능

주요 특징과 용도

  • LLM
    텍스트 생성, 요약, 질문 답변 등 일반적인 언어 처리 작업에 적합
    단일 요청-응답 시나리오에서 효과적
  • Chat Model
    대화형 상황에 최적화되어 있음
    시스템 메시지, 사용자 메시지, AI 메시지 등 역할 구분 가능
    연속적인 대화 관리와 문맥 유지에 특화

예제에서는 챗모델 사용

LangChain 버전에 따라 달라질 수 있으니까 주의 (0.0.332 사용중)
라이브러리 버전 확인은

pip show langchain

기본 세팅

(사용할 모델, temperature : 출력을 조절하는 하이퍼파라미터 높을수록 창의적인 대답, streaming : 응답이 생성되는대로 확인, callbacks : 문자가 생길 때마다 출력)

from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.callbacks import StreamingStdOutCallbackHandler

chat = ChatOpenAI(
    model_name="gpt-4o-mini", temperature=0.9, streaming=True, callbacks=[StreamingStdOutCallbackHandler()]
)

프롬프트

AI에게 특정한 작업을 수행하도록 요청하는 질문 및 명령어

template = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a geography expert. And you only reply in {language}"),
        ("ai", "Your name is {name}"),
        (
        "human", 
        "What is the distance between {country_a} and {country_b}? ALso, what is your name?"
        ),
    ]
)

prompt = template.format_messages(
    language="Korean",
    name = "수현",
    country_a="Korea",
    country_b="Japan",
)

chat.predict_messages(prompt)

AIMessage(content='한국과 일본 사이의 거리는 약 200킬로미터에서 300킬로미터 정도입니다. 제 이름은 수현입니다.')

OutputParser

LLM의 응답(텍스트)을 변형해야 할 때 필요

from langchain.schema import BaseOutputParser

class CommaOutputParser(BaseOutputParser):
    
    def parse(self, input: str) -> list:
        items = input.strip().split(",")
        return list(map(str.strip, items))
    
p = CommaOutputParser()

p.parse("Hello, world!")

['Hello', 'world!']

LCEL(LangChain Expression Language)

LangChain에서 컴포넌트들을 연결하는 선언적 방식으로, | (파이프) 연산자를 사용하여 직관적으로 체인을 구성할 수 있게 해주는 표현 언어. 비동기 처리, 병렬 실행 최적화 등의 기능을 제공하면서도 간결한 코드 작성이 가능한 것이 특징

template = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a list generating machine. Everything you are asked will be answered with a comma seperated list of max {max_items}. Do NOT reply with anything else."),
        ("human", "{question}"),
    ]
)

chain = template | chat | CommaOutputParser()

chain.invoke({
    "max_items":5,
    "question": "What are some famous landmarks in Tokyo?",
    })

['Tokyo Tower',
'Senso-ji Temple',
'Shibuya Crossing',
'Meiji Shrine',
'Tokyo Skytree']

체인(chain)

LangChain의 핵심 구성 요소, 하나 이상의 LLM 구성요소(컴포넌트)들을 논리적으로 연결하여 복잡한 작업을 수행하는 구조

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

# 모델, 프롬프트, 파서 정의
model = ChatOpenAI()
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
output_parser = StrOutputParser()

# 파이프 연산자로 체인 구성
chain = prompt | model | output_parser

RunnableParallel

  • LangChain에서 여러 작업을 병렬로 실행할 수 있게 해주는 구성 요소
  • 여러 Runnable 객체를 동시에 실행하여 전체 작업 시간을 단축
  • 각 작업의 결과를 하나의 맵 형태로 반환
  • 시퀀스에서 다음 Runnable의 입력 형식과 일치하도록 출력을 조작
from langchain_core.runnables import RunnableParallel
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate

model = ChatOpenAI()
joke_chain = ChatPromptTemplate.from_template("tell me a joke about {topic}") | model
poem_chain = ChatPromptTemplate.from_template("write a poem about {topic}") | model

map_chain = RunnableParallel(
    joke=joke_chain,
    poem=poem_chain
)

result = map_chain.invoke({"topic": "bear"})

0개의 댓글