Prompt templates
Prompt templates는 사용자의 raw information을 LLM이 작업할 수 있는 형식으로 변화하는 데에 도움을 줍니다. 오늘 실습에서는 먼저 사용자의 instructions이 포함된 system message를 추가해보겠습니다. 그 다음으로는 messages 이외에 다양한 input을 추가해보겠습니다.
다음과 같은 코드를 통해 input type을 변경할 수 있습니다. 단순한 메시지 대신, 메시지를 포함하고 있는 'messages key'를 딕셔너리 형태로 전달하게 됩니다.
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant. Answer all questions to the best of your ability.",
),
MessagesPlaceholder(variable_name="messages"),
]
)
chain = prompt | model
response = chain.invoke({"messages": [HumanMessage(content="hi! I'm 준언")]})
response.content
그 다음 이전 실습에서와 같이 Message History object에 적용해줍니다.
with_message_history = RunnableWithMessageHistory(chain, get_session_history)
config = {"configurable": {"session_id": "abc5"}}
response = with_message_history.invoke(
[HumanMessage(content="Hi! I'm 준언")],
config=config,
)
response.content
response = with_message_history.invoke(
[HumanMessage(content="What's my name?")],
config=config,
)
response.content
다음으로는 프롬프트를 더 복잡하게 만들어보겠습니다. 다음과 같이 프롬프트 템플릿을 적용해줍니다.
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant. Answer all questions to the best of your ability in {language}.",
),
MessagesPlaceholder(variable_name="messages"),
]
)
chain = prompt | model
프롬프트에 'language'를 설정해보겠습니다. 다음 코드를 통해 원하는 언어로 답변을 출력하도록 설정할 수 있습니다. 저는 불어로 설정을 해보겠습니다.
response = chain.invoke(
{"messages": [HumanMessage(content="hi! I'm Juneon")], "language": "French"}
)
response.content
이제 이 체인을 Message History class로 감싸보겠습니다. 이번에는 입력 부분에 여러 개의 키가 있으므로 채팅 기록을 저장하는 데 사용할 올바른 키를 지정해야합니다.
with_message_history = RunnableWithMessageHistory(
chain,
get_session_history,
input_messages_key="messages",
)
config = {"configurable": {"session_id": "abc11"}}
response = with_message_history.invoke(
{"messages": [HumanMessage(content="hi! I'm Juneon")], "language": "French"},
config=config,
)
response.content
response = with_message_history.invoke(
{"messages": [HumanMessage(content="Did you see this Paris Olympic which was held in this year?")], "language": "French"},
config=config,
)
response.content
다음 실습으로는 대화 기록을 관리하는 법을 알아보겠습니다!
'인공지능 > LangChain' 카테고리의 다른 글
검색증강생성 (RAG) (1) | 2024.07.29 |
---|---|
[LangChain] 공식문서 Build a Chatbot 실습 (2) (2) | 2024.07.26 |
[LangChain] 공식문서 Build a Chatbot 실습 (1) (0) | 2024.07.25 |
[LangChain] 공식문서 Conceptual Guide docs (2) Components (0) | 2024.07.21 |
[LangChain] 공식문서 Conceptual Guide (1) Architecture, LCEL (0) | 2024.07.21 |