29일차 Langchain, RAG

Peter·2025년 5월 14일
0

Langchain에 이어 RAG를 중심으로 실습했다.
오전에 매니저님과 이력서 상담이 이어졌는데 제 3자 입장에서 내 자소서와 포트폴리오가 어떤지 들어볼 수 있어서 좋았다.

Langchain에서 대화 히스토리를 기록할 때 필요한 메모리 예제 코드는 다음과 같다.

메모리 (Memory)

from langchain.memory import ConversationBufferMemory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

# 메모리 설정
memory = ConversationBufferMemory(return_messages=True, memory_key="chat_history")

# 프롬프트 템플릿
prompt = ChatPromptTemplate.from_messages([
    ("system", "당신은 친절한 AI 비서입니다."),
    MessagesPlaceholder(variable_name="chat_history"),
    ("human", "{input}")
])

# 체인 구성
conversation_chain = (
    RunnablePassthrough.assign(
        chat_history=lambda _: memory.load_memory_variables({})["chat_history"]
    )
    | prompt
    | ChatOpenAI(temperature=0.7)
    | StrOutputParser()
)

# 대화 시뮬레이션
def chat(user_input):
    response = conversation_chain.invoke({"input": user_input})
    memory.save_context({"input": user_input}, {"output": response})
    return response

# 대화 테스트
print(chat("안녕하세요! 저는 김철수입니다."))
print(chat("제 이름이 뭐였지?"))
print(chat("오늘 날씨가 어때?"))

추가 학습 자료

  1. LangChain공식 문서 [https://python.langchain.com/docs/introduction/]
  2. LangChain GitHub [https://github.com/langchain-ai/langchain]
  3. 가이드 [https://python.langchain.com/docs/how_to/#chat-models]
  4. LangChain 애플리케이션의 디버깅 및 모니터링 도구 [https://smith.langchain.com/]
profile
개발자 지망생. 일단 하고보자

0개의 댓글