랭체인
- LLM을 이용한 애플리케이션 개발 프레임워크
- 파이썬과 자바스크립트/ 타입스크립트로 구현가능
랭체인 응용 프로그램
- 챗봇
- 문장 요약도구
- AI 에이전트
Language models
- 랭체인에서 언어 모델을 사용하는 방법을 제공하는 모듈
- 다양한 언어 모델을 공통된 인터페이스로 사용가능
- LLMS와 Chat models 가 있다.
- LLMS
- 하나의 텍스트 입력에 대해 하나의 텍스트 출력 반환
- Chat models
- 채팅 형식의 대화를 입력하면 응답을 받을 수 있음
- OpenAI 의 Chat Completions API를 지원하기 위해 만들어진 랭체인 모듈
- ChatOpenAI 클래스 사용
...
"messages":[
{“role”:”system”,"content" :"you are a helpful assistant"},
{“role”:”user”,"content" :"안녕하세요 저는 존입니다."},
{“role”:”assistant”,"content" :"안녕하세요 존씨! 어떻게 도와드릴까요?"},
{“role”:”user”,"content" :"제이름을 아시나요?"},
]
...
...
"messages":[
SystemMessage(content = "you are a helpful assistant"),
HumanMesage(content = "안녕하세요 저는 존입니다."},
AIMessage(content = "안녕하세요 존씨! 어떻게 도와드릴까요?"},
HumanMesage(content :"제이름을 아시나요?"},
]
...
- 랭체인의 SystemMessage, HumanMesage, AIMessage는 Chat Completions API의 “role”:”system”,“role”:”user”,“role”:”assistant” 에 해당한다.
Callback 을 이용한 스트리밍
- Chat Completions API 응답을 스트리밍으로 처리할 수 있다.
- StreamingStdOutCallbackHandler를 ChatOpenAI로 설정하면 된다.
chat = ChatOpenAI(
momdel_name = "gpt-3.5-turbo",
temperature = 0, // 숫자가 클수록 무작위 숫자가 나옴
streaming = True,
callbacks =[StreamingStdOutCallbackHandler()],
)
프롬프트
PromptTemplate
- 프롬프트를 템플릿화 할 수 있다.
template = """
다음 요리의 레시피를 생각해주세요
요리 : {dish}
"""
prompt = PromptTemplate(
input_variables=["dish"],
template = template,
)
result = prompt.format(dish = 카레)
print(result)
ChatPromptTemplate
- PromptTemplate를 Chat Completions API의 형식에 맞게 만든 것
- SystemMessage, HumanMesage, AIMessage를 각각 템플릿화해서 ChatPromptTemplate이라는 클래스에서 일괄적으로 사용가능하다.
Output parsers
- JSON과 같은 출력 형식을 지정하는 프롬트 생성 및 응답 텍스트를 Python 객체로 변환하는 기능을 제공한다.
- 랭체인의 PydanticOutputParser를 사용하면 Python객체를 쉽게 가져올 수 있다.
Chain
- 단순 LLM에 입력하서 출력을 얻고 끝나는게 아니라 처리를 연쇄적으로 연결할수 있는 것이 랭체인의 ‘chains’ 이다.
1. LLMChain-PromptTemplate, Language model, OutputParser 연결
from langchain_openai import ChatOpenAI
from langchain.output_parsers import PydanticOutputParser
from langchain.prompts import PromptTemplate
from pydantic import BaseModel, Field
class Recipe(BaseModel):
ingredients: list[str] = Field(description="ingredients of dish")
steps: list[str] = Field(description="steps to make the dish")
# OutputParser
output_parser = PydanticOutputParser(pydantic_object=Recipe)
template = """
다음 요리의 레시피를 생각해주세요
{format_instructions}
요리 : {dish}
"""
# PromptTemplate
promt = PromptTemplate(
template=template,
input_variable=["dish"],
partial_variables={"format_instruction": output_parser.get_format_instructions()}
)
# Language Model
chat = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
+) ouputparser를 지정하지 않은 경우, 기본 작동으로 LLM의 출력 문자열이 그대로 Chain의 text이 출력된다.
2. SimpleSequentialChain-Chain과 Chain 연결
fin_chain = SimpleSequenceChain(chains=[chain_one, chain_two])
result =fin_chain.invoke("...")
Memory
- Chat Completions API는 stateless로 대화 이력을 바탕으로 응답을 얻기 위해서는 대화 이력을 요청에 포함 시켜야 한다.
ConversationBufferMemory
- Memory를 사용하여 히스토리를 기반으로 대화할 수 있는 ConversationChain 예시
from langchain.chains.conversation.base import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain_openai import ChatOpenAI
chat = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
conversaion = ConversationChain(
llm = chat,
memory = ConversationBufferMemory()
)
while True :
user_message = input( "you : ")
if user_message == "끝" :
print("대화종료")
break
ai_message = conversaion.invoke(input=user_message)["response"]
print(f"AI:{ai_message}")
- 단순 대화기록을 보관하고 사용하는 것으로 충분하다면 위의 ConversationBufferMemory를 사용하면 된다.
+) ConversationBufferWindowMemory : 최근 k개의 대화만 프롬프트에 포함
+) ConversationSummaryMemory : llm을 사용하여 대화 기록 요약
+) ConversationSummaryBufferMemory : 최근 대화는 프롬프트에 그대로 포함하되, 이전 대화 내용은 요약
Memory 저장 위치
- 랭체인의 Memory에서 대화기록은 기본적으로 메모리에 저장된다. 따라서 프로세스가 종료되면 대화 기록은 유지되지 않는다.
- 또한 여러 프로세스 서버로 부하를 분산하는 경우나 AWS Lambda와 같은 서버리스 환경에서 실행하는 경우에는 잘 작동하지 않는다. ⇒ 이러한 상황에 대응하기 위해 대화 이력을 애플리케이션 외부에 저장해야한다!
Memory 사용 시 주의 사항
...
"messages":[
{“role”:”system”,"content" :"you are a helpful assistant"},
{“role”:”user”,"content" :"안녕하세요 저는 존입니다."},
{“role”:”assistant”,"content" :"안녕하세요 존씨! 어떻게 도와드릴까요?"},
{“role”:”user”,"content" :"제이름을 아시나요?"},
]
...
이런식으로 요청일 때, “role”:”user” 이 content로 대화기록에 포함되어있다. → 저자의 경험사 이런 형태의 요청은 대화 기록을 잘 인식하지 못하는 경우가 많았다고 한다.
+)챗GPT와 랭체인을 활용한 LLM 기반 AI 앱 개발 (요시다 신고, 오시마 유키 (지은이), 최용 (옮긴이) 위키북스 2024-06-29)
를 읽고 정리하였습니다.
'AI' 카테고리의 다른 글
RAG(Retrieval-Augmented Generation) 비교 (5) | 2024.10.11 |
---|---|
PyTorch설치 중 마주한 No space left on device (0) | 2024.07.28 |