Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13981c047b | ||
|
|
02d57f82dc |
@@ -155,9 +155,11 @@ test/media.test.js 元信息白名单、base64 解码、会话生命周期
|
|||||||
- 小程序录音使用 `wx.getRecorderManager()`,`format: 'mp3'`、`sampleRate: 16000`、`numberOfChannels: 1`,
|
- 小程序录音使用 `wx.getRecorderManager()`,`format: 'mp3'`、`sampleRate: 16000`、`numberOfChannels: 1`,
|
||||||
并带 `frameSize`(单位 KB)以触发 `onFrameRecorded`:每帧转 base64 后按 `asr_chunk` 实时上传,
|
并带 `frameSize`(单位 KB)以触发 `onFrameRecorded`:每帧转 base64 后按 `asr_chunk` 实时上传,
|
||||||
点麦克风结束(或满 60 秒)时发 `asr_stop`。
|
点麦克风结束(或满 60 秒)时发 `asr_stop`。
|
||||||
- **两种录音格式都能实时回填**:真机录的是 mp3 分片,服务端按首帧魔数确认为 mp3 后直接透传给供应商;
|
- **两种录音格式都能实时回填**:真机录的是 16k 单声道 MP3(MPEG-2 Layer III),
|
||||||
开发者工具录的是 WebM(Matroska)/Opus(文件名仍是 `.mp3`),服务端用流式解码器同步转成
|
开发者工具录的是 WebM(Matroska)/Opus(文件名仍是 `.mp3`)。供应商自带的解码器对这两种容器
|
||||||
16bit 单声道 PCM(48k 抽取到 16k)后再推给供应商,因此工具里也能逐字出中间结果。
|
都不可靠(真机 mp3 实测直接报 `DecodePost resample audio from 0 to 16000 failed`),
|
||||||
|
因此服务端按首帧魔数识别容器后,统一用流式解码器(WebM/Opus、mp3/mpg123)转成
|
||||||
|
16bit 单声道 PCM(48k 抽取到 16k、16k 原样)再推给供应商,两种环境都能逐字出中间结果。
|
||||||
客户端不再判断容器,分片一律上传;只有服务端明确回 `asr_error`(认不出容器 / 供应商失败)时
|
客户端不再判断容器,分片一律上传;只有服务端明确回 `asr_error`(认不出容器 / 供应商失败)时
|
||||||
才降级为「结束后整段转写」。首帧认不出容器时服务端先缓存至多 16KB 再判,避免误杀只有 cluster 的平台。
|
才降级为「结束后整段转写」。首帧认不出容器时服务端先缓存至多 16KB 再判,避免误杀只有 cluster 的平台。
|
||||||
- 整段识别遇到供应商偶发断流(`asr socket closed` / 建连超时)会自动重试一次(间隔 600ms),
|
- 整段识别遇到供应商偶发断流(`asr socket closed` / 建连超时)会自动重试一次(间隔 600ms),
|
||||||
@@ -166,9 +168,9 @@ test/media.test.js 元信息白名单、base64 解码、会话生命周期
|
|||||||
一次性把几秒 PCM 塞进 socket 会让供应商来不及消费而直接断流。
|
一次性把几秒 PCM 塞进 socket 会让供应商来不及消费而直接断流。
|
||||||
- 实时链路在说话途中失败时客户端不弹错、不中断录音,标记为降级并继续采集;结束时用完整录音文件
|
- 实时链路在说话途中失败时客户端不弹错、不中断录音,标记为降级并继续采集;结束时用完整录音文件
|
||||||
(而不是失败瞬间的半截分片)整段提交 `/health/ai/asr`,只有整段也失败才提示用户。
|
(而不是失败瞬间的半截分片)整段提交 `/health/ai/asr`,只有整段也失败才提示用户。
|
||||||
- 微信开发者工具的录音实际是 WebM(Matroska)/Opus(文件名仍是 `.mp3`,控制台会提示格式与移动端不同)。
|
- 微信开发者工具的录音实际是 WebM(Matroska)/Opus(文件名仍是 `.mp3`,控制台会提示格式与移动端不同);
|
||||||
服务端按文件头识别容器,WebM 会先解码成 16bit 单声道 PCM(48k 抽取到 16k)再交给供应商,
|
真机才是真正的 16k mp3。服务端按文件头识别容器后都先解码成 16bit 单声道 PCM 再交给供应商,
|
||||||
因此工具里也能正常转写;真机录制的 mp3 直接透传。
|
整段兜底的 `/health/ai/asr` 走同一个识别入口,因此两条链路都能正常转写。
|
||||||
- 拍照 / 选图使用 `wx.chooseMedia`,上传前压缩到 1~2MB。图片不走确认面板:选中后立即作为一条用户消息上屏,
|
- 拍照 / 选图使用 `wx.chooseMedia`,上传前压缩到 1~2MB。图片不走确认面板:选中后立即作为一条用户消息上屏,
|
||||||
`/health/ai/ocr` 返回的文本直接落成 AI 回复;图片临时路径不落 storage,重启后历史里只保留 `[图片]` 占位。
|
`/health/ai/ocr` 返回的文本直接落成 AI 回复;图片临时路径不落 storage,重启后历史里只保留 `[图片]` 占位。
|
||||||
- 语音识别结果实时回填输入框;**再次点麦克风结束识别后直接发送**(`asr_final` 定稿或整段兜底成功后
|
- 语音识别结果实时回填输入框;**再次点麦克风结束识别后直接发送**(`asr_final` 定稿或整段兜底成功后
|
||||||
|
|||||||
@@ -13,19 +13,22 @@ class EscortAdminPrompts {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return `
|
return `
|
||||||
# 角色定义
|
# 角色
|
||||||
你是小暖,暖橙陪诊平台的管理助手,直接、高效的解决平台问题。
|
你是小暖,暖橙陪诊平台的管理助手。直接、高效地解决平台问题。
|
||||||
|
|
||||||
# 核心能力
|
# 职责
|
||||||
- 解答服务流程、价格、注意事项
|
1. 服务咨询:依据参考信息解答陪诊流程、价格、注意事项;服务边界/流程/质量类问题遵循国标 GB/T 47801—2026(medical-escort-standard 技能),必要时查阅后回答
|
||||||
- 提供就诊准备建议
|
2. 就诊准备:提供符合医疗规范的就诊准备建议,不提供医疗诊断
|
||||||
- 通过tools和skills,为用户提供其他服务。如:查询天气、路线、查询医院信息、查询医生信息等。
|
3. 工具与技能:通过 tools/skills 查询天气、路线、医院、医生等信息
|
||||||
|
|
||||||
# 铁律(必须遵守)
|
# 铁律
|
||||||
1. 思考和理解任务意图,专业、谨慎、高效、专注的完成任务。
|
1. 服务回答必须基于参考信息,不编造;超出能力范围如实说明。
|
||||||
|
2. 涉及医疗问题,提醒以医生诊断为准。
|
||||||
|
|
||||||
## 参考信息
|
# 参考信息
|
||||||
管理员信息:${userInfo_str};
|
管理员信息:${userInfo_str}
|
||||||
|
服务项目:${JSON.stringify(services)}
|
||||||
|
服务协议:${JSON.stringify(agreement)}
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,29 +30,26 @@ class Prompts {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return `
|
return `
|
||||||
# 角色定义
|
# 角色
|
||||||
你是小橙,为需要就医和陪诊的用户提供咨询和情绪价值。温暖、共情、简洁、专业。
|
你是小橙,陪诊服务平台顾问。温暖、共情、简洁、专业地解答就医陪诊问题,提供情绪价值。
|
||||||
|
|
||||||
# 能力
|
# 职责
|
||||||
- 基于服务项目和服务协议,解答陪诊流程、价格、注意事项
|
1. 服务咨询:依据参考信息解答陪诊流程、价格、注意事项;服务边界/流程/质量类问题遵循国标 GB/T 47801—2026(medical-escort-standard 技能),必要时查阅后回答
|
||||||
- 提供就医规划,就诊准备建议,情绪价值(不提供医疗诊断)
|
2. 就医规划:提供就诊准备建议(需符合医疗规范),不提供医疗诊断
|
||||||
- 就诊准备要专业,符合医疗规范
|
3. 信息查询:调用工具查天气、路线、医院、医生等
|
||||||
- 调用工具查询天气、路线、医院、医生等信息
|
|
||||||
|
|
||||||
# 铁律
|
# 铁律
|
||||||
1. 服务相关回答必须基于参考信息,不编造。
|
1. 服务回答必须基于参考信息,不编造;超出能力范围引导联系客服。
|
||||||
2. 服务边界、服务流程、服务质量类问题,遵循国家标准 GB/T 47801—2026《社会化陪同就医服务 基本要求》(medical-escort-standard 技能),必要时查阅后回答。
|
2. 涉及医疗问题,提醒以医生诊断为准。
|
||||||
3. 感知用户情绪,给予共情回应。
|
3. 语音/图片识别文本可能有错漏,图片内容以【图像识别】/【原文转写】段落为准;涉及数值、单位、药名、日期先与用户确认,不臆测未显示内容。
|
||||||
4. 涉及医疗问题,提醒以医生诊断为准。
|
4. 感知用户情绪并共情回应;保护用户隐私,提示AI内容需甄别。
|
||||||
5. 超出能力范围,引导联系客服。
|
|
||||||
6. 保护用户隐私,提示AI内容需甄别。
|
|
||||||
|
|
||||||
## 参考信息
|
# 参考信息
|
||||||
用户信息:${userInfo_str};
|
用户信息:${userInfo_str}
|
||||||
用户记忆:${usermem_str};
|
用户记忆:${usermem_str}
|
||||||
服务项目:${JSON.stringify(services)};
|
服务项目:${JSON.stringify(services)}
|
||||||
服务协议:${JSON.stringify(agreement)};
|
服务协议:${JSON.stringify(agreement)}
|
||||||
联系电话: 18618162956(微信同号)
|
联系电话:18618162956(微信同号)
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+73
-14
@@ -1,14 +1,16 @@
|
|||||||
/**
|
/**
|
||||||
* 音频容器识别与 WebM 解码
|
* 音频容器识别与解码
|
||||||
*
|
*
|
||||||
* 小程序在真机上按 `format: 'mp3'` 落盘,但开发者工具用浏览器的 MediaRecorder,
|
* 小程序真机按 `format: 'mp3'` 录音,产物是 16k 单声道的 MPEG-2 Layer III;
|
||||||
* 产物是 WebM(Matroska)/Opus,文件名却仍是 `.mp3`。若直接按声明格式转给供应商,
|
* 开发者工具用浏览器的 MediaRecorder,产物是 WebM(Matroska)/Opus,文件名却仍是 `.mp3`。
|
||||||
* DashScope 会报「DecodePost resample audio from 0 to 16000 failed」。
|
* DashScope 自带的解码器对这两种容器都不可靠(mp3 实测报
|
||||||
|
* 「DecodePost resample audio from 0 to 16000 failed」),直接透传会整轮失败。
|
||||||
*
|
*
|
||||||
* 因此这里按文件头识别真实容器:WebM 先解码成 16bit 单声道 PCM 再走识别,
|
* 因此这里按文件头识别真实容器:WebM 与 mp3 都先在服务端解码成 16bit 单声道 PCM
|
||||||
* 其余格式保持原有链路(供应商直接支持 mp3/aac/wav/pcm)。
|
* 再推给供应商,其余格式保持原有链路(供应商直接支持 aac/wav/pcm)。
|
||||||
*/
|
*/
|
||||||
import decodeWebm, { decoder as createWebmDecoder } from '@audio/decode-webm';
|
import decodeWebm, { decoder as createWebmDecoder } from '@audio/decode-webm';
|
||||||
|
import decodeMp3, { decoder as createMp3Decoder } from '@audio/decode-mp3';
|
||||||
|
|
||||||
/** WebM / Matroska 的 EBML 魔数:1A 45 DF A3 */
|
/** WebM / Matroska 的 EBML 魔数:1A 45 DF A3 */
|
||||||
const EBML_MAGIC = 0x1a45dfa3;
|
const EBML_MAGIC = 0x1a45dfa3;
|
||||||
@@ -113,6 +115,25 @@ export async function webmToPcm(audio, decodeImpl = decodeWebm) {
|
|||||||
return { pcm, rate: Number(result.sampleRate) || 48000, samples: pcm.length / 2 };
|
return { pcm, rate: Number(result.sampleRate) || 48000, samples: pcm.length / 2 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MP3 解码为 16bit 单声道 PCM
|
||||||
|
*
|
||||||
|
* 真机录音是 16k 单声道 MPEG-2 Layer III,mpg123 能正常解出音频;
|
||||||
|
* 解码后再按实际采样率(16k 时无需抽取)推给供应商,避开供应商侧的解码失败。
|
||||||
|
*
|
||||||
|
* @param {Buffer|Uint8Array} audio - MP3 原始字节
|
||||||
|
* @param {Function} [decodeImpl] - 测试注入的解码实现
|
||||||
|
* @returns {Promise<{pcm: Buffer, rate: number, samples: number}>}
|
||||||
|
*/
|
||||||
|
export async function mp3ToPcm(audio, decodeImpl = decodeMp3) {
|
||||||
|
const result = await decodeImpl(audio);
|
||||||
|
const channelData = Array.isArray(result?.channelData) ? result.channelData : [];
|
||||||
|
const pcm = channelsToPcm16(channelData);
|
||||||
|
if (!pcm.length) throw new Error('mp3 decoded audio is empty');
|
||||||
|
|
||||||
|
return { pcm, rate: Number(result.sampleRate) || 16000, samples: pcm.length / 2 };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 16bit 单声道 PCM 降采样(整数倍抽取)
|
* 16bit 单声道 PCM 降采样(整数倍抽取)
|
||||||
*
|
*
|
||||||
@@ -143,18 +164,20 @@ export function downsamplePcm16(pcm, fromRate, toRate = 16000) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建 WebM 流式解码器:边收分片边出 16bit 单声道 PCM
|
* 把容器解码器包成统一的「边收分片边出 16bit 单声道 PCM」接口
|
||||||
*
|
*
|
||||||
* 开发者工具的录音是 WebM/Opus,供应商无法直接识别这种容器;
|
* WebM(Opus) 与 MP3 的增量解码接口一致(decode 返回 channelData/sampleRate),
|
||||||
* 整段路径可以等录完再解码,实时链路必须边收边解,才能逐字回填。
|
* 区别只在 WebM 需要 flush 冲尾部、MP3 帧间独立且没有 flush。
|
||||||
* 解码器按 Matroska 结构增量解析,分片边界不必对齐 cluster。
|
|
||||||
*
|
*
|
||||||
* @param {Function} [factory] - 测试注入的解码器工厂
|
* @param {Function} factory - 解码器工厂
|
||||||
|
* @param {Object} [options]
|
||||||
|
* @param {number} [options.defaultRate] - 首帧前使用的默认采样率
|
||||||
|
* @param {boolean} [options.hasFlush] - 是否支持 flush
|
||||||
* @returns {Promise<{rate: number, push: Function, flush: Function, free: Function}>}
|
* @returns {Promise<{rate: number, push: Function, flush: Function, free: Function}>}
|
||||||
*/
|
*/
|
||||||
export async function createStreamingWebmDecoder(factory = createWebmDecoder) {
|
async function wrapStreamingDecoder(factory, { defaultRate = 48000, hasFlush = true } = {}) {
|
||||||
const decoder = await factory();
|
const decoder = await factory();
|
||||||
let rate = 48000;
|
let rate = defaultRate;
|
||||||
|
|
||||||
const toPcm = (audioData) => {
|
const toPcm = (audioData) => {
|
||||||
const sampleRate = Number(audioData?.sampleRate);
|
const sampleRate = Number(audioData?.sampleRate);
|
||||||
@@ -167,13 +190,14 @@ export async function createStreamingWebmDecoder(factory = createWebmDecoder) {
|
|||||||
get rate() {
|
get rate() {
|
||||||
return rate;
|
return rate;
|
||||||
},
|
},
|
||||||
/** 推入一个 WebM 分片,返回该分片解出的 PCM(可能为空) */
|
/** 推入一个容器分片,返回该分片解出的 PCM(可能为空) */
|
||||||
async push(chunk) {
|
async push(chunk) {
|
||||||
// Opus/Vorbis 同步返回,Matroska-only 编码首次加载编码器时是 Promise
|
// Opus/Vorbis 同步返回,Matroska-only 编码首次加载编码器时是 Promise
|
||||||
return toPcm(await decoder.decode(chunk));
|
return toPcm(await decoder.decode(chunk));
|
||||||
},
|
},
|
||||||
/** 收尾,返回剩余 PCM(可能为空) */
|
/** 收尾,返回剩余 PCM(可能为空) */
|
||||||
async flush() {
|
async flush() {
|
||||||
|
if (!hasFlush || typeof decoder.flush !== 'function') return Buffer.alloc(0);
|
||||||
return toPcm(await decoder.flush());
|
return toPcm(await decoder.flush());
|
||||||
},
|
},
|
||||||
free() {
|
free() {
|
||||||
@@ -185,3 +209,38 @@ export async function createStreamingWebmDecoder(factory = createWebmDecoder) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建 WebM 流式解码器
|
||||||
|
* @param {Function} [factory] - 测试注入的解码器工厂
|
||||||
|
* @returns {Promise<{rate: number, push: Function, flush: Function, free: Function}>}
|
||||||
|
*/
|
||||||
|
export async function createStreamingWebmDecoder(factory = createWebmDecoder) {
|
||||||
|
return wrapStreamingDecoder(factory, { defaultRate: 48000, hasFlush: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建 MP3 流式解码器
|
||||||
|
* @param {Function} [factory] - 测试注入的解码器工厂
|
||||||
|
* @returns {Promise<{rate: number, push: Function, flush: Function, free: Function}>}
|
||||||
|
*/
|
||||||
|
export async function createStreamingMp3Decoder(factory = createMp3Decoder) {
|
||||||
|
return wrapStreamingDecoder(factory, { defaultRate: 16000, hasFlush: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 需要服务端解码的容器(其余格式仍直接交给供应商) */
|
||||||
|
const STREAMING_DECODERS = {
|
||||||
|
webm: createStreamingWebmDecoder,
|
||||||
|
mp3: createStreamingMp3Decoder
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按容器创建流式解码器
|
||||||
|
* @param {'webm'|'mp3'} format - sniffAudioFormat 的结果
|
||||||
|
* @returns {Promise<{rate: number, push: Function, flush: Function, free: Function}>}
|
||||||
|
*/
|
||||||
|
export async function createStreamingAudioDecoder(format) {
|
||||||
|
const factory = STREAMING_DECODERS[format];
|
||||||
|
if (!factory) throw new Error(`unsupported streaming audio format: ${format}`);
|
||||||
|
return factory();
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
import config from '../../../config.js';
|
import config from '../../../config.js';
|
||||||
import logger from '../../../utils/logger.js';
|
import logger from '../../../utils/logger.js';
|
||||||
import { createRecognizer, DEFAULT_AUDIO_FORMAT } from './asr.js';
|
import { createRecognizer, DEFAULT_AUDIO_FORMAT } from './asr.js';
|
||||||
import { sniffAudioFormat, webmToPcm, downsamplePcm16 } from './audio.js';
|
import { sniffAudioFormat, webmToPcm, mp3ToPcm, downsamplePcm16 } from './audio.js';
|
||||||
import { createOcrSession, DEFAULT_IMAGE_FORMAT } from './ocr.js';
|
import { createOcrSession, DEFAULT_IMAGE_FORMAT } from './ocr.js';
|
||||||
|
|
||||||
/** conf.json 的 agent.media 段(缺失时用内置默认值) */
|
/** conf.json 的 agent.media 段(缺失时用内置默认值) */
|
||||||
@@ -232,13 +232,14 @@ async function pushChunks(session, chunks) {
|
|||||||
export async function recognizeAudio(audio, meta = {}) {
|
export async function recognizeAudio(audio, meta = {}) {
|
||||||
const cfg = MEDIA_CONFIG.asr ?? {};
|
const cfg = MEDIA_CONFIG.asr ?? {};
|
||||||
|
|
||||||
// 开发者工具的录音实际是 WebM/Opus(扩展名仍是 .mp3,见 audio.js)。
|
// 两条录音链路的容器供应商都解不了(开发者工具是 WebM/Opus,真机是 16k MP3,
|
||||||
// 供应商按声明格式解析会直接报解码失败,这里按文件头识别后先转成 PCM。
|
// 实测都会报 DecodePost 解码失败,见 audio.js),这里按文件头识别后统一转成 PCM。
|
||||||
let input = audio;
|
let input = audio;
|
||||||
let inputMeta = meta;
|
let inputMeta = meta;
|
||||||
if (sniffAudioFormat(audio) === 'webm') {
|
const container = sniffAudioFormat(audio);
|
||||||
|
if (container === 'webm' || container === 'mp3') {
|
||||||
try {
|
try {
|
||||||
const decoded = await webmToPcm(audio);
|
const decoded = container === 'webm' ? await webmToPcm(audio) : await mp3ToPcm(audio);
|
||||||
// 实时协议对裸 PCM 只稳定支持 16k:48k 先整数倍抽取,与实时链路保持一致
|
// 实时协议对裸 PCM 只稳定支持 16k:48k 先整数倍抽取,与实时链路保持一致
|
||||||
const rate = Number.isInteger(decoded.rate / 16000) && decoded.rate > 16000 ? 16000 : decoded.rate;
|
const rate = Number.isInteger(decoded.rate / 16000) && decoded.rate > 16000 ? 16000 : decoded.rate;
|
||||||
input = rate === decoded.rate ? decoded.pcm : downsamplePcm16(decoded.pcm, decoded.rate, rate);
|
input = rate === decoded.rate ? decoded.pcm : downsamplePcm16(decoded.pcm, decoded.rate, rate);
|
||||||
@@ -250,8 +251,9 @@ export async function recognizeAudio(audio, meta = {}) {
|
|||||||
rate,
|
rate,
|
||||||
channels: 1
|
channels: 1
|
||||||
};
|
};
|
||||||
logger.info('webm audio decoded for asr', {
|
logger.info('audio container decoded for asr', {
|
||||||
requestId: meta.requestId || '',
|
requestId: meta.requestId || '',
|
||||||
|
container,
|
||||||
bytes: audio.length,
|
bytes: audio.length,
|
||||||
sourceRate: decoded.rate,
|
sourceRate: decoded.rate,
|
||||||
pcmBytes: input.length,
|
pcmBytes: input.length,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: baidu-ai-map
|
name: baidu-ai-map
|
||||||
description: 使用百度地图 Agent Plan 直接完成地理任务:语义化地点检索、路线规划、地理编码与逆地理编码、天气查询。用户要的是地点、路线、地址或天气答案时优先使用;不用于生成地图代码、查询官方接口文档或管理百度地图账号。
|
description: 使用百度地图 Agent Plan 直接完成地理任务:语义化地点检索、路线规划(含途经点/沿途搜索)、地理编码与逆地理编码、天气查询、地图展示链接生成。用户要的是地点、路线、地址或天气答案时优先使用;不用于生成地图代码、查询官方接口文档或管理百度地图账号。
|
||||||
---
|
---
|
||||||
|
|
||||||
# 百度地图 Agent Plan
|
# 百度地图 Agent Plan
|
||||||
@@ -56,12 +56,13 @@ http_get({
|
|||||||
4. 不得编造坐标;`center` / `location` / `refer_pois` 仅可来自用户明确提供或可信来源。无可靠坐标时,必须先向用户澄清,或先调用 `geocoding` / `place` 获取。
|
4. 不得编造坐标;`center` / `location` / `refer_pois` 仅可来自用户明确提供或可信来源。无可靠坐标时,必须先向用户澄清,或先调用 `geocoding` / `place` 获取。
|
||||||
5. 经纬度至少保留小数点后 6 位,坐标类型统一为 `gcj02`。
|
5. 经纬度至少保留小数点后 6 位,坐标类型统一为 `gcj02`。
|
||||||
6. 直接解析 `http_get` 返回的 JSON,不使用正则或脚本裁剪响应后猜测字段;短时间内遇到相同或高度相似请求时,优先复用已有结果,避免重复调用。
|
6. 直接解析 `http_get` 返回的 JSON,不使用正则或脚本裁剪响应后猜测字段;短时间内遇到相同或高度相似请求时,优先复用已有结果,避免重复调用。
|
||||||
7. `direction` 可能返回两类结果:路线结果,或起终点澄清结果。返回澄清结果时,先根据用户需求推理最合理候选;仍无法唯一确定时,引导用户在候选中选择后再继续规划。
|
7. `direction` 通过 `answer_type` 区分结果:`gptmodel_navigate` 为路线结果;`gptmodel_poi_clarify` / `gptmodel_onway_search_clarify` 为澄清结果。返回澄清结果时,先根据用户需求推理最合理候选;仍无法唯一确定时,引导用户在候选中选择。用户选择后重新规划时,必须同时改写 `user_raw_request` 明确指定选中 POI,并传入该 POI 的 `refer_pois`。
|
||||||
8. 医疗陪诊场景只查询完成当前任务所必需的位置信息;回答中不要泄露用户精确住址或坐标。
|
8. 用户明确要求"在地图上显示/标出"等可视化意图时,取 `place` / `direction` 响应中的 `resource_key` 生成展示链接回复用户(详见 MapRender);不要尝试打开浏览器。
|
||||||
|
9. 医疗陪诊场景只查询完成当前任务所必需的位置信息;回答中不要泄露用户精确住址或坐标。
|
||||||
|
|
||||||
## 执行工作流
|
## 执行工作流
|
||||||
|
|
||||||
1. 根据需求选择 `place`、`direction`、`geocoding`、`reverse_geocoding` 或 `weather`。
|
1. 根据需求选择 `place`、`direction`、`geocoding`、`reverse_geocoding`、`weather` 或 MapRender(地图展示链接)。
|
||||||
2. 读取 `agent/infra/skills/baidu-ai-map/references/agent-plan-api.md` 中对应接口的必填参数、约束和示例,不要一次加载无关接口资料。
|
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`。
|
3. 用 `http_get` 发起请求:`url` 指向 `https://api.map.baidu.com/agent_plan/v1/...`,查询参数放在 `params`。
|
||||||
4. 解析返回的完整 JSON;`http_get` 返回 `{ success, status, body, truncated, ... }`,业务数据通常在 `body` 中。
|
4. 解析返回的完整 JSON;`http_get` 返回 `{ success, status, body, truncated, ... }`,业务数据通常在 `body` 中。
|
||||||
@@ -73,10 +74,11 @@ http_get({
|
|||||||
| 需求 | 接口 | 参考位置 |
|
| 需求 | 接口 | 参考位置 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 语义化地点检索 | `GET /agent_plan/v1/place` | `references/agent-plan-api.md#place` |
|
| 语义化地点检索 | `GET /agent_plan/v1/place` | `references/agent-plan-api.md#place` |
|
||||||
| 语义化路线规划 | `GET /agent_plan/v1/direction` | `references/agent-plan-api.md#direction` |
|
| 语义化路线规划(含沿途搜索) | `GET /agent_plan/v1/direction` | `references/agent-plan-api.md#direction` |
|
||||||
| 地址转坐标 | `GET /agent_plan/v1/geocoding` | `references/agent-plan-api.md#geocoding` |
|
| 地址转坐标 | `GET /agent_plan/v1/geocoding` | `references/agent-plan-api.md#geocoding` |
|
||||||
| 坐标转地址 | `GET /agent_plan/v1/reverse_geocoding` | `references/agent-plan-api.md#reverse-geocoding` |
|
| 坐标转地址 | `GET /agent_plan/v1/reverse_geocoding` | `references/agent-plan-api.md#reverse-geocoding` |
|
||||||
| 天气查询 | `GET /agent_plan/v1/weather` | `references/agent-plan-api.md#weather` |
|
| 天气查询 | `GET /agent_plan/v1/weather` | `references/agent-plan-api.md#weather` |
|
||||||
|
| 地图展示链接 | 无独立接口,用 place/direction 的 `resource_key` | `references/agent-plan-api.md#maprender地图展示` |
|
||||||
|
|
||||||
## 错误处理
|
## 错误处理
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"ownerId": "kn778b6bf766ym71fdvrc5yvg98319rv",
|
"ownerId": "kn778b6bf766ym71fdvrc5yvg98319rv",
|
||||||
"slug": "baidu-ai-map",
|
"slug": "baidu-ai-map",
|
||||||
"version": "1.2.0",
|
"version": "1.3.0",
|
||||||
"publishedAt": 1793156191329
|
"publishedAt": 1793156191329
|
||||||
}
|
}
|
||||||
@@ -13,6 +13,7 @@
|
|||||||
- [Geocoding](#geocoding)
|
- [Geocoding](#geocoding)
|
||||||
- [Reverse Geocoding](#reverse-geocoding)
|
- [Reverse Geocoding](#reverse-geocoding)
|
||||||
- [Weather](#weather)
|
- [Weather](#weather)
|
||||||
|
- [MapRender](#maprender地图展示)
|
||||||
- [响应与排错](#响应与排错)
|
- [响应与排错](#响应与排错)
|
||||||
|
|
||||||
## Place
|
## Place
|
||||||
@@ -67,17 +68,22 @@ http_get({
|
|||||||
|
|
||||||
必填参数:
|
必填参数:
|
||||||
|
|
||||||
- `user_raw_request`:包含起终点并保留完整路线约束。接口仅支持驾车、步行、骑行、公交,其他交通方式需改写为其中一种。
|
- `user_raw_request`:用户原始需求,包含起点、终点、途经点;支持沿途搜索 POI(如"路上买杯咖啡");保留路线约束词。出现驾车/步行/骑行/公交以外的交通方式(如打车、坐地铁)时,需推理改写为这四种之一(如"打车"改写为"驾车")。
|
||||||
- `location`:用户当前位置,格式为 `lat,lng`,坐标系为 `gcj02`;用于推理模糊或同名起点。
|
- `location`:用户当前位置,格式为 `lat,lng`,坐标系为 `gcj02`;用于推理模糊或同名起点。
|
||||||
|
|
||||||
可选参数:
|
可选参数:
|
||||||
|
|
||||||
- `refer_pois`:地点精确映射,格式 `地点名称:uid,纬度,经度;地点名称:uid,纬度,经度`。仅在明确存在同名地点或别名消歧时传入。
|
- `refer_pois`:地点精确映射,格式 `地点名称:uid,纬度,经度;地点名称:uid,纬度,经度`。默认不传,仅在澄清消歧后重新规划时传入。
|
||||||
|
|
||||||
规则:
|
规则:
|
||||||
|
|
||||||
- `location` 与 `refer_pois` 的坐标必须来自用户或可信接口结果,经纬度至少保留 6 位小数。
|
- `location` 与 `refer_pois` 的坐标必须来自用户或可信接口结果,经纬度至少保留 6 位小数。
|
||||||
- 响应可能是路线,也可能是起终点候选;无法根据用户需求唯一消歧时,再请用户选择。
|
- 响应通过 `answer_type` 区分两类结果:
|
||||||
|
- `gptmodel_navigate`:路线规划结果,直接解析路线方案回答用户。
|
||||||
|
- `gptmodel_poi_clarify` / `gptmodel_onway_search_clarify`:起终点 POI 澄清或沿途搜索 POI 澄清。先根据用户需求推理最合理候选;无法唯一确定时展示候选并请用户选择。
|
||||||
|
- 澄清后重新规划必须同时满足两个条件:
|
||||||
|
1. 改写 `user_raw_request`,明确指定选中的 POI(如"路上买杯咖啡" → "先去星巴克(知春路店)买杯咖啡");
|
||||||
|
2. 传入选中 POI 的 `refer_pois` 精确坐标映射。
|
||||||
|
|
||||||
示例:
|
示例:
|
||||||
|
|
||||||
@@ -104,6 +110,30 @@ http_get({
|
|||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
交通方式推理改写(打车 → 驾车):
|
||||||
|
|
||||||
|
```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: "39.914590,116.403770"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
## Geocoding
|
## Geocoding
|
||||||
|
|
||||||
`GET /agent_plan/v1/geocoding`
|
`GET /agent_plan/v1/geocoding`
|
||||||
@@ -171,6 +201,31 @@ http_get({
|
|||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## MapRender(地图展示)
|
||||||
|
|
||||||
|
在用户明确表达"在地图上显示/标出""打开地图查看""地图里看看"等可视化意图时,基于上一步 `place` / `direction` 响应中的 `resource_key` 字段生成地图展示链接,回复给用户。
|
||||||
|
|
||||||
|
参数:
|
||||||
|
|
||||||
|
- `resource_key`(必填):取自上一步 `place` / `direction` 接口响应中的 `resource_key` 字段。
|
||||||
|
|
||||||
|
规则:
|
||||||
|
|
||||||
|
1. 必须先调用 `place` 或 `direction` 拿到 `resource_key`,才能生成展示链接。
|
||||||
|
2. 展示链接格式:`https://lbs.baidu.com/mapstatic/agentui_resource.html?resource_key=<resource_key>`。
|
||||||
|
3. 本环境没有浏览器/shell 工具,**不要尝试打开浏览器**;直接把链接作为回复内容发给用户,由用户自行点击查看。
|
||||||
|
4. 仅在用户明确表达可视化意图时使用;单纯信息查询("附近有什么""怎么走""多久到")不触发。
|
||||||
|
5. `direction` 返回非 `gptmodel_navigate` 结果(澄清列表)时,不生成展示链接。
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```text
|
||||||
|
# 用户:"帮我找北京可带宠物的咖啡馆,在地图上标出来"
|
||||||
|
# 步骤1: 调用 place 获取 POI 列表和 resource_key
|
||||||
|
# 步骤2: 回复用户结果,并附上链接
|
||||||
|
https://lbs.baidu.com/mapstatic/agentui_resource.html?resource_key=abc123def456
|
||||||
|
```
|
||||||
|
|
||||||
## 响应与排错
|
## 响应与排错
|
||||||
|
|
||||||
`http_get` 返回结构:
|
`http_get` 返回结构:
|
||||||
|
|||||||
@@ -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 { Solar } from "lunar-javascript"
|
import { Solar } from "lunar-javascript"
|
||||||
|
import logger from "../../../../utils/logger.js"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 日历工具
|
* 日历工具
|
||||||
@@ -75,7 +76,7 @@ async function getBeijingNow() {
|
|||||||
success: true
|
success: true
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(`获取网络时间失败,使用本机时间: ${error.message}`)
|
logger.warn(`获取网络时间失败,使用本机时间: ${error.message}`)
|
||||||
const now = new Date()
|
const now = new Date()
|
||||||
return {
|
return {
|
||||||
...getBeijingDateParts(now),
|
...getBeijingDateParts(now),
|
||||||
@@ -118,7 +119,7 @@ export const getCalendarInfoTool = tool(
|
|||||||
const solar = Solar.fromYmd(now.year, now.month, now.day)
|
const solar = Solar.fromYmd(now.year, now.month, now.day)
|
||||||
return JSON.stringify({ now, ...buildDayInfo(solar) }, null, 2)
|
return JSON.stringify({ now, ...buildDayInfo(solar) }, null, 2)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error in calendar tool:", error)
|
logger.error("Error in calendar tool:", error)
|
||||||
return JSON.stringify({ error: error.message }, null, 2)
|
return JSON.stringify({ error: error.message }, null, 2)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { tool } from "langchain"
|
import { tool } from "@langchain/core/tools";
|
||||||
import lunarLib from "lunar-javascript"
|
import { z } from "zod";
|
||||||
|
import lunarLib from "lunar-javascript";
|
||||||
const { Solar, HolidayUtil } = lunarLib
|
const { Solar, HolidayUtil } = lunarLib
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -36,17 +37,8 @@ export const getYearHolidaysTool = tool(
|
|||||||
{
|
{
|
||||||
name: "get_year_holidays",
|
name: "get_year_holidays",
|
||||||
description: "查询给定年份节日所在日期列表,包括法定节假日安排(含调休)与传统节日",
|
description: "查询给定年份节日所在日期列表,包括法定节假日安排(含调休)与传统节日",
|
||||||
schema: {
|
schema: z.object({
|
||||||
type: "object",
|
year: z.number().int().min(1900).max(2100).describe("年份")
|
||||||
properties: {
|
})
|
||||||
year: {
|
|
||||||
type: "number",
|
|
||||||
description: "年份",
|
|
||||||
minimum: 1900,
|
|
||||||
maximum: 2100
|
|
||||||
}
|
|
||||||
},
|
|
||||||
required: ["year"]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
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";
|
import { escapeRegex } from "./utils.js";
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
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 mongoose from "mongoose";
|
||||||
import { DBModel } from "../../../../models/index.js";
|
import { DBModel } from "../../../../models/index.js";
|
||||||
import { canTransition, STATUS_TRANSITIONS } from "../../../../utils/record_state.js";
|
import { canTransition, STATUS_TRANSITIONS } from "../../../../utils/record_state.js";
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
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 mongoose from "mongoose";
|
||||||
import { DBModel } from "../../../../models/index.js";
|
import { DBModel } from "../../../../models/index.js";
|
||||||
import { escapeRegex } from "./utils.js";
|
import { escapeRegex } from "./utils.js";
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
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 mongoose from "mongoose";
|
||||||
import { DBModel } from "../../../../models/index.js";
|
import { DBModel } from "../../../../models/index.js";
|
||||||
import { genPinyin, genPinyinFL } from "../../../../models/schema/health_profile.js";
|
import { genPinyin, genPinyinFL } from "../../../../models/schema/health_profile.js";
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
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";
|
import { escapeRegex } from "./utils.js";
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
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 mongoose from "mongoose";
|
||||||
import { DBModel } from "../../../../models/index.js";
|
import { DBModel } from "../../../../models/index.js";
|
||||||
import { escapeRegex } from "./utils.js";
|
import { escapeRegex } from "./utils.js";
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
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";
|
import { escapeRegex } from "./utils.js";
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
// Tool 模块统一导出入口
|
// Tool 模块统一导出入口
|
||||||
|
|
||||||
// Web 工具
|
// Web 工具
|
||||||
export { webFetchTool } from './web/fetch.js';
|
export { webSearchTool, webFetchTool } from './web/tavily.js';
|
||||||
export { webSearchTool } from './web/search.js';
|
|
||||||
export { httpGetTool } from './web/http_get.js';
|
export { httpGetTool } from './web/http_get.js';
|
||||||
|
|
||||||
// 日历工具
|
// 日历工具
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
import { TavilyExtract } from "@langchain/tavily";
|
|
||||||
import { tool } from "@langchain/core/tools";
|
|
||||||
import { z } from "zod";
|
|
||||||
import config from "../../../../config.js";
|
|
||||||
|
|
||||||
const webFetchTool = tool(
|
|
||||||
async ({
|
|
||||||
extractDepth = "basic",
|
|
||||||
includeImages = false,
|
|
||||||
format = "markdown",
|
|
||||||
urls = [],
|
|
||||||
}) => {
|
|
||||||
const tavilyExtract = new TavilyExtract({
|
|
||||||
tavilyApiKey: config.agent.tavily.apiKey,
|
|
||||||
extractDepth,
|
|
||||||
includeImages,
|
|
||||||
format
|
|
||||||
});
|
|
||||||
return await tavilyExtract._call({ urls });
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "web_fetch",
|
|
||||||
description:
|
|
||||||
"抓取并提取指定网页的正文内容(默认 Markdown),适合阅读医院官网、政策公告、新闻等长文页面。",
|
|
||||||
schema: z.object({
|
|
||||||
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("返回格式"),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
export { webFetchTool };
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { tool } from 'langchain';
|
import { tool } from "@langchain/core/tools";
|
||||||
import * as z from 'zod';
|
import { 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_HOST = 'api.map.baidu.com';
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
import { TavilySearch } from "@langchain/tavily";
|
|
||||||
import { tool } from "@langchain/core/tools";
|
|
||||||
import { z } from "zod";
|
|
||||||
import config from "../../../../config.js";
|
|
||||||
|
|
||||||
const webSearchTool = tool(
|
|
||||||
async ({
|
|
||||||
query,
|
|
||||||
maxResults = 5,
|
|
||||||
topic = "general",
|
|
||||||
includeRawContent = false,
|
|
||||||
}) => {
|
|
||||||
const tavilySearch = new TavilySearch({
|
|
||||||
maxResults,
|
|
||||||
tavilyApiKey: config.agent.tavily.apiKey,
|
|
||||||
includeRawContent,
|
|
||||||
topic,
|
|
||||||
});
|
|
||||||
return await tavilySearch._call({ query });
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "web_search",
|
|
||||||
description:
|
|
||||||
"联网搜索公开网页信息,返回摘要与链接。适合查询医院公示、就医政策、停诊/号源公告等时效性信息。",
|
|
||||||
schema: z.object({
|
|
||||||
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")
|
|
||||||
.describe("搜索主题,政策/新闻类查询建议用 news"),
|
|
||||||
includeRawContent: z
|
|
||||||
.boolean()
|
|
||||||
.optional()
|
|
||||||
.default(false)
|
|
||||||
.describe("是否返回网页原文(内容较长,默认关闭)"),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
export { webSearchTool };
|
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
/**
|
||||||
|
* Tavily 联网工具:搜索 + 网页正文提取。
|
||||||
|
* 两个工具共用同一个 Tavily apiKey,合并在一个文件里便于维护。
|
||||||
|
*/
|
||||||
|
import { TavilySearch, TavilyExtract } from "@langchain/tavily";
|
||||||
|
import { tool } from "@langchain/core/tools";
|
||||||
|
import { z } from "zod";
|
||||||
|
import config from "../../../../config.js";
|
||||||
|
|
||||||
|
const webSearchTool = tool(
|
||||||
|
async ({ query, maxResults = 5, topic = "general", includeRawContent = false }) => {
|
||||||
|
const tavilySearch = new TavilySearch({
|
||||||
|
maxResults,
|
||||||
|
tavilyApiKey: config.agent.tavily.apiKey,
|
||||||
|
includeRawContent,
|
||||||
|
topic,
|
||||||
|
});
|
||||||
|
return await tavilySearch._call({ query });
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "web_search",
|
||||||
|
description:
|
||||||
|
"联网搜索公开网页信息,返回摘要与链接。适合查询医院公示、就医政策、停诊/号源公告等时效性信息。",
|
||||||
|
schema: z.object({
|
||||||
|
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")
|
||||||
|
.describe("搜索主题,政策/新闻类查询建议用 news"),
|
||||||
|
includeRawContent: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.default(false)
|
||||||
|
.describe("是否返回网页原文(内容较长,默认关闭)"),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const webFetchTool = tool(
|
||||||
|
async ({
|
||||||
|
extractDepth = "basic",
|
||||||
|
includeImages = false,
|
||||||
|
format = "markdown",
|
||||||
|
urls = [],
|
||||||
|
}) => {
|
||||||
|
const tavilyExtract = new TavilyExtract({
|
||||||
|
tavilyApiKey: config.agent.tavily.apiKey,
|
||||||
|
extractDepth,
|
||||||
|
includeImages,
|
||||||
|
format
|
||||||
|
});
|
||||||
|
return await tavilyExtract._call({ urls });
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "web_fetch",
|
||||||
|
description:
|
||||||
|
"抓取并提取指定网页的正文内容(默认 Markdown),适合阅读医院官网、政策公告、新闻等长文页面。",
|
||||||
|
schema: z.object({
|
||||||
|
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("返回格式"),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export { webSearchTool, webFetchTool };
|
||||||
@@ -249,8 +249,7 @@ EmployeeSchema.statics.findOnlineAttendants = async function (options = {}) {
|
|||||||
// ==================== 索引定义 ====================
|
// ==================== 索引定义 ====================
|
||||||
|
|
||||||
EmployeeSchema.index({ "profile.name": 1 });
|
EmployeeSchema.index({ "profile.name": 1 });
|
||||||
EmployeeSchema.index({ employeeNo: 1 });
|
// 注意:employeeNo(unique+sparse)与 userId 的索引在字段定义处声明,勿在此重复声明
|
||||||
EmployeeSchema.index({ userId: 1 });
|
|
||||||
EmployeeSchema.index({ orgId: 1, role: 1, status: 1 });
|
EmployeeSchema.index({ orgId: 1, role: 1, status: 1 });
|
||||||
EmployeeSchema.index({ role: 1, status: 1 });
|
EmployeeSchema.index({ role: 1, status: 1 });
|
||||||
EmployeeSchema.index({ "profile.phone": 1 });
|
EmployeeSchema.index({ "profile.phone": 1 });
|
||||||
|
|||||||
@@ -192,8 +192,6 @@ HealthProfileSchema.statics.deleteProfileById = async function (id) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// ==================== 索引定义 ====================
|
// ==================== 索引定义 ====================
|
||||||
|
// 注意:userId(sparse)与 profile.mobile 的索引在字段定义处声明,勿在此重复声明
|
||||||
HealthProfileSchema.index({ userId: 1 }, { sparse: true });
|
|
||||||
HealthProfileSchema.index({ "profile.mobile": 1 });
|
|
||||||
|
|
||||||
export { HealthProfileSchema, genPinyin, genPinyinFL };
|
export { HealthProfileSchema, genPinyin, genPinyinFL };
|
||||||
@@ -196,8 +196,7 @@ OrganizationSchema.statics.updateOrg = async function (id, update) {
|
|||||||
|
|
||||||
// ==================== 索引定义 ====================
|
// ==================== 索引定义 ====================
|
||||||
|
|
||||||
OrganizationSchema.index({ name: 1 });
|
// 注意:name 与 code(unique+sparse)的索引在字段定义处声明,勿在此重复声明
|
||||||
OrganizationSchema.index({ code: 1 });
|
|
||||||
OrganizationSchema.index({ type: 1, status: 1 });
|
OrganizationSchema.index({ type: 1, status: 1 });
|
||||||
OrganizationSchema.index({ "address.city": 1, "address.district": 1 });
|
OrganizationSchema.index({ "address.city": 1, "address.district": 1 });
|
||||||
OrganizationSchema.index({ status: 1 });
|
OrganizationSchema.index({ status: 1 });
|
||||||
|
|||||||
Generated
+1
@@ -8,6 +8,7 @@
|
|||||||
"name": "attendant-api",
|
"name": "attendant-api",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@audio/decode-mp3": "^1.3.1",
|
||||||
"@audio/decode-webm": "^1.6.1",
|
"@audio/decode-webm": "^1.6.1",
|
||||||
"@langchain/anthropic": "^1.5.9",
|
"@langchain/anthropic": "^1.5.9",
|
||||||
"@langchain/core": "^1.2.9",
|
"@langchain/core": "^1.2.9",
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
"test": "node --test test/*.test.js"
|
"test": "node --test test/*.test.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@audio/decode-mp3": "^1.3.1",
|
||||||
"@audio/decode-webm": "^1.6.1",
|
"@audio/decode-webm": "^1.6.1",
|
||||||
"@langchain/anthropic": "^1.5.9",
|
"@langchain/anthropic": "^1.5.9",
|
||||||
"@langchain/core": "^1.2.9",
|
"@langchain/core": "^1.2.9",
|
||||||
|
|||||||
@@ -16,9 +16,12 @@ import {
|
|||||||
MediaInputError,
|
MediaInputError,
|
||||||
} from "../agent/infra/media/index.js";
|
} from "../agent/infra/media/index.js";
|
||||||
import {
|
import {
|
||||||
|
createStreamingAudioDecoder,
|
||||||
|
createStreamingMp3Decoder,
|
||||||
createStreamingWebmDecoder,
|
createStreamingWebmDecoder,
|
||||||
downsamplePcm16,
|
downsamplePcm16,
|
||||||
findEbmlHeader,
|
findEbmlHeader,
|
||||||
|
mp3ToPcm,
|
||||||
sniffAudioFormat,
|
sniffAudioFormat,
|
||||||
webmToPcm,
|
webmToPcm,
|
||||||
} from "../agent/infra/media/audio.js";
|
} from "../agent/infra/media/audio.js";
|
||||||
@@ -120,6 +123,63 @@ test("WebM 流式解码器按分片连续产出 PCM", async () => {
|
|||||||
decoder.free();
|
decoder.free();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("MP3 解码结果下混为 16bit 单声道 PCM", async () => {
|
||||||
|
// mpg123 对单声道也输出左右两路相同的通道数据,下混后仍是原样本
|
||||||
|
const { pcm, rate, samples } = await mp3ToPcm(Buffer.from("mp3"), async () => ({
|
||||||
|
channelData: [
|
||||||
|
new Float32Array([0.5, -0.5]),
|
||||||
|
new Float32Array([0.5, -0.5]),
|
||||||
|
],
|
||||||
|
sampleRate: 16000,
|
||||||
|
}));
|
||||||
|
assert.equal(rate, 16000);
|
||||||
|
assert.equal(samples, 2);
|
||||||
|
assert.equal(pcm.length, 4);
|
||||||
|
assert.equal(pcm.readInt16LE(0), Math.round(0.5 * 32767));
|
||||||
|
assert.equal(pcm.readInt16LE(2), Math.round(-0.5 * 32767));
|
||||||
|
|
||||||
|
await assert.rejects(
|
||||||
|
() => mp3ToPcm(Buffer.from("mp3"), async () => ({ channelData: [] })),
|
||||||
|
/decoded audio is empty/
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("MP3 流式解码器按分片产出 PCM,并以解码器实际采样率为准", async () => {
|
||||||
|
const fakeDecoder = {
|
||||||
|
decode(chunk) {
|
||||||
|
// 不足一帧时 mpg123 返回空通道数据和 0 采样率,不能把 rate 写成 0
|
||||||
|
if (chunk.length < 4) return { channelData: [], sampleRate: 0 };
|
||||||
|
return {
|
||||||
|
channelData: [new Float32Array([0.5]), new Float32Array([0.5])],
|
||||||
|
sampleRate: 16000,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
free() {},
|
||||||
|
};
|
||||||
|
|
||||||
|
const decoder = await createStreamingMp3Decoder(async () => fakeDecoder);
|
||||||
|
assert.equal(decoder.rate, 16000);
|
||||||
|
|
||||||
|
assert.equal((await decoder.push(Buffer.from([1, 2, 3]))).length, 0);
|
||||||
|
assert.equal(decoder.rate, 16000);
|
||||||
|
|
||||||
|
const pcm = await decoder.push(Buffer.from([4, 5, 6, 7]));
|
||||||
|
assert.equal(pcm.length, 2);
|
||||||
|
assert.equal(pcm.readInt16LE(0), Math.round(0.5 * 32767));
|
||||||
|
|
||||||
|
// mp3 没有尾部缓冲,flush 必须是空结果而不是抛错
|
||||||
|
assert.equal((await decoder.flush()).length, 0);
|
||||||
|
decoder.free();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("流式解码器按容器分发,未知容器直接报错", async () => {
|
||||||
|
// 只验证分发入口的契约,避免在单测里加载 WASM 解码器
|
||||||
|
await assert.rejects(
|
||||||
|
() => createStreamingAudioDecoder("aac"),
|
||||||
|
/unsupported streaming audio format/
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test("48k PCM 按整数倍抽取到 16k,非整数倍保持原样", () => {
|
test("48k PCM 按整数倍抽取到 16k,非整数倍保持原样", () => {
|
||||||
const pcm = Buffer.alloc(48 * 2);
|
const pcm = Buffer.alloc(48 * 2);
|
||||||
for (let i = 0; i < 48; i += 1) {
|
for (let i = 0; i < 48; i += 1) {
|
||||||
|
|||||||
+35
-37
@@ -16,7 +16,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
sniffAudioFormat,
|
sniffAudioFormat,
|
||||||
findEbmlHeader,
|
findEbmlHeader,
|
||||||
createStreamingWebmDecoder,
|
createStreamingAudioDecoder,
|
||||||
downsamplePcm16
|
downsamplePcm16
|
||||||
} from "./agent/infra/media/audio.js";
|
} from "./agent/infra/media/audio.js";
|
||||||
|
|
||||||
@@ -352,8 +352,9 @@ export default class WebSocketServerManager {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 供应商会话按首帧确认真实容器后再建:真机是真 mp3,浏览器(开发者工具)是 WebM,
|
// 供应商会话按首帧确认真实容器后再建:真机是 16k mp3,浏览器(开发者工具)是 WebM。
|
||||||
// 后者要先流式解码成 PCM 才能推给供应商,两种编码不能共用一份 run-task 参数
|
// 两种容器供应商都解不了(实测报 DecodePost 解码失败),都要先在服务端流式解成 PCM,
|
||||||
|
// 因此不能把原始分片直接透传,也不能按声明格式共用一份 run-task 参数
|
||||||
const state = {
|
const state = {
|
||||||
id: msg.id || `asr_${Date.now()}`,
|
id: msg.id || `asr_${Date.now()}`,
|
||||||
userId: String(userInfo._id),
|
userId: String(userInfo._id),
|
||||||
@@ -365,7 +366,7 @@ export default class WebSocketServerManager {
|
|||||||
decoder: null,
|
decoder: null,
|
||||||
// 帧头诊断只打一次:确认客户端分片是否带完整容器头
|
// 帧头诊断只打一次:确认客户端分片是否带完整容器头
|
||||||
headLogged: false,
|
headLogged: false,
|
||||||
// 推给供应商的 PCM 采样率(WebM 解码后归一,mp3 链路不用)
|
// 推给供应商的 PCM 采样率(解码后按实际输出归一)
|
||||||
rate: 0,
|
rate: 0,
|
||||||
// 是否已收到过中间结果(仅用于诊断日志)
|
// 是否已收到过中间结果(仅用于诊断日志)
|
||||||
partialSeen: false,
|
partialSeen: false,
|
||||||
@@ -427,10 +428,10 @@ export default class WebSocketServerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 处理一帧音频:首帧先判真实容器,再决定直接推 mp3 还是先流式解码 WebM
|
* 处理一帧音频:首帧先判真实容器,再决定解码方式
|
||||||
*
|
*
|
||||||
* 真机录的是 mp3 分片,容器直接交给供应商;
|
* 真机录的是 16k mp3,开发者工具录的是 WebM/Opus,
|
||||||
* 开发者工具录的是 WebM/Opus,供应商不认这个容器,必须边收边解码成 PCM。
|
* 两种容器供应商都解不了,统一在服务端边收边解码成 PCM 再推。
|
||||||
*/
|
*/
|
||||||
async _consumeAsrChunk(ws, state, buffer) {
|
async _consumeAsrChunk(ws, state, buffer) {
|
||||||
if (ws.asrSession !== state || state.failed) return;
|
if (ws.asrSession !== state || state.failed) return;
|
||||||
@@ -477,27 +478,27 @@ export default class WebSocketServerManager {
|
|||||||
|
|
||||||
state.format = sniffed;
|
state.format = sniffed;
|
||||||
state.pending = [];
|
state.pending = [];
|
||||||
// 排查实时链路时先看这一行:确认服务端认出的真实容器
|
// 排查实时链路时先看这一行:确认服务端认出的真实容器与帧头
|
||||||
logger.info('asr stream format detected', {
|
logger.info('asr stream format detected', {
|
||||||
requestId: state.id,
|
requestId: state.id,
|
||||||
format: sniffed,
|
format: sniffed,
|
||||||
headBytes: head.length
|
headBytes: head.length,
|
||||||
|
firstBytes: head.subarray(0, Math.min(head.length, 16)).toString('hex')
|
||||||
});
|
});
|
||||||
|
|
||||||
if (sniffed === 'webm') {
|
// webm(开发者工具)与 mp3(真机)都先流式解码成 PCM:
|
||||||
try {
|
// 供应商对这两种容器的解码都不可靠,透传会整轮失败
|
||||||
state.decoder = await createStreamingWebmDecoder();
|
try {
|
||||||
} catch (err) {
|
state.decoder = await createStreamingAudioDecoder(sniffed);
|
||||||
console.warn('[ASR] webm decoder init failed:', err?.message ?? err, { requestId: state.id });
|
} catch (err) {
|
||||||
this._failAsrStream(ws, state, '语音识别失败,请稍后重试');
|
console.warn('[ASR] audio decoder init failed:', err?.message ?? err, {
|
||||||
return;
|
requestId: state.id,
|
||||||
}
|
format: sniffed
|
||||||
// 供应商会话等第一段 PCM 解出来再建:采样率以解码器实际输出为准
|
});
|
||||||
await this._pushAsrAudio(ws, state, head);
|
this._failAsrStream(ws, state, '语音识别失败,请稍后重试');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// 供应商会话等第一段 PCM 解出来再建:采样率以解码器实际输出为准
|
||||||
this._createAsrSession(ws, state, { codec: state.meta.codec, rate: state.meta.rate });
|
|
||||||
await this._pushAsrAudio(ws, state, head);
|
await this._pushAsrAudio(ws, state, head);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -505,25 +506,22 @@ export default class WebSocketServerManager {
|
|||||||
await this._pushAsrAudio(ws, state, buffer);
|
await this._pushAsrAudio(ws, state, buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 把一帧音频推给供应商:WebM 先解码成 PCM,mp3 原样推 */
|
/** 把一帧音频推给供应商:容器分片先解码成 PCM,再按 16k 归一推流 */
|
||||||
async _pushAsrAudio(ws, state, buffer) {
|
async _pushAsrAudio(ws, state, buffer) {
|
||||||
if (ws.asrSession !== state || state.failed) return;
|
if (ws.asrSession !== state || state.failed || !state.decoder) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (state.decoder) {
|
const pcm = await state.decoder.push(buffer);
|
||||||
const pcm = await state.decoder.push(buffer);
|
// 首帧往往只有容器头(WebM 的 EBML / mp3 的元信息),解不出音频:
|
||||||
// 首帧往往只有 WebM 头,解不出音频:等第一段 PCM 出来再建供应商会话
|
// 等第一段 PCM 出来再建供应商会话
|
||||||
if (!pcm.length) return;
|
if (!pcm.length) return;
|
||||||
if (!state.session) {
|
if (!state.session) {
|
||||||
// 采样率以首帧解码结果为准:Opus 是 48k,整数倍抽取到 16k
|
// 采样率以首帧解码结果为准:Opus 是 48k,真机 mp3 是 16k
|
||||||
state.rate = resolveAsrRate(state.decoder.rate);
|
state.rate = resolveAsrRate(state.decoder.rate);
|
||||||
this._createAsrSession(ws, state, { codec: 'pcm16', rate: state.rate });
|
this._createAsrSession(ws, state, { codec: 'pcm16', rate: state.rate });
|
||||||
}
|
|
||||||
const out = downsamplePcm16(pcm, state.decoder.rate, state.rate);
|
|
||||||
if (out.length) state.session.push(out);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
if (state.session) state.session.push(buffer);
|
const out = downsamplePcm16(pcm, state.decoder.rate, state.rate);
|
||||||
|
if (out.length) state.session.push(out);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// 解码失败说明这一轮的分片无法拼成完整音频,交给客户端结束后的整段兜底
|
// 解码失败说明这一轮的分片无法拼成完整音频,交给客户端结束后的整段兜底
|
||||||
console.warn('[ASR] audio decode failed:', err?.message ?? err, { requestId: state.id });
|
console.warn('[ASR] audio decode failed:', err?.message ?? err, { requestId: state.id });
|
||||||
@@ -562,7 +560,7 @@ export default class WebSocketServerManager {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// WebM 流式解码:把解码器里剩余的帧冲出来再收尾
|
// 流式解码收尾:把解码器里剩余的音频冲出来再收(mp3 无尾部缓冲,返回空)
|
||||||
if (state.decoder) {
|
if (state.decoder) {
|
||||||
const tail = await state.decoder.flush();
|
const tail = await state.decoder.flush();
|
||||||
if (!state.session && tail.length) {
|
if (!state.session && tail.length) {
|
||||||
|
|||||||
Reference in New Issue
Block a user