mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-23 03:19:41 +00:00
Compare commits
32 commits
cda17f4d6a
...
3219a28039
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3219a28039 | ||
|
|
aa524af1d3 | ||
|
|
39d4905137 | ||
|
|
bc4bc661f5 | ||
|
|
a2f949c347 | ||
|
|
ad0e514666 | ||
|
|
74fd778601 | ||
|
|
e6d711e8fe | ||
|
|
d7751f468e | ||
|
|
285d47783c | ||
|
|
01f65ee5c4 | ||
|
|
4e898819dd | ||
|
|
c1906d5dff | ||
|
|
462b288bda | ||
|
|
7c5fe74410 | ||
|
|
4ae96c6e02 | ||
|
|
a1919f7db3 | ||
|
|
5b0c8c303b | ||
|
|
9100e7ecd2 | ||
|
|
4c04b9dd37 | ||
|
|
f441703e6c | ||
|
|
398f0bd097 | ||
|
|
e09df59c13 | ||
|
|
7f0d416e66 | ||
|
|
c282397cd2 | ||
|
|
7e450fca0d | ||
|
|
42f7e55c72 | ||
|
|
5f6e191d11 | ||
|
|
27833f918c | ||
|
|
3bf619e2dd | ||
|
|
1120be2f60 | ||
|
|
9880ce998f |
45 changed files with 1075 additions and 106 deletions
|
|
@ -64,6 +64,37 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
|
||||
private static final String DEFAULT_TITLE_PROMPT = "请根据以下对话内容,生成一个简洁的会话标题(约15字以内),只返回标题,不要包含任何解释或标点符号:\n{conversation}";
|
||||
|
||||
/**
|
||||
* Ollama的OpenAI兼容端点位于{base_url}/v1下,与xiaozhi-server侧ollama provider逻辑保持一致:
|
||||
* 先去尾斜杠、再剥离用户误填的完整端点后缀,仅对不含路径的纯主机地址补/v1。
|
||||
* 空串返回null,交由上层"配置不完整"必填校验拦截
|
||||
*/
|
||||
private static String normalizeOllamaBaseUrl(String baseUrl) {
|
||||
if (baseUrl == null) {
|
||||
return null;
|
||||
}
|
||||
String url = baseUrl.trim();
|
||||
if (url.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
while (url.endsWith("/")) {
|
||||
url = url.substring(0, url.length() - 1);
|
||||
}
|
||||
if (url.endsWith("/chat/completions")) {
|
||||
url = url.substring(0, url.length() - "/chat/completions".length());
|
||||
while (url.endsWith("/")) {
|
||||
url = url.substring(0, url.length() - 1);
|
||||
}
|
||||
}
|
||||
if (url.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (url.replaceFirst("^https?://[^/]+", "").isEmpty()) {
|
||||
url = url + "/v1";
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateSummary(String conversation) {
|
||||
return generateSummary(conversation, null, null);
|
||||
|
|
@ -101,6 +132,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
String baseUrl = configJson.getStr("base_url");
|
||||
String model = configJson.getStr("model_name");
|
||||
String apiKey = configJson.getStr("api_key");
|
||||
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
|
||||
baseUrl = normalizeOllamaBaseUrl(baseUrl);
|
||||
// Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致
|
||||
if (StringUtils.isBlank(apiKey)) {
|
||||
apiKey = "ollama";
|
||||
}
|
||||
}
|
||||
Double temperature = configJson.getDouble("temperature");
|
||||
Integer maxTokens = configJson.getInt("max_tokens");
|
||||
|
||||
|
|
@ -196,6 +234,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
String baseUrl = configJson.getStr("base_url");
|
||||
String model = configJson.getStr("model_name");
|
||||
String apiKey = configJson.getStr("api_key");
|
||||
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
|
||||
baseUrl = normalizeOllamaBaseUrl(baseUrl);
|
||||
// Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致
|
||||
if (StringUtils.isBlank(apiKey)) {
|
||||
apiKey = "ollama";
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
|
||||
log.error("LLM配置不完整,baseUrl或apiKey为空");
|
||||
|
|
@ -271,8 +316,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
String baseUrl = configJson.getStr("base_url");
|
||||
String apiKey = configJson.getStr("api_key");
|
||||
|
||||
// Ollama免鉴权:不要求api_key
|
||||
boolean ollama = "ollama".equalsIgnoreCase(configJson.getStr("type"));
|
||||
return baseUrl != null && !baseUrl.trim().isEmpty() &&
|
||||
apiKey != null && !apiKey.trim().isEmpty();
|
||||
(ollama || (apiKey != null && !apiKey.trim().isEmpty()));
|
||||
} catch (Exception e) {
|
||||
log.error("检查LLM服务可用性时发生异常:", e);
|
||||
return false;
|
||||
|
|
@ -297,8 +344,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
String baseUrl = configJson.getStr("base_url");
|
||||
String apiKey = configJson.getStr("api_key");
|
||||
|
||||
// Ollama免鉴权:不要求api_key
|
||||
boolean ollama = "ollama".equalsIgnoreCase(configJson.getStr("type"));
|
||||
return baseUrl != null && !baseUrl.trim().isEmpty() &&
|
||||
apiKey != null && !apiKey.trim().isEmpty();
|
||||
(ollama || (apiKey != null && !apiKey.trim().isEmpty()));
|
||||
} catch (Exception e) {
|
||||
log.error("检查LLM服务可用性时发生异常,modelId: {}", modelId, e);
|
||||
return false;
|
||||
|
|
@ -354,6 +403,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
|
|||
String baseUrl = configJson.getStr("base_url");
|
||||
String model = configJson.getStr("model_name");
|
||||
String apiKey = configJson.getStr("api_key");
|
||||
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
|
||||
baseUrl = normalizeOllamaBaseUrl(baseUrl);
|
||||
// Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致
|
||||
if (StringUtils.isBlank(apiKey)) {
|
||||
apiKey = "ollama";
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
|
||||
log.error("LLM配置不完整,baseUrl或apiKey为空");
|
||||
|
|
|
|||
|
|
@ -0,0 +1,4 @@
|
|||
-- 添加MCP接入点附带说话人身份的开关参数配置
|
||||
delete from `sys_params` where param_code = 'mcp_forward_speaker';
|
||||
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark)
|
||||
VALUES (313, 'mcp_forward_speaker', 'true', 'boolean', 1, '是否随MCP调用附带说话人身份');
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
-- Ollama LLM配置补充api_key占位值,走鉴权网关/Ollama Cloud时使用
|
||||
UPDATE `ai_model_config`
|
||||
SET `config_json` = JSON_SET(`config_json`, '$.api_key', 'ollama')
|
||||
WHERE `id` = 'LLM_OllamaLLM' AND JSON_EXTRACT(`config_json`, '$.api_key') IS NULL;
|
||||
|
||||
-- Ollama供应商追加api_key字段定义,password类型
|
||||
UPDATE `ai_model_provider`
|
||||
SET `fields` = JSON_ARRAY_APPEND(COALESCE(`fields`, JSON_ARRAY()), '$',
|
||||
JSON_OBJECT('key', 'api_key', 'label', 'API密钥', 'type', 'password'))
|
||||
WHERE `id` = 'SYSTEM_LLM_ollama'
|
||||
AND JSON_SEARCH(`fields`, 'one', 'api_key', NULL, '$[*].key') IS NULL;
|
||||
|
||||
-- 配置说明补充api_key条目
|
||||
UPDATE `ai_model_config`
|
||||
SET `remark` = CONCAT(`remark`, '\n4. 走鉴权网关或使用Ollama Cloud时,需填写api_key')
|
||||
WHERE `id` = 'LLM_OllamaLLM'
|
||||
AND `remark` IS NOT NULL AND `remark` NOT LIKE '%api_key%';
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
-- 为 LLM 的 OpenAI 接口配置表单新增 chat_template_kwargs 字段(dict, 前端映射为 JSON 文本框)
|
||||
-- 用于向 vLLM/SGLang 等自托管 OpenAI 兼容后端透传 chat template 控制参数(如 enable_thinking)
|
||||
-- 注意: DashScope 等云服务不识别此字段, 仅供自托管后端使用
|
||||
UPDATE `ai_model_provider`
|
||||
SET `fields` = '[{"key":"base_url","label":"基础URL","type":"string"},{"key":"model_name","label":"模型名称","type":"string"},{"key":"api_key","label":"API密钥","type":"string"},{"key":"temperature","label":"温度","type":"number"},{"key":"max_tokens","label":"最大令牌数","type":"number"},{"key":"top_p","label":"top_p值","type":"number"},{"key":"top_k","label":"top_k值","type":"number"},{"key":"frequency_penalty","label":"频率惩罚","type":"number"},{"key":"chat_template_kwargs","label":"模板变量(JSON)","type":"dict"}]'
|
||||
WHERE `id` = 'SYSTEM_LLM_openai';
|
||||
|
|
@ -753,6 +753,20 @@ databaseChangeLog:
|
|||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202609172100.sql
|
||||
- changeSet:
|
||||
id: 202610261030
|
||||
author: RanChen
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202610261030.sql
|
||||
- changeSet:
|
||||
id: 202610291451
|
||||
author: RanChen
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202610291451.sql
|
||||
- changeSet:
|
||||
id: 202610302051
|
||||
author: shinjiyu
|
||||
|
|
@ -774,3 +788,10 @@ databaseChangeLog:
|
|||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202611101200.sql
|
||||
- changeSet:
|
||||
id: 202611181622
|
||||
author: RanChen
|
||||
changes:
|
||||
- sqlFile:
|
||||
encoding: utf8
|
||||
path: classpath:db/changelog/202611181622.sql
|
||||
|
|
|
|||
|
|
@ -120,6 +120,11 @@ export default defineManifestConfig({
|
|||
/* 小程序特有相关 */
|
||||
'mp-weixin': {
|
||||
appid: VITE_WX_APPID,
|
||||
// 仅供开发者工具选择调试基础库版本;线上客户端的最低基础库门槛需在
|
||||
// 微信公众平台「开发管理 → 基础库最低版本设置」中配置(代码里改不动)。
|
||||
// 功能硬性要求:wx.getRandomValues 需基础库 >= 2.17.3,低于该版本的
|
||||
// 线上客户端登录时将收到 fail-closed 报错
|
||||
libVersion: '2.19.4',
|
||||
setting: {
|
||||
urlCheck: false,
|
||||
// 是否启用 ES6 转 ES5
|
||||
|
|
|
|||
|
|
@ -101,7 +101,7 @@
|
|||
"js-cookie": "^3.0.5",
|
||||
"pinia": "2.0.36",
|
||||
"pinia-plugin-persistedstate": "3.2.1",
|
||||
"sm-crypto": "^0.3.13",
|
||||
"sm-crypto": "0.5.8",
|
||||
"vue": "^3.4.21",
|
||||
"wot-design-uni": "^1.9.1",
|
||||
"z-paging": "2.8.7"
|
||||
|
|
|
|||
29
main/manager-mobile/patches/sm-crypto@0.5.8.patch
Normal file
29
main/manager-mobile/patches/sm-crypto@0.5.8.patch
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
diff --git a/src/sm2/rng.js b/src/sm2/rng.js
|
||||
index c6572c1756579fb100c0d7bdf0cec323971ec211..cdb1f1fcc7d58c52138f6f9fd76240bae5dde5d4 100644
|
||||
--- a/src/sm2/rng.js
|
||||
+++ b/src/sm2/rng.js
|
||||
@@ -54,8 +54,14 @@ function rngSeedTime() {
|
||||
rngSeedInt(new Date().getTime())
|
||||
}
|
||||
|
||||
-// Initialize the pool with junk if needed.
|
||||
-if (rngPool == null) {
|
||||
+// [xiaozhi patch] 熵池初始化从模块加载时推迟到首次取随机字节时(见 rngGetByte)。
|
||||
+// 原因:微信小程序等环境没有同步的 crypto.getRandomValues,模块加载即取熵会直接抛异常;
|
||||
+// 推迟后,调用方可在首次使用前异步准备好真随机源(见 manager-mobile/src/utils/secure-random.ts)。
|
||||
+// fail-closed 语义保持不变:首次取熵时仍要求存在可用的 crypto.getRandomValues,否则抛出异常。
|
||||
+function ensureRngPool() {
|
||||
+ if (rngPool != null)
|
||||
+ return
|
||||
+
|
||||
rngPool = []
|
||||
rngPptr = 0
|
||||
let t
|
||||
@@ -82,6 +88,7 @@ if (rngPool == null) {
|
||||
|
||||
function rngGetByte() {
|
||||
if (rngState == null) {
|
||||
+ ensureRngPool()
|
||||
rngSeedTime()
|
||||
rngState = new Arcfour()
|
||||
rngState.init(rngPool)
|
||||
|
|
@ -11,6 +11,9 @@ patchedDependencies:
|
|||
'@dcloudio/uni-h5':
|
||||
hash: 5763725268e9a493075be3c82d91b590b9ae30e997a04a418494dd7d6d327b9d
|
||||
path: patches/@dcloudio__uni-h5.patch
|
||||
sm-crypto@0.5.8:
|
||||
hash: 62930665cf9612107916df2f12c9deab4ad907f6ac9080520b84bffe016c3352
|
||||
path: patches/sm-crypto@0.5.8.patch
|
||||
|
||||
importers:
|
||||
|
||||
|
|
@ -92,8 +95,8 @@ importers:
|
|||
specifier: 3.2.1
|
||||
version: 3.2.1(pinia@2.0.36(typescript@5.7.2)(vue@3.5.15(typescript@5.7.2)))
|
||||
sm-crypto:
|
||||
specifier: ^0.3.13
|
||||
version: 0.3.14
|
||||
specifier: 0.5.8
|
||||
version: 0.5.8(patch_hash=62930665cf9612107916df2f12c9deab4ad907f6ac9080520b84bffe016c3352)
|
||||
vue:
|
||||
specifier: ^3.4.21
|
||||
version: 3.5.15(typescript@5.7.2)
|
||||
|
|
@ -6026,8 +6029,8 @@ packages:
|
|||
resolution: {integrity: sha512-bSiSngZ/jWeX93BqeIAbImyTbEihizcwNjFoRUIY/T1wWQsfsm2Vw1agPKylXvQTU7iASGdHhyqRlqQzfz+Htg==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
sm-crypto@0.3.14:
|
||||
resolution: {integrity: sha512-sR7NuGAJH93Om8keAF2/rj1EqFzEiUey4aKGyDo3nQ2BiVqhgq8UkiIoIp5qhV9w4pG7qArhfqyewcG8AbhXbg==}
|
||||
sm-crypto@0.5.8:
|
||||
resolution: {integrity: sha512-bpz1/PthgZHcLHyIl28mbYZHmeuTDrdWpwHZ7BGzFjQuB7OOhjlbcPEMt44aqUfZ2S5YJXM8v20xYO1j9CC45Q==}
|
||||
|
||||
source-map-js@1.2.1:
|
||||
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
||||
|
|
@ -14156,7 +14159,7 @@ snapshots:
|
|||
ansi-styles: 6.2.1
|
||||
is-fullwidth-code-point: 5.0.0
|
||||
|
||||
sm-crypto@0.3.14:
|
||||
sm-crypto@0.5.8(patch_hash=62930665cf9612107916df2f12c9deab4ad907f6ac9080520b84bffe016c3352):
|
||||
dependencies:
|
||||
jsbn: 1.1.0
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
packages:
|
||||
- '**'
|
||||
- '!node_modules'
|
||||
|
||||
patchedDependencies:
|
||||
'@dcloudio/uni-h5': patches/@dcloudio__uni-h5.patch
|
||||
sm-crypto@0.5.8: patches/sm-crypto@0.5.8.patch
|
||||
|
|
|
|||
|
|
@ -0,0 +1,136 @@
|
|||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
// #ifdef APP-PLUS
|
||||
import { ensureSecureRandomReady, registerRandomBridge, unregisterRandomBridge } from '@/utils/secure-random'
|
||||
// #endif
|
||||
|
||||
interface BridgeItem {
|
||||
length: number
|
||||
resolve: (bytes: number[]) => void
|
||||
reject: (err: Error) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* App 端专用(页面中 #ifdef APP-PLUS 条件挂载):
|
||||
* 逻辑层无 Web Crypto,经 renderjs 在视图层 WebView 取
|
||||
* crypto.getRandomValues 后 callMethod 回传,注册为 secure-random 的随机源。
|
||||
*/
|
||||
export default defineComponent({
|
||||
data() {
|
||||
return {
|
||||
/** 变化后触发 renderjs 取随机(每次新对象引用确保 prop 变更被感知) */
|
||||
bridgeRequest: null as { id: number, length: number } | null,
|
||||
// 仅类型检查用:renderjs 模块绑定由 uni-app 编译期处理,运行时不读取
|
||||
secureRandomRenderer: { onPropChange: () => {} } as { onPropChange: (...args: any[]) => void },
|
||||
seq: 0,
|
||||
queue: [] as BridgeItem[],
|
||||
sending: false,
|
||||
currentId: 0,
|
||||
timeoutTimer: undefined as ReturnType<typeof setTimeout> | undefined,
|
||||
provider: undefined as ((length: number) => Promise<Uint8Array>) | undefined,
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
// #ifdef APP-PLUS
|
||||
this.provider = (length: number) =>
|
||||
this.requestBytes(length).then(bytes => new Uint8Array(bytes))
|
||||
registerRandomBridge(this.provider)
|
||||
ensureSecureRandomReady().catch((e: Error) => {
|
||||
console.warn('[secure-random] App 端随机源预热失败', e)
|
||||
})
|
||||
// #endif
|
||||
},
|
||||
beforeUnmount() {
|
||||
// #ifdef APP-PLUS
|
||||
// 拒绝队列项并注销,否则销毁后 pending 的 Promise 永不 settle,readyPromise 死锁
|
||||
if (this.provider)
|
||||
unregisterRandomBridge(this.provider)
|
||||
for (const item of this.queue)
|
||||
item.reject(new Error('secure-random-bridge 组件已卸载,随机数请求中止'))
|
||||
this.queue = []
|
||||
this.sending = false
|
||||
// #endif
|
||||
clearTimeout(this.timeoutTimer)
|
||||
},
|
||||
methods: {
|
||||
requestBytes(length: number): Promise<number[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.queue.push({ length, resolve, reject })
|
||||
this.pump()
|
||||
})
|
||||
},
|
||||
/** 串行发送:prop 变更过快时视图层可能丢失中间状态,故一次只发一个请求 */
|
||||
pump() {
|
||||
if (this.sending || this.queue.length === 0)
|
||||
return
|
||||
this.sending = true
|
||||
const item = this.queue[0]
|
||||
this.currentId = ++this.seq
|
||||
this.bridgeRequest = { id: this.currentId, length: item.length }
|
||||
// 超时保护:视图层无响应时按 fail-closed 报错,避免登录流程永久挂起
|
||||
clearTimeout(this.timeoutTimer)
|
||||
this.timeoutTimer = setTimeout(() => {
|
||||
this.onRandomResult({ id: this.currentId, error: 'renderjs 随机数请求超时' })
|
||||
}, 5000)
|
||||
},
|
||||
/** renderjs 通过 callMethod 回传结果(或错误) */
|
||||
onRandomResult(res: { id: number, bytes?: number[], error?: string }) {
|
||||
if (res.id !== this.currentId)
|
||||
return
|
||||
clearTimeout(this.timeoutTimer)
|
||||
const item = this.queue.shift()
|
||||
this.sending = false
|
||||
if (item) {
|
||||
if (res.error)
|
||||
item.reject(new Error(res.error))
|
||||
else
|
||||
item.resolve(res.bytes || [])
|
||||
}
|
||||
this.pump()
|
||||
},
|
||||
},
|
||||
})
|
||||
</script>
|
||||
|
||||
<script module="secureRandomRenderer" lang="renderjs">
|
||||
// 视图层(WebView):可访问 crypto.getRandomValues
|
||||
export default {
|
||||
methods: {
|
||||
onPropChange(newVal, oldVal, ownerInstance, instance) {
|
||||
if (!newVal || !newVal.id || !newVal.length)
|
||||
return
|
||||
try {
|
||||
const cryptoObj = (typeof crypto !== 'undefined' && crypto)
|
||||
|| (typeof window !== 'undefined' && window.crypto)
|
||||
if (!cryptoObj || typeof cryptoObj.getRandomValues !== 'function')
|
||||
throw new Error('视图层缺少 crypto.getRandomValues')
|
||||
const bytes = new Uint8Array(newVal.length)
|
||||
cryptoObj.getRandomValues(bytes)
|
||||
ownerInstance.callMethod('onRandomResult', { id: newVal.id, bytes: Array.from(bytes) })
|
||||
}
|
||||
catch (e) {
|
||||
ownerInstance.callMethod('onRandomResult', {
|
||||
id: newVal.id,
|
||||
error: String((e && e.message) || e),
|
||||
})
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<view
|
||||
class="secure-random-bridge"
|
||||
:prop="bridgeRequest"
|
||||
:change:prop="secureRandomRenderer.onPropChange"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.secure-random-bridge {
|
||||
width: 0;
|
||||
height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -92,6 +92,7 @@
|
|||
"minified": true
|
||||
},
|
||||
"usingComponents": true,
|
||||
"libVersion": "2.19.4",
|
||||
"optimization": {
|
||||
"subPackages": true
|
||||
},
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@ import { onLoad } from '@dcloudio/uni-app'
|
|||
import { computed, onMounted, ref } from 'vue'
|
||||
// 导入API接口
|
||||
import { retrievePassword, sendSmsCode } from '@/api/auth'
|
||||
// #ifdef APP-PLUS
|
||||
// App 端随机源桥接:为 SM2 加密提供安全随机数(无视觉展示)
|
||||
import SecureRandomBridge from '@/components/secure-random-bridge/index.vue'
|
||||
// #endif
|
||||
// 导入国际化相关功能
|
||||
import { initI18n, t } from '@/i18n'
|
||||
import { useConfigStore } from '@/store'
|
||||
|
|
@ -235,7 +239,7 @@ async function handleResetPassword() {
|
|||
try {
|
||||
// 拼接图形验证码和新密码进行加密
|
||||
const captchaAndPassword = formData.value.captcha + formData.value.newPassword
|
||||
encryptedPassword = sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
|
||||
encryptedPassword = await sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
|
||||
}
|
||||
catch (error) {
|
||||
console.error('密码加密失败:', error)
|
||||
|
|
@ -305,6 +309,9 @@ onMounted(async () => {
|
|||
class="app-container box-border h-screen w-full"
|
||||
:style="{ paddingTop: `${safeAreaInsets?.top}px` }"
|
||||
>
|
||||
<!-- #ifdef APP-PLUS -->
|
||||
<SecureRandomBridge />
|
||||
<!-- #endif -->
|
||||
<view class="header">
|
||||
<view class="back-button" @click="goBack">
|
||||
<wd-icon name="arrow-left" custom-class="back-icon" />
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@ import type { LoginData } from '@/api/auth'
|
|||
import type { Language } from '@/store/lang'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { login } from '@/api/auth'
|
||||
// #ifdef APP-PLUS
|
||||
// App 端随机源桥接:为 SM2 加密提供安全随机数(无视觉展示)
|
||||
import SecureRandomBridge from '@/components/secure-random-bridge/index.vue'
|
||||
// #endif
|
||||
// 导入国际化相关功能
|
||||
import { changeLanguage, getCurrentLanguage, getSupportedLanguages, initI18n, t } from '@/i18n'
|
||||
import { useConfigStore, useUserStore } from '@/store'
|
||||
|
|
@ -202,7 +206,7 @@ async function handleLogin() {
|
|||
try {
|
||||
// 拼接验证码和密码
|
||||
const captchaAndPassword = formData.value.captcha + formData.value.password
|
||||
encryptedPassword = sm2Encrypt(sm2PublicKey, captchaAndPassword)
|
||||
encryptedPassword = await sm2Encrypt(sm2PublicKey, captchaAndPassword)
|
||||
}
|
||||
catch (error) {
|
||||
console.error('密码加密失败:', error)
|
||||
|
|
@ -281,6 +285,9 @@ onMounted(async () => {
|
|||
|
||||
<template>
|
||||
<view class="app-container box-border h-screen w-full" :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
|
||||
<!-- #ifdef APP-PLUS -->
|
||||
<SecureRandomBridge />
|
||||
<!-- #endif -->
|
||||
<view class="header">
|
||||
<view class="logo-section">
|
||||
<wd-img :width="80" :height="80" round src="/static/logo.png" class="logo" />
|
||||
|
|
|
|||
|
|
@ -11,6 +11,10 @@
|
|||
<script lang="ts" setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { register, sendSmsCode } from '@/api/auth'
|
||||
// #ifdef APP-PLUS
|
||||
// App 端随机源桥接:为 SM2 加密提供安全随机数(无视觉展示)
|
||||
import SecureRandomBridge from '@/components/secure-random-bridge/index.vue'
|
||||
// #endif
|
||||
// 导入国际化相关功能
|
||||
import { initI18n, t } from '@/i18n'
|
||||
import { useConfigStore } from '@/store'
|
||||
|
|
@ -251,7 +255,7 @@ async function handleRegister() {
|
|||
try {
|
||||
// 拼接验证码和密码
|
||||
const captchaAndPassword = formData.value.captcha + formData.value.password
|
||||
encryptedPassword = sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
|
||||
encryptedPassword = await sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
|
||||
}
|
||||
catch (error) {
|
||||
console.error('密码加密失败:', error)
|
||||
|
|
@ -325,6 +329,9 @@ onMounted(async () => {
|
|||
|
||||
<template>
|
||||
<view class="app-container box-border h-screen w-full" :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
|
||||
<!-- #ifdef APP-PLUS -->
|
||||
<SecureRandomBridge />
|
||||
<!-- #endif -->
|
||||
<view class="header">
|
||||
<view class="back-button" @click="goBack">
|
||||
<wd-icon name="arrow-left" custom-class="back-icon" />
|
||||
|
|
|
|||
|
|
@ -2,6 +2,21 @@ import smCrypto from 'sm-crypto'
|
|||
import { pages, subPackages } from '@/pages.json'
|
||||
|
||||
import { isMpWeixin } from './platform'
|
||||
import { ensureSecureRandomReady } from './secure-random'
|
||||
|
||||
/**
|
||||
* 获取 sm2 模块(确保密码学安全随机源已就绪)。
|
||||
*
|
||||
* sm-crypto >= 0.5.0(CVE-2026-73567 修复)强制要求 crypto.getRandomValues。
|
||||
* 小程序等环境没有该 API,项目中通过 pnpm patch(patches/sm-crypto@0.5.8.patch)
|
||||
* 将 sm-crypto 的熵池初始化推迟到首次取随机字节时,并由 secure-random.ts 提供
|
||||
* 垫片。因此小程序端首次调用 sm2 前必须 await 本方法,用 wx.getRandomValues
|
||||
* 预热真随机缓冲池;浏览器 / Node 等原生支持 globalThis.crypto 的环境立即就绪。
|
||||
*/
|
||||
async function getSm2(): Promise<typeof smCrypto.sm2> {
|
||||
await ensureSecureRandomReady()
|
||||
return smCrypto.sm2
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行时服务端地址覆盖存储键
|
||||
|
|
@ -201,11 +216,11 @@ export function getEnvBaseUploadUrl() {
|
|||
|
||||
/**
|
||||
* 生成SM2密钥对(十六进制格式)
|
||||
* @returns {object} 包含公钥和私钥的对象
|
||||
* @returns {Promise<object>} 包含公钥和私钥的对象
|
||||
*/
|
||||
export function generateSm2KeyPairHex() {
|
||||
export async function generateSm2KeyPairHex() {
|
||||
// 使用sm-crypto库生成SM2密钥对
|
||||
const sm2 = smCrypto.sm2
|
||||
const sm2 = await getSm2()
|
||||
const keypair = sm2.generateKeyPairHex()
|
||||
|
||||
return {
|
||||
|
|
@ -220,9 +235,9 @@ export function generateSm2KeyPairHex() {
|
|||
* SM2公钥加密
|
||||
* @param {string} publicKey 公钥(十六进制格式)
|
||||
* @param {string} plainText 明文
|
||||
* @returns {string} 加密后的密文(十六进制格式)
|
||||
* @returns {Promise<string>} 加密后的密文(十六进制格式)
|
||||
*/
|
||||
export function sm2Encrypt(publicKey: string, plainText: string): string {
|
||||
export async function sm2Encrypt(publicKey: string, plainText: string): Promise<string> {
|
||||
if (!publicKey) {
|
||||
throw new Error('公钥不能为null或undefined')
|
||||
}
|
||||
|
|
@ -231,7 +246,7 @@ export function sm2Encrypt(publicKey: string, plainText: string): string {
|
|||
throw new Error('明文不能为空')
|
||||
}
|
||||
|
||||
const sm2 = smCrypto.sm2
|
||||
const sm2 = await getSm2()
|
||||
// SM2加密,添加04前缀表示未压缩公钥
|
||||
const encrypted = sm2.doEncrypt(plainText, publicKey, 1)
|
||||
// 转换为十六进制格式(与后端保持一致,添加04前缀)
|
||||
|
|
@ -244,10 +259,10 @@ export function sm2Encrypt(publicKey: string, plainText: string): string {
|
|||
* SM2私钥解密
|
||||
* @param {string} privateKey 私钥(十六进制格式)
|
||||
* @param {string} cipherText 密文(十六进制格式)
|
||||
* @returns {string} 解密后的明文
|
||||
* @returns {Promise<string>} 解密后的明文(当前项目内暂无调用点,保留备用)
|
||||
*/
|
||||
export function sm2Decrypt(privateKey: string, cipherText: string): string {
|
||||
const sm2 = smCrypto.sm2
|
||||
export async function sm2Decrypt(privateKey: string, cipherText: string): Promise<string> {
|
||||
const sm2 = await getSm2()
|
||||
// 移除04前缀(与后端保持一致)
|
||||
const dataWithoutPrefix = cipherText.startsWith('04') ? cipherText.substring(2) : cipherText
|
||||
// SM2解密
|
||||
|
|
|
|||
206
main/manager-mobile/src/utils/secure-random.ts
Normal file
206
main/manager-mobile/src/utils/secure-random.ts
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
/**
|
||||
* 为 sm-crypto >= 0.5.0 提供 crypto.getRandomValues 兼容层
|
||||
* (0.5.0 起强制要求 CSPRNG,不支持时模块加载即抛异常,见 CVE-2026-73567)。
|
||||
*
|
||||
* 策略:
|
||||
* 1. 经平台异步 CSPRNG API 分块并行取真随机字节,填入同步缓冲池。
|
||||
* 探测顺序 wx → uni → my → tt → swan → ks → qq → jd → lark → xhs;
|
||||
* App 端逻辑层无 CSPRNG,
|
||||
* 由 secure-random-bridge 组件经 renderjs 回传(registerRandomBridge 兜底)。
|
||||
* 2. 垫片同步从缓冲池取字节,池不足即抛错,不回退弱随机(fail-closed)。
|
||||
* 3. sm-crypto 熵池初始化已通过 pnpm patch 推迟到首次取随机
|
||||
* (patches/sm-crypto@0.5.8.patch),首次 sm2 调用前 await
|
||||
* ensureSecureRandomReady() 即可。
|
||||
*
|
||||
* 无任何 CSPRNG 的平台(如支付宝/百度小程序)会 reject,属预期行为。
|
||||
*/
|
||||
const CHUNK_SIZE = 64
|
||||
const CHUNK_COUNT = 8
|
||||
const LOW_WATER_MARK = 128
|
||||
|
||||
// 标记垫片自身,探测时与原生实现区分,避免失败重试被短路成假成功
|
||||
const SHIM_MARKER = Symbol('secureRandomShim')
|
||||
|
||||
// App 端桥接通道,由 secure-random-bridge 组件挂载时注册
|
||||
let bridgeProvider: ((length: number) => Promise<Uint8Array>) | null = null
|
||||
|
||||
export function registerRandomBridge(provider: (length: number) => Promise<Uint8Array>) {
|
||||
bridgeProvider = provider
|
||||
}
|
||||
|
||||
/** 仅当当前注册者仍是该实例时注销,避免多页栈下误清后挂载实例的注册 */
|
||||
export function unregisterRandomBridge(provider: (length: number) => Promise<Uint8Array>) {
|
||||
if (bridgeProvider === provider)
|
||||
bridgeProvider = null
|
||||
}
|
||||
|
||||
let pool: number[] = []
|
||||
let readyPromise: Promise<void> | null = null
|
||||
let refillInFlight = false
|
||||
|
||||
function getGlobalObj(): Record<string, any> | null {
|
||||
// sm-crypto 读取的是 globalThis.crypto,垫片必须装在同一对象上
|
||||
if (typeof globalThis !== 'undefined')
|
||||
return globalThis as unknown as Record<string, any>
|
||||
return null
|
||||
}
|
||||
|
||||
function hasNativeGetRandomValues(): boolean {
|
||||
try {
|
||||
// 探测 globalThis.crypto:Node、h5:ssr 等环境有原生 CSPRNG 但无 window
|
||||
const fn = getGlobalObj()?.crypto?.getRandomValues
|
||||
// 排除垫片自身,否则失败重试会被短路成假成功
|
||||
return typeof fn === 'function' && !(fn as any)[SHIM_MARKER]
|
||||
}
|
||||
catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按优先级探测提供异步 CSPRNG 的平台全局对象。
|
||||
* uni.getRandomValues 仅有声明无实现,故排在 wx 之后兜底;
|
||||
* 其余平台对象未在 TS 类型中声明,经 globalThis 探测,
|
||||
* 对应平台未来实现同名 API 时自动生效。
|
||||
*/
|
||||
function findRandomApi(): { name: string, api: any } | null {
|
||||
const globalObj = getGlobalObj()
|
||||
const candidates: Array<[string, any]> = [
|
||||
['wx', typeof wx !== 'undefined' ? wx : null],
|
||||
['uni', typeof uni !== 'undefined' ? uni : null],
|
||||
['my', globalObj ? globalObj.my : null],
|
||||
['tt', globalObj ? globalObj.tt : null],
|
||||
['swan', globalObj ? globalObj.swan : null],
|
||||
['ks', globalObj ? globalObj.ks : null],
|
||||
['qq', globalObj ? globalObj.qq : null],
|
||||
['jd', globalObj ? globalObj.jd : null],
|
||||
['lark', globalObj ? globalObj.lark : null],
|
||||
['xhs', globalObj ? globalObj.xhs : null],
|
||||
]
|
||||
for (const [name, api] of candidates) {
|
||||
if (api && typeof api.getRandomValues === 'function')
|
||||
return { name, api }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function fetchRandomChunk(length: number): Promise<Uint8Array> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const found = findRandomApi()
|
||||
if (!found && !bridgeProvider) {
|
||||
reject(new Error(
|
||||
'当前平台不支持获取密码学安全随机数(getRandomValues),无法安全执行 SM2 加密。'
|
||||
+ '当前已适配:微信小程序(wx.getRandomValues)、浏览器、Node 环境、'
|
||||
+ 'App 端(renderjs 桥接,需页面挂载 secure-random-bridge 组件);'
|
||||
+ '其余小程序平台因缺少 CSPRNG API 被按 fail-closed 原则拒绝,'
|
||||
+ '如需支持请扩展 secure-random.ts 的 findRandomApi 适配链。',
|
||||
))
|
||||
return
|
||||
}
|
||||
if (found) {
|
||||
// 平台 API 异常时可能 success/fail 均不回调,超时兜底防止 readyPromise 死锁
|
||||
const timer = setTimeout(() => {
|
||||
reject(new Error(`${found.name}.getRandomValues 超时(5s 无响应)`))
|
||||
}, 5000)
|
||||
found.api.getRandomValues({
|
||||
length,
|
||||
success: (res: { randomValues: ArrayBuffer | Uint8Array | number[] }) => {
|
||||
clearTimeout(timer)
|
||||
resolve(new Uint8Array(res.randomValues))
|
||||
},
|
||||
fail: (err: unknown) => {
|
||||
clearTimeout(timer)
|
||||
reject(err instanceof Error ? err : new Error(`getRandomValues 调用失败: ${JSON.stringify(err)}`))
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
bridgeProvider!(length).then(resolve, (err: unknown) => {
|
||||
reject(err instanceof Error ? err : new Error(`renderjs 桥接取随机失败: ${String(err)}`))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function refillPool(totalLength: number): Promise<void> {
|
||||
const chunks = await Promise.all(
|
||||
Array.from({ length: Math.ceil(totalLength / CHUNK_SIZE) }, () => fetchRandomChunk(CHUNK_SIZE)),
|
||||
)
|
||||
for (const chunk of chunks) {
|
||||
for (let i = 0; i < chunk.length; i++)
|
||||
pool.push(chunk[i])
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleRefill() {
|
||||
if (refillInFlight)
|
||||
return
|
||||
refillInFlight = true
|
||||
refillPool(256)
|
||||
.catch((err) => {
|
||||
// 补充失败仅告警:池仍够用则无感,耗尽时由 getRandomValues 抛错兜底
|
||||
console.warn('[secure-random] 补充随机数缓冲池失败', err)
|
||||
})
|
||||
.finally(() => {
|
||||
refillInFlight = false
|
||||
})
|
||||
}
|
||||
|
||||
function createGetRandomValues<T extends ArrayBufferView>(array: T): T {
|
||||
// 按字节拷贝,兼容 Uint16Array/Uint32Array 等视图
|
||||
const view = array as unknown as ArrayBufferView
|
||||
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength)
|
||||
if (pool.length < bytes.length) {
|
||||
scheduleRefill()
|
||||
throw new Error('安全随机数缓冲池未就绪或已耗尽,请先等待 ensureSecureRandomReady() 完成')
|
||||
}
|
||||
for (let i = 0; i < bytes.length; i++)
|
||||
bytes[i] = pool[i]
|
||||
pool = pool.slice(bytes.length)
|
||||
if (pool.length < LOW_WATER_MARK)
|
||||
scheduleRefill()
|
||||
return array
|
||||
}
|
||||
|
||||
;(createGetRandomValues as any)[SHIM_MARKER] = true
|
||||
|
||||
function installShim() {
|
||||
const globalObj = getGlobalObj()
|
||||
if (!globalObj)
|
||||
throw new Error('无法获取全局对象,无法安装 crypto.getRandomValues 垫片')
|
||||
|
||||
if (globalObj.crypto && typeof globalObj.crypto.getRandomValues === 'function')
|
||||
return
|
||||
|
||||
if (globalObj.crypto) {
|
||||
// 只补缺的方法,保留宿主 crypto 其他成员;defineProperty 规避只读访问器赋值失败
|
||||
Object.defineProperty(globalObj.crypto, 'getRandomValues', {
|
||||
value: createGetRandomValues,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
}
|
||||
else {
|
||||
globalObj.crypto = { getRandomValues: createGetRandomValues }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保密码学安全随机源可用(首次 sm2 调用前必须 await)。
|
||||
* 原生支持的环境直接就绪;缺失环境安装垫片并预热缓冲池;
|
||||
* 无 CSPRNG 的环境 reject,由调用方 fail-closed 处理。
|
||||
*/
|
||||
export function ensureSecureRandomReady(): Promise<void> {
|
||||
if (hasNativeGetRandomValues())
|
||||
return Promise.resolve()
|
||||
if (!readyPromise) {
|
||||
readyPromise = (async () => {
|
||||
installShim()
|
||||
await refillPool(CHUNK_SIZE * CHUNK_COUNT)
|
||||
})().catch((err) => {
|
||||
// 失败后重置,允许后续重试
|
||||
readyPromise = null
|
||||
throw err
|
||||
})
|
||||
}
|
||||
return readyPromise
|
||||
}
|
||||
8
main/manager-web/package-lock.json
generated
8
main/manager-web/package-lock.json
generated
|
|
@ -17,7 +17,7 @@
|
|||
"normalize.css": "^8.0.1",
|
||||
"opus-decoder": "^0.7.7",
|
||||
"opus-recorder": "^8.0.5",
|
||||
"sm-crypto": "^0.3.13",
|
||||
"sm-crypto": "^0.5.8",
|
||||
"v-code-diff": "^1.16.0",
|
||||
"vue": "^2.6.14",
|
||||
"vue-axios": "^3.5.2",
|
||||
|
|
@ -12485,9 +12485,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/sm-crypto": {
|
||||
"version": "0.3.13",
|
||||
"resolved": "https://registry.npmmirror.com/sm-crypto/-/sm-crypto-0.3.13.tgz",
|
||||
"integrity": "sha512-ztNF+pZq6viCPMA1A6KKu3bgpkmYti5avykRHbcFIdSipFdkVmfUw2CnpM2kBJyppIalqvczLNM3wR8OQ0pT5w==",
|
||||
"version": "0.5.8",
|
||||
"resolved": "https://registry.npmmirror.com/sm-crypto/-/sm-crypto-0.5.8.tgz",
|
||||
"integrity": "sha512-bpz1/PthgZHcLHyIl28mbYZHmeuTDrdWpwHZ7BGzFjQuB7OOhjlbcPEMt44aqUfZ2S5YJXM8v20xYO1j9CC45Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jsbn": "^1.1.0"
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@
|
|||
"normalize.css": "^8.0.1",
|
||||
"opus-decoder": "^0.7.7",
|
||||
"opus-recorder": "^8.0.5",
|
||||
"sm-crypto": "^0.3.13",
|
||||
"sm-crypto": "^0.5.8",
|
||||
"v-code-diff": "^1.16.0",
|
||||
"vue": "^2.6.14",
|
||||
"vue-axios": "^3.5.2",
|
||||
|
|
|
|||
|
|
@ -119,6 +119,10 @@ wakeup_words:
|
|||
# MCP接入点地址,地址格式为:ws://你的mcp接入点ip或者域名:端口号/mcp/?token=你的token
|
||||
# 详细教程 https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mcp-endpoint-integration.md
|
||||
mcp_endpoint: 你的接入点 websocket地址
|
||||
# 声纹识别到说话人后,是否把身份附在 MCP 接入点 tools/call 的 params._meta 上。
|
||||
# true:写入 speakerId、speakerName。未识别到说话人时不附带,请求与原来一致。
|
||||
# 工具参数本身不改。false:完全不附带。
|
||||
mcp_forward_speaker: true
|
||||
|
||||
# 上下文源配置
|
||||
# 用于在系统提示词中注入动态数据,如健康数据、股票信息等
|
||||
|
|
@ -626,6 +630,10 @@ LLM:
|
|||
max_tokens: 500 # 最大生成token数
|
||||
top_p: 1
|
||||
frequency_penalty: 0 # 频率惩罚
|
||||
# 可选: chat_template_kwargs 仅供 vLLM/SGLang 等自托管 OpenAI 兼容后端使用(请求级控制 chat template, 例如思考开关)
|
||||
# 注意: DashScope 等云服务不支持此字段, 请勿在 AliLLM 等云服务配置段启用; 此处示例仅作参数格式参考
|
||||
# chat_template_kwargs:
|
||||
# enable_thinking: true
|
||||
AliAppLLM:
|
||||
# 定义LLM API类型
|
||||
type: AliBL
|
||||
|
|
@ -668,6 +676,7 @@ LLM:
|
|||
type: ollama
|
||||
model_name: qwen2.5 # 使用的模型名称,需要预先使用ollama pull下载
|
||||
base_url: http://localhost:11434 # Ollama服务地址
|
||||
api_key: ollama # 本地部署无需真实密钥,占位即可;走鉴权网关或Ollama Cloud时修改为真实key
|
||||
DifyLLM:
|
||||
# 定义LLM API类型
|
||||
type: dify
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType
|
|||
from config.logger import setup_logging, build_module_string, create_connection_logger
|
||||
from config.manage_api_client import DeviceNotFoundException, DeviceBindException, generate_and_save_chat_title
|
||||
from core.utils.prompt_manager import PromptManager
|
||||
from core.utils.voiceprint_provider import VoiceprintProvider
|
||||
from core.utils.voiceprint_provider import VoiceprintProvider, UNKNOWN_SPEAKER_NAME
|
||||
from core.utils.util import get_system_error_response
|
||||
from core.utils import textUtils
|
||||
|
||||
|
|
@ -158,7 +158,7 @@ class ConnectionHandler:
|
|||
# 所以涉及到ASR的变量,需要在这里定义,属于connection的私有变量
|
||||
self.asr_audio = [] # 存储PCM帧列表,供VAD和ASR共享
|
||||
self.asr_audio_queue = queue.Queue()
|
||||
self.current_speaker = None # 存储当前说话人
|
||||
self.current_speaker = None # 当前说话人展示名
|
||||
self.introduced_speakers = set() # 已"首次引入"的说话人,控制只在首轮带名字
|
||||
self.system_introduced_speakers = set() # 已在 system 注入过身份的说话人,控制 system 身份只首轮出现
|
||||
|
||||
|
|
@ -916,6 +916,8 @@ class ConnectionHandler:
|
|||
self.chat_history_conf = int(private_config["chat_history_conf"])
|
||||
if private_config.get("mcp_endpoint", None) is not None:
|
||||
self.config["mcp_endpoint"] = private_config["mcp_endpoint"]
|
||||
if private_config.get("mcp_forward_speaker", None) is not None:
|
||||
self.config["mcp_forward_speaker"] = private_config["mcp_forward_speaker"]
|
||||
if private_config.get("context_providers", None) is not None:
|
||||
self.config["context_providers"] = private_config["context_providers"]
|
||||
|
||||
|
|
@ -1052,7 +1054,8 @@ class ConnectionHandler:
|
|||
# 更新系统prompt至上下文
|
||||
self.dialogue.update_system_message(self.prompt)
|
||||
|
||||
def chat(self, query, depth=0):
|
||||
def chat(self, query, depth=0, speaker=None):
|
||||
# speaker: 本轮声纹身份快照,随工具调用下传
|
||||
# 保存当前任务的sentence_id到局部变量,避免被新任务覆盖
|
||||
current_sentence_id = None
|
||||
|
||||
|
|
@ -1121,8 +1124,20 @@ class ConnectionHandler:
|
|||
# 仅在该说话人首次出现时把身份注入 system,之后靠对话历史首轮保留,
|
||||
# 避免每轮在 system 重复出现名字诱导模型反复称呼
|
||||
speaker_for_system = None
|
||||
cs = (self.current_speaker or "").strip()
|
||||
if cs and cs != "未知说话人" and cs not in self.system_introduced_speakers:
|
||||
# 展示名只取本轮数据(声纹快照 → query JSON),不读并发下会被覆盖的连接态
|
||||
cs = ""
|
||||
if speaker is not None:
|
||||
cs = (speaker.name or "").strip()
|
||||
if not cs and depth == 0 and query:
|
||||
q = query.strip()
|
||||
if q.startswith("{") and q.endswith("}"):
|
||||
try:
|
||||
parsed = json.loads(q)
|
||||
if isinstance(parsed, dict):
|
||||
cs = str(parsed.get("speaker") or "").strip()
|
||||
except (json.JSONDecodeError, TypeError, ValueError):
|
||||
pass
|
||||
if cs and cs != UNKNOWN_SPEAKER_NAME and cs not in self.system_introduced_speakers:
|
||||
self.system_introduced_speakers.add(cs)
|
||||
speaker_for_system = cs
|
||||
|
||||
|
|
@ -1337,7 +1352,7 @@ class ConnectionHandler:
|
|||
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.func_handler.handle_llm_function_call(
|
||||
self, tool_call_data
|
||||
self, tool_call_data, speaker=speaker
|
||||
),
|
||||
self.loop,
|
||||
)
|
||||
|
|
@ -1369,7 +1384,7 @@ class ConnectionHandler:
|
|||
|
||||
# 统一处理工具调用结果
|
||||
if tool_results:
|
||||
self._handle_function_result(tool_results, depth=depth, streamed_text=streamed_text)
|
||||
self._handle_function_result(tool_results, depth=depth, streamed_text=streamed_text, speaker=speaker)
|
||||
|
||||
# 存储对话内容
|
||||
if len(response_message) > 0:
|
||||
|
|
@ -1394,7 +1409,7 @@ class ConnectionHandler:
|
|||
|
||||
return True
|
||||
|
||||
def _handle_function_result(self, tool_results, depth, streamed_text=""):
|
||||
def _handle_function_result(self, tool_results, depth, streamed_text="", speaker=None):
|
||||
need_llm_tools = []
|
||||
record_tools = []
|
||||
|
||||
|
|
@ -1500,7 +1515,7 @@ class ConnectionHandler:
|
|||
)
|
||||
)
|
||||
|
||||
self.chat(None, depth=depth + 1)
|
||||
self.chat(None, depth=depth + 1, speaker=speaker)
|
||||
|
||||
def _report_worker(self):
|
||||
"""聊天记录上报工作线程"""
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType
|
|||
TAG = __name__
|
||||
|
||||
|
||||
async def handle_user_intent(conn: "ConnectionHandler", text):
|
||||
async def handle_user_intent(conn: "ConnectionHandler", text, speaker=None):
|
||||
# 预处理输入文本,处理可能的JSON格式
|
||||
try:
|
||||
if text.strip().startswith("{") and text.strip().endswith("}"):
|
||||
|
|
@ -47,7 +47,7 @@ async def handle_user_intent(conn: "ConnectionHandler", text):
|
|||
# 会话开始时生成sentence_id
|
||||
conn.sentence_id = str(uuid.uuid4().hex)
|
||||
# 处理各种意图
|
||||
return await process_intent_result(conn, intent_result, text)
|
||||
return await process_intent_result(conn, intent_result, text, speaker=speaker)
|
||||
|
||||
|
||||
async def check_direct_exit(conn: "ConnectionHandler", text):
|
||||
|
|
@ -81,7 +81,7 @@ async def analyze_intent_with_llm(conn: "ConnectionHandler", text):
|
|||
|
||||
|
||||
async def process_intent_result(
|
||||
conn: "ConnectionHandler", intent_result, original_text
|
||||
conn: "ConnectionHandler", intent_result, original_text, speaker=None
|
||||
):
|
||||
"""处理意图识别结果"""
|
||||
try:
|
||||
|
|
@ -172,7 +172,7 @@ async def process_intent_result(
|
|||
try:
|
||||
result = asyncio.run_coroutine_threadsafe(
|
||||
conn.func_handler.handle_llm_function_call(
|
||||
conn, function_call_data
|
||||
conn, function_call_data, speaker=speaker
|
||||
),
|
||||
conn.loop,
|
||||
).result(timeout=tool_call_timeout)
|
||||
|
|
|
|||
|
|
@ -40,7 +40,8 @@ async def resume_vad_detection(conn: "ConnectionHandler"):
|
|||
conn.just_woken_up = False
|
||||
|
||||
|
||||
async def startToChat(conn: "ConnectionHandler", text):
|
||||
async def startToChat(conn: "ConnectionHandler", text, speaker=None):
|
||||
"""speaker: 本轮声纹身份快照,随调用链传递。"""
|
||||
# 检查输入是否是JSON格式(包含说话人信息)
|
||||
speaker_name = None
|
||||
actual_text = text
|
||||
|
|
@ -69,11 +70,8 @@ async def startToChat(conn: "ConnectionHandler", text):
|
|||
# 如果解析失败,继续使用原始文本
|
||||
pass
|
||||
|
||||
# 保存说话人信息到连接对象
|
||||
if speaker_name:
|
||||
conn.current_speaker = speaker_name
|
||||
else:
|
||||
conn.current_speaker = None
|
||||
# 说话人名供提示词注入;声纹身份走 speaker 快照,不挂连接
|
||||
conn.current_speaker = speaker_name
|
||||
|
||||
if conn.need_bind:
|
||||
await check_bind_device(conn)
|
||||
|
|
@ -92,7 +90,7 @@ async def startToChat(conn: "ConnectionHandler", text):
|
|||
await handleAbortMessage(conn)
|
||||
|
||||
# 首先进行意图分析,使用实际文本内容
|
||||
intent_handled = await handle_user_intent(conn, actual_text)
|
||||
intent_handled = await handle_user_intent(conn, actual_text, speaker=speaker)
|
||||
|
||||
if intent_handled:
|
||||
# 如果意图已被处理,不再进行聊天
|
||||
|
|
@ -104,7 +102,7 @@ async def startToChat(conn: "ConnectionHandler", text):
|
|||
# 准备开始新会话
|
||||
conn.client_abort = False
|
||||
|
||||
conn.executor.submit(conn.chat, actual_text)
|
||||
conn.executor.submit(conn.chat, actual_text, depth=0, speaker=speaker)
|
||||
|
||||
|
||||
async def no_voice_close_connect(conn: "ConnectionHandler", have_voice):
|
||||
|
|
|
|||
|
|
@ -106,8 +106,8 @@ class ListenTextMessageHandler(TextMessageHandler):
|
|||
elif is_wakeup_words:
|
||||
conn.just_woken_up = True
|
||||
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
||||
enqueue_asr_report(conn, "嘿,你好呀", [])
|
||||
await startToChat(conn, "嘿,你好呀")
|
||||
enqueue_asr_report(conn, filtered_text, [])
|
||||
await startToChat(conn, filtered_text)
|
||||
else:
|
||||
conn.just_woken_up = True
|
||||
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ from core.providers.asr.dto.dto import InterfaceType
|
|||
from core.handle.receiveAudioHandle import startToChat
|
||||
from core.handle.reportHandle import enqueue_asr_report
|
||||
from core.utils.util import remove_punctuation_and_length
|
||||
from core.utils.voiceprint_provider import SpeakerIdentification
|
||||
from core.handle.receiveAudioHandle import handleAudioMessage
|
||||
from typing import Optional, Tuple, List, NamedTuple, TYPE_CHECKING
|
||||
|
||||
|
|
@ -101,7 +102,7 @@ class ASRProviderBase(ABC):
|
|||
)
|
||||
|
||||
if conn.voiceprint_provider and wav_data:
|
||||
voiceprint_task = conn.voiceprint_provider.identify_speaker(
|
||||
voiceprint_task = conn.voiceprint_provider.identify_speaker_detail(
|
||||
wav_data, conn.session_id
|
||||
)
|
||||
# 并发等待两个结果
|
||||
|
|
@ -119,11 +120,11 @@ class ASRProviderBase(ABC):
|
|||
else:
|
||||
raw_text, _ = asr_result
|
||||
|
||||
speaker_name = ""
|
||||
if isinstance(voiceprint_result, Exception):
|
||||
logger.bind(tag=TAG).error(f"声纹识别失败: {voiceprint_result}")
|
||||
speaker_name = ""
|
||||
else:
|
||||
speaker_name = voiceprint_result
|
||||
elif voiceprint_result is not None:
|
||||
speaker_name = voiceprint_result.name or ""
|
||||
|
||||
# 判断 ASR 结果类型
|
||||
if isinstance(raw_text, dict):
|
||||
|
|
@ -164,10 +165,16 @@ class ASRProviderBase(ABC):
|
|||
self.stop_ws_connection()
|
||||
|
||||
if text_len > 0:
|
||||
# 本轮声纹身份快照,随调用链供 MCP 接入点工具使用
|
||||
speaker = (
|
||||
voiceprint_result
|
||||
if isinstance(voiceprint_result, SpeakerIdentification)
|
||||
else None
|
||||
)
|
||||
audio_snapshot = asr_audio_task.copy()
|
||||
enqueue_asr_report(conn, enhanced_text, audio_snapshot)
|
||||
# 使用自定义模块进行上报
|
||||
await startToChat(conn, enhanced_text)
|
||||
await startToChat(conn, enhanced_text, speaker=speaker)
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
|
||||
import traceback
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
from config.logger import setup_logging
|
||||
from openai import OpenAI
|
||||
from urllib.parse import urlsplit
|
||||
import json
|
||||
from core.providers.llm.base import LLMProviderBase
|
||||
|
||||
|
|
@ -10,15 +11,20 @@ logger = setup_logging()
|
|||
class LLMProvider(LLMProviderBase):
|
||||
def __init__(self, config):
|
||||
self.model_name = config.get("model_name")
|
||||
self.base_url = config.get("base_url", "http://localhost:11434")
|
||||
self.base_url = (
|
||||
str(config.get("base_url") or "").strip() or "http://localhost:11434"
|
||||
).rstrip("/")
|
||||
# 兼容处理用户输入完整端点的情况
|
||||
if self.base_url.endswith("/chat/completions"):
|
||||
self.base_url = self.base_url[:-len("/chat/completions")].rstrip("/")
|
||||
# Initialize OpenAI client with Ollama base URL
|
||||
# 如果没有v1,增加v1
|
||||
if not self.base_url.endswith("/v1"):
|
||||
# 纯主机地址补/v1(Ollama默认约定);带路径的地址尊重用户输入,不再改写
|
||||
if not urlsplit(self.base_url).path.strip("/"):
|
||||
self.base_url = f"{self.base_url}/v1"
|
||||
|
||||
self.client = OpenAI(
|
||||
base_url=self.base_url,
|
||||
api_key="ollama", # Ollama doesn't need an API key but OpenAI client requires one
|
||||
api_key=config.get("api_key") or "ollama",
|
||||
)
|
||||
|
||||
# 检查是否是qwen3模型
|
||||
|
|
|
|||
|
|
@ -31,6 +31,13 @@ class LLMProvider(LLMProviderBase):
|
|||
# 可选实例级思考强度: off/disabled/none/disable | low/medium/high | 空/其他=按域名默认
|
||||
self.thinking_mode = str(config.get("thinking") or "").strip().lower()
|
||||
self.api_key = config.get("api_key")
|
||||
# 可选: 透传给后端的 chat_template_kwargs(供 vLLM/SGLang 等自托管 OpenAI 兼容后端使用)
|
||||
chat_template_kwargs = config.get("chat_template_kwargs")
|
||||
if chat_template_kwargs and not isinstance(chat_template_kwargs, dict):
|
||||
logger.bind(tag=TAG).warning(
|
||||
f"chat_template_kwargs 配置格式错误, 应为键值对象, 已忽略: {chat_template_kwargs!r}")
|
||||
chat_template_kwargs = None
|
||||
self.chat_template_kwargs = chat_template_kwargs or {}
|
||||
if "base_url" in config:
|
||||
self.base_url = config.get("base_url")
|
||||
else:
|
||||
|
|
@ -117,6 +124,11 @@ class LLMProvider(LLMProviderBase):
|
|||
logger.bind(tag=TAG).info(f"为域名 {domain} 禁用思考模式,参数: {params}")
|
||||
break
|
||||
|
||||
def _apply_chat_template_kwargs(self, request_params: dict):
|
||||
"""透传 chat_template_kwargs 到 extra_body(仅 vLLM/SGLang 等自托管 OpenAI 兼容后端识别, 云服务会忽略)"""
|
||||
if self.chat_template_kwargs:
|
||||
request_params.setdefault("extra_body", {})["chat_template_kwargs"] = self.chat_template_kwargs
|
||||
|
||||
def response(self, session_id, dialogue, **kwargs):
|
||||
dialogue = self.normalize_dialogue(dialogue)
|
||||
|
||||
|
|
@ -140,6 +152,7 @@ class LLMProvider(LLMProviderBase):
|
|||
|
||||
# 禁用思考模式
|
||||
self._apply_thinking_disabled(request_params)
|
||||
self._apply_chat_template_kwargs(request_params)
|
||||
|
||||
responses = self.client.chat.completions.create(**request_params)
|
||||
|
||||
|
|
@ -186,6 +199,7 @@ class LLMProvider(LLMProviderBase):
|
|||
|
||||
# 禁用思考模式
|
||||
self._apply_thinking_disabled(request_params)
|
||||
self._apply_chat_template_kwargs(request_params)
|
||||
|
||||
stream = self.client.chat.completions.create(**request_params)
|
||||
|
||||
|
|
|
|||
|
|
@ -11,9 +11,9 @@ class ToolExecutor(ABC):
|
|||
|
||||
@abstractmethod
|
||||
async def execute(
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行工具调用"""
|
||||
"""执行工具调用。speaker: 可选的说话人身份快照。"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class DeviceIoTExecutor(ToolExecutor):
|
|||
self.iot_tools: Dict[str, ToolDefinition] = {}
|
||||
|
||||
async def execute(
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行设备端IoT工具"""
|
||||
if not self.has_tool(tool_name):
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ class DeviceMCPExecutor(ToolExecutor):
|
|||
self.conn = conn
|
||||
|
||||
async def execute(
|
||||
self, conn: "ConnectionHandler", tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn: "ConnectionHandler", tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行设备端MCP工具"""
|
||||
if not hasattr(conn, "mcp_client") or not conn.mcp_client:
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
"""MCP接入点工具执行器"""
|
||||
|
||||
from typing import Dict, Any
|
||||
from typing import Dict, Any, Optional
|
||||
from ..base import ToolType, ToolDefinition, ToolExecutor
|
||||
from plugins_func.register import Action, ActionResponse
|
||||
from core.utils.voiceprint_provider import SpeakerIdentification
|
||||
from .mcp_endpoint_handler import call_mcp_endpoint_tool
|
||||
from .mcp_speaker import should_forward_speaker, speaker_call_meta
|
||||
|
||||
|
||||
class MCPEndpointExecutor(ToolExecutor):
|
||||
|
|
@ -13,9 +15,9 @@ class MCPEndpointExecutor(ToolExecutor):
|
|||
self.conn = conn
|
||||
|
||||
async def execute(
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any], speaker: Optional[SpeakerIdentification] = None
|
||||
) -> ActionResponse:
|
||||
"""执行MCP接入点工具"""
|
||||
"""执行MCP接入点工具。speaker: 本轮说话人快照。"""
|
||||
if not hasattr(conn, "mcp_endpoint_client") or not conn.mcp_endpoint_client:
|
||||
return ActionResponse(
|
||||
action=Action.ERROR,
|
||||
|
|
@ -29,14 +31,20 @@ class MCPEndpointExecutor(ToolExecutor):
|
|||
)
|
||||
|
||||
try:
|
||||
# 转换参数为JSON字符串
|
||||
# 转换参数为JSON字符串。说话人身份不写入参数,只放在 _meta。
|
||||
import json
|
||||
|
||||
meta = None
|
||||
if speaker is not None and should_forward_speaker(
|
||||
getattr(conn, "config", None)
|
||||
):
|
||||
meta = speaker_call_meta(speaker.speaker_id, speaker.name)
|
||||
|
||||
args_str = json.dumps(arguments) if arguments else "{}"
|
||||
|
||||
# 调用MCP接入点工具
|
||||
result = await call_mcp_endpoint_tool(
|
||||
conn.mcp_endpoint_client, tool_name, args_str
|
||||
conn.mcp_endpoint_client, tool_name, args_str, meta=meta
|
||||
)
|
||||
|
||||
resultJson = None
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import re
|
|||
import websockets
|
||||
from config.logger import setup_logging
|
||||
from .mcp_endpoint_client import MCPEndpointClient
|
||||
from .mcp_speaker import build_mcp_endpoint_tool_payload
|
||||
|
||||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
|
@ -284,7 +285,11 @@ async def send_mcp_endpoint_tools_list_continue(
|
|||
|
||||
|
||||
async def call_mcp_endpoint_tool(
|
||||
mcp_client: MCPEndpointClient, tool_name: str, args: str = "{}", timeout: int = 30
|
||||
mcp_client: MCPEndpointClient,
|
||||
tool_name: str,
|
||||
args: str = "{}",
|
||||
timeout: int = 30,
|
||||
meta: dict = None,
|
||||
):
|
||||
"""
|
||||
调用指定的MCP接入点工具,并等待响应
|
||||
|
|
@ -350,16 +355,17 @@ async def call_mcp_endpoint_tool(
|
|||
raise e
|
||||
|
||||
actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
|
||||
payload = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": tool_call_id,
|
||||
"method": "tools/call",
|
||||
"params": {"name": actual_name, "arguments": arguments},
|
||||
}
|
||||
payload = build_mcp_endpoint_tool_payload(
|
||||
tool_call_id, actual_name, arguments, meta
|
||||
)
|
||||
|
||||
message = json.dumps(payload)
|
||||
log_suffix = ""
|
||||
if meta:
|
||||
# 只记是否附带身份及字段名,不输出 speakerId/speakerName 明文
|
||||
log_suffix = f",_meta: 附带身份字段 {list(meta.keys())}"
|
||||
logger.bind(tag=TAG).info(
|
||||
f"发送MCP接入点工具调用请求: {actual_name},参数: {json.dumps(arguments, ensure_ascii=False)}"
|
||||
f"发送MCP接入点工具调用请求: {actual_name},参数: {json.dumps(arguments, ensure_ascii=False)}{log_suffix}"
|
||||
)
|
||||
await mcp_client.send_message(message)
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,51 @@
|
|||
"""把已识别的说话人附到 MCP 接入点 tools/call 上。
|
||||
|
||||
工具参数保持模型给出的原样。身份放在 MCP 的 params._meta 里,
|
||||
接入点上的服务可以读取,不读的服务按协议忽略。
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from core.utils.voiceprint_provider import UNKNOWN_SPEAKER_NAME
|
||||
|
||||
|
||||
def should_forward_speaker(config: Optional[dict]) -> bool:
|
||||
"""mcp_forward_speaker 缺省为开启。显式 false 时不附带身份。"""
|
||||
if not isinstance(config, dict):
|
||||
return True
|
||||
value = config.get("mcp_forward_speaker", True)
|
||||
if value is None:
|
||||
return True
|
||||
return str(value).strip().lower() in ("true", "1", "yes")
|
||||
|
||||
|
||||
def speaker_call_meta(speaker_id: Any, speaker_name: Any) -> Optional[Dict[str, str]]:
|
||||
"""有真实身份时返回 _meta;没有则返回 None,调用方不写这个字段。"""
|
||||
meta: Dict[str, str] = {}
|
||||
if isinstance(speaker_id, str):
|
||||
speaker_id = speaker_id.strip()
|
||||
if speaker_id:
|
||||
meta["speakerId"] = speaker_id
|
||||
if isinstance(speaker_name, str):
|
||||
speaker_name = speaker_name.strip()
|
||||
if speaker_name and speaker_name != UNKNOWN_SPEAKER_NAME:
|
||||
meta["speakerName"] = speaker_name
|
||||
return meta or None
|
||||
|
||||
|
||||
def build_mcp_endpoint_tool_payload(
|
||||
tool_call_id: int,
|
||||
name: str,
|
||||
arguments: Dict[str, Any],
|
||||
meta: Optional[Dict[str, str]] = None,
|
||||
) -> dict:
|
||||
"""组装 tools/call。meta 为空时不出现 _meta,参数字典原样放进 arguments。"""
|
||||
params: Dict[str, Any] = {"name": name, "arguments": arguments}
|
||||
if meta:
|
||||
params["_meta"] = meta
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": tool_call_id,
|
||||
"method": "tools/call",
|
||||
"params": params,
|
||||
}
|
||||
|
|
@ -22,7 +22,7 @@ class ServerMCPExecutor(ToolExecutor):
|
|||
await self.mcp_manager.initialize_servers()
|
||||
|
||||
async def execute(
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn, tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行服务端MCP工具"""
|
||||
if not self._initialized or not self.mcp_manager:
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ class ServerPluginExecutor(ToolExecutor):
|
|||
self.config = conn.config
|
||||
|
||||
async def execute(
|
||||
self, conn: "ConnectionHandler", tool_name: str, arguments: Dict[str, Any]
|
||||
self, conn: "ConnectionHandler", tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行服务端插件工具"""
|
||||
func_item = all_function_registry.get(tool_name)
|
||||
|
|
|
|||
|
|
@ -137,16 +137,16 @@ class UnifiedToolHandler:
|
|||
return self.tool_manager.has_tool(tool_name)
|
||||
|
||||
async def handle_llm_function_call(
|
||||
self, conn, function_call_data: Dict[str, Any]
|
||||
self, conn, function_call_data: Dict[str, Any], speaker=None
|
||||
) -> Optional[ActionResponse]:
|
||||
"""处理LLM函数调用"""
|
||||
"""处理LLM函数调用。speaker: 本轮说话人快照。"""
|
||||
try:
|
||||
# 处理多函数调用
|
||||
if "function_calls" in function_call_data:
|
||||
responses = []
|
||||
for call in function_call_data["function_calls"]:
|
||||
result = await self.tool_manager.execute_tool(
|
||||
call["name"], call.get("arguments", {})
|
||||
call["name"], call.get("arguments", {}), speaker=speaker
|
||||
)
|
||||
responses.append(result)
|
||||
return self._combine_responses(responses)
|
||||
|
|
@ -175,7 +175,9 @@ class UnifiedToolHandler:
|
|||
self.logger.warning(f"发送工具调用显示消息失败: {e}")
|
||||
|
||||
# 执行工具调用
|
||||
result = await self.tool_manager.execute_tool(function_name, arguments)
|
||||
result = await self.tool_manager.execute_tool(
|
||||
function_name, arguments, speaker=speaker
|
||||
)
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
|
|
|
|||
|
|
@ -74,9 +74,9 @@ class ToolManager:
|
|||
return tool_def.tool_type if tool_def else None
|
||||
|
||||
async def execute_tool(
|
||||
self, tool_name: str, arguments: Dict[str, Any]
|
||||
self, tool_name: str, arguments: Dict[str, Any], speaker=None
|
||||
) -> ActionResponse:
|
||||
"""执行工具调用"""
|
||||
"""执行工具调用。speaker: 本轮说话人快照。"""
|
||||
try:
|
||||
# 查找工具类型
|
||||
tool_type = self.get_tool_type(tool_name)
|
||||
|
|
@ -96,7 +96,7 @@ class ToolManager:
|
|||
|
||||
# 执行工具
|
||||
self.logger.info(f"执行工具: {tool_name},参数: {arguments}")
|
||||
result = await executor.execute(self.conn, tool_name, arguments)
|
||||
result = await executor.execute(self.conn, tool_name, arguments, speaker=speaker)
|
||||
self.logger.debug(f"工具执行结果: {result}")
|
||||
return result
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ import re
|
|||
from typing import List, Dict
|
||||
from datetime import datetime
|
||||
|
||||
from core.utils.voiceprint_provider import UNKNOWN_SPEAKER_NAME
|
||||
|
||||
|
||||
class Message:
|
||||
def __init__(
|
||||
|
|
@ -125,7 +127,7 @@ class Dialogue:
|
|||
current_speaker_name = (current_speaker or "").strip()
|
||||
# 仅在本轮注入了有效身份时才输出 speakers_info,避免列表里的名字每轮
|
||||
# 重复出现诱导模型反复称呼;后续轮不再注入身份,靠对话历史首轮保留
|
||||
if current_speaker_name and current_speaker_name != "未知说话人":
|
||||
if current_speaker_name and current_speaker_name != UNKNOWN_SPEAKER_NAME:
|
||||
speakers = voiceprint_config.get("speakers", [])
|
||||
speakers_info = "\n<speakers_info>"
|
||||
speakers_info += f"\n当前说话人:{current_speaker_name}"
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import time
|
|||
import aiohttp
|
||||
import requests
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
from typing import Optional, Dict
|
||||
from typing import Optional, Dict, NamedTuple
|
||||
from config.logger import setup_logging
|
||||
from core.utils.cache.manager import cache_manager
|
||||
from core.utils.cache.config import CacheType
|
||||
|
|
@ -11,6 +11,30 @@ from core.utils.cache.config import CacheType
|
|||
TAG = __name__
|
||||
logger = setup_logging()
|
||||
|
||||
# 未命中声纹时沿用的展示名。下游只把这个名字交给 LLM,不把它当成真实身份。
|
||||
UNKNOWN_SPEAKER_NAME = "未知说话人"
|
||||
|
||||
|
||||
class SpeakerIdentification(NamedTuple):
|
||||
"""一次声纹识别结果。speaker_id 仅在命中已配置说话人时有值。"""
|
||||
|
||||
speaker_id: Optional[str]
|
||||
name: str
|
||||
|
||||
|
||||
def resolve_speaker_identification(
|
||||
speaker_id: Optional[str],
|
||||
score: float,
|
||||
speaker_map: Dict[str, Dict[str, str]],
|
||||
similarity_threshold: float,
|
||||
) -> SpeakerIdentification:
|
||||
"""把声纹接口返回的 speaker_id / score 解析成展示名,并保留命中的 id。"""
|
||||
if score < similarity_threshold:
|
||||
return SpeakerIdentification(None, UNKNOWN_SPEAKER_NAME)
|
||||
if speaker_id and speaker_id in speaker_map:
|
||||
return SpeakerIdentification(speaker_id, speaker_map[speaker_id]["name"])
|
||||
return SpeakerIdentification(None, UNKNOWN_SPEAKER_NAME)
|
||||
|
||||
|
||||
class VoiceprintProvider:
|
||||
"""声纹识别服务提供者"""
|
||||
|
|
@ -138,7 +162,16 @@ class VoiceprintProvider:
|
|||
return is_healthy
|
||||
|
||||
async def identify_speaker(self, audio_data: bytes, session_id: str) -> Optional[str]:
|
||||
"""识别说话人"""
|
||||
"""识别说话人,返回展示名。需要 speaker_id 时用 identify_speaker_detail。"""
|
||||
identified = await self.identify_speaker_detail(audio_data, session_id)
|
||||
if identified is None:
|
||||
return None
|
||||
return identified.name
|
||||
|
||||
async def identify_speaker_detail(
|
||||
self, audio_data: bytes, session_id: str
|
||||
) -> Optional[SpeakerIdentification]:
|
||||
"""识别说话人,同时返回声纹 id 和展示名。"""
|
||||
if not self.enabled or not self.api_url or not self.api_key:
|
||||
logger.bind(tag=TAG).debug("声纹识别功能已禁用或未配置,跳过识别")
|
||||
return None
|
||||
|
|
@ -171,18 +204,19 @@ class VoiceprintProvider:
|
|||
|
||||
logger.bind(tag=TAG).info(f"声纹识别耗时: {total_elapsed_time:.3f}s")
|
||||
|
||||
# 相似度阈值检查
|
||||
if score < self.similarity_threshold:
|
||||
identified = resolve_speaker_identification(
|
||||
speaker_id, score, self.speaker_map, self.similarity_threshold
|
||||
)
|
||||
# 三种结果:命中 / 低于阈值 / id不在配置中
|
||||
if identified.speaker_id:
|
||||
logger.bind(tag=TAG).info(
|
||||
f"声纹识别成功: {identified.name} (id: {identified.speaker_id}, 相似度: {score:.3f})"
|
||||
)
|
||||
elif score < self.similarity_threshold:
|
||||
logger.bind(tag=TAG).warning(f"声纹识别相似度{score:.3f}低于阈值{self.similarity_threshold}")
|
||||
return "未知说话人"
|
||||
|
||||
if speaker_id and speaker_id in self.speaker_map:
|
||||
result_name = self.speaker_map[speaker_id]["name"]
|
||||
logger.bind(tag=TAG).info(f"声纹识别成功: {result_name} (相似度: {score:.3f})")
|
||||
return result_name
|
||||
else:
|
||||
logger.bind(tag=TAG).warning(f"未识别的说话人ID: {speaker_id}")
|
||||
return "未知说话人"
|
||||
return identified
|
||||
else:
|
||||
logger.bind(tag=TAG).error(f"声纹识别API错误: HTTP {response.status}")
|
||||
return None
|
||||
|
|
|
|||
|
|
@ -119,7 +119,12 @@ class LLMPerformanceTester:
|
|||
return chunks, first_token_time
|
||||
|
||||
async def _check_ollama_service(self, base_url: str, model_name: str) -> bool:
|
||||
"""异步检查 Ollama 服务状态"""
|
||||
"""异步检查 Ollama 服务状态(兼容带/v1或完整端点的base_url写法)"""
|
||||
base_url = base_url.strip().rstrip("/")
|
||||
if base_url.endswith("/chat/completions"):
|
||||
base_url = base_url[: -len("/chat/completions")].rstrip("/")
|
||||
if base_url.endswith("/v1"):
|
||||
base_url = base_url[: -len("/v1")].rstrip("/")
|
||||
async with aiohttp.ClientSession() as session:
|
||||
try:
|
||||
async with session.get(f"{base_url}/api/version") as response:
|
||||
|
|
@ -230,7 +235,7 @@ class LLMPerformanceTester:
|
|||
"""异步测试单个 LLM 性能"""
|
||||
try:
|
||||
# 对于 Ollama,跳过 api_key 检查并进行特殊处理
|
||||
if llm_name == "Ollama":
|
||||
if llm_name == "OllamaLLM" or str(config.get("type", "")).lower() == "ollama":
|
||||
base_url = config.get("base_url", "http://localhost:11434")
|
||||
model_name = config.get("model_name")
|
||||
if not model_name:
|
||||
|
|
@ -474,7 +479,7 @@ class LLMPerformanceTester:
|
|||
continue
|
||||
|
||||
# 对于 Ollama,先检查服务状态
|
||||
if llm_name == "Ollama":
|
||||
if llm_name == "OllamaLLM" or str(config.get("type", "")).lower() == "ollama":
|
||||
base_url = config.get("base_url", "http://localhost:11434")
|
||||
model_name = config.get("model_name")
|
||||
if not model_name:
|
||||
|
|
|
|||
|
|
@ -203,7 +203,8 @@ def get_provider_type(module: str, provider_name: str | None = None) -> str | No
|
|||
def has_real_key(config: dict, *keys: str) -> bool:
|
||||
"""任一候选 key 名下值不是占位符就算有真密钥。
|
||||
|
||||
占位符判定:空 / "你的..." / 包含 "placeholder" / 字面 "none"。
|
||||
占位符判定:空 / "你的..." / 包含 "placeholder" / 字面 "none" / "ollama"
|
||||
(Ollama本地服务无需鉴权,config.yaml默认占位值即为"ollama")。
|
||||
"""
|
||||
if not config:
|
||||
return False
|
||||
|
|
@ -212,7 +213,7 @@ def has_real_key(config: dict, *keys: str) -> bool:
|
|||
if val is None:
|
||||
continue
|
||||
s = str(val).strip().lower()
|
||||
if not s or s == "none":
|
||||
if not s or s == "none" or s == "ollama":
|
||||
continue
|
||||
if s.startswith("你的") or "placeholder" in s:
|
||||
continue
|
||||
|
|
@ -399,6 +400,9 @@ def _check_modules_ready() -> None:
|
|||
f"{module}.{provider_name} 配置缺失(CFG 字典里没这个 provider)"
|
||||
)
|
||||
continue
|
||||
# Ollama免鉴权供应器无需真实key,跳过占位符检查
|
||||
if str(cfg.get("type", "")).lower() == "ollama":
|
||||
continue
|
||||
secret_keys_present = [k for k in _SECRET_FIELDS if k in cfg]
|
||||
if secret_keys_present and not any(
|
||||
has_real_key(cfg, k) for k in secret_keys_present
|
||||
|
|
|
|||
|
|
@ -0,0 +1,164 @@
|
|||
"""MCP 接入点 tools/call 通过 _meta 携带说话人,不改工具参数。"""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from core.providers.tools.mcp_endpoint.mcp_speaker import (
|
||||
build_mcp_endpoint_tool_payload,
|
||||
should_forward_speaker,
|
||||
speaker_call_meta,
|
||||
)
|
||||
from core.utils.voiceprint_provider import UNKNOWN_SPEAKER_NAME, SpeakerIdentification
|
||||
|
||||
|
||||
def test_meta_includes_id_and_name():
|
||||
assert speaker_call_meta(" test1 ", " 张三 ") == {
|
||||
"speakerId": "test1",
|
||||
"speakerName": "张三",
|
||||
}
|
||||
|
||||
|
||||
def test_meta_omits_unknown_speaker_and_blank_id():
|
||||
assert speaker_call_meta(None, UNKNOWN_SPEAKER_NAME) is None
|
||||
assert speaker_call_meta(" ", "张三") == {"speakerName": "张三"}
|
||||
assert speaker_call_meta("test1", UNKNOWN_SPEAKER_NAME) == {"speakerId": "test1"}
|
||||
|
||||
|
||||
def test_forwarding_defaults_on_and_can_be_disabled():
|
||||
assert should_forward_speaker(None) is True
|
||||
assert should_forward_speaker({}) is True
|
||||
assert should_forward_speaker({"mcp_forward_speaker": True}) is True
|
||||
assert should_forward_speaker({"mcp_forward_speaker": False}) is False
|
||||
# 字符串 false 可关闭;空值视为缺省开启
|
||||
assert should_forward_speaker({"mcp_forward_speaker": "false"}) is False
|
||||
assert should_forward_speaker({"mcp_forward_speaker": "False"}) is False
|
||||
assert should_forward_speaker({"mcp_forward_speaker": "0"}) is False
|
||||
assert should_forward_speaker({"mcp_forward_speaker": "true"}) is True
|
||||
assert should_forward_speaker({"mcp_forward_speaker": None}) is True
|
||||
# 空串按关闭处理,与 manager-api 的 Boolean.parseBoolean("") 一致
|
||||
assert should_forward_speaker({"mcp_forward_speaker": ""}) is False
|
||||
|
||||
|
||||
def test_payload_adds_meta_without_touching_arguments():
|
||||
arguments = {"name": "灯"}
|
||||
payload = build_mcp_endpoint_tool_payload(
|
||||
7,
|
||||
"HassTurnOn",
|
||||
arguments,
|
||||
{"speakerId": "test1", "speakerName": "张三"},
|
||||
)
|
||||
assert payload["method"] == "tools/call"
|
||||
assert payload["params"]["arguments"] is arguments
|
||||
assert "speakerId" not in arguments
|
||||
assert payload["params"]["_meta"]["speakerId"] == "test1"
|
||||
|
||||
|
||||
def test_payload_without_meta_matches_previous_shape():
|
||||
payload = build_mcp_endpoint_tool_payload(7, "calculator", {"a": 1})
|
||||
assert set(payload["params"]) == {"name", "arguments"}
|
||||
assert "_meta" not in payload["params"]
|
||||
|
||||
|
||||
class _Client:
|
||||
async def is_ready(self):
|
||||
return True
|
||||
|
||||
|
||||
class _Conn:
|
||||
def __init__(self, config=None):
|
||||
self.mcp_endpoint_client = _Client()
|
||||
self.config = {} if config is None else config
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_executor_forwards_speaker_in_meta_only(monkeypatch):
|
||||
from core.providers.tools.mcp_endpoint import mcp_endpoint_executor as executor_mod
|
||||
|
||||
captured = {}
|
||||
|
||||
async def fake_call(client, tool_name, args_str="{}", timeout=30, meta=None):
|
||||
captured["tool_name"] = tool_name
|
||||
captured["args"] = args_str
|
||||
captured["meta"] = meta
|
||||
return "done"
|
||||
|
||||
monkeypatch.setattr(executor_mod, "call_mcp_endpoint_tool", fake_call)
|
||||
arguments = {"area": "客厅"}
|
||||
conn = _Conn()
|
||||
result = await executor_mod.MCPEndpointExecutor(conn).execute(
|
||||
conn,
|
||||
"HassTurnOn",
|
||||
arguments,
|
||||
speaker=SpeakerIdentification("test1", "张三"),
|
||||
)
|
||||
|
||||
assert json.loads(captured["args"]) == {"area": "客厅"}
|
||||
assert captured["meta"] == {"speakerId": "test1", "speakerName": "张三"}
|
||||
assert arguments == {"area": "客厅"}
|
||||
assert result.result == "done"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_executor_skips_meta_when_disabled(monkeypatch):
|
||||
from core.providers.tools.mcp_endpoint import mcp_endpoint_executor as executor_mod
|
||||
|
||||
captured = {}
|
||||
|
||||
async def fake_call(client, tool_name, args_str="{}", timeout=30, meta=None):
|
||||
captured["meta"] = meta
|
||||
return "done"
|
||||
|
||||
monkeypatch.setattr(executor_mod, "call_mcp_endpoint_tool", fake_call)
|
||||
conn = _Conn(config={"mcp_forward_speaker": False})
|
||||
await executor_mod.MCPEndpointExecutor(conn).execute(
|
||||
conn,
|
||||
"HassTurnOn",
|
||||
{"area": "客厅"},
|
||||
speaker=SpeakerIdentification("test1", "张三"),
|
||||
)
|
||||
assert captured["meta"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_executor_omits_meta_for_unknown_speaker(monkeypatch):
|
||||
from core.providers.tools.mcp_endpoint import mcp_endpoint_executor as executor_mod
|
||||
|
||||
captured = {}
|
||||
|
||||
async def fake_call(client, tool_name, args_str="{}", timeout=30, meta=None):
|
||||
captured["meta"] = meta
|
||||
return "done"
|
||||
|
||||
monkeypatch.setattr(executor_mod, "call_mcp_endpoint_tool", fake_call)
|
||||
conn = _Conn()
|
||||
await executor_mod.MCPEndpointExecutor(conn).execute(
|
||||
conn,
|
||||
"HassTurnOn",
|
||||
{},
|
||||
speaker=SpeakerIdentification(None, UNKNOWN_SPEAKER_NAME),
|
||||
)
|
||||
assert captured["meta"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_executor_reads_snapshot_not_conn_state(monkeypatch):
|
||||
"""meta 取自快照,不受连接态影响。"""
|
||||
from core.providers.tools.mcp_endpoint import mcp_endpoint_executor as executor_mod
|
||||
|
||||
captured = {}
|
||||
|
||||
async def fake_call(client, tool_name, args_str="{}", timeout=30, meta=None):
|
||||
captured["meta"] = meta
|
||||
return "done"
|
||||
|
||||
monkeypatch.setattr(executor_mod, "call_mcp_endpoint_tool", fake_call)
|
||||
conn = _Conn()
|
||||
# 模拟并发场景:连接态已被下一轮覆盖成另一个人,meta 仍必须取自快照
|
||||
conn.current_speaker = "旧说话人"
|
||||
await executor_mod.MCPEndpointExecutor(conn).execute(
|
||||
conn,
|
||||
"HassTurnOn",
|
||||
{},
|
||||
speaker=SpeakerIdentification("test1", "张三"),
|
||||
)
|
||||
assert captured["meta"] == {"speakerId": "test1", "speakerName": "张三"}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
"""声纹识别结果要同时保留 speaker_id 和展示名。"""
|
||||
import aiohttp
|
||||
import pytest
|
||||
|
||||
from core.utils.voiceprint_provider import (
|
||||
UNKNOWN_SPEAKER_NAME,
|
||||
VoiceprintProvider,
|
||||
resolve_speaker_identification,
|
||||
)
|
||||
|
||||
SPEAKERS = {"test1": {"name": "张三", "description": "程序员"}}
|
||||
|
||||
|
||||
def test_matched_speaker_keeps_id_and_name():
|
||||
identified = resolve_speaker_identification("test1", 0.91, SPEAKERS, 0.4)
|
||||
assert identified.speaker_id == "test1"
|
||||
assert identified.name == "张三"
|
||||
|
||||
|
||||
def test_score_equal_to_threshold_still_matches():
|
||||
identified = resolve_speaker_identification("test1", 0.4, SPEAKERS, 0.4)
|
||||
assert identified.speaker_id == "test1"
|
||||
|
||||
|
||||
def test_low_score_hides_id_and_uses_unknown_name():
|
||||
identified = resolve_speaker_identification("test1", 0.39, SPEAKERS, 0.4)
|
||||
assert identified.speaker_id is None
|
||||
assert identified.name == UNKNOWN_SPEAKER_NAME
|
||||
|
||||
|
||||
def test_unconfigured_speaker_id_is_unknown():
|
||||
identified = resolve_speaker_identification("other", 0.99, SPEAKERS, 0.4)
|
||||
assert identified.speaker_id is None
|
||||
assert identified.name == UNKNOWN_SPEAKER_NAME
|
||||
|
||||
|
||||
class _Response:
|
||||
def __init__(self, status, payload):
|
||||
self.status = status
|
||||
self._payload = payload
|
||||
|
||||
async def json(self):
|
||||
return self._payload
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb):
|
||||
return False
|
||||
|
||||
|
||||
class _Session:
|
||||
def __init__(self, response):
|
||||
self._response = response
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb):
|
||||
return False
|
||||
|
||||
def post(self, *args, **kwargs):
|
||||
return self._response
|
||||
|
||||
|
||||
def _enabled_provider():
|
||||
provider = VoiceprintProvider({})
|
||||
provider.enabled = True
|
||||
provider.api_url = "http://voiceprint.local/voiceprint/identify"
|
||||
provider.api_key = "k"
|
||||
provider.speaker_ids = ["test1"]
|
||||
provider.speaker_map = SPEAKERS
|
||||
provider.similarity_threshold = 0.4
|
||||
return provider
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_identify_speaker_still_returns_display_name(monkeypatch):
|
||||
provider = _enabled_provider()
|
||||
monkeypatch.setattr(
|
||||
aiohttp,
|
||||
"ClientSession",
|
||||
lambda *args, **kwargs: _Session(
|
||||
_Response(200, {"speaker_id": "test1", "score": 0.88})
|
||||
),
|
||||
)
|
||||
|
||||
assert await provider.identify_speaker(b"wav", "session") == "张三"
|
||||
detail = await provider.identify_speaker_detail(b"wav", "session")
|
||||
assert detail.speaker_id == "test1"
|
||||
assert detail.name == "张三"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_identify_speaker_disabled_returns_none():
|
||||
provider = VoiceprintProvider({})
|
||||
assert await provider.identify_speaker(b"wav", "session") is None
|
||||
assert await provider.identify_speaker_detail(b"wav", "session") is None
|
||||
|
|
@ -11,7 +11,9 @@ Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 LLM provider,参考
|
|||
|
||||
特殊处理:
|
||||
- CozeLLM 看 bot_id / user_id 而非 api_key
|
||||
- Ollama 要 model_name + 本地服务可用
|
||||
- Ollama(type=ollama)免鉴权:api_key 占位值 "ollama" 不算缺失,
|
||||
只要求 model_name 已配置;mock 模式无本地服务桩直接 skip,
|
||||
live 模式下直连本地 Ollama 服务
|
||||
- placeholder 检测("你的" / "placeholder" / "xxx" / "sk-xxx")
|
||||
- 因为 LLM 是同步 generator,不能直接 asyncio.wait_for → 线程池
|
||||
"""
|
||||
|
|
@ -43,16 +45,30 @@ def _build_provider():
|
|||
if not cfg:
|
||||
pytest.skip(f"LLM provider '{name}' 配置缺失")
|
||||
|
||||
ptype = get_provider_type("LLM", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"LLM '{name}' 的 type 字段缺失")
|
||||
|
||||
# 任何模式下:key 是占位符 → skip。真请求需要真 key;mock 模式下
|
||||
# 没有真 key 跑下去也会撞真 SDK 的网络栈(openai/edge_tts)报错。
|
||||
if name == "CozeLLM":
|
||||
# Ollama 免鉴权供应器(比照 conftest._check_modules_ready 按 type 判断,
|
||||
# provider 名是 OllamaLLM 而非 Ollama):api_key 占位 "ollama" 不算缺失,
|
||||
# 只校验 model_name。
|
||||
if str(cfg.get("type", "")).lower() == "ollama":
|
||||
if not cfg.get("model_name"):
|
||||
pytest.skip(f"LLM '{name}' 的 model_name 未配置")
|
||||
if not LIVE_API_TESTS:
|
||||
# mock 层没有本地 Ollama / openai 响应桩(httpx 网络桩只会抛
|
||||
# ConnectError),链路测试放行只会 fail —— 仅 live 模式运行。
|
||||
pytest.skip(
|
||||
"ollama 链路测试仅 live 模式运行(mock 层无本地 Ollama 响应桩)。"
|
||||
"真请求模式:export RUN_LIVE_API_TESTS=1 并确保本地 Ollama 可用。"
|
||||
)
|
||||
elif name == "CozeLLM":
|
||||
if any(x in cfg.get("bot_id", "") for x in ["你的"]) or any(
|
||||
x in cfg.get("user_id", "") for x in ["你的"]
|
||||
):
|
||||
pytest.skip("LLM 'CozeLLM' 的 bot_id/user_id 未配置")
|
||||
elif name == "Ollama":
|
||||
if not cfg.get("model_name"):
|
||||
pytest.skip("LLM 'Ollama' 的 model_name 未配置")
|
||||
elif not has_real_key(cfg, "api_key"):
|
||||
if LIVE_API_TESTS:
|
||||
pytest.skip(f"LLM '{name}' 的 api_key 未配置")
|
||||
|
|
@ -62,6 +78,7 @@ def _build_provider():
|
|||
"真请求模式:export RUN_LIVE_API_TESTS=1 并填真 key 后再跑。"
|
||||
)
|
||||
|
||||
|
||||
ptype = get_provider_type("LLM", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"LLM '{name}' 的 type 字段缺失")
|
||||
|
|
|
|||
|
|
@ -94,6 +94,14 @@ def test_tts_text_to_speak_writes_file() -> None:
|
|||
"""
|
||||
provider = _build_provider()
|
||||
|
||||
# 会话型流式 TTS(activate_session)依赖真实长连接,text_to_speak 只发
|
||||
# 会话请求、由异步监听任务收流,不走“同步写文件”契约,本测试不适用。
|
||||
if getattr(provider, "activate_session", None) is not None:
|
||||
pytest.skip(
|
||||
f"会话型流式 TTS '{type(provider).__name__}' 需要真实连接,"
|
||||
"文件链路测试不适用"
|
||||
)
|
||||
|
||||
# 参考 performance_tester_tts.py:部分 provider 内部访问 self.conn.sample_rate 等
|
||||
if not hasattr(provider, "conn") or provider.conn is None:
|
||||
provider.conn = SimpleNamespace(
|
||||
|
|
@ -102,6 +110,7 @@ def test_tts_text_to_speak_writes_file() -> None:
|
|||
stop_event=threading.Event(),
|
||||
client_abort=False,
|
||||
headers={},
|
||||
sentence_id="test-sentence", # huoshan_double_stream 等会话型 TTS 需要
|
||||
)
|
||||
if not hasattr(provider, "opus_encoder") or provider.opus_encoder is None:
|
||||
provider.opus_encoder = SimpleNamespace()
|
||||
|
|
|
|||
Loading…
Reference in a new issue