본문 바로가기
공부/AI

GPT_3(노마드코더)

by 줘요 2024. 1. 18.

1. ConversationBufferMemory : 이전 대화 내용 전체를 저장하는 메모리

 

from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(return_messages=True)

memory.save_context({"input": "Hi!"}, {"output": "How are you?"})

memory.load_memory_variables({})

 

해당 텍스트가 메모리에 저장됨 

 

해당 코드를 반복하면 계속 저장되는 것을 볼 수 있음

memory.save_context({"input": "Hi!"}, {"output": "How are you?"})

memory.load_memory_variables({})

 

 

2. ConversationBufferWindowMemory : 대화의 특정 부분만을 저장하는 메모리 ex) 최근 5개의 메시지를 저장하게 하면 6번째 메시지 작성 시 1번째 메시지 삭제

 

단점: 최근 대화에만 집중

 

4개의 메시지를 저장하고

from langchain.memory import ConversationBufferWindowMemory

memory = ConversationBufferWindowMemory(
    return_messages=True,
    k=4
)

def add_message(input, output):
    memory.save_context({"input":input},{"output":output})

add_message(1,1)
add_message(2,2)
add_message(3,3)
add_message(4,4)

 

메모리 로드

memory.load_memory_variables({})

 

 

5번째 메시지를 출력하면 1번 메시지가 사라짐

add_message(5,5)

 

 

3. ConversationSummaryMemory : llm 사용, 메시지를 그대로 저장하는 것이 아니라 대화를 요약해줌

from langchain.memory import ConversationSummaryMemory
from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(temperature=0.1)

memory = ConversationSummaryMemory(llm=llm)

def add_message(input, output):
    memory.save_context({"input":input},{"output":output})

def get_history():
    return memory.load_memory_variables({})

add_message("Hi I'm juho, I live in South Korea", "Wow that is so cool")
add_message("South Korea is so pretty", "I wish I could go!")
get_history()

 

두 문장을 요약해서 출력해 줌

 

4. ConversationSummaryBufferMemory : 메모리에 보내온 메시지의 수를 저장, 오래된 대화 내용은 요약해서 저장

 

5. ConversationKGMemory : 가장 중요한 것들을 뽑아내는 요약본

 

----------------------------------------------------------------------------------------------------------------------

 

메모리를 체인에 꽂는 방법 

 

1. LLM chain (chain에 verbose=True를 통해 디버깅 가능 )

 

from langchain.memory import ConversationSummaryBufferMemory
from langchain.chat_models import ChatOpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

llm = ChatOpenAI(temperature=0.1)

# 대화 내역을 저장하고 관리하기 위한 메모리 객체 생성.
# max_token_limit은 메모리가 저장할 수 있는 최대 토큰 수를 설정합니다.
# memory_key는 이 메모리 인스턴스를 식별하는 데 사용됩니다.
# return_messages는 메모리에서 메시지를 반환할지 여부를 결정합니다.
memory = ConversationSummaryBufferMemory(
    llm=llm,
    max_token_limit=120,
    memory_key="chat_history",
    return_messages=True,
)

template = """
    You are a helpful AI talking to a human

    {chat_history}
    Human:{question}
    You:
"""

chain = LLMChain(
    llm=llm,
    memory=memory,
    prompt=PromptTemplate.from_template(template),
    verbose=True,
)

chain.predict(question="My name is juho")

 

 

 

chain.predict(question="I live in Seoul")

chain.predict(question="What is my name?")

 

위 과정을 통해 대화 내용이 저장되고 이전에 대화 내용을 기반으로 답변을 해주는 것을 확인해 볼 수 있다.

 

심화: 대화형식으로 메시지 출력하기 

 

import 해주기

from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder

 

template 부분을 아래와 같이 바꿔주기

# 채팅 프롬프트 템플릿을 설정합니다.
# 여기서는 시스템 메시지로 "You are a helpful AI talking to a human"를 설정하고,
# 이전 대화 내역을 포함시키기 위해 MessagesPlaceholder를 사용합니다.
# 사용자의 질문은 "{question}"으로 표시됩니다.
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful AI talking to a human"),
    MessagesPlaceholder(variable_name="chat_history"),
    ("human","{question}"),
])

 

chain을 아래와 같이 바꿔주기

# LLMChain 인스턴스를 생성합니다.
# 이 객체는 LLM(대규모 언어 모델), 메모리, 프롬프트 템플릿을 사용하여
# 사용자의 질문에 대한 응답을 생성합니다.
chain = LLMChain(
    llm=llm,
    memory=memory,
    prompt=prompt,
    verbose=True,  # verbose=True는 추가적인 디버깅 정보를 출력합니다.
)

 

변경해 주면 아래와 같이 system, human, AI 메시지를 대화형식으로 바꿔주는 것을 확인해 볼 수 있다.

 

 

'공부 > AI' 카테고리의 다른 글

GPT_2(노마드코더)  (0) 2023.11.30
GPT_1(노마드코더)  (0) 2023.11.28
모델 분류 성능 평가 지표(Classification Metric)  (0) 2023.10.02
AI 기초 실습  (0) 2023.09.06

댓글