LangChain 공식 문서 :
https://python.langchain.com/docs/introduction/
LangChain은 LLM과 Chat model 두가지를 모두 지원
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
예제에서는 챗모델 사용
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킬로미터 정도입니다. 제 이름은 수현입니다.')
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!']
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']
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
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"})