语音识别上游参数改为随请求带入,init.sh 不再绑定平台
- mcp_asr 不再从容器 env 读 key/base_url/model,改为逐请求 header (Authorization / X-ASR-Base-Url / X-ASR-Model),容器不存任何平台密钥 - core 的 /api/asr 从 config.yml 的 mcp_servers[asr].headers 取值转发, /status 增加 reason(未接线时前端 console 直接打印原因) - init.sh 只自动启用模型平台与 web_search;image_task / video_task / asr 改为带默认 url 与 header 名的注释模板,删掉 ASR_API_* 输入与 BIGMODEL_KEY 复用 - docker-compose 去掉 mcp_asr 的三个上游 env - 同步 README / AGENTS / app/config.example.yml / mcp 文档
This commit is contained in:
+10
-3
@@ -35,6 +35,10 @@ mcp_servers:
|
||||
# 可选:语音转写(低频,建议 skill 模式,不占每轮工具表)
|
||||
- name: asr
|
||||
url: "http://mcp_asr:3000/mcp"
|
||||
headers:
|
||||
Authorization: Bearer <key> # 免鉴权的自建服务可省
|
||||
X-ASR-Base-Url: "https://<host>/v1"
|
||||
X-ASR-Model: "whisper-1"
|
||||
mode: skill
|
||||
```
|
||||
|
||||
@@ -47,8 +51,11 @@ mcp_servers:
|
||||
`image_task` 用对应上游(智谱或 OpenAI 兼容网关)的 token,上游地址与模型分别由
|
||||
`X-Image-Task-Base-Url` / `X-Image-Task-Model` 指定。所以这两个服务不用配任何密钥。
|
||||
|
||||
`asr` 是例外:输入框那条路(`agent-core` → `POST /transcribe`)不经过 MCP 调用,拿不到 header,
|
||||
所以它自己的上游密钥由容器 env `ASR_API_KEY` 提供(写在根 `.env`,已 gitignore,不挂给其他容器)。
|
||||
`asr` 同理:上游的 key / base_url / model 全部由调用方随请求 header 带入
|
||||
(`Authorization` / `X-ASR-Base-Url` / `X-ASR-Model`,agent 侧配在 `config.yml` 的
|
||||
`mcp_servers[name=asr].headers`)。输入框那条路(`agent-core` → `POST /transcribe`)不经过 MCP 调用,
|
||||
但 core 同样会从那段 `headers` 取值转发过去,所以两边只有一处配置。容器自己不存任何平台密钥,
|
||||
也不预设任何厂商——任何 OpenAI 兼容的 `/audio/transcriptions` 都能用。
|
||||
|
||||
### 调试端口
|
||||
|
||||
@@ -86,7 +93,7 @@ AI 把拿到的 URL 当 image_url 交给 video_task:3000/mcp
|
||||
| `mcp_web_search` | 无 | 服务端无鉴权,**永远不要映射出去**(会被白嫖搜索额度);agent 走内网访问 |
|
||||
| `mcp_image_task` | 无 | token 由调用方自带,暴露后可被拿去消耗你的上游图片额度 |
|
||||
| `mcp_video_task` | 无 | 它需要的公开临时 URL 由 agent 侧集成的工具提供,自己不占端口 |
|
||||
| `mcp_asr` | 无 | `/mcp` 与 `/transcribe` 都无鉴权,只能由 core 经内网调用;它持有上游 ASR 密钥 |
|
||||
| `mcp_asr` | 无 | `/mcp` 与 `/transcribe` 都无鉴权,只能由 core 经内网调用;它不存密钥(上游参数随请求带入) |
|
||||
|
||||
## 单独调试
|
||||
|
||||
|
||||
+40
-14
@@ -6,7 +6,7 @@
|
||||
|---|---|---|
|
||||
| `POST /transcribe` | `agent-core` 的 `/api/asr/transcribe`(H5 输入框) | 普通 HTTP,音频二进制进、`{text}` 出。**不经过模型、不消耗 token、1~3s** |
|
||||
| `POST /mcp` | 模型(MCP 工具 `transcribe_audio`) | 转写任务目录里已有的音频,参数是公网 URL(与 `video_task` 的 `image_url` 同构) |
|
||||
| `GET /health` | compose healthcheck | `{ok, model, configured}` |
|
||||
| `GET /health` | compose healthcheck | `{ok, service}`(无状态服务,不反映上游配置) |
|
||||
|
||||
端口 `3000` **只在 `agent-mcp-net` 内网**,不映射宿主机——本服务自身没有鉴权,暴露即被白嫖。
|
||||
对外唯一入口仍是 `agent-core`(`/api/asr` 走登录态鉴权)。
|
||||
@@ -19,26 +19,43 @@
|
||||
## 部署
|
||||
|
||||
```bash
|
||||
# 1) 配上游密钥(写进仓库根 .env,已 gitignore)
|
||||
# ASR_API_KEY=你的智谱 token
|
||||
# 1) 配上游:写进仓库根 config.yml 的 mcp_servers(与 image_task 同构),容器不存任何密钥
|
||||
# - name: asr
|
||||
# url: "http://mcp_asr:3000/mcp"
|
||||
# headers:
|
||||
# Authorization: Bearer <key> # 免鉴权的自建服务可省
|
||||
# X-ASR-Base-Url: "https://<host>/v1"
|
||||
# X-ASR-Model: "whisper-1"
|
||||
# mode: skill
|
||||
# 2) 起服务
|
||||
|
||||
docker compose up -d --build mcp_asr
|
||||
docker compose restart agent-core # core 要在启动时读到 ASR_URL
|
||||
docker compose restart agent-core # core 要在启动时读到 config.yml 与 ASR_URL
|
||||
curl -s http://127.0.0.1:8090/api/asr/status # {"enabled":true,...}
|
||||
```
|
||||
|
||||
`agent-core` 的环境变量 `ASR_URL`(compose 里固定为 `http://mcp_asr:3000`)是开关:置空即
|
||||
不启用,`/api/asr/*` 回 503,前端不显示麦克风按钮。
|
||||
`agent-core` 的环境变量 `ASR_URL`(compose 里固定为 `http://mcp_asr:3000`)是部署接线;
|
||||
真正的开关是 config.yml 里那段 `asr`:置为 `mode: disable` 或删掉 = 不启用,`/api/asr/*` 回 503,
|
||||
前端不显示麦克风按钮。
|
||||
|
||||
> 从旧版升级:以前上游 key 写在根 `.env` 的 `ASR_API_KEY`(并默认复用 `BIGMODEL_KEY`),
|
||||
> 现在容器不再读它。把原来那三个值搬到 `config.yml` 的 `asr.headers` 即可,`.env` 里那行可以删掉;
|
||||
> 不搬的话语音入口会自动关闭(`GET /api/asr/status` 会返回具体 `reason`)。
|
||||
|
||||
## 上游
|
||||
|
||||
任何 OpenAI 兼容的 `/audio/transcriptions` 都能用;默认智谱:
|
||||
任何 OpenAI 兼容的 `/audio/transcriptions` 都能用。**本服务不保存、也不预设任何平台**:
|
||||
key / base_url / model 全部由调用方随每个请求用 header 带入(与 `image_task` 同构)。
|
||||
|
||||
| 变量 | 默认 |
|
||||
|---|---|
|
||||
| `ASR_API_BASE` | `https://open.bigmodel.cn/api/paas/v4` |
|
||||
| `ASR_API_KEY` | 空(空则 `/transcribe` 回 503) |
|
||||
| `ASR_MODEL` | `glm-asr` |
|
||||
| Header | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| `X-ASR-Base-Url` | 是 | 上游地址,如 `https://<host>/v1`(服务自己拼 `/audio/transcriptions`) |
|
||||
| `X-ASR-Model` | 是 | 模型名,如 `glm-asr` / `whisper-1` |
|
||||
| `Authorization` | 否 | `Bearer <key>`;写成裸 key 也会自动补 `Bearer `;免鉴权的自建服务可省 |
|
||||
|
||||
`agent-core` 从 `config.yml` 的 `mcp_servers[name=asr].headers` 取这三个头,两条入口(`/transcribe`
|
||||
与 `/mcp`)共用同一处配置——所以换平台只改 YAML + 重启 core,不碰 `.env`、不重建镜像。
|
||||
缺 `X-ASR-Base-Url` / `X-ASR-Model` 时回 503,并在错误文案里指出缺哪个。
|
||||
|
||||
常驻内存约 35~40MB,CPU 基本为 0。没有本地模型可选:2 vCPU / 2GB 的机器跑不动能用的
|
||||
whisper(固定 30 秒窗口,`small` 单次要 15~30 秒),需要私有化就把这个容器放到另一台机器,
|
||||
@@ -50,8 +67,11 @@ whisper(固定 30 秒窗口,`small` 单次要 15~30 秒),需要私有化
|
||||
# 任意格式(webm / mp4 / mp3 / wav / ogg / aac / flac),服务端用 ffmpeg 归一化
|
||||
curl -s -X POST http://mcp_asr:3000/transcribe \
|
||||
-H 'Content-Type: audio/webm' \
|
||||
-H 'X-ASR-Base-Url: https://<host>/v1' \
|
||||
-H 'X-ASR-Model: whisper-1' \
|
||||
-H 'Authorization: Bearer <key>' \
|
||||
--data-binary @voice.webm
|
||||
# → {"text":"打开今天的日报","ms":842,"model":"glm-asr"}
|
||||
# → {"text":"打开今天的日报","ms":842,"model":"whisper-1"}
|
||||
```
|
||||
|
||||
- 上限 20MB;超过 `ASR_MAX_CHUNK_SEC`(默认 25s)的音频自动切片后逐段识别再拼接
|
||||
@@ -65,6 +85,10 @@ curl -s -X POST http://mcp_asr:3000/transcribe \
|
||||
mcp_servers:
|
||||
- name: asr
|
||||
url: "http://mcp_asr:3000/mcp"
|
||||
headers: # 上游参数随请求带入,同「上游」一节
|
||||
X-ASR-Base-Url: "https://<host>/v1"
|
||||
X-ASR-Model: "whisper-1"
|
||||
Authorization: Bearer <key>
|
||||
mode: skill # 低频能力,别每轮都发 schema
|
||||
```
|
||||
|
||||
@@ -75,11 +99,13 @@ mcp_servers:
|
||||
|
||||
| 变量 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `ASR_API_BASE` / `ASR_API_KEY` / `ASR_MODEL` | 见上 | 上游语音识别 |
|
||||
| `ASR_MAX_BYTES` | 20971520 | 单次上传上限 |
|
||||
| `ASR_MAX_CHUNK_SEC` | `25` | 超长音频切片长度,`0` = 不切 |
|
||||
| `ASR_MAX_CONCURRENT` | `2` | 并发转写数 |
|
||||
| `ASR_LOG_LEVEL` | `info` | debug / info / warn / error / none |
|
||||
| `FFMPEG_BIN` | `ffmpeg` | 归一化工具路径 |
|
||||
|
||||
上游参数(key / base_url / model)**不是环境变量**,见上面「上游」一节。
|
||||
|
||||
## 客户端怎么录音
|
||||
|
||||
|
||||
+51
-27
@@ -14,7 +14,8 @@
|
||||
// tools/call 三种请求,手写这几十行 JSON-RPC 就够;本机内存只有 2G,省掉 SDK 与 express
|
||||
// 的常驻开销(本服务空载约 35MB)。
|
||||
//
|
||||
// 转写走上游的 OpenAI 兼容 /audio/transcriptions(默认智谱 glm-asr,换平台改 env 即可)。
|
||||
// 转写走上游的 OpenAI 兼容 /audio/transcriptions(任何平台都行)。上游三要素——key、base_url、
|
||||
// model——一律由调用方随请求 header 带入,本容器不存任何平台密钥、也不认任何平台默认值。
|
||||
// 音频一律先经 ffmpeg 归一化成 16kHz 单声道 wav:WebView 录出来是 webm/opus,iOS 是 mp4/aac,
|
||||
// 上游只认 wav/mp3,归一化后两端都自由。
|
||||
|
||||
@@ -25,13 +26,18 @@ import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
// ── 配置(全部走 env,不读 config.yml:本容器按仓库惯例只拿 env) ──────────────
|
||||
// ── 配置 ──────────────────────────────────────────────────────────────────
|
||||
const PORT = Number(process.env.PORT || 3000);
|
||||
|
||||
// 上游:任何 OpenAI 兼容的 /audio/transcriptions(智谱 glm-asr、OpenAI whisper-1 等)
|
||||
const API_BASE = String(process.env.ASR_API_BASE || 'https://open.bigmodel.cn/api/paas/v4').trim().replace(/\/+$/, '');
|
||||
const API_KEY = String(process.env.ASR_API_KEY || '').trim();
|
||||
const API_MODEL = String(process.env.ASR_MODEL || 'glm-asr').trim();
|
||||
// 上游参数逐请求带入(与 mcp/image_task 同构:密钥由调用方提供,服务端不保存):
|
||||
// Authorization: Bearer <key> ← 免鉴权的自建服务可省
|
||||
// X-ASR-Base-Url: https://.../v1
|
||||
// X-ASR-Model: whisper-1
|
||||
// 为什么不留 env 兜底:两条来源会让「到底生效的是哪个 key」变成靠猜,而且密钥越少地方存越好
|
||||
//(容器 env 用 docker inspect 就能看,config.yml 至少还受登录态保护)。
|
||||
const HDR_AUTH = 'authorization';
|
||||
const HDR_BASE = 'x-asr-base-url';
|
||||
const HDR_MODEL = 'x-asr-model';
|
||||
// 单次上传上限。60s 的 AAC 约 240KB、16k wav 约 1.9MB,20MB 是给长音频留的余量。
|
||||
const MAX_BYTES = Math.max(1024 * 1024, Number(process.env.ASR_MAX_BYTES || 20 * 1024 * 1024));
|
||||
// 云端多数 ASR 单次只吃 ~30s:超长音频按这个秒数切片后逐段识别再拼接(0 = 不切)。
|
||||
@@ -49,6 +55,27 @@ function log(level, msg) {
|
||||
console.log('[asr ' + level + '] ' + msg);
|
||||
}
|
||||
|
||||
// 从请求 header 取上游三要素。Authorization 允许写成裸 key(自动补 Bearer),
|
||||
// 省得用户还要记各平台前缀有没有写全。
|
||||
function upstreamOf(req) {
|
||||
const h = (req && req.headers) || {};
|
||||
const raw = String(h[HDR_AUTH] || '').trim();
|
||||
return {
|
||||
auth: raw ? (/^bearer\s/i.test(raw) ? raw : 'Bearer ' + raw) : '',
|
||||
base: String(h[HDR_BASE] || '').trim().replace(/\/+$/, ''),
|
||||
model: String(h[HDR_MODEL] || '').trim(),
|
||||
};
|
||||
}
|
||||
|
||||
// 缺参数直接 503:这是部署问题(config.yml 没配),不是用户输入问题——回 4xx 会让人以为音频坏了。
|
||||
function assertUpstream(up) {
|
||||
const miss = !up.base ? 'X-ASR-Base-Url' : !up.model ? 'X-ASR-Model' : '';
|
||||
if (!miss) return;
|
||||
const e = new Error('语音识别未配置上游:config.yml 的 mcp_servers 里 asr 需要 headers.' + miss);
|
||||
e.status = 503;
|
||||
throw e;
|
||||
}
|
||||
|
||||
// ── 子进程:统一超时 + 收 stdout/stderr ────────────────────────────────────
|
||||
function run(cmd, args, timeoutMs) {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -140,21 +167,17 @@ function extractText(obj) {
|
||||
return '';
|
||||
}
|
||||
|
||||
async function runCloud(wavPath) {
|
||||
if (!API_KEY) {
|
||||
const e = new Error('语音识别未配置:容器环境变量 ASR_API_KEY 为空');
|
||||
e.status = 503;
|
||||
throw e;
|
||||
}
|
||||
async function runCloud(wavPath, up) {
|
||||
assertUpstream(up);
|
||||
const buf = await fs.readFile(wavPath);
|
||||
const form = new FormData();
|
||||
form.append('model', API_MODEL);
|
||||
form.append('model', up.model);
|
||||
form.append('file', new Blob([buf], { type: 'audio/wav' }), 'audio.wav');
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(API_BASE + '/audio/transcriptions', {
|
||||
res = await fetch(up.base + '/audio/transcriptions', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer ' + API_KEY },
|
||||
headers: up.auth ? { Authorization: up.auth } : {},
|
||||
body: form,
|
||||
signal: AbortSignal.timeout(60000),
|
||||
});
|
||||
@@ -208,6 +231,8 @@ async function wavLevel(wavPath) {
|
||||
|
||||
// 转写一段音频缓冲:归一化 →(超长则切片)→ 逐段识别 → 拼接。
|
||||
async function transcribeBuffer(buf, opts) {
|
||||
const up = (opts && opts.up) || {};
|
||||
assertUpstream(up);
|
||||
const wavPath = await toWav(buf, opts && opts.ext);
|
||||
const parts = [];
|
||||
try {
|
||||
@@ -222,7 +247,7 @@ async function transcribeBuffer(buf, opts) {
|
||||
}
|
||||
if (!parts.length) {
|
||||
try {
|
||||
return (await runCloud(wavPath)).trim();
|
||||
return (await runCloud(wavPath, up)).trim();
|
||||
} catch (e) {
|
||||
// 只在上游判定“没有语音”时量一遍音量(正常路径零开销):
|
||||
// 静音是 -91dB,正常语音 -20dB 上下,一眼就能分清是设备没收到声还是文件坏了。
|
||||
@@ -237,7 +262,7 @@ async function transcribeBuffer(buf, opts) {
|
||||
for (const p of parts) {
|
||||
// 每段独立识别;单段失败不连累其他段(长录音里偶发静音段常见)
|
||||
try {
|
||||
out.push((await runCloud(p)).trim());
|
||||
out.push((await runCloud(p, up)).trim());
|
||||
} catch (e) {
|
||||
log('warn', '切片识别失败(跳过):' + String(e && e.message || e).slice(0, 200));
|
||||
}
|
||||
@@ -301,15 +326,18 @@ async function handleTranscribe(req, res, url) {
|
||||
if (active >= MAX_CONCURRENT) {
|
||||
return json(res, 429, { error: '语音识别繁忙,请稍后再试' });
|
||||
}
|
||||
// 先判配置再读 body:没配上游时不必白读 20MB
|
||||
const up = upstreamOf(req);
|
||||
assertUpstream(up);
|
||||
const buf = await readBody(req, MAX_BYTES);
|
||||
if (!buf.length) return json(res, 400, { error: '未收到音频数据' });
|
||||
|
||||
active++;
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const text = await transcribeBuffer(buf, { ext: extOf(req.headers['content-type']) });
|
||||
const text = await transcribeBuffer(buf, { ext: extOf(req.headers['content-type']), up });
|
||||
log('info', 'transcribed ' + buf.length + 'B → ' + text.length + ' 字,' + (Date.now() - t0) + 'ms');
|
||||
json(res, 200, { text, ms: Date.now() - t0, model: API_MODEL });
|
||||
json(res, 200, { text, ms: Date.now() - t0, model: up.model });
|
||||
} finally {
|
||||
active--;
|
||||
}
|
||||
@@ -375,7 +403,7 @@ async function handleMcp(req, res) {
|
||||
if (!urlStr) return ok({ isError: true, content: [{ type: 'text', text: '缺少 url 参数' }] });
|
||||
try {
|
||||
const { buf, ext } = await fetchAudio(urlStr);
|
||||
const text = await transcribeBuffer(buf, { ext });
|
||||
const text = await transcribeBuffer(buf, { ext, up: upstreamOf(req) });
|
||||
return ok({ content: [{ type: 'text', text }] });
|
||||
} catch (e) {
|
||||
return ok({ isError: true, content: [{ type: 'text', text: '转写失败:' + String(e && e.message || e) }] });
|
||||
@@ -402,11 +430,8 @@ const server = http.createServer((req, res) => {
|
||||
};
|
||||
|
||||
if (req.method === 'GET' && url.pathname === '/health') {
|
||||
return json(res, 200, {
|
||||
ok: true,
|
||||
model: API_MODEL,
|
||||
configured: !!API_KEY,
|
||||
});
|
||||
// 无状态服务:健康 = 进程活着。上游参数逐请求带入,没有全局「configured」可言。
|
||||
return json(res, 200, { ok: true, service: 'asr' });
|
||||
}
|
||||
if (req.method === 'POST' && url.pathname === '/transcribe') return done(handleTranscribe(req, res, url));
|
||||
if (url.pathname === '/mcp') {
|
||||
@@ -428,6 +453,5 @@ process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||
|
||||
server.listen(PORT, '0.0.0.0', () => {
|
||||
log('info', 'listening on ' + PORT + ',model=' + API_MODEL + ' @ ' + API_BASE);
|
||||
if (!API_KEY) log('warn', 'ASR_API_KEY 为空:/transcribe 会返回 503');
|
||||
log('info', 'listening on ' + PORT + '(上游 key/base_url/model 由调用方随请求 header 带入)');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user