LangChain의 DatetimeOutputParser에 대해 알아보겠습니다.
참고
형식 코드 | 설명 | 예시 |
---|---|---|
%Y | 4자리 연도 | 2024 |
%y | 2자리 연도 | 24 |
%m | 2자리 월 | 07 |
%d | 2자리 일 | 04 |
%H | 24시간제 시간 | 14 |
%I | 12시간제 시간 | 02 |
%p | AM 또는 PM | PM |
%M | 2자리 분 | 45 |
%S | 2자리 초 | 08 |
%f | 마이크로초 (6자리) | 000123 |
%z | UTC 오프셋 | +0900 |
%Z | 시간대 이름 | KST |
%a | 요일 약어 | Thu |
%A | 요일 전체 | Thursday |
%b | 월 약어 | Jul |
%B | 월 전체 | July |
%c | 전체 날짜와 시간 | Thu Jul 4 14:45:08 2024 |
%x | 전체 날짜 | 07/04/24 |
%X | 전체 시간 | 14:45:08 |
다음과 같은 형식코드가 있습니다.
from langchain.output_parsers import DatetimeOutputParser
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
# 날짜 및 시간 출력 파서
output_parser = DatetimeOutputParser()
output_parser.format = "%Y-%m-%d"
# 사용자 질문에 대한 답변 템플릿
template = """Answer the users question:\n\n#Format Instructions: \n{format_instructions}\n\n#Question: \n{question}\n\n#Answer:"""
prompt = PromptTemplate.from_template(
template,
partial_variables={
"format_instructions": output_parser.get_format_instructions()
}, # 지침을 템플릿에 적용
)
# 프롬프트 내용을 출력
prompt
출력
PromptTemplate(input_variables=['question'], input_types={}, partial_variables={'format_instructions': "Write a datetime string that matches the following pattern: '%Y-%m-%d'.\n\nExamples: 1695-07-26, 1254-12-06, 1336-03-02\n\nReturn ONLY this string, no other words!"}, template='Answer the users question:\n\n#Format Instructions: \n{format_instructions}\n\n#Question: \n{question}\n\n#Answer:')
와 같이 날짜에 대해서 어떤 정형화된 형식으로 출력하도록 돕는 outputparser입니다.
print(output_parser.get_format_instructions())
출력
Write a datetime string that matches the following pattern: '%Y-%m-%d'.
Examples: 0792-06-14, 1373-08-10, 1982-08-30
Return ONLY this string, no other words!
와 같은 지침이 있는 것을 아실 수 있습니다.
# Chain 을 생성합니다.
chain = prompt | ChatOpenAI() | output_parser
# 체인을 호출하여 질문에 대한 답변을 받습니다.
output = chain.invoke({"question": "Google 이 창업한 연도"})
출력

output
이제 깔끔하게 날짜를 받으려면

와 같이 깔끔한 날짜로 출력됨을 아실 수 있습니다.
strftime이라는 함수 자체는 꽤 major한 함수인듯 합니다.
https://docs.python.org/3.6/library/datetime.html
해당 파이썬 공식문서에서 해당 함수에 대해 설명하는 내용을 읽어보세요