138 lines
4.3 KiB
JavaScript
138 lines
4.3 KiB
JavaScript
import { tool } from "@langchain/core/tools"
|
|
import { z } from "zod"
|
|
import { Solar } from "lunar-javascript"
|
|
import logger from "../../../../utils/logger.js"
|
|
|
|
/**
|
|
* 日历工具
|
|
*
|
|
* 陪诊场景只关心:当前日期时间、星期、农历日期、节日/节气。
|
|
* 黄历宜忌、财神喜神方位等与就医无关的信息不再返回。
|
|
*
|
|
* 时间以北京时间(Asia/Shanghai)为准:服务器可能运行在 UTC,
|
|
* 直接用 new Date() 取日期会差一天,因此统一用 Intl 取北京时间的年月日。
|
|
*/
|
|
|
|
const TIME_API = "https://timeapi.io/api/Time/current/zone?timeZone=Asia/Shanghai"
|
|
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/
|
|
|
|
/** 校验日期在公历中真实存在(如 2026-02-30 不合法) */
|
|
function isValidYmd(year, month, day) {
|
|
const d = new Date(Date.UTC(year, month - 1, day))
|
|
return (
|
|
d.getUTCFullYear() === year &&
|
|
d.getUTCMonth() === month - 1 &&
|
|
d.getUTCDate() === day
|
|
)
|
|
}
|
|
|
|
function getBeijingDateParts(date = new Date()) {
|
|
const parts = new Intl.DateTimeFormat("en-US", {
|
|
timeZone: "Asia/Shanghai",
|
|
year: "numeric",
|
|
month: "2-digit",
|
|
day: "2-digit"
|
|
}).formatToParts(date)
|
|
const pick = (type) => Number(parts.find((p) => p.type === type)?.value)
|
|
return { year: pick("year"), month: pick("month"), day: pick("day") }
|
|
}
|
|
|
|
function formatBeijingTime(timestamp) {
|
|
return new Intl.DateTimeFormat("zh-CN", {
|
|
timeZone: "Asia/Shanghai",
|
|
dateStyle: "full",
|
|
timeStyle: "medium"
|
|
}).format(new Date(timestamp))
|
|
}
|
|
|
|
/**
|
|
* 获取当前北京时间日期。
|
|
* 优先请求授时接口,失败则回退本机时间(按 Asia/Shanghai 换算)。
|
|
*/
|
|
async function getBeijingNow() {
|
|
try {
|
|
const res = await fetch(TIME_API, { signal: AbortSignal.timeout(3000) })
|
|
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
|
const data = await res.json()
|
|
if (!data?.year || !data?.month || !data?.day) throw new Error("invalid response")
|
|
|
|
// 接口返回的是北京时间字段,换算成 UTC 时间戳,避免依赖服务器时区
|
|
const timestamp = Date.UTC(
|
|
data.year,
|
|
data.month - 1,
|
|
data.day,
|
|
(data.hour ?? 0) - 8,
|
|
data.minute ?? 0,
|
|
Math.floor(data.seconds ?? 0)
|
|
)
|
|
if (!Number.isFinite(timestamp)) throw new Error("invalid time")
|
|
|
|
return {
|
|
year: data.year,
|
|
month: data.month,
|
|
day: data.day,
|
|
localTime: formatBeijingTime(timestamp),
|
|
source: "timeapi.io",
|
|
success: true
|
|
}
|
|
} catch (error) {
|
|
logger.warn(`获取网络时间失败,使用本机时间: ${error.message}`)
|
|
const now = new Date()
|
|
return {
|
|
...getBeijingDateParts(now),
|
|
localTime: formatBeijingTime(now.getTime()),
|
|
source: "local",
|
|
success: false
|
|
}
|
|
}
|
|
}
|
|
|
|
function buildDayInfo(solar) {
|
|
const lunar = solar.getLunar()
|
|
return {
|
|
date: solar.toString(),
|
|
weekday: `星期${solar.getWeekInChinese()}`,
|
|
lunar: lunar.toString(),
|
|
festivals: [...solar.getFestivals(), ...lunar.getFestivals()],
|
|
solarTerm: lunar.getJieQi() || null
|
|
}
|
|
}
|
|
|
|
export const getCalendarInfoTool = tool(
|
|
async ({ date } = {}) => {
|
|
try {
|
|
if (date) {
|
|
if (!DATE_PATTERN.test(date)) {
|
|
return JSON.stringify({ error: "date 格式应为 YYYY-MM-DD" }, null, 2)
|
|
}
|
|
const [year, month, day] = date.split("-").map(Number)
|
|
if (year < 1900 || year > 2100) {
|
|
return JSON.stringify({ error: "date 年份需在 1900-2100 之间" }, null, 2)
|
|
}
|
|
if (!isValidYmd(year, month, day)) {
|
|
return JSON.stringify({ error: `无效日期: ${date}` }, null, 2)
|
|
}
|
|
return JSON.stringify(buildDayInfo(Solar.fromYmd(year, month, day)), null, 2)
|
|
}
|
|
|
|
const now = await getBeijingNow()
|
|
const solar = Solar.fromYmd(now.year, now.month, now.day)
|
|
return JSON.stringify({ now, ...buildDayInfo(solar) }, null, 2)
|
|
} catch (error) {
|
|
logger.error("Error in calendar tool:", error)
|
|
return JSON.stringify({ error: error.message }, null, 2)
|
|
}
|
|
},
|
|
{
|
|
name: "get_calendar_info",
|
|
description:
|
|
"获取当前日期时间(北京时间)及农历、星期、节日、节气;传入 date(YYYY-MM-DD)时查询指定日期的信息。",
|
|
schema: z.object({
|
|
date: z
|
|
.string()
|
|
.optional()
|
|
.describe("要查询的日期,格式 YYYY-MM-DD;不传则返回当前日期时间")
|
|
})
|
|
}
|
|
)
|