调整了agent

This commit is contained in:
lik
2026-10-28 11:15:29 +08:00
parent b8f53d3660
commit c4f6be6494
29 changed files with 703 additions and 921 deletions
+121 -27
View File
@@ -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"]
}
}
)
-87
View File
@@ -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: '使用本地时间作为备份'
}
}
-46
View File
@@ -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"]
}
}
)
+62 -49
View File
@@ -3,43 +3,72 @@ import z from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
function createEscortRecordQueryTool(userInfo) {
const userId = userInfo?._id;
const STATUS_VALUES = ["pending", "confirmed", "in_progress", "completed", "cancelled"];
const STATUS_DESC =
"Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)";
/**
* 陪诊记录查询工具
*
* 用户端与管理端共用同一套查询实现,差异只有两处:
* - 用户端强制按 userId 隔离,且不暴露手机号筛选;
* - 管理端可跨用户查询,并支持按患者手机号精确筛选。
* 两端不会出现在同一个 Agent 中,因此可以共用工具名 escort_record_query。
*/
function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {}) {
const shape = {
patientName: z.string().optional().describe("Patient name for fuzzy search"),
status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC),
page: z.number().int().min(1).optional().describe("Page number, starting from 1"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("Records per page (1-50), default 20"),
};
if (allowMobile) {
shape.mobile = z.string().optional().describe("Patient mobile phone number for exact match");
}
return tool(
async ({ patientName, status, page = 1, pageSize = 20 }) => {
async ({ patientName, mobile, status, page = 1, pageSize = 20 }) => {
try {
const filter = {};
if (!userId && !allowMobile) {
return { success: false, error: "用户未登录,无法查询陪诊记录" };
}
const filter = { deletedAt: null };
if (patientName) {
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
}
// 按订单归属用户过滤:不能用手机号作为隔离键,
// 因为手机号可由用户自行修改(改到他人号码即可读到他人订单)
if (!userId) {
return {
success: false,
error: "用户未登录,无法查询陪诊记录",
};
if (allowMobile && mobile) {
filter["patient.mobile"] = mobile;
}
filter.userId = userId;
// 软删除的订单对用户端不可见
filter.deletedAt = null;
if (status) {
filter.status = status;
}
// 用户端按订单归属过滤;不能用手机号作为隔离键(手机号可由用户自行修改)
if (userId) {
filter.userId = userId;
}
const skip = (page - 1) * pageSize;
const records = await DBModel.EscortRecord.find(filter)
.sort({ "schedule.date": -1 })
.skip(skip)
.limit(pageSize)
.lean();
const total = await DBModel.EscortRecord.countDocuments(filter);
const [records, total] = await Promise.all([
DBModel.EscortRecord.find(filter)
.sort({ "schedule.date": -1 })
.skip(skip)
.limit(pageSize)
.lean(),
DBModel.EscortRecord.countDocuments(filter),
]);
return {
success: true,
@@ -57,35 +86,19 @@ function createEscortRecordQueryTool(userInfo) {
},
{
name: "escort_record_query",
description:
"Query escort records from database for the current user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current logged-in user.",
schema: z.object({
patientName: z
.string()
.optional()
.describe("Patient name for fuzzy search"),
status: z
.enum(["pending", "confirmed", "in_progress", "completed", "cancelled"])
.optional()
.describe(
"Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)"
),
page: z
.number()
.int()
.min(1)
.optional()
.describe("Page number, starting from 1"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("Records per page (1-50), default 20"),
}),
description: allowMobile
? "Query all escort records (admin scope). Supports filtering by patient name, mobile phone number, and appointment status. Returns paginated results sorted by appointment date in descending order."
: "Query escort records of the current logged-in user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current user.",
schema: z.object(shape),
}
);
}
export { createEscortRecordQueryTool };
/** 用户端:按当前登录用户隔离 */
const createEscortRecordQueryTool = (userInfo) =>
buildEscortRecordQueryTool({ userId: userInfo?._id });
/** 管理端:跨用户查询,支持手机号 */
const escortRecordQueryTool = buildEscortRecordQueryTool({ allowMobile: true });
export { createEscortRecordQueryTool, escortRecordQueryTool };
@@ -1,80 +0,0 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
const escortRecordQueryTool = tool(
async ({ patientName, mobile, status, page = 1, pageSize = 20 }) => {
try {
const filter = { deletedAt: null };
if (patientName) {
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
}
if (mobile) {
filter["patient.mobile"] = mobile;
}
if (status) {
filter.status = status;
}
const skip = (page - 1) * pageSize;
const records = await DBModel.EscortRecord.find(filter)
.sort({ "schedule.date": -1 })
.skip(skip)
.limit(pageSize)
.lean();
const total = await DBModel.EscortRecord.countDocuments(filter);
return {
success: true,
data: records,
};
} catch (error) {
return {
success: false,
error: error.message,
};
}
},
{
name: "escort_record_query",
description:
"Query escort records from database. Supports filtering by patient name, mobile phone number, and appointment status. Returns paginated results sorted by appointment date in descending order.",
schema: z.object({
patientName: z
.string()
.optional()
.describe("Patient name for fuzzy search"),
mobile: z
.string()
.optional()
.describe("Patient mobile phone number for exact match"),
status: z
.enum(["pending", "confirmed", "in_progress", "completed", "cancelled"])
.optional()
.describe(
"Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)"
),
page: z
.number()
.int()
.min(1)
.optional()
.describe("Page number, starting from 1"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("Records per page (1-50), default 20"),
}),
}
);
export { escortRecordQueryTool };
+2 -2
View File
@@ -2,6 +2,7 @@ import { tool } from "@langchain/core/tools";
import z from "zod";
import mongoose from "mongoose";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
const healthProfileQueryTool = tool(
async ({ profileId, userId, name, mobile, page = 1, pageSize = 20 }) => {
@@ -28,8 +29,7 @@ const healthProfileQueryTool = tool(
}
if (name) {
// 转义正则特殊字符,避免查询报错或 ReDoS;姓名支持中文、全拼、拼音首字母匹配
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = { $regex: escaped, $options: "i" };
const re = { $regex: escapeRegex(name), $options: "i" };
filter.$or = [{ "profile.name": re }, { "profile.pinyin": re }, { "profile.pinyinFL": re }];
}
if (mobile) {
-32
View File
@@ -1,32 +0,0 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { DBModel } from "../../../../models/index.js";
const hospitalInfoGetTool = tool(
async ({ hospitalId }) => {
try {
if (!hospitalId) {
return { success: false, error: "hospitalId 不能为空" };
}
const org = await DBModel.Organization.findById(hospitalId).lean();
if (!org) {
return { success: false, error: `未找到 id 为「${hospitalId}」的机构` };
}
return { success: true, data: org };
} catch (error) {
return { success: false, error: error.message };
}
},
{
name: "hospital_info_get",
description:
"根据医院 id 获取医院完整信息。id 可通过 hospital_info_list 获取。",
schema: z.object({
hospitalId: z.string().describe("医院 id(MongoDB ObjectId,来自 hospital_info_list)"),
}),
}
);
export { hospitalInfoGetTool };
+6 -8
View File
@@ -1,24 +1,22 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
const hospitalInfoListTool = tool(
async ({ keyword }) => {
try {
const filter = {};
if (keyword) {
const escaped = String(keyword).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = { $regex: escaped, $options: "i" };
const re = { $regex: escapeRegex(keyword), $options: "i" };
filter.$or = [{ name: re }, { pinyin: re }, { pinyinFL: re }];
}
const total = await DBModel.Organization.countDocuments(filter);
// 轻量列表:只取 id+名称,用于先定位医院,再按 id 查详情
const orgs = await DBModel.Organization.find(filter)
.sort({ name: 1 })
.limit(1000)
.select("name")
.lean();
const [total, orgs] = await Promise.all([
DBModel.Organization.countDocuments(filter),
DBModel.Organization.find(filter).sort({ name: 1 }).limit(1000).select("name").lean(),
]);
return { success: true, total, data: orgs.map((o) => ({ id: o._id, name: o.name })) };
} catch (error) {
+35 -10
View File
@@ -1,23 +1,44 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import mongoose from "mongoose";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
/**
* 医院信息查询工具
*
* 两种用法:
* - 传 hospitalId:返回该院完整档案(id 可先用 hospital_info_list 获取);
* - 传 hospitalName:按名称模糊查询,并可按科室 / 医生名过滤,返回面向上层展示的精简字段。
*/
const hospitalInfoQueryTool = tool(
async ({ hospitalName, department, doctorName }) => {
async ({ hospitalId, hospitalName, department, doctorName }) => {
try {
if (!hospitalName) {
return { success: false, error: "hospitalName 不能为空" };
if (hospitalId) {
if (!mongoose.Types.ObjectId.isValid(hospitalId)) {
return { success: false, error: `Invalid hospital ID: ${hospitalId}` };
}
const org = await DBModel.Organization.findById(hospitalId).lean();
if (!org) {
return { success: false, error: `未找到 id 为「${hospitalId}」的机构` };
}
return { success: true, total: 1, data: [org] };
}
const filter = { name: { $regex: hospitalName, $options: "i" } };
const total = await DBModel.Organization.countDocuments(filter);
if (!hospitalName) {
return { success: false, error: "请提供 hospitalId 或 hospitalName" };
}
const filter = { name: { $regex: escapeRegex(hospitalName), $options: "i" } };
// 医院总量小,一次最多取 10 家,命中过多时由调用方细化名称
const [total, orgs] = await Promise.all([
DBModel.Organization.countDocuments(filter),
DBModel.Organization.find(filter).limit(10).lean(),
]);
if (total === 0) {
return { success: false, error: `未找到名称包含「${hospitalName}」的机构` };
}
// 医院总量小,一次最多取 10 家,命中过多时由调用方细化名称
const orgs = await DBModel.Organization.find(filter).limit(10).lean();
const data = orgs.map((org) => {
const fa = org.forAgent ?? {};
let departments = fa.departments ?? [];
@@ -51,9 +72,13 @@ const hospitalInfoQueryTool = tool(
{
name: "hospital_info_query",
description:
"查询医院就医信息:医院总览(门诊/挂号/缴费/医保/交通)、科室(位置/电话/就诊提示)、医生(职称/擅长/号别/坐班)、场景指南(初诊/住院/检查须知/老人服务)、照片。按医院名称模糊查询,可按科室、医生名过滤。最多返回 10 家医院信息。",
"查询医院就医信息。传 hospitalId 返回该院完整档案;传 hospitalName 按名称模糊查询,可再按科室、医生名过滤,返回医院总览(门诊/挂号/缴费/医保/交通)、科室(位置/电话/就诊提示)、医生(职称/擅长/号别/坐班)、场景指南、照片。最多返回 10 家医院。",
schema: z.object({
hospitalName: z.string().describe("医院名称,支持模糊匹配(如 协和)"),
hospitalId: z
.string()
.optional()
.describe("医院 id(MongoDB ObjectId,来自 hospital_info_list),提供时忽略其他查询条件"),
hospitalName: z.string().optional().describe("医院名称,支持模糊匹配(如 协和)"),
department: z.string().optional().describe("科室名称过滤(如 风湿免疫科、放射科)"),
doctorName: z.string().optional().describe("医生姓名过滤"),
}),
+5 -2
View File
@@ -1,6 +1,7 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
const hospitalInfoSetTool = tool(
async ({ hospitalName, section, action, content, guides, entry, entryName, updatedBy }) => {
@@ -9,8 +10,10 @@ const hospitalInfoSetTool = tool(
return { success: false, error: "hospitalName 不能为空" };
}
// 定位医院:名称必须唯一命中
const orgs = await DBModel.Organization.find({ name: { $regex: hospitalName, $options: "i" } }).exec();
// 定位医院:名称必须唯一命中;转义正则元字符,避免非法表达式与 ReDoS
const orgs = await DBModel.Organization.find({
name: { $regex: escapeRegex(hospitalName), $options: "i" },
}).exec();
if (orgs.length === 0) {
return { success: false, error: `未找到名称包含「${hospitalName}」的机构,请确认医院名称后重试` };
}
-40
View File
@@ -1,40 +0,0 @@
import * as z from "zod"
import { tool } from "langchain"
/**
* 获取城市经纬度工具
* @param {string} city - 城市名称
* @returns {Object|null} - 返回经纬度对象 {lat, lng},如果未找到则返回null
*/
export const getLatLngTool = tool(
async (input) => {
const { city } = input
try {
// 使用open-meteo地理编码API获取经纬度
console.log('获取城市经纬度:', city)
const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&language=zh&count=1`
const res = await fetch(url)
const data = await res.json()
if (data.results?.length) {
return {
lat: data.results[0].latitude,
lng: data.results[0].longitude
}
}
// 如果没有找到结果,返回null
return null
} catch (error) {
console.error('地理编码API调用失败:', error)
return null
}
},
{
name: "get_lat_lng",
description: `根据城市名称获取经纬度信息`,
schema: z.object({
city: z.string().describe("城市名称,例如:北京市海淀区")
})
}
)
+4 -15
View File
@@ -1,30 +1,19 @@
// Tool 模块统一导出入口
// 提供工具基类、注册表和所有工具类的统一导出
// Web工具 (LangChain format)
// Web 工具
export { webFetchTool } from './web/fetch.js';
export { webSearchTool } from './web/search.js';
export { httpGetTool } from './web/http_get.js';
export { httpPostTool } from './web/http_post.js';
// 日历工具 (LangChain format)
// 日历工具
export { getCalendarInfoTool } from './calendar/calendar_info.js';
export { getLunarCalendarInfoTool } from './calendar/lunar_calendar_info.js';
export { getYearHolidaysTool } from './calendar/year_holidays.js';
export { getYearTermsTool } from './calendar/year_terms.js';
// 地理工具 (LangChain format)
export { getLatLngTool } from './geo/latlon.js';
export { getEnvTool } from './system/envs.js';
// db
export { createEscortRecordQueryTool } from './db/escort_record_query.js';
export { escortRecordQueryTool } from './db/escort_record_query_admin.js';
// 数据库工具
export { createEscortRecordQueryTool, escortRecordQueryTool } from './db/escort_record_query.js';
export { escortRecordSetTool } from './db/escort_record_set.js';
export { healthProfileQueryTool } from './db/health_profile_query.js';
export { healthProfileSetTool } from './db/health_profile_set.js';
export { hospitalInfoListTool } from './db/hospital_info_list.js';
export { hospitalInfoGetTool } from './db/hospital_info_get.js';
export { hospitalInfoQueryTool } from './db/hospital_info_query.js';
export { hospitalInfoSetTool } from './db/hospital_info_set.js';
-70
View File
@@ -1,70 +0,0 @@
// LangChain 环境变量工具
import { tool } from '@langchain/core/tools';
import { z } from 'zod';
/**
* 敏感变量判定:按命名模式兜底,而不是只认几个固定关键词。
*
* 原实现只匹配 API_KEY/SECRET/PASSWORD/TOKEN/CREDENTIAL,
* 会漏掉 MONGODB_URI、DB_PASS、SIGN_KEY 这类常见命名。
*/
const SENSITIVE_PATTERNS = [
/API_?KEY/i,
/SECRET/i,
/PASS(WORD|WD)?/i,
/TOKEN/i,
/CREDENTIAL/i,
/PRIVATE/i,
/AUTH/i,
/(^|_)KEY($|_)/i,
/(^|_)URI($|_)/i,
/DSN/i,
/CONN(ECTION)?/i,
];
/**
* @param {string} key 环境变量名
* @returns {boolean}
*/
const isSensitive = (key) => SENSITIVE_PATTERNS.some((p) => p.test(key));
/**
* 获取环境变量工具
* @param {Object} input - 输入参数
* @param {string} [input.name] - 环境变量名,不指定则返回所有
* @returns {string} - 返回环境变量值或所有环境变量的JSON字符串
*/
export const getEnvTool = tool(
async (input) => {
const { name } = input || {};
if (name) {
const value = process.env[name];
if (value === undefined) {
return JSON.stringify({ error: `Environment variable '${name}' not found` });
}
// 按名查询同样脱敏,防止 LLM 绕过读取密钥
return JSON.stringify({ name, value: isSensitive(name) ? '***REDACTED***' : value });
}
// 返回所有环境变量(过滤敏感信息)
const env = { ...process.env };
for (const key of Object.keys(env)) {
if (isSensitive(key)) {
env[key] = '***REDACTED***';
}
}
return JSON.stringify({ env });
},
{
name: 'env_get',
description: '获取环境变量的值。如果不指定变量名,则返回所有环境变量。',
schema: z.object({
name: z.string().optional().describe('环境变量名,不指定则返回所有')
})
}
);
export default getEnvTool;
-17
View File
@@ -1,17 +0,0 @@
import * as z from "zod"
import { tool } from "langchain"
/**
* 获取系统时间工具
* @returns {string} - 返回当前系统时间
*/
export const getSystemTimeTool = tool(
(input) => {
return new Date().toLocaleString()
},
{
name: "get_system_time",
description: `获取当前系统时间`,
schema: z.object({})
}
)
+7 -8
View File
@@ -1,6 +1,6 @@
import { TavilyExtract } from "@langchain/tavily";
import { tool } from "@langchain/core/tools";
import * as z from "zod"
import { z } from "zod";
import config from "../../../../config.js";
const webFetchTool = tool(
@@ -20,14 +20,13 @@ const webFetchTool = tool(
},
{
name: "web_fetch",
description: "Run a web fetch",
description:
"抓取并提取指定网页的正文内容(默认 Markdown),适合阅读医院官网、政策公告、新闻等长文页面。",
schema: z.object({
extractDepth: z.enum(["basic", "advanced"]).default("basic"),
includeImages: z.boolean().default(false),
format: z
.enum(["markdown", "json"])
.default("markdown"),
urls: z.array(z.string().describe("The urls")).default([]),
urls: z.array(z.string()).min(1).max(5).describe("要抓取的网页 URL 列表(1-5 个)"),
extractDepth: z.enum(["basic", "advanced"]).default("basic").describe("提取深度:basic 更快,advanced 更完整"),
includeImages: z.boolean().default(false).describe("是否包含图片"),
format: z.enum(["markdown", "json"]).default("markdown").describe("返回格式"),
}),
},
);
+4 -11
View File
@@ -1,12 +1,10 @@
/**
* Agent 出网 HTTP 客户端:统一承载 SSRF 校验、重定向控制、超时上限与响应体截断。
*
* http_get / http_post 只负责参数整理,真正的安全约束集中在这里,
* 避免两个工具各写一套、修了一个漏掉另一个。
* 目前只有 http_get 使用,安全约束集中在这里,避免工具各自实现一套。
*
* 约束:
* - 每一跳都重新做同步 + DNS 校验,最多 3 跳(重定向可被用来绕过首次校验);
* - POST 不跟随重定向(303/302 会改写成 GET,语义与安全性都不可控);
* - 超时由服务端夹紧到 1s~15s,不接受模型传入的任意大值;
* - 响应体最多读取 2MB,超出即截断并标记 truncated。
*/
@@ -63,17 +61,14 @@ async function readBodyLimited(response) {
}
/**
* 发起受控的 HTTP 请求
* 发起受控的 GET 请求
* @param {string} url 目标地址
* @param {Object} options
* @param {string} [options.method] 请求方法
* @param {Object} [options]
* @param {Object} [options.headers] 请求头
* @param {string} [options.body] 请求体
* @param {number} [options.timeout] 超时毫秒数(会被夹紧)
* @returns {Promise<{status:number,statusText:string,headers:Object,buffer:Buffer,text:string,truncated:boolean,url:string}>}
*/
async function safeFetch(url, options = {}) {
const method = (options.method || "GET").toUpperCase();
const timeout = clampTimeout(options.timeout);
let currentUrl = url;
@@ -87,9 +82,8 @@ async function safeFetch(url, options = {}) {
try {
const response = await fetch(currentUrl, {
method,
method: "GET",
headers: options.headers,
body: options.body,
redirect: "manual",
signal: controller.signal,
});
@@ -98,7 +92,6 @@ async function safeFetch(url, options = {}) {
const location = response.headers.get("location");
await response.body?.cancel().catch(() => {});
if (!location) throw new Error(`Redirect without location: ${response.status}`);
if (method !== "GET") throw new Error("Redirects are not followed for non-GET requests");
currentUrl = new URL(location, currentUrl).toString();
continue;
}
+60 -5
View File
@@ -2,15 +2,66 @@ import { tool } from 'langchain';
import * as z from 'zod';
import { safeFetch } from './http_client.js';
const BAIDU_MAP_HOST = 'api.map.baidu.com';
const BAIDU_MAP_TOKEN_ENV = 'BAIDU_MAP_AUTH_TOKEN';
/**
* 拼查询参数。统一用 URLSearchParams,避免模型手工拼接导致中文/特殊字符未编码。
*/
function buildRequestUrl(url, params) {
if (!params) return url;
const parsed = new URL(url);
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null) continue;
parsed.searchParams.append(key, String(value));
}
return parsed.toString();
}
/**
* 百度地图 Agent Plan 鉴权由运行时注入,不把 token 暴露给模型。
* 仅对 https://api.map.baidu.com/agent_plan/ 生效,其他地址不附加凭证。
*/
function applyBaiduAuthorization(url, headers = {}) {
const parsed = new URL(url);
// 只给 Agent Plan 接口附加凭证,避免 token 被带到百度地图的其他接口
if (
parsed.protocol !== 'https:'
|| parsed.hostname !== BAIDU_MAP_HOST
|| !parsed.pathname.startsWith('/agent_plan/')
) {
return headers;
}
const token = process.env[BAIDU_MAP_TOKEN_ENV];
if (!token) return headers;
const next = { ...headers };
const authorizationKey = Object.keys(next)
.find((key) => key.toLowerCase() === 'authorization');
const key = authorizationKey || 'Authorization';
// 兼容旧 skill 中写占位符的调用方式;模型不应主动传真实 token
if (!authorizationKey || !String(next[key] ?? '').trim()) {
next[key] = `Bearer ${token}`;
return next;
}
next[key] = String(next[key])
.replace(/\$\{BAIDU_MAP_AUTH_TOKEN\}|\$BAIDU_MAP_AUTH_TOKEN/g, token);
return next;
}
export { buildRequestUrl, applyBaiduAuthorization };
export const httpGetTool = tool(
async ({ url, headers = {}, timeout = 15000 }) => {
async ({ url, params, headers = {}, timeout = 15000 }) => {
try {
const requestUrl = buildRequestUrl(url, params);
// 校验(含 DNS)、重定向控制、超时夹紧、响应体截断统一在 safeFetch 内完成
const response = await safeFetch(url, {
method: 'GET',
const response = await safeFetch(requestUrl, {
headers: {
'User-Agent': 'XAgent-Bot/1.0',
...headers
...applyBaiduAuthorization(requestUrl, headers)
},
timeout
});
@@ -48,9 +99,13 @@ export const httpGetTool = tool(
},
{
name: 'http_get',
description: 'Send HTTP GET request and return response content. Response body is capped at 2MB.',
description: 'Send HTTP GET request and return response content. Query params are URL-encoded automatically; Baidu Map Agent Plan auth is injected server-side. Response body is capped at 2MB.',
schema: z.object({
url: z.string().describe('Request URL'),
params: z.record(
z.string(),
z.union([z.string(), z.number(), z.boolean()])
).optional().describe('Query parameters, encoded automatically'),
headers: z.record(z.string(), z.string()).optional().describe('Request headers'),
timeout: z.number().optional().describe('Timeout in milliseconds, clamped to 1s-15s')
})
-84
View File
@@ -1,84 +0,0 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { safeFetch } from "./http_client.js";
const httpPostTool = tool(
async ({ url, body, headers = {}, contentType = 'json', timeout = 15000 }) => {
let requestBody;
const requestHeaders = {
'User-Agent': 'XAgent-Bot/1.0',
...headers
};
switch (contentType) {
case 'json':
requestHeaders['Content-Type'] = 'application/json';
requestBody = typeof body === 'string' ? body : JSON.stringify(body);
break;
case 'form':
requestHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
if (typeof body === 'object') {
requestBody = new URLSearchParams(body).toString();
} else {
requestBody = body;
}
break;
case 'text':
requestHeaders['Content-Type'] = 'text/plain';
requestBody = typeof body === 'string' ? body : JSON.stringify(body);
break;
default:
requestBody = typeof body === 'string' ? body : JSON.stringify(body);
}
try {
// 校验(含 DNS)、超时夹紧、响应体截断统一在 safeFetch 内完成;POST 不跟随重定向
const response = await safeFetch(url, {
method: 'POST',
headers: requestHeaders,
body: requestBody,
timeout
});
const responseContentType = response.headers['content-type'] || '';
let responseBody;
if (responseContentType.includes('application/json')) {
try {
responseBody = JSON.parse(response.text);
} catch (e) {
responseBody = response.text;
}
} else {
responseBody = response.text;
}
return {
success: true,
status: response.status,
statusText: response.statusText,
headers: response.headers,
truncated: response.truncated,
body: responseBody
};
} catch (error) {
if (error.name === 'AbortError') {
return { success: false, error: 'Request timed out' };
}
return { success: false, error: error.message };
}
},
{
name: "http_post",
description: "Send HTTP POST request. Supports JSON and form data. Response body is capped at 2MB.",
schema: z.object({
url: z.string().describe("Request URL"),
body: z.union([z.string(), z.object({})]).describe("Request body, can be string or JSON object"),
headers: z.record(z.string()).optional().describe("Request headers"),
contentType: z.enum(['json', 'form', 'text', 'raw']).optional().describe("Content type, default json"),
timeout: z.number().optional().describe("Timeout in milliseconds, clamped to 1s-15s")
}),
},
);
export { httpPostTool };
+20 -7
View File
@@ -1,6 +1,6 @@
import { TavilySearch } from "@langchain/tavily";
import { tool } from "@langchain/core/tools";
import * as z from "zod"
import { z } from "zod";
import config from "../../../../config.js";
const webSearchTool = tool(
@@ -19,16 +19,29 @@ const webSearchTool = tool(
return await tavilySearch._call({ query });
},
{
name: "internet_search",
description: "Run a web search",
name: "web_search",
description:
"联网搜索公开网页信息,返回摘要与链接。适合查询医院公示、就医政策、停诊/号源公告等时效性信息。",
schema: z.object({
query: z.string().describe("The search query"),
maxResults: z.number().optional().default(5),
query: z.string().describe("搜索关键词或问题"),
maxResults: z
.number()
.int()
.min(1)
.max(10)
.optional()
.default(5)
.describe("返回结果数量(1-10),默认 5"),
topic: z
.enum(["general", "news", "finance"])
.optional()
.default("general"),
includeRawContent: z.boolean().optional().default(false),
.default("general")
.describe("搜索主题,政策/新闻类查询建议用 news"),
includeRawContent: z
.boolean()
.optional()
.default(false)
.describe("是否返回网页原文(内容较长,默认关闭)"),
}),
},
);