AI开发-python-langchain框架(1-10 返回日期-格式解析器)

如何让大模型返回的结果是一个标准的日期格式?

如下这段代码展示了如何使用 LangChain 构建一个结构化输出链(chain),将自然语言问题("中华人民共和国是什么时候创立的?")通过大语言模型(LLM)转换为标准的 Python datetime 对象

复制代码
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from langchain.output_parsers import DatetimeOutputParser
import os

# 日期时间输出解析器 自动将模型返回的文本字符串解析为 Python 的 datetime 对象
output_parser = DatetimeOutputParser()

print('###########原生的提示词是英文的')
format_instructions=output_parser.get_format_instructions()
print(format_instructions)
print('###########')


template = """回答用户的问题:
{question}
{format_instructions}"""

format_instructions='''响应的格式用日期时间字符串:“%Y-%m-%dT%H:%M:%S.%fZ”。
示例: 1898-05-31T06:59:40.248940Z, 1808- 10-20T01:56:09.167633Z、0226-10-17T06:18:24.192024Z
仅返回此字符串!'''

prompt = PromptTemplate.from_template(
    template,
    partial_variables={"format_instructions":format_instructions},
)

#输出提示词
print(prompt.invoke({"question": "中华人民共和国是什么时候创立的?"}).text)

llm = ChatOpenAI(
    api_key=os.getenv("DEEPSEEK_API_KEY"),
    base_url=os.getenv("BASE_URL"),  # Deepseek 的 API 基础地址
    model="deepseek-v3:671b",  # Deepseek 对话模型(可选:deepseek-chat-pro 等高级模型)
    temperature=0.7,  # 温度参数(0-1,越低越稳定)
    max_tokens=1024  # 最大生成 tokens
)


chain = prompt | llm | output_parser

print('--------------')
result = chain.invoke({"question": "中华人民共和国是什么时候创立的?"})
print(result)

返回结果:

###########原生的提示词是英文的

Write a datetime string that matches the following pattern: '%Y-%m-%dT%H:%M:%S.%fZ'.

Examples: 1466-10-12T18:56:24.473648Z, 0322-04-03T12:00:41.805552Z, 1762-08-02T08:58:50.100670Z

Return ONLY this string, no other words!

###########

回答用户的问题:

中华人民共和国是什么时候创立的?

响应的格式用日期时间字符串:"%Y-%m-%dT%H:%M:%S.%fZ"。

示例: 1898-05-31T06:59:40.248940Z, 1808- 10-20T01:56:09.167633Z、0226-10-17T06:18:24.192024Z

仅返回此字符串!


1949-10-01 00:00:00