LangChain 정리 (2025-06-30) #2

LangChain의 DatetimeOutputParser에 대해 알아보겠습니다.

참고

형식 코드설명예시
%Y4자리 연도2024
%y2자리 연도24
%m2자리 월07
%d2자리 일04
%H24시간제 시간14
%I12시간제 시간02
%pAM 또는 PMPM
%M2자리 분45
%S2자리 초08
%f마이크로초 (6자리)000123
%zUTC 오프셋+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

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

와 같이 깔끔한 날짜로 출력됨을 아실 수 있습니다.

https://modoocode.com/122

strftime이라는 함수 자체는 꽤 major한 함수인듯 합니다.

https://docs.python.org/3.6/library/datetime.html

해당 파이썬 공식문서에서 해당 함수에 대해 설명하는 내용을 읽어보세요