调整了agent
This commit is contained in:
@@ -7,17 +7,15 @@ import config from '../../../config.js';
|
|||||||
import logger from '../../../utils/logger.js';
|
import logger from '../../../utils/logger.js';
|
||||||
import { createRestrictedBackend } from "../../infra/restricted_fs_backend.js";
|
import { createRestrictedBackend } from "../../infra/restricted_fs_backend.js";
|
||||||
|
|
||||||
// 密钥由 conf.json 统一提供;百度地图 skill 通过 env_get 读环境变量,此处桥接
|
// 密钥由 conf.json 统一提供;百度地图 token 由 http_get 按域名在服务端注入
|
||||||
process.env.TAVILY_API_KEY ??= config.agent.tavily?.apiKey;
|
process.env.TAVILY_API_KEY ??= config.agent.tavily?.apiKey;
|
||||||
process.env.BAIDU_MAP_AUTH_TOKEN ??= config.agent.baiduMap?.authToken;
|
process.env.BAIDU_MAP_AUTH_TOKEN ??= config.agent.baiduMap?.authToken;
|
||||||
import EscortAdminPrompts from "./prompts.js";
|
import EscortAdminPrompts from "./prompts.js";
|
||||||
import { createPatientRecordSubagent } from "../../subagent/patient_record.js";
|
import { createPatientRecordSubagent } from "../../subagent/patient_record.js";
|
||||||
import { createResearchSubagent } from "../../subagent/research.js";
|
|
||||||
import { createHospitalInfoSubagent } from "../../subagent/hospital_info.js";
|
import { createHospitalInfoSubagent } from "../../subagent/hospital_info.js";
|
||||||
import {
|
import {
|
||||||
getEnvTool, webFetchTool, webSearchTool, getCalendarInfoTool,
|
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
|
||||||
getLunarCalendarInfoTool, getYearHolidaysTool, getYearTermsTool, getLatLngTool,
|
httpGetTool, escortRecordQueryTool, escortRecordSetTool
|
||||||
httpGetTool, httpPostTool, escortRecordQueryTool, escortRecordSetTool
|
|
||||||
} from "../../infra/tools/index.js";
|
} from "../../infra/tools/index.js";
|
||||||
|
|
||||||
export default class EscortAdminAgent {
|
export default class EscortAdminAgent {
|
||||||
@@ -138,11 +136,6 @@ export default class EscortAdminAgent {
|
|||||||
apiKey: config.agent.deepseek.apiKey,
|
apiKey: config.agent.deepseek.apiKey,
|
||||||
temperature: 0.0
|
temperature: 0.0
|
||||||
});
|
});
|
||||||
this.proModel = new ChatDeepSeek({
|
|
||||||
model: config.agent.deepseek.proModel,
|
|
||||||
apiKey: config.agent.deepseek.apiKey,
|
|
||||||
temperature: 0.3
|
|
||||||
});
|
|
||||||
|
|
||||||
return createDeepAgent({
|
return createDeepAgent({
|
||||||
name: "deep-agent",
|
name: "deep-agent",
|
||||||
@@ -150,10 +143,10 @@ export default class EscortAdminAgent {
|
|||||||
systemPrompt: EscortAdminPrompts.buildSystemPrompt(userInfo),
|
systemPrompt: EscortAdminPrompts.buildSystemPrompt(userInfo),
|
||||||
backend,
|
backend,
|
||||||
middleware: [todoListMiddleware()], // deepagents 1.12 起 todo 计划工具改为显式开启,多步记录操作用
|
middleware: [todoListMiddleware()], // deepagents 1.12 起 todo 计划工具改为显式开启,多步记录操作用
|
||||||
tools: [getEnvTool, webFetchTool, webSearchTool, getLatLngTool, httpGetTool, httpPostTool,
|
tools: [webFetchTool, webSearchTool, httpGetTool,
|
||||||
getCalendarInfoTool, getLunarCalendarInfoTool, getYearHolidaysTool, getYearTermsTool,
|
getCalendarInfoTool, getYearHolidaysTool,
|
||||||
escortRecordQueryTool, escortRecordSetTool],
|
escortRecordQueryTool, escortRecordSetTool],
|
||||||
subagents: [createPatientRecordSubagent(this.flashModel), createResearchSubagent(this.proModel), createHospitalInfoSubagent(this.flashModel)]
|
subagents: [createPatientRecordSubagent(this.flashModel), createHospitalInfoSubagent(this.flashModel, { allowWrite: true })]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,16 +9,15 @@ import { ChatDeepSeek } from "@langchain/deepseek";
|
|||||||
import config from '../../../config.js';
|
import config from '../../../config.js';
|
||||||
import logger from '../../../utils/logger.js';
|
import logger from '../../../utils/logger.js';
|
||||||
|
|
||||||
// 密钥由 conf.json 统一提供;百度地图 skill 通过 env_get 读环境变量,此处桥接
|
// 密钥由 conf.json 统一提供;百度地图 token 由 http_get 按域名在服务端注入
|
||||||
process.env.TAVILY_API_KEY ??= config.agent.tavily?.apiKey;
|
process.env.TAVILY_API_KEY ??= config.agent.tavily?.apiKey;
|
||||||
process.env.BAIDU_MAP_AUTH_TOKEN ??= config.agent.baiduMap?.authToken;
|
process.env.BAIDU_MAP_AUTH_TOKEN ??= config.agent.baiduMap?.authToken;
|
||||||
import Prompts from "./prompts.js";
|
import Prompts from "./prompts.js";
|
||||||
import { createRestrictedBackend } from "../../infra/restricted_fs_backend.js";
|
import { createRestrictedBackend } from "../../infra/restricted_fs_backend.js";
|
||||||
import { createHospitalInfoSubagent } from "../../subagent/hospital_info.js";
|
import { createHospitalInfoSubagent } from "../../subagent/hospital_info.js";
|
||||||
import {
|
import {
|
||||||
getEnvTool, webFetchTool, webSearchTool, getCalendarInfoTool,
|
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
|
||||||
getLunarCalendarInfoTool, getYearHolidaysTool, getYearTermsTool, getLatLngTool,
|
httpGetTool, createEscortRecordQueryTool
|
||||||
httpGetTool, httpPostTool, createEscortRecordQueryTool
|
|
||||||
} from "../../infra/tools/index.js";
|
} from "../../infra/tools/index.js";
|
||||||
|
|
||||||
export default class EscortAgent {
|
export default class EscortAgent {
|
||||||
@@ -188,8 +187,8 @@ export default class EscortAgent {
|
|||||||
systemPrompt: Prompts.buildSystemPrompt(userInfo),
|
systemPrompt: Prompts.buildSystemPrompt(userInfo),
|
||||||
memory: ["./agent/bots/bot-escort/AGENTS.md"],
|
memory: ["./agent/bots/bot-escort/AGENTS.md"],
|
||||||
backend,
|
backend,
|
||||||
tools: [getEnvTool, webFetchTool, webSearchTool, getLatLngTool, httpGetTool, httpPostTool,
|
tools: [webFetchTool, webSearchTool, httpGetTool,
|
||||||
getCalendarInfoTool, getLunarCalendarInfoTool, getYearHolidaysTool, getYearTermsTool,
|
getCalendarInfoTool, getYearHolidaysTool,
|
||||||
createEscortRecordQueryTool(userInfo)],
|
createEscortRecordQueryTool(userInfo)],
|
||||||
subagents: [createHospitalInfoSubagent(this.flashModel)],
|
subagents: [createHospitalInfoSubagent(this.flashModel)],
|
||||||
skills: ["./agent/infra/skills/"],
|
skills: ["./agent/infra/skills/"],
|
||||||
|
|||||||
@@ -1,243 +1,88 @@
|
|||||||
---
|
---
|
||||||
name: baidu-ai-map
|
name: baidu-ai-map
|
||||||
description: 为Agent提供地图和位置相关的能力,例如 AI 地点检索(周边信息)、AI 路线规划、地理编码与逆地理编码、天气查询等地图工具。
|
description: 使用百度地图 Agent Plan 直接完成地理任务:语义化地点检索、路线规划、地理编码与逆地理编码、天气查询。用户要的是地点、路线、地址或天气答案时优先使用;不用于生成地图代码、查询官方接口文档或管理百度地图账号。
|
||||||
---
|
---
|
||||||
|
|
||||||
# 百度地图服务 Agent Plan
|
# 百度地图 Agent Plan
|
||||||
|
|
||||||
提供大模型友好调用的地图工具skills/baidu-ai-map/SKILL.md,支持POI搜索、导航、语义化 AI 搜索、语义化 AI 路线规划、地理编码与逆地理编码、天气查询。
|
提供大模型友好调用的地图能力:语义化 AI 地点检索、语义化 AI 路线规划、地理编码与逆地理编码、天气查询。统一使用 `https://api.map.baidu.com/`。
|
||||||
|
|
||||||
## 使用准则
|
## 适用边界
|
||||||
|
|
||||||
### 准则 1:API 端点
|
**适用**:用户想直接知道「附近有什么」「怎么走」「这个坐标是哪」「天气如何」等地理答案。问题简单或复杂都优先使用本 skill。
|
||||||
|
|
||||||
所有能力统一使用:
|
**不适用**:
|
||||||
|
|
||||||
> **Base URL**: `https://api.map.baidu.com/`
|
- 生成 HTML、前端地图代码或服务端调用代码。
|
||||||
|
- 查询百度地图官方接口的参数定义、字段含义、配额和版本说明;以官方文档为准,不要凭本 skill 编造。
|
||||||
|
- 申请 AK、管理账号、配额、样式等账户资源。
|
||||||
|
|
||||||
### 准则 2:SK 凭证安全处理
|
> 本环境不需要 AK,也不要引导用户申请 AK。Agent Plan 使用独立的 SK 凭证。
|
||||||
|
|
||||||
SK(Service Key)是调用所有 API 的必须凭证:
|
## 凭证与鉴权
|
||||||
|
|
||||||
1. 优先读取环境变量 `BAIDU_MAP_AUTH_TOKEN`。
|
1. 服务端已从 `conf.json` 的 `agent.baiduMap.authToken` 注入环境变量 `BAIDU_MAP_AUTH_TOKEN`。
|
||||||
2. 如果为空,提示用户前往 [百度地图 Agent Plan](https://lbs.baidu.com/apiconsole/agentplan) 申请。
|
2. **不要读取、回显或向用户索要 token**。本 skill 不需要读取该变量,鉴权由 `http_get` 在服务端完成。
|
||||||
3. 设置环境变量:
|
3. 使用 `http_get` 请求 `https://api.map.baidu.com/agent_plan/...` 时,工具会自动注入请求头:
|
||||||
|
|
||||||
```bash
|
`Authorization: Bearer <BAIDU_MAP_AUTH_TOKEN>`
|
||||||
export BAIDU_MAP_AUTH_TOKEN="你的SK"
|
|
||||||
|
因此不要在 `headers` 中手写 `Authorization`,也不要把 token 放进 URL、日志或回答。
|
||||||
|
4. 若接口返回 `401` / `403`,说明服务端 token 未配置或已失效:告知用户地图服务暂时不可用;管理员侧检查 `conf.json` 的 `agent.baiduMap.authToken` 或环境变量 `BAIDU_MAP_AUTH_TOKEN`。不要向普通用户展示技术细节,也不要索要明文 token。
|
||||||
|
|
||||||
|
## 调用方式
|
||||||
|
|
||||||
|
统一使用 `http_get` 工具,不要使用 `curl`(本 agent 没有 shell 工具,curl 示例不可执行)。
|
||||||
|
|
||||||
|
```text
|
||||||
|
http_get({
|
||||||
|
url: "https://api.map.baidu.com/agent_plan/v1/place",
|
||||||
|
params: {
|
||||||
|
user_raw_request: "帮我找北京可带宠物的咖啡馆",
|
||||||
|
region: "北京市"
|
||||||
|
}
|
||||||
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
### 准则 3:统一鉴权方式(Header 传入)
|
- `params` 会由工具统一做 URL 编码,中文和特殊字符不需要手工编码。
|
||||||
|
- 不要手工拼接查询字符串;参数一律放在 `params` 对象里。
|
||||||
调用所有 API 时,统一通过 Header 传入:
|
- 鉴权头由工具注入,示例中不需要写 `headers`。
|
||||||
|
|
||||||
- `Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN`
|
|
||||||
|
|
||||||
示例:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl --get "https://api.map.baidu.com/agent_plan/v1/place" \
|
|
||||||
-H "Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN" \
|
|
||||||
--data-urlencode "user_raw_request=帮我找北京可带宠物的咖啡馆" \
|
|
||||||
--data-urlencode "region=北京市"
|
|
||||||
```
|
|
||||||
|
|
||||||
### 准则 4:优先使用http_get工具,避免直接调用curl,curl在window下支持不好
|
|
||||||
|
|
||||||
## 全局参数与行为约束
|
## 全局参数与行为约束
|
||||||
|
|
||||||
1. `user_raw_request` 必须是完整的用户需求,不可压缩为关键词。
|
1. `user_raw_request` 必须是完整的用户需求,不可压缩为关键词。
|
||||||
2. `user_raw_request` 出现“我附近”等非明确地点时,可根据上下文为用户推理为具体地点名称,但不可对坐标进行推理。
|
2. `user_raw_request` 出现“我附近”等非明确地点时,可根据上下文推理为具体地点名称,但不可对坐标进行推理。
|
||||||
3. `user_raw_request` 需保留定语/约束词,例如“评分最高”“最近”“最便宜”“3公里内”。
|
3. `user_raw_request` 需保留定语/约束词,例如“评分最高”“最近”“最便宜”“3公里内”。
|
||||||
4. 不得编造坐标;`center` / `location` / `refer_pois` 仅可来自用户明确提供或可信来源,当无可靠坐标时,必须先向用户澄清或先调用 `geocoding` / `place` 等工具获取。
|
4. 不得编造坐标;`center` / `location` / `refer_pois` 仅可来自用户明确提供或可信来源。无可靠坐标时,必须先向用户澄清,或先调用 `geocoding` / `place` 获取。
|
||||||
5. 统一使用 Header 鉴权:`Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN`。
|
5. 经纬度至少保留小数点后 6 位,坐标类型统一为 `gcj02`。
|
||||||
6. 经纬度至少保留小数点后 6 位。
|
6. 直接解析 `http_get` 返回的 JSON,不使用正则或脚本裁剪响应后猜测字段;短时间内遇到相同或高度相似请求时,优先复用已有结果,避免重复调用。
|
||||||
7. 所有工具返回坐标类型统一为 `gcj02`。
|
7. `direction` 可能返回两类结果:路线结果,或起终点澄清结果。返回澄清结果时,先根据用户需求推理最合理候选;仍无法唯一确定时,引导用户在候选中选择后再继续规划。
|
||||||
8. 禁止使用 grep/sed/awk/jq/python脚本 正则裁剪响应后再推断字段,这会造成百度地图 Agent Plan 巨额的token消耗;短时间内遇到相同或高度相似请求时,应优先基于结果直接推理,避免重复发起请求。
|
8. 医疗陪诊场景只查询完成当前任务所必需的位置信息;回答中不要泄露用户精确住址或坐标。
|
||||||
9. `direction` 可能返回两类结果:路线结果,或起终点澄清结果。当返回起终点澄清结果时,应先根据用户需求推理最合理候选;若仍无法唯一确定,应引导用户在候选中选择后再继续规划。
|
|
||||||
|
|
||||||
## 工具详解
|
## 执行工作流
|
||||||
|
|
||||||
### 1. Place(语义化AI地点检索)
|
1. 根据需求选择 `place`、`direction`、`geocoding`、`reverse_geocoding` 或 `weather`。
|
||||||
|
2. 读取 `agent/infra/skills/baidu-ai-map/references/agent-plan-api.md` 中对应接口的必填参数、约束和示例,不要一次加载无关接口资料。
|
||||||
|
3. 用 `http_get` 发起请求:`url` 指向 `https://api.map.baidu.com/agent_plan/v1/...`,查询参数放在 `params`。
|
||||||
|
4. 解析返回的完整 JSON;`http_get` 返回 `{ success, status, body, truncated, ... }`,业务数据通常在 `body` 中。
|
||||||
|
5. 结果有歧义时,先利用响应候选和用户上下文消歧;仍无法唯一确定再询问用户。
|
||||||
|
6. 参数错误时,重新阅读对应 reference;不要凭记忆补齐字段。
|
||||||
|
|
||||||
#### API
|
## API 索引
|
||||||
|
|
||||||
`GET /agent_plan/v1/place`
|
| 需求 | 接口 | 参考位置 |
|
||||||
|
|---|---|---|
|
||||||
#### 参数输入(给模型)
|
| 语义化地点检索 | `GET /agent_plan/v1/place` | `references/agent-plan-api.md#place` |
|
||||||
|
| 语义化路线规划 | `GET /agent_plan/v1/direction` | `references/agent-plan-api.md#direction` |
|
||||||
Required:
|
| 地址转坐标 | `GET /agent_plan/v1/geocoding` | `references/agent-plan-api.md#geocoding` |
|
||||||
- `user_raw_request`: 用户原始需求,原样完整传入,不可压缩为关键词;保留约束词(如“评分最高”“最近”“3公里内”)
|
| 坐标转地址 | `GET /agent_plan/v1/reverse_geocoding` | `references/agent-plan-api.md#reverse-geocoding` |
|
||||||
- `region`: 城市或区域限制
|
| 天气查询 | `GET /agent_plan/v1/weather` | `references/agent-plan-api.md#weather` |
|
||||||
|
|
||||||
Optional:
|
|
||||||
- `center`: 检索中心点和排序参考点(`lat,lng`,gcj02)
|
|
||||||
- `sort`: `distance` 或 `relevance`(默认 `relevance`)
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
- `sort=distance` 时,`center` 必传
|
|
||||||
- `center` 只能来自用户明确提供或可信来源,禁止推测/编造,可通过 `geocoding` / `place` 等工具获取
|
|
||||||
- 经纬度至少保留小数点后 6 位
|
|
||||||
|
|
||||||
#### 鉴权
|
|
||||||
|
|
||||||
- GET:Header `Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN`
|
|
||||||
|
|
||||||
#### 示例
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 1) 帮我查一下八达岭长城附近的五星级酒店
|
|
||||||
curl --get "https://api.map.baidu.com/agent_plan/v1/place" \
|
|
||||||
-H "Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN" \
|
|
||||||
--data-urlencode "user_raw_request=帮我查一下八达岭长城附近的五星级酒店" \
|
|
||||||
--data-urlencode "region=延庆区" \
|
|
||||||
--data-urlencode "sort=relevance"
|
|
||||||
|
|
||||||
# 2) 离我最近的火锅店(distance 排序)
|
|
||||||
curl --get "https://api.map.baidu.com/agent_plan/v1/place" \
|
|
||||||
-H "Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN" \
|
|
||||||
--data-urlencode "user_raw_request=离我最近的火锅店" \
|
|
||||||
--data-urlencode "region=北京市" \
|
|
||||||
--data-urlencode "center=40.056800,116.308300" \
|
|
||||||
--data-urlencode "sort=distance"
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Direction(语义化AI路线规划)
|
|
||||||
|
|
||||||
#### API
|
|
||||||
|
|
||||||
`GET /agent_plan/v1/direction`
|
|
||||||
|
|
||||||
#### 参数输入
|
|
||||||
|
|
||||||
Required:
|
|
||||||
- `user_raw_request`: 用户原始需求,包含起点和终点;保留路线约束词,需要推理并改写用户原始的交通方式
|
|
||||||
- `location`: 用户当前位置坐标(`lat,lng`,gcj02)
|
|
||||||
|
|
||||||
Optional:
|
|
||||||
- `refer_pois`: 地点精确映射,格式 `地点名称:uid,纬度,经度;地点名称:uid,纬度,经度`
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
- 当前仅支持驾车、步行、骑行、公交路线规划。`user_raw_request` 中出现其他交通方式时,需要改写到这四种交通方式
|
|
||||||
- `location` 当起点有歧义(如同名地标、模糊起点)时,路线规划服务会基于当前位置推理最合理的起点位置
|
|
||||||
- `refer_pois` 默认不传,用于同名地点消歧,仅在 `user_raw_request` 中明确有歧义地点时传入
|
|
||||||
- `refer_pois` / `location` 的经纬度至少保留小数点后 6 位,禁止推测/编造,可通过 `geocoding` / `place` 等工具获取
|
|
||||||
|
|
||||||
#### 鉴权
|
|
||||||
|
|
||||||
- GET:Header `Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN`
|
|
||||||
|
|
||||||
#### 示例
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 1) 帮我规划从故宫到颐和园的驾车路线
|
|
||||||
curl --get "https://api.map.baidu.com/agent_plan/v1/direction" \
|
|
||||||
-H "Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN" \
|
|
||||||
--data-urlencode "user_raw_request=帮我规划从故宫到颐和园的驾车路线" \
|
|
||||||
--data-urlencode "location=39.914590,116.403770"
|
|
||||||
|
|
||||||
# 2) “我家”别名映射
|
|
||||||
curl --get "https://api.map.baidu.com/agent_plan/v1/direction" \
|
|
||||||
-H "Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN" \
|
|
||||||
--data-urlencode "user_raw_request=步行去我家附近最近的中餐厅" \
|
|
||||||
--data-urlencode "location=40.056800,116.308300" \
|
|
||||||
--data-urlencode "refer_pois=我家:fbc88a21464370106e3e1b52,40.092180,116.345310"
|
|
||||||
|
|
||||||
# 2) 交通方式推理改写:从王府井打车去三里屯要多久
|
|
||||||
curl --get "https://api.map.baidu.com/agent_plan/v1/direction" \
|
|
||||||
-H "Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN" \
|
|
||||||
--data-urlencode "user_raw_request=从王府井驾车去三里屯要多久" \
|
|
||||||
--data-urlencode "location=39.914590,116.403770"
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Geocoding(地理编码)
|
|
||||||
|
|
||||||
#### API
|
|
||||||
|
|
||||||
`GET /agent_plan/v1/geocoding`
|
|
||||||
|
|
||||||
#### 参数输入
|
|
||||||
|
|
||||||
Required:
|
|
||||||
- `address`: 要解析的完整地址
|
|
||||||
|
|
||||||
Optional:
|
|
||||||
- `region`: 城市/区域提示(减少歧义)
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
- 地址越完整,解析越稳定
|
|
||||||
|
|
||||||
#### 鉴权
|
|
||||||
|
|
||||||
- GET:Header `Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN`
|
|
||||||
|
|
||||||
#### 示例
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl --get "https://api.map.baidu.com/agent_plan/v1/geocoding" \
|
|
||||||
-H "Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN" \
|
|
||||||
--data-urlencode "address=北京市海淀区上地十街10号百度大厦" \
|
|
||||||
--data-urlencode "region=北京市"
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4. Reverse Geocoding(逆地理编码)
|
|
||||||
|
|
||||||
#### API
|
|
||||||
|
|
||||||
`GET /agent_plan/v1/reverse_geocoding`
|
|
||||||
|
|
||||||
#### 参数输入
|
|
||||||
|
|
||||||
Required:
|
|
||||||
- `location`: `lat,lng` 格式坐标(gcj02)
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
- 经纬度至少保留小数点后 6 位
|
|
||||||
|
|
||||||
#### 鉴权
|
|
||||||
|
|
||||||
- GET:Header `Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN`
|
|
||||||
|
|
||||||
#### 示例
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl --get "https://api.map.baidu.com/agent_plan/v1/reverse_geocoding" \
|
|
||||||
-H "Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN" \
|
|
||||||
--data-urlencode "location=40.056800,116.308300"
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5. Weather(天气查询)
|
|
||||||
|
|
||||||
#### API
|
|
||||||
|
|
||||||
`GET /agent_plan/v1/weather`
|
|
||||||
|
|
||||||
#### 参数输入
|
|
||||||
|
|
||||||
Optional:
|
|
||||||
- `region`: 行政区划名称
|
|
||||||
- `location`: `lat,lng` 格式坐标(gcj02)
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
- `region` 与 `location` 至少传一个
|
|
||||||
- `location` 传入时,经纬度至少保留小数点后 6 位
|
|
||||||
|
|
||||||
#### 鉴权
|
|
||||||
|
|
||||||
- GET:Header `Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN`
|
|
||||||
|
|
||||||
#### 示例
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 1) 按坐标查询天气
|
|
||||||
curl --get "https://api.map.baidu.com/agent_plan/v1/weather" \
|
|
||||||
-H "Authorization: Bearer $BAIDU_MAP_AUTH_TOKEN" \
|
|
||||||
--data-urlencode "location=38.766230,116.432130"
|
|
||||||
```
|
|
||||||
|
|
||||||
## 错误处理
|
## 错误处理
|
||||||
|
|
||||||
1. 如果缺少 token,提示用户执行:
|
- `success: false`:网络、DNS、超时或被出网策略拦截;向用户说明失败原因,不要假装拿到了结果。
|
||||||
申请地址:https://lbs.baidu.com/apiconsole/agentplan
|
- `401` / `403`:服务端未配置或 token 失效;按上文凭证说明排查,不要向用户索要 token。
|
||||||
`export BAIDU_MAP_AUTH_TOKEN="<YOUR_BAIDU_MAP_AUTH_TOKEN>"`
|
- `400`:参数错误;重新阅读对应 reference,检查必填项、`sort=distance` 是否带 `center` 等约束。
|
||||||
2. 如果提示参数错误,重新阅读本Skills查阅如何传参
|
- `429`:触发频控;提示用户稍后重试,不要连续重试。
|
||||||
|
- `5xx`:百度地图服务异常;提示用户稍后重试。
|
||||||
|
- `truncated: true`:响应超过 2MB 被截断;缩小检索范围或改查更具体的接口。
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"ownerId": "kn778b6bf766ym71fdvrc5yvg98319rv",
|
"ownerId": "kn778b6bf766ym71fdvrc5yvg98319rv",
|
||||||
"slug": "baidu-ai-map",
|
"slug": "baidu-ai-map",
|
||||||
"version": "1.0.6",
|
"version": "1.2.0",
|
||||||
"publishedAt": 1776928968682
|
"publishedAt": 1793156191329
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
# Agent Plan API 参考
|
||||||
|
|
||||||
|
所有接口统一使用 `https://api.map.baidu.com`,鉴权由 `http_get` 工具自动注入:
|
||||||
|
|
||||||
|
`Authorization: Bearer <BAIDU_MAP_AUTH_TOKEN>`
|
||||||
|
|
||||||
|
调用时不要把 token 写进 URL、headers 或回答。查询参数放在 `params` 对象中,工具会统一做 URL 编码。
|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
- [Place](#place)
|
||||||
|
- [Direction](#direction)
|
||||||
|
- [Geocoding](#geocoding)
|
||||||
|
- [Reverse Geocoding](#reverse-geocoding)
|
||||||
|
- [Weather](#weather)
|
||||||
|
- [响应与排错](#响应与排错)
|
||||||
|
|
||||||
|
## Place
|
||||||
|
|
||||||
|
`GET /agent_plan/v1/place`
|
||||||
|
|
||||||
|
必填参数:
|
||||||
|
|
||||||
|
- `user_raw_request`:完整保留用户原始需求和约束词,不压缩成关键词。
|
||||||
|
- `region`:城市或区域限制。
|
||||||
|
|
||||||
|
可选参数:
|
||||||
|
|
||||||
|
- `center`:检索中心和排序参考点,格式为 `lat,lng`,坐标系为 `gcj02`。
|
||||||
|
- `sort`:`distance` 或 `relevance`,默认为 `relevance`。
|
||||||
|
|
||||||
|
规则:
|
||||||
|
|
||||||
|
- `sort=distance` 时必须传 `center`。
|
||||||
|
- `center` 必须来自用户或可信接口结果,不得推测;经纬度至少保留 6 位小数。
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http_get({
|
||||||
|
url: "https://api.map.baidu.com/agent_plan/v1/place",
|
||||||
|
params: {
|
||||||
|
user_raw_request: "帮我查一下八达岭长城附近的五星级酒店",
|
||||||
|
region: "延庆区",
|
||||||
|
sort: "relevance"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
按距离排序:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http_get({
|
||||||
|
url: "https://api.map.baidu.com/agent_plan/v1/place",
|
||||||
|
params: {
|
||||||
|
user_raw_request: "离我最近的火锅店",
|
||||||
|
region: "北京市",
|
||||||
|
center: "40.056800,116.308300",
|
||||||
|
sort: "distance"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Direction
|
||||||
|
|
||||||
|
`GET /agent_plan/v1/direction`
|
||||||
|
|
||||||
|
必填参数:
|
||||||
|
|
||||||
|
- `user_raw_request`:包含起终点并保留完整路线约束。接口仅支持驾车、步行、骑行、公交,其他交通方式需改写为其中一种。
|
||||||
|
- `location`:用户当前位置,格式为 `lat,lng`,坐标系为 `gcj02`;用于推理模糊或同名起点。
|
||||||
|
|
||||||
|
可选参数:
|
||||||
|
|
||||||
|
- `refer_pois`:地点精确映射,格式 `地点名称:uid,纬度,经度;地点名称:uid,纬度,经度`。仅在明确存在同名地点或别名消歧时传入。
|
||||||
|
|
||||||
|
规则:
|
||||||
|
|
||||||
|
- `location` 与 `refer_pois` 的坐标必须来自用户或可信接口结果,经纬度至少保留 6 位小数。
|
||||||
|
- 响应可能是路线,也可能是起终点候选;无法根据用户需求唯一消歧时,再请用户选择。
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http_get({
|
||||||
|
url: "https://api.map.baidu.com/agent_plan/v1/direction",
|
||||||
|
params: {
|
||||||
|
user_raw_request: "从故宫驾车到颐和园",
|
||||||
|
location: "39.914590,116.403770"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
别名精确映射:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http_get({
|
||||||
|
url: "https://api.map.baidu.com/agent_plan/v1/direction",
|
||||||
|
params: {
|
||||||
|
user_raw_request: "步行去我家附近最近的中餐厅",
|
||||||
|
location: "40.056800,116.308300",
|
||||||
|
refer_pois: "我家:fbc88a21464370106e3e1b52,40.092180,116.345310"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Geocoding
|
||||||
|
|
||||||
|
`GET /agent_plan/v1/geocoding`
|
||||||
|
|
||||||
|
- 必填 `address`:尽量完整的地址。
|
||||||
|
- 可选 `region`:城市或区域提示,用于减少歧义。
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http_get({
|
||||||
|
url: "https://api.map.baidu.com/agent_plan/v1/geocoding",
|
||||||
|
params: {
|
||||||
|
address: "北京市海淀区上地十街10号百度大厦",
|
||||||
|
region: "北京市"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Reverse Geocoding
|
||||||
|
|
||||||
|
`GET /agent_plan/v1/reverse_geocoding`
|
||||||
|
|
||||||
|
必填 `location`,格式为 `lat,lng`,坐标系为 `gcj02`,经纬度至少保留 6 位小数。
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http_get({
|
||||||
|
url: "https://api.map.baidu.com/agent_plan/v1/reverse_geocoding",
|
||||||
|
params: {
|
||||||
|
location: "40.056800,116.308300"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Weather
|
||||||
|
|
||||||
|
`GET /agent_plan/v1/weather`
|
||||||
|
|
||||||
|
- `region`:行政区划名称。
|
||||||
|
- `location`:`lat,lng` 格式的 gcj02 坐标。
|
||||||
|
|
||||||
|
两者至少传一个。传坐标时,经纬度至少保留 6 位小数。
|
||||||
|
|
||||||
|
按行政区划:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http_get({
|
||||||
|
url: "https://api.map.baidu.com/agent_plan/v1/weather",
|
||||||
|
params: {
|
||||||
|
region: "北京市"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
按坐标:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http_get({
|
||||||
|
url: "https://api.map.baidu.com/agent_plan/v1/weather",
|
||||||
|
params: {
|
||||||
|
location: "38.766230,116.432130"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## 响应与排错
|
||||||
|
|
||||||
|
`http_get` 返回结构:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"status": 200,
|
||||||
|
"body": {},
|
||||||
|
"truncated": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- 业务数据在 `body` 中;`body` 可能是字符串,也可能是已解析的 JSON 对象,按实际类型读取。
|
||||||
|
- `success: false`:网络、DNS、超时或出网策略拦截,查看 `error` 字段并向用户说明。
|
||||||
|
- `401` / `403`:服务端未配置 `BAIDU_MAP_AUTH_TOKEN`,或 token 已失效;告知普通用户地图服务暂不可用,管理员侧检查 `conf.json` 的 `agent.baiduMap.authToken` / 环境变量,不要索要明文 token。
|
||||||
|
- `400`:参数错误;检查必填项、坐标格式、`sort=distance` 是否带 `center`。
|
||||||
|
- `429`:频控;提示用户稍后重试。
|
||||||
|
- `5xx`:百度地图服务异常;提示用户稍后重试。
|
||||||
|
- `truncated: true`:响应超过 2MB 被截断;缩小检索范围或改查更具体的接口。
|
||||||
|
- 不要用正则从响应文本中猜测字段;直接读取 JSON 结构。
|
||||||
@@ -1,42 +1,136 @@
|
|||||||
import { tool } from "langchain"
|
import { tool } from "@langchain/core/tools"
|
||||||
import lunar from "lunar-javascript"
|
import { z } from "zod"
|
||||||
const { Solar, Lunar, HolidayUtil, TermUtil } = lunar
|
import { Solar } from "lunar-javascript"
|
||||||
import { getAccurateTime } from "./utils.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) {
|
||||||
|
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(
|
export const getCalendarInfoTool = tool(
|
||||||
async () => {
|
async ({ date } = {}) => {
|
||||||
try {
|
try {
|
||||||
// 获取准确时间
|
if (date) {
|
||||||
const timeInfo = await getAccurateTime()
|
if (!DATE_PATTERN.test(date)) {
|
||||||
|
return JSON.stringify({ error: "date 格式应为 YYYY-MM-DD" }, null, 2)
|
||||||
// 获取农历信息
|
|
||||||
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(),
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
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) {
|
} catch (error) {
|
||||||
console.error('Error in calendar tool:', error)
|
console.error("Error in calendar tool:", error)
|
||||||
return JSON.stringify({ error: error.message }, null, 2)
|
return JSON.stringify({ error: error.message }, null, 2)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "get_calendar_info",
|
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"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
@@ -3,43 +3,72 @@ import z from "zod";
|
|||||||
import { DBModel } from "../../../../models/index.js";
|
import { DBModel } from "../../../../models/index.js";
|
||||||
import { escapeRegex } from "./utils.js";
|
import { escapeRegex } from "./utils.js";
|
||||||
|
|
||||||
function createEscortRecordQueryTool(userInfo) {
|
const STATUS_VALUES = ["pending", "confirmed", "in_progress", "completed", "cancelled"];
|
||||||
const userId = userInfo?._id;
|
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(
|
return tool(
|
||||||
async ({ patientName, status, page = 1, pageSize = 20 }) => {
|
async ({ patientName, mobile, status, page = 1, pageSize = 20 }) => {
|
||||||
try {
|
try {
|
||||||
const filter = {};
|
if (!userId && !allowMobile) {
|
||||||
|
return { success: false, error: "用户未登录,无法查询陪诊记录" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const filter = { deletedAt: null };
|
||||||
|
|
||||||
if (patientName) {
|
if (patientName) {
|
||||||
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
|
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 按订单归属用户过滤:不能用手机号作为隔离键,
|
if (allowMobile && mobile) {
|
||||||
// 因为手机号可由用户自行修改(改到他人号码即可读到他人订单)
|
filter["patient.mobile"] = mobile;
|
||||||
if (!userId) {
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
error: "用户未登录,无法查询陪诊记录",
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
filter.userId = userId;
|
|
||||||
// 软删除的订单对用户端不可见
|
|
||||||
filter.deletedAt = null;
|
|
||||||
|
|
||||||
if (status) {
|
if (status) {
|
||||||
filter.status = status;
|
filter.status = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 用户端按订单归属过滤;不能用手机号作为隔离键(手机号可由用户自行修改)
|
||||||
|
if (userId) {
|
||||||
|
filter.userId = userId;
|
||||||
|
}
|
||||||
|
|
||||||
const skip = (page - 1) * pageSize;
|
const skip = (page - 1) * pageSize;
|
||||||
|
|
||||||
const records = await DBModel.EscortRecord.find(filter)
|
const [records, total] = await Promise.all([
|
||||||
.sort({ "schedule.date": -1 })
|
DBModel.EscortRecord.find(filter)
|
||||||
.skip(skip)
|
.sort({ "schedule.date": -1 })
|
||||||
.limit(pageSize)
|
.skip(skip)
|
||||||
.lean();
|
.limit(pageSize)
|
||||||
|
.lean(),
|
||||||
const total = await DBModel.EscortRecord.countDocuments(filter);
|
DBModel.EscortRecord.countDocuments(filter),
|
||||||
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
@@ -57,35 +86,19 @@ function createEscortRecordQueryTool(userInfo) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "escort_record_query",
|
name: "escort_record_query",
|
||||||
description:
|
description: allowMobile
|
||||||
"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.",
|
? "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."
|
||||||
schema: z.object({
|
: "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.",
|
||||||
patientName: z
|
schema: z.object(shape),
|
||||||
.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"),
|
|
||||||
}),
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
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,6 +2,7 @@ import { tool } from "@langchain/core/tools";
|
|||||||
import z from "zod";
|
import z from "zod";
|
||||||
import mongoose from "mongoose";
|
import mongoose from "mongoose";
|
||||||
import { DBModel } from "../../../../models/index.js";
|
import { DBModel } from "../../../../models/index.js";
|
||||||
|
import { escapeRegex } from "./utils.js";
|
||||||
|
|
||||||
const healthProfileQueryTool = tool(
|
const healthProfileQueryTool = tool(
|
||||||
async ({ profileId, userId, name, mobile, page = 1, pageSize = 20 }) => {
|
async ({ profileId, userId, name, mobile, page = 1, pageSize = 20 }) => {
|
||||||
@@ -28,8 +29,7 @@ const healthProfileQueryTool = tool(
|
|||||||
}
|
}
|
||||||
if (name) {
|
if (name) {
|
||||||
// 转义正则特殊字符,避免查询报错或 ReDoS;姓名支持中文、全拼、拼音首字母匹配
|
// 转义正则特殊字符,避免查询报错或 ReDoS;姓名支持中文、全拼、拼音首字母匹配
|
||||||
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
const re = { $regex: escapeRegex(name), $options: "i" };
|
||||||
const re = { $regex: escaped, $options: "i" };
|
|
||||||
filter.$or = [{ "profile.name": re }, { "profile.pinyin": re }, { "profile.pinyinFL": re }];
|
filter.$or = [{ "profile.name": re }, { "profile.pinyin": re }, { "profile.pinyinFL": re }];
|
||||||
}
|
}
|
||||||
if (mobile) {
|
if (mobile) {
|
||||||
|
|||||||
@@ -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 };
|
|
||||||
@@ -1,24 +1,22 @@
|
|||||||
import { tool } from "@langchain/core/tools";
|
import { tool } from "@langchain/core/tools";
|
||||||
import z from "zod";
|
import z from "zod";
|
||||||
import { DBModel } from "../../../../models/index.js";
|
import { DBModel } from "../../../../models/index.js";
|
||||||
|
import { escapeRegex } from "./utils.js";
|
||||||
|
|
||||||
const hospitalInfoListTool = tool(
|
const hospitalInfoListTool = tool(
|
||||||
async ({ keyword }) => {
|
async ({ keyword }) => {
|
||||||
try {
|
try {
|
||||||
const filter = {};
|
const filter = {};
|
||||||
if (keyword) {
|
if (keyword) {
|
||||||
const escaped = String(keyword).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
const re = { $regex: escapeRegex(keyword), $options: "i" };
|
||||||
const re = { $regex: escaped, $options: "i" };
|
|
||||||
filter.$or = [{ name: re }, { pinyin: re }, { pinyinFL: re }];
|
filter.$or = [{ name: re }, { pinyin: re }, { pinyinFL: re }];
|
||||||
}
|
}
|
||||||
|
|
||||||
const total = await DBModel.Organization.countDocuments(filter);
|
|
||||||
// 轻量列表:只取 id+名称,用于先定位医院,再按 id 查详情
|
// 轻量列表:只取 id+名称,用于先定位医院,再按 id 查详情
|
||||||
const orgs = await DBModel.Organization.find(filter)
|
const [total, orgs] = await Promise.all([
|
||||||
.sort({ name: 1 })
|
DBModel.Organization.countDocuments(filter),
|
||||||
.limit(1000)
|
DBModel.Organization.find(filter).sort({ name: 1 }).limit(1000).select("name").lean(),
|
||||||
.select("name")
|
]);
|
||||||
.lean();
|
|
||||||
|
|
||||||
return { success: true, total, data: orgs.map((o) => ({ id: o._id, name: o.name })) };
|
return { success: true, total, data: orgs.map((o) => ({ id: o._id, name: o.name })) };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,23 +1,44 @@
|
|||||||
import { tool } from "@langchain/core/tools";
|
import { tool } from "@langchain/core/tools";
|
||||||
import z from "zod";
|
import z from "zod";
|
||||||
|
import mongoose from "mongoose";
|
||||||
import { DBModel } from "../../../../models/index.js";
|
import { DBModel } from "../../../../models/index.js";
|
||||||
|
import { escapeRegex } from "./utils.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 医院信息查询工具
|
||||||
|
*
|
||||||
|
* 两种用法:
|
||||||
|
* - 传 hospitalId:返回该院完整档案(id 可先用 hospital_info_list 获取);
|
||||||
|
* - 传 hospitalName:按名称模糊查询,并可按科室 / 医生名过滤,返回面向上层展示的精简字段。
|
||||||
|
*/
|
||||||
const hospitalInfoQueryTool = tool(
|
const hospitalInfoQueryTool = tool(
|
||||||
async ({ hospitalName, department, doctorName }) => {
|
async ({ hospitalId, hospitalName, department, doctorName }) => {
|
||||||
try {
|
try {
|
||||||
if (!hospitalName) {
|
if (hospitalId) {
|
||||||
return { success: false, error: "hospitalName 不能为空" };
|
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" } };
|
if (!hospitalName) {
|
||||||
const total = await DBModel.Organization.countDocuments(filter);
|
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) {
|
if (total === 0) {
|
||||||
return { success: false, error: `未找到名称包含「${hospitalName}」的机构` };
|
return { success: false, error: `未找到名称包含「${hospitalName}」的机构` };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 医院总量小,一次最多取 10 家,命中过多时由调用方细化名称
|
|
||||||
const orgs = await DBModel.Organization.find(filter).limit(10).lean();
|
|
||||||
|
|
||||||
const data = orgs.map((org) => {
|
const data = orgs.map((org) => {
|
||||||
const fa = org.forAgent ?? {};
|
const fa = org.forAgent ?? {};
|
||||||
let departments = fa.departments ?? [];
|
let departments = fa.departments ?? [];
|
||||||
@@ -51,9 +72,13 @@ const hospitalInfoQueryTool = tool(
|
|||||||
{
|
{
|
||||||
name: "hospital_info_query",
|
name: "hospital_info_query",
|
||||||
description:
|
description:
|
||||||
"查询医院就医信息:医院总览(门诊/挂号/缴费/医保/交通)、科室(位置/电话/就诊提示)、医生(职称/擅长/号别/坐班)、场景指南(初诊/住院/检查须知/老人服务)、照片。按医院名称模糊查询,可按科室、医生名过滤。最多返回 10 家医院信息。",
|
"查询医院就医信息。传 hospitalId 返回该院完整档案;传 hospitalName 按名称模糊查询,可再按科室、医生名过滤,返回医院总览(门诊/挂号/缴费/医保/交通)、科室(位置/电话/就诊提示)、医生(职称/擅长/号别/坐班)、场景指南、照片。最多返回 10 家医院。",
|
||||||
schema: z.object({
|
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("科室名称过滤(如 风湿免疫科、放射科)"),
|
department: z.string().optional().describe("科室名称过滤(如 风湿免疫科、放射科)"),
|
||||||
doctorName: z.string().optional().describe("医生姓名过滤"),
|
doctorName: z.string().optional().describe("医生姓名过滤"),
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { tool } from "@langchain/core/tools";
|
import { tool } from "@langchain/core/tools";
|
||||||
import z from "zod";
|
import z from "zod";
|
||||||
import { DBModel } from "../../../../models/index.js";
|
import { DBModel } from "../../../../models/index.js";
|
||||||
|
import { escapeRegex } from "./utils.js";
|
||||||
|
|
||||||
const hospitalInfoSetTool = tool(
|
const hospitalInfoSetTool = tool(
|
||||||
async ({ hospitalName, section, action, content, guides, entry, entryName, updatedBy }) => {
|
async ({ hospitalName, section, action, content, guides, entry, entryName, updatedBy }) => {
|
||||||
@@ -9,8 +10,10 @@ const hospitalInfoSetTool = tool(
|
|||||||
return { success: false, error: "hospitalName 不能为空" };
|
return { success: false, error: "hospitalName 不能为空" };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 定位医院:名称必须唯一命中
|
// 定位医院:名称必须唯一命中;转义正则元字符,避免非法表达式与 ReDoS
|
||||||
const orgs = await DBModel.Organization.find({ name: { $regex: hospitalName, $options: "i" } }).exec();
|
const orgs = await DBModel.Organization.find({
|
||||||
|
name: { $regex: escapeRegex(hospitalName), $options: "i" },
|
||||||
|
}).exec();
|
||||||
if (orgs.length === 0) {
|
if (orgs.length === 0) {
|
||||||
return { success: false, error: `未找到名称包含「${hospitalName}」的机构,请确认医院名称后重试` };
|
return { success: false, error: `未找到名称包含「${hospitalName}」的机构,请确认医院名称后重试` };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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("城市名称,例如:北京市海淀区")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
)
|
|
||||||
@@ -1,30 +1,19 @@
|
|||||||
// Tool 模块统一导出入口
|
// Tool 模块统一导出入口
|
||||||
// 提供工具基类、注册表和所有工具类的统一导出
|
|
||||||
|
|
||||||
// Web工具 (LangChain format)
|
// Web 工具
|
||||||
export { webFetchTool } from './web/fetch.js';
|
export { webFetchTool } from './web/fetch.js';
|
||||||
export { webSearchTool } from './web/search.js';
|
export { webSearchTool } from './web/search.js';
|
||||||
export { httpGetTool } from './web/http_get.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 { getCalendarInfoTool } from './calendar/calendar_info.js';
|
||||||
export { getLunarCalendarInfoTool } from './calendar/lunar_calendar_info.js';
|
|
||||||
export { getYearHolidaysTool } from './calendar/year_holidays.js';
|
export { getYearHolidaysTool } from './calendar/year_holidays.js';
|
||||||
export { getYearTermsTool } from './calendar/year_terms.js';
|
|
||||||
|
|
||||||
// 地理工具 (LangChain format)
|
// 数据库工具
|
||||||
export { getLatLngTool } from './geo/latlon.js';
|
export { createEscortRecordQueryTool, escortRecordQueryTool } from './db/escort_record_query.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 { escortRecordSetTool } from './db/escort_record_set.js';
|
export { escortRecordSetTool } from './db/escort_record_set.js';
|
||||||
export { healthProfileQueryTool } from './db/health_profile_query.js';
|
export { healthProfileQueryTool } from './db/health_profile_query.js';
|
||||||
export { healthProfileSetTool } from './db/health_profile_set.js';
|
export { healthProfileSetTool } from './db/health_profile_set.js';
|
||||||
export { hospitalInfoListTool } from './db/hospital_info_list.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 { hospitalInfoQueryTool } from './db/hospital_info_query.js';
|
||||||
export { hospitalInfoSetTool } from './db/hospital_info_set.js';
|
export { hospitalInfoSetTool } from './db/hospital_info_set.js';
|
||||||
|
|||||||
@@ -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;
|
|
||||||
@@ -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({})
|
|
||||||
}
|
|
||||||
)
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { TavilyExtract } from "@langchain/tavily";
|
import { TavilyExtract } from "@langchain/tavily";
|
||||||
import { tool } from "@langchain/core/tools";
|
import { tool } from "@langchain/core/tools";
|
||||||
import * as z from "zod"
|
import { z } from "zod";
|
||||||
import config from "../../../../config.js";
|
import config from "../../../../config.js";
|
||||||
|
|
||||||
const webFetchTool = tool(
|
const webFetchTool = tool(
|
||||||
@@ -20,14 +20,13 @@ const webFetchTool = tool(
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "web_fetch",
|
name: "web_fetch",
|
||||||
description: "Run a web fetch",
|
description:
|
||||||
|
"抓取并提取指定网页的正文内容(默认 Markdown),适合阅读医院官网、政策公告、新闻等长文页面。",
|
||||||
schema: z.object({
|
schema: z.object({
|
||||||
extractDepth: z.enum(["basic", "advanced"]).default("basic"),
|
urls: z.array(z.string()).min(1).max(5).describe("要抓取的网页 URL 列表(1-5 个)"),
|
||||||
includeImages: z.boolean().default(false),
|
extractDepth: z.enum(["basic", "advanced"]).default("basic").describe("提取深度:basic 更快,advanced 更完整"),
|
||||||
format: z
|
includeImages: z.boolean().default(false).describe("是否包含图片"),
|
||||||
.enum(["markdown", "json"])
|
format: z.enum(["markdown", "json"]).default("markdown").describe("返回格式"),
|
||||||
.default("markdown"),
|
|
||||||
urls: z.array(z.string().describe("The urls")).default([]),
|
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
/**
|
/**
|
||||||
* Agent 出网 HTTP 客户端:统一承载 SSRF 校验、重定向控制、超时上限与响应体截断。
|
* Agent 出网 HTTP 客户端:统一承载 SSRF 校验、重定向控制、超时上限与响应体截断。
|
||||||
*
|
*
|
||||||
* http_get / http_post 只负责参数整理,真正的安全约束集中在这里,
|
* 目前只有 http_get 使用,安全约束集中在这里,避免工具各自实现一套。
|
||||||
* 避免两个工具各写一套、修了一个漏掉另一个。
|
|
||||||
*
|
*
|
||||||
* 约束:
|
* 约束:
|
||||||
* - 每一跳都重新做同步 + DNS 校验,最多 3 跳(重定向可被用来绕过首次校验);
|
* - 每一跳都重新做同步 + DNS 校验,最多 3 跳(重定向可被用来绕过首次校验);
|
||||||
* - POST 不跟随重定向(303/302 会改写成 GET,语义与安全性都不可控);
|
|
||||||
* - 超时由服务端夹紧到 1s~15s,不接受模型传入的任意大值;
|
* - 超时由服务端夹紧到 1s~15s,不接受模型传入的任意大值;
|
||||||
* - 响应体最多读取 2MB,超出即截断并标记 truncated。
|
* - 响应体最多读取 2MB,超出即截断并标记 truncated。
|
||||||
*/
|
*/
|
||||||
@@ -63,17 +61,14 @@ async function readBodyLimited(response) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 发起受控的 HTTP 请求
|
* 发起受控的 GET 请求
|
||||||
* @param {string} url 目标地址
|
* @param {string} url 目标地址
|
||||||
* @param {Object} options
|
* @param {Object} [options]
|
||||||
* @param {string} [options.method] 请求方法
|
|
||||||
* @param {Object} [options.headers] 请求头
|
* @param {Object} [options.headers] 请求头
|
||||||
* @param {string} [options.body] 请求体
|
|
||||||
* @param {number} [options.timeout] 超时毫秒数(会被夹紧)
|
* @param {number} [options.timeout] 超时毫秒数(会被夹紧)
|
||||||
* @returns {Promise<{status:number,statusText:string,headers:Object,buffer:Buffer,text:string,truncated:boolean,url:string}>}
|
* @returns {Promise<{status:number,statusText:string,headers:Object,buffer:Buffer,text:string,truncated:boolean,url:string}>}
|
||||||
*/
|
*/
|
||||||
async function safeFetch(url, options = {}) {
|
async function safeFetch(url, options = {}) {
|
||||||
const method = (options.method || "GET").toUpperCase();
|
|
||||||
const timeout = clampTimeout(options.timeout);
|
const timeout = clampTimeout(options.timeout);
|
||||||
let currentUrl = url;
|
let currentUrl = url;
|
||||||
|
|
||||||
@@ -87,9 +82,8 @@ async function safeFetch(url, options = {}) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(currentUrl, {
|
const response = await fetch(currentUrl, {
|
||||||
method,
|
method: "GET",
|
||||||
headers: options.headers,
|
headers: options.headers,
|
||||||
body: options.body,
|
|
||||||
redirect: "manual",
|
redirect: "manual",
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
});
|
});
|
||||||
@@ -98,7 +92,6 @@ async function safeFetch(url, options = {}) {
|
|||||||
const location = response.headers.get("location");
|
const location = response.headers.get("location");
|
||||||
await response.body?.cancel().catch(() => {});
|
await response.body?.cancel().catch(() => {});
|
||||||
if (!location) throw new Error(`Redirect without location: ${response.status}`);
|
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();
|
currentUrl = new URL(location, currentUrl).toString();
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,15 +2,66 @@ import { tool } from 'langchain';
|
|||||||
import * as z from 'zod';
|
import * as z from 'zod';
|
||||||
import { safeFetch } from './http_client.js';
|
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(
|
export const httpGetTool = tool(
|
||||||
async ({ url, headers = {}, timeout = 15000 }) => {
|
async ({ url, params, headers = {}, timeout = 15000 }) => {
|
||||||
try {
|
try {
|
||||||
|
const requestUrl = buildRequestUrl(url, params);
|
||||||
// 校验(含 DNS)、重定向控制、超时夹紧、响应体截断统一在 safeFetch 内完成
|
// 校验(含 DNS)、重定向控制、超时夹紧、响应体截断统一在 safeFetch 内完成
|
||||||
const response = await safeFetch(url, {
|
const response = await safeFetch(requestUrl, {
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
headers: {
|
||||||
'User-Agent': 'XAgent-Bot/1.0',
|
'User-Agent': 'XAgent-Bot/1.0',
|
||||||
...headers
|
...applyBaiduAuthorization(requestUrl, headers)
|
||||||
},
|
},
|
||||||
timeout
|
timeout
|
||||||
});
|
});
|
||||||
@@ -48,9 +99,13 @@ export const httpGetTool = tool(
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'http_get',
|
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({
|
schema: z.object({
|
||||||
url: z.string().describe('Request URL'),
|
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'),
|
headers: z.record(z.string(), z.string()).optional().describe('Request headers'),
|
||||||
timeout: z.number().optional().describe('Timeout in milliseconds, clamped to 1s-15s')
|
timeout: z.number().optional().describe('Timeout in milliseconds, clamped to 1s-15s')
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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 };
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { TavilySearch } from "@langchain/tavily";
|
import { TavilySearch } from "@langchain/tavily";
|
||||||
import { tool } from "@langchain/core/tools";
|
import { tool } from "@langchain/core/tools";
|
||||||
import * as z from "zod"
|
import { z } from "zod";
|
||||||
import config from "../../../../config.js";
|
import config from "../../../../config.js";
|
||||||
|
|
||||||
const webSearchTool = tool(
|
const webSearchTool = tool(
|
||||||
@@ -19,16 +19,29 @@ const webSearchTool = tool(
|
|||||||
return await tavilySearch._call({ query });
|
return await tavilySearch._call({ query });
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "internet_search",
|
name: "web_search",
|
||||||
description: "Run a web search",
|
description:
|
||||||
|
"联网搜索公开网页信息,返回摘要与链接。适合查询医院公示、就医政策、停诊/号源公告等时效性信息。",
|
||||||
schema: z.object({
|
schema: z.object({
|
||||||
query: z.string().describe("The search query"),
|
query: z.string().describe("搜索关键词或问题"),
|
||||||
maxResults: z.number().optional().default(5),
|
maxResults: z
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.min(1)
|
||||||
|
.max(10)
|
||||||
|
.optional()
|
||||||
|
.default(5)
|
||||||
|
.describe("返回结果数量(1-10),默认 5"),
|
||||||
topic: z
|
topic: z
|
||||||
.enum(["general", "news", "finance"])
|
.enum(["general", "news", "finance"])
|
||||||
.optional()
|
.optional()
|
||||||
.default("general"),
|
.default("general")
|
||||||
includeRawContent: z.boolean().optional().default(false),
|
.describe("搜索主题,政策/新闻类查询建议用 news"),
|
||||||
|
includeRawContent: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.default(false)
|
||||||
|
.describe("是否返回网页原文(内容较长,默认关闭)"),
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,28 +1,39 @@
|
|||||||
import {
|
import {
|
||||||
hospitalInfoListTool,
|
hospitalInfoListTool,
|
||||||
hospitalInfoGetTool,
|
|
||||||
hospitalInfoQueryTool,
|
hospitalInfoQueryTool,
|
||||||
hospitalInfoSetTool,
|
hospitalInfoSetTool,
|
||||||
} from "../infra/tools/index.js";
|
} from "../infra/tools/index.js";
|
||||||
|
|
||||||
// 医院就医信息查询与维护(医生资料/坐班、科室、看病指南等)
|
// 医院就医信息查询与维护(医生资料/坐班、科室、看病指南等)
|
||||||
export const createHospitalInfoSubagent = (model) => ({
|
|
||||||
name: "hospital-info-subagent",
|
|
||||||
description: "查询和维护医院基本资料及就医信息:医院电话、医生资料、出诊信息、科室位置与电话、看病指南(门诊/挂号/医保/住院/检查须知)等",
|
|
||||||
systemPrompt: `你负责医院就医信息的查询、维护、更新、核验。
|
|
||||||
|
|
||||||
查询:
|
const QUERY_PROMPT = `查询:
|
||||||
- 先用 hospital_info_list 拿到医院(名称、id)列表定位医院,再用 hospital_info_get 按医院 id 获取完整信息。
|
- 先用 hospital_info_list 拿到医院(名称、id)列表定位医院,再用 hospital_info_query 传 hospitalId 获取完整信息。
|
||||||
- 需要按科室、医生名过滤时,可用名称模糊查询,返回精准信息。
|
- 需要按医院名称、科室、医生名过滤时,直接用 hospital_info_query(hospitalName/department/doctorName)。
|
||||||
- 出诊信息等时效性数据必须注明信息更新时间,并提示用户以医院最新公告为准。
|
- 出诊信息等时效性数据必须注明信息更新时间,并提示用户以医院最新公告为准。
|
||||||
- 查不到的信息如实告知,禁止编造。
|
- 查不到的信息如实告知,禁止编造。`;
|
||||||
|
|
||||||
维护:
|
const MAINTAIN_PROMPT = `维护:
|
||||||
- overview:医院级文本全量替换,写入前先查询现有内容,合并整理后整体写入,不得丢失原有信息。
|
- overview:医院级文本全量替换,写入前先查询现有内容,合并整理后整体写入,不得丢失原有信息。
|
||||||
- guides:场景键值对浅合并,新增场景直接传键值对;删除场景将值置为 null。
|
- guides:场景键值对浅合并,新增场景直接传键值对;删除场景将值置为 null。
|
||||||
- photos/departments/doctors:列表按锚点操作,锚点为 照片=url、科室=name、医生=name+department;upsert 新增或整条更新,remove 删除。
|
- photos/departments/doctors:列表按锚点操作,锚点为 照片=url、科室=name、医生=name+department;upsert 新增或整条更新,remove 删除。
|
||||||
- doctors 的 detail 包含职称、擅长方向、号别(普通/专家/特需)、坐班与停诊安排。
|
- doctors 的 detail 包含职称、擅长方向、号别(普通/专家/特需)、坐班与停诊安排。
|
||||||
- 尽量提供 updatedBy 记录操作人。图片只存 URL 链接,不负责图片上传。`,
|
- 尽量提供 updatedBy 记录操作人。图片只存 URL 链接,不负责图片上传。`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Object} model
|
||||||
|
* @param {Object} [options]
|
||||||
|
* @param {boolean} [options.allowWrite] 是否允许维护医院资料。用户端默认只读,避免普通用户改写医院数据。
|
||||||
|
*/
|
||||||
|
export const createHospitalInfoSubagent = (model, { allowWrite = false } = {}) => ({
|
||||||
|
name: "hospital-info-subagent",
|
||||||
|
description: allowWrite
|
||||||
|
? "查询和维护医院基本资料及就医信息:医院电话、医生资料、出诊信息、科室位置与电话、看病指南(门诊/挂号/医保/住院/检查须知)等"
|
||||||
|
: "查询医院基本资料及就医信息:医院电话、医生资料、出诊信息、科室位置与电话、看病指南(门诊/挂号/医保/住院/检查须知)等",
|
||||||
|
systemPrompt: `你负责医院就医信息的查询${allowWrite ? "、维护、更新、核验" : ""}。
|
||||||
|
|
||||||
|
${QUERY_PROMPT}${allowWrite ? `\n\n${MAINTAIN_PROMPT}` : ""}`,
|
||||||
model,
|
model,
|
||||||
tools: [hospitalInfoListTool, hospitalInfoGetTool, hospitalInfoQueryTool, hospitalInfoSetTool],
|
tools: allowWrite
|
||||||
|
? [hospitalInfoListTool, hospitalInfoQueryTool, hospitalInfoSetTool]
|
||||||
|
: [hospitalInfoListTool, hospitalInfoQueryTool],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
import { webFetchTool, webSearchTool } from "../infra/tools/index.js";
|
|
||||||
|
|
||||||
// 陪诊(陪同就医)行业问题研究和解答
|
|
||||||
export const createResearchSubagent = (model) => ({
|
|
||||||
name: "escort-research-subagent",
|
|
||||||
description: "陪诊(陪同就医)行业问题研究和解答",
|
|
||||||
systemPrompt: "你是陪诊(陪同就医)行业政策、发展趋势、行业知识研究和解答专家。",
|
|
||||||
model,
|
|
||||||
tools: [webFetchTool, webSearchTool],
|
|
||||||
});
|
|
||||||
@@ -9,6 +9,10 @@ import {
|
|||||||
isPrivateAddress,
|
isPrivateAddress,
|
||||||
} from "../agent/infra/tools/web/url_guard.js";
|
} from "../agent/infra/tools/web/url_guard.js";
|
||||||
import { clampTimeout } from "../agent/infra/tools/web/http_client.js";
|
import { clampTimeout } from "../agent/infra/tools/web/http_client.js";
|
||||||
|
import {
|
||||||
|
applyBaiduAuthorization,
|
||||||
|
buildRequestUrl,
|
||||||
|
} from "../agent/infra/tools/web/http_get.js";
|
||||||
|
|
||||||
test("订单状态机只允许正向流转", () => {
|
test("订单状态机只允许正向流转", () => {
|
||||||
assert.equal(canTransition("pending", "confirmed"), true);
|
assert.equal(canTransition("pending", "confirmed"), true);
|
||||||
@@ -73,6 +77,71 @@ test("出网超时被夹紧在 1s-15s", () => {
|
|||||||
assert.equal(clampTimeout(5000), 5000);
|
assert.equal(clampTimeout(5000), 5000);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("http_get 查询参数统一编码", () => {
|
||||||
|
const url = buildRequestUrl("https://api.map.baidu.com/agent_plan/v1/place", {
|
||||||
|
user_raw_request: "附近 火锅",
|
||||||
|
region: "北京市",
|
||||||
|
sort: "distance",
|
||||||
|
empty: undefined,
|
||||||
|
});
|
||||||
|
const parsed = new URL(url);
|
||||||
|
assert.equal(parsed.searchParams.get("user_raw_request"), "附近 火锅");
|
||||||
|
assert.equal(parsed.searchParams.get("region"), "北京市");
|
||||||
|
assert.equal(parsed.searchParams.get("sort"), "distance");
|
||||||
|
assert.equal(parsed.searchParams.has("empty"), false);
|
||||||
|
assert.equal(
|
||||||
|
buildRequestUrl("https://api.map.baidu.com/agent_plan/v1/place"),
|
||||||
|
"https://api.map.baidu.com/agent_plan/v1/place"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("百度地图请求自动注入鉴权且不影响其他域名", () => {
|
||||||
|
const previous = process.env.BAIDU_MAP_AUTH_TOKEN;
|
||||||
|
process.env.BAIDU_MAP_AUTH_TOKEN = "test-token";
|
||||||
|
try {
|
||||||
|
const injected = applyBaiduAuthorization(
|
||||||
|
"https://api.map.baidu.com/agent_plan/v1/place",
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
assert.equal(injected.Authorization, "Bearer test-token");
|
||||||
|
|
||||||
|
// 兼容旧 skill 的占位符写法,同时不覆盖调用方显式传入的真实值
|
||||||
|
const placeholder = applyBaiduAuthorization(
|
||||||
|
"https://api.map.baidu.com/agent_plan/v1/direction",
|
||||||
|
{ authorization: "Bearer $BAIDU_MAP_AUTH_TOKEN" }
|
||||||
|
);
|
||||||
|
assert.equal(placeholder.authorization, "Bearer test-token");
|
||||||
|
|
||||||
|
const explicit = applyBaiduAuthorization(
|
||||||
|
"https://api.map.baidu.com/agent_plan/v1/weather",
|
||||||
|
{ Authorization: "Bearer explicit" }
|
||||||
|
);
|
||||||
|
assert.equal(explicit.Authorization, "Bearer explicit");
|
||||||
|
|
||||||
|
const otherHost = applyBaiduAuthorization("https://example.com/", {});
|
||||||
|
assert.equal(otherHost.Authorization, undefined);
|
||||||
|
|
||||||
|
const lookalike = applyBaiduAuthorization(
|
||||||
|
"https://api.map.baidu.com.evil.example/",
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
assert.equal(lookalike.Authorization, undefined);
|
||||||
|
|
||||||
|
// 同一个百度域名下的非 Agent Plan 接口不附加 token
|
||||||
|
const otherPath = applyBaiduAuthorization(
|
||||||
|
"https://api.map.baidu.com/place/v2/search",
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
assert.equal(otherPath.Authorization, undefined);
|
||||||
|
} finally {
|
||||||
|
if (previous === undefined) {
|
||||||
|
delete process.env.BAIDU_MAP_AUTH_TOKEN;
|
||||||
|
} else {
|
||||||
|
process.env.BAIDU_MAP_AUTH_TOKEN = previous;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("状态机表覆盖全部订单状态", () => {
|
test("状态机表覆盖全部订单状态", () => {
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
Object.keys(STATUS_TRANSITIONS).sort(),
|
Object.keys(STATUS_TRANSITIONS).sort(),
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
|
||||||
|
import { getCalendarInfoTool } from "../agent/infra/tools/calendar/calendar_info.js";
|
||||||
|
|
||||||
|
test("日历工具查询指定日期并校验非法输入", async () => {
|
||||||
|
const valid = JSON.parse(await getCalendarInfoTool.invoke({ date: "2026-10-28" }));
|
||||||
|
assert.equal(valid.date, "2026-10-28");
|
||||||
|
assert.equal(valid.weekday, "星期三");
|
||||||
|
assert.ok(valid.lunar.includes("二〇二六"));
|
||||||
|
|
||||||
|
const invalidDate = JSON.parse(await getCalendarInfoTool.invoke({ date: "2026-02-30" }));
|
||||||
|
assert.match(invalidDate.error, /无效日期/);
|
||||||
|
|
||||||
|
const badFormat = JSON.parse(await getCalendarInfoTool.invoke({ date: "2026/10/28" }));
|
||||||
|
assert.match(badFormat.error, /YYYY-MM-DD/);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user