调整了agent
This commit is contained in:
@@ -1,42 +1,136 @@
|
||||
import { tool } from "langchain"
|
||||
import lunar from "lunar-javascript"
|
||||
const { Solar, Lunar, HolidayUtil, TermUtil } = lunar
|
||||
import { getAccurateTime } from "./utils.js"
|
||||
import { tool } from "@langchain/core/tools"
|
||||
import { z } from "zod"
|
||||
import { Solar } from "lunar-javascript"
|
||||
|
||||
/**
|
||||
* 日历工具
|
||||
* 提供准确时间、农历信息、节气、节日和老黄历等信息
|
||||
*
|
||||
* 陪诊场景只关心:当前日期时间、星期、农历日期、节日/节气。
|
||||
* 黄历宜忌、财神喜神方位等与就医无关的信息不再返回。
|
||||
*
|
||||
* 时间以北京时间(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) {
|
||||
console.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 () => {
|
||||
async ({ date } = {}) => {
|
||||
try {
|
||||
// 获取准确时间
|
||||
const timeInfo = await getAccurateTime()
|
||||
|
||||
// 获取农历信息
|
||||
const date = new Date(timeInfo.timestamp)
|
||||
const solar = Solar.fromDate(date)
|
||||
const lunar = solar.getLunar()
|
||||
|
||||
// 组合返回结果
|
||||
const result = {
|
||||
time: timeInfo,
|
||||
weekday: solar.getWeek(),
|
||||
lunar: {
|
||||
lunar: lunar.toString(),
|
||||
solar: solar.toString(),
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
return JSON.stringify(result, 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) {
|
||||
console.error('Error in calendar tool:', error)
|
||||
console.error("Error in calendar tool:", error)
|
||||
return JSON.stringify({ error: error.message }, null, 2)
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "get_calendar_info",
|
||||
description: "获取当前准确日期时间,以及对应的农历日期"
|
||||
description:
|
||||
"获取当前日期时间(北京时间)及农历、星期、节日、节气;传入 date(YYYY-MM-DD)时查询指定日期的信息。",
|
||||
schema: z.object({
|
||||
date: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("要查询的日期,格式 YYYY-MM-DD;不传则返回当前日期时间")
|
||||
})
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { tool } from "langchain"
|
||||
import lunarLib from "lunar-javascript"
|
||||
const { Solar } = lunarLib
|
||||
|
||||
/**
|
||||
* 特定日期日历工具
|
||||
* 基于 lunar-javascript 提供指定日期的完整农历信息
|
||||
*/
|
||||
export const getLunarCalendarInfoTool = tool(
|
||||
async ({ year, month, day }) => {
|
||||
try {
|
||||
const solar = Solar.fromYmd(year, month, day)
|
||||
const lunar = solar.getLunar()
|
||||
|
||||
const result = {
|
||||
solar: solar.toString(),
|
||||
weekday: `星期${solar.getWeekInChinese()}`,
|
||||
lunar: lunar.toString(),
|
||||
ganzhiYear: lunar.getYearInGanZhi(),
|
||||
zodiac: lunar.getYearShengXiao(),
|
||||
solarTerms: lunar.getJieQi() || null,
|
||||
festivals: [...solar.getFestivals(), ...lunar.getFestivals()],
|
||||
yi: lunar.getDayYi(),
|
||||
ji: lunar.getDayJi(),
|
||||
xiShen: lunar.getDayPositionXiDesc(),
|
||||
caiShen: lunar.getDayPositionCaiDesc()
|
||||
}
|
||||
|
||||
return JSON.stringify(result, null, 2)
|
||||
} catch (error) {
|
||||
return JSON.stringify({ error: error.message }, null, 2)
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "get_lunar_calendar_info",
|
||||
description: "获取指定日期的日历信息,包括农历信息、老黄历、当年生肖、今日宜忌、喜神方位、财神方位、今日节气、今日节日等",
|
||||
schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
year: {
|
||||
type: "number",
|
||||
description: "年份",
|
||||
minimum: 1900,
|
||||
maximum: 2100
|
||||
},
|
||||
month: {
|
||||
type: "number",
|
||||
description: "月份",
|
||||
minimum: 1,
|
||||
maximum: 12
|
||||
},
|
||||
day: {
|
||||
type: "number",
|
||||
description: "日期",
|
||||
minimum: 1,
|
||||
maximum: 31
|
||||
}
|
||||
},
|
||||
required: ["year", "month", "day"]
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -1,87 +0,0 @@
|
||||
import * as z from "zod"
|
||||
import { tool } from "langchain"
|
||||
import lunar from "lunar-javascript"
|
||||
const { Solar, Lunar, HolidayUtil, TermUtil } = lunar
|
||||
|
||||
/**
|
||||
* 获取准确时间工具
|
||||
* 通过国内权威时间源获取当前准确时间
|
||||
* @returns {string} - 返回当前准确时间的JSON字符串
|
||||
*/
|
||||
export async function getAccurateTime() {
|
||||
const timeSources = [
|
||||
{
|
||||
name: 'timeapi.io',
|
||||
url: 'https://timeapi.io/api/Time/current/zone?timeZone=Asia/Shanghai',
|
||||
method: 'json'
|
||||
},
|
||||
{
|
||||
name: '国家授时中心',
|
||||
url: 'http://www.ntsc.ac.cn',
|
||||
method: 'header'
|
||||
},
|
||||
{
|
||||
name: '阿里云',
|
||||
url: 'https://www.aliyun.com',
|
||||
method: 'header'
|
||||
},
|
||||
{
|
||||
name: '腾讯云',
|
||||
url: 'https://cloud.tencent.com',
|
||||
method: 'header'
|
||||
},
|
||||
{
|
||||
name: '华为云',
|
||||
url: 'https://www.huaweicloud.com',
|
||||
method: 'header'
|
||||
}
|
||||
]
|
||||
|
||||
for (const source of timeSources) {
|
||||
try {
|
||||
const startTime = Date.now()
|
||||
// 每个时间源限时 3 秒,防止单个源 TCP 挂起长时间阻塞
|
||||
const res = await fetch(source.url, { signal: AbortSignal.timeout(3000) })
|
||||
const latency = Date.now() - startTime
|
||||
|
||||
let timestamp = null
|
||||
let beijingTime = null
|
||||
|
||||
if (source.method === 'json') {
|
||||
const data = await res.json()
|
||||
timestamp = new Date(data.dateTime).getTime()
|
||||
beijingTime = data.dateTime
|
||||
} else if (source.method === 'header') {
|
||||
const dateHeader = res.headers.get('Date')
|
||||
if (dateHeader) {
|
||||
timestamp = new Date(dateHeader).getTime()
|
||||
beijingTime = new Date(timestamp).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })
|
||||
}
|
||||
}
|
||||
|
||||
if (timestamp) {
|
||||
return {
|
||||
timestamp,
|
||||
date: new Date(timestamp).toISOString(),
|
||||
localTime: beijingTime,
|
||||
source: source.name,
|
||||
latency: latency,
|
||||
success: true
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`从 ${source.name} 获取时间失败: ${error.message}`)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
const date = new Date()
|
||||
return {
|
||||
timestamp: date.getTime(),
|
||||
date: date.toISOString(),
|
||||
localTime: date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }),
|
||||
success: false,
|
||||
message: '使用本地时间作为备份'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
import { tool } from "langchain"
|
||||
import lunarLib from "lunar-javascript"
|
||||
const { Lunar } = lunarLib
|
||||
|
||||
// 当年冬至在节气表中的 key 为英文(上一年冬至占用中文 key)
|
||||
const EN_TERM_NAMES = { DONG_ZHI: "冬至" }
|
||||
|
||||
/**
|
||||
* 年份节气列表工具
|
||||
* 基于 lunar-javascript 计算给定年份的 24 节气精确日期
|
||||
*/
|
||||
export const getYearTermsTool = tool(
|
||||
async ({ year }) => {
|
||||
try {
|
||||
const table = Lunar.fromYmd(year, 1, 1).getJieQiTable()
|
||||
const terms = []
|
||||
for (const [key, solar] of Object.entries(table)) {
|
||||
// 只保留属于目标年份的节气(表首含上一年边界节气)
|
||||
if (solar.getYear() !== year) continue
|
||||
const name = EN_TERM_NAMES[key] ?? key
|
||||
terms.push({ date: solar.toString(), name })
|
||||
}
|
||||
terms.sort((a, b) => a.date.localeCompare(b.date))
|
||||
|
||||
return JSON.stringify({ year, terms }, null, 2)
|
||||
} catch (error) {
|
||||
return JSON.stringify({ error: error.message }, null, 2)
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "get_year_terms",
|
||||
description: "查询给定年份节气所在日期列表",
|
||||
schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
year: {
|
||||
type: "number",
|
||||
description: "年份",
|
||||
minimum: 1900,
|
||||
maximum: 2100
|
||||
}
|
||||
},
|
||||
required: ["year"]
|
||||
}
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user