-
登陆
@@ -55,8 +63,9 @@
-
diff --git a/main/manager-web/src/views/register.vue b/main/manager-web/src/views/register.vue
new file mode 100644
index 000000000..8158b6c4b
--- /dev/null
+++ b/main/manager-web/src/views/register.vue
@@ -0,0 +1,173 @@
+
+
+
+
+
+
+

+

+
+
+
+
+
+
+
+

+
注册
+
+ WELCOME TO REGISTER
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
![验证码]()
+
+
+
+
+
+
+
+
立即注册
+
+
+
+ 注册即同意
+
《用户协议》
+ 和
+
《隐私政策》
+
+
+
+
+
+
+
+ ©2025 xiaozhi-esp32-server
+
+
+
+
+
+
+
+
+
diff --git a/main/manager-web/src/views/roleConfig.vue b/main/manager-web/src/views/roleConfig.vue
new file mode 100644
index 000000000..d0f0000e4
--- /dev/null
+++ b/main/manager-web/src/views/roleConfig.vue
@@ -0,0 +1,294 @@
+
+
+
+
+
+
+
+
+

+
+ {{ deviceMac }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
当前记忆(每次对话后重新生成)
+
+
+ 清除
+
+
+
{{ form.prompt.length }}/1000
+
+
+
+
+
+
+
+
+
+ 除了“Qwen
+ 实时”,其他模型通常会增加约1秒的延迟。改变模型后,建议清空记忆体,以免影响体验。
+
+
+
+
+
+
+ 保存配置
+
+
+ 重制
+
+
+

+ 保存配置后,需要重启设备,新的配置才会生效。
+
+
+
+
+ ©2025 xiaozhi-esp32-server
+
+
+
+
+
+
+
+
+
diff --git a/main/manager-web/vue.config.js b/main/manager-web/vue.config.js
new file mode 100644
index 000000000..c10f5e55d
--- /dev/null
+++ b/main/manager-web/vue.config.js
@@ -0,0 +1,24 @@
+const { defineConfig } = require('@vue/cli-service');
+const dotenv = require('dotenv');
+
+// 确保加载 .env 文件
+dotenv.config();
+
+module.exports = defineConfig({
+ devServer: {
+ // Bug 修复:将代理配置为环境变量中定义的 API 基础 URL
+ port: 8001, // 指定端口为 8001
+ proxy: {
+ '/xiaozhi-esp32-api': {
+ target: process.env.VUE_APP_API_BASE_URL || 'http://localhost:8002', // 后端 API 的基础 URL
+ changeOrigin: true, // 允许跨域
+ // pathRewrite: {
+ // '^/api': '', // 路径重写
+ // },
+ },
+ },
+ client: {
+ overlay: false,
+ },
+ },
+});
diff --git a/main/xiaozhi-server/app.py b/main/xiaozhi-server/app.py
index bd23c7bcd..ca3ab5453 100644
--- a/main/xiaozhi-server/app.py
+++ b/main/xiaozhi-server/app.py
@@ -1,10 +1,27 @@
import asyncio
+import sys
+import signal
from config.settings import load_config, check_config_file
from core.websocket_server import WebSocketServer
from core.utils.util import check_ffmpeg_installed
TAG = __name__
+async def wait_for_exit():
+ """Windows 和 Linux 兼容的退出监听"""
+ loop = asyncio.get_running_loop()
+ stop_event = asyncio.Event()
+
+ if sys.platform == "win32":
+ # Windows: 用 sys.stdin.read() 监听 Ctrl + C
+ await loop.run_in_executor(None, sys.stdin.read)
+ else:
+ # Linux/macOS: 用 signal 监听 Ctrl + C
+ def stop():
+ stop_event.set()
+ loop.add_signal_handler(signal.SIGINT, stop)
+ loop.add_signal_handler(signal.SIGTERM, stop) # 支持 kill 进程
+ await stop_event.wait()
async def main():
check_config_file()
@@ -16,11 +33,19 @@ async def main():
ws_task = asyncio.create_task(ws_server.start())
try:
- # 等待 WebSocket 服务器运行
- await ws_task
+ await wait_for_exit() # 监听退出信号
+ except asyncio.CancelledError:
+ print("任务被取消,清理资源中...")
finally:
ws_task.cancel()
-
+ try:
+ await ws_task
+ except asyncio.CancelledError:
+ pass
+ print("服务器已关闭,程序退出。")
if __name__ == "__main__":
- asyncio.run(main())
+ try:
+ asyncio.run(main())
+ except KeyboardInterrupt:
+ print("手动中断,程序终止。")
diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml
index a23750552..6e4daae2e 100644
--- a/main/xiaozhi-server/config.yaml
+++ b/main/xiaozhi-server/config.yaml
@@ -35,10 +35,7 @@ log:
log_file: "server.log"
# 设置数据文件路径
data_dir: data
-iot:
- Speaker:
- # 设置esp32的音量,范围0-100
- volume: 80
+
xiaozhi:
type: hello
version: 1
@@ -51,13 +48,23 @@ xiaozhi:
prompt: |
你是一个叫小智/小志的台湾女孩,说话机车,声音好听,习惯简短表达,爱用网络梗。
请注意,要像一个人一样说话,请不要回复表情符号、代码、和xml标签。
- 当前时间是:{date_time},现在我正在和你进行语音聊天,我们开始吧。
- 如果用户希望结束对话,请在最后说“拜拜”或“再见”。
+ 现在我正在和你进行语音聊天,我们开始吧。
+
# 使用完声音文件后删除文件(Delete the sound file when you are done using it)
delete_audio: true
# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒
close_connection_no_voice_time: 120
+# TTS请求超时时间(秒)
+tts_timeout: 10
+# 开启唤醒词加速
+enable_wakeup_words_response_cache: true
+# 开场是否回复唤醒词
+enable_greeting: true
+# 说完话是否开启提示音
+enable_stop_tts_notify: false
+# 说完话是否开启提示音,音效地址
+stop_tts_notify_voice: "config/assets/tts_notify.mp3"
CMD_exit:
- "退出"
@@ -75,24 +82,67 @@ selected_module:
TTS: EdgeTTS
# 记忆模块,默认不开启记忆;如果想使用超长记忆,推荐使用mem0ai;如果注重隐私,请使用本地的mem_local_short
Memory: nomem
- # 意图识别模块,默认不开启。开启后,可以播放音乐、控制音量、识别退出指令
+ # 意图识别模块,默认使用function_call。开启后,可以播放音乐、控制音量、识别退出指令
# 意图识别使用intent_llm,优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间
# 意图识别使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快
- # 如果意图识别设置成 function_call,建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-pro-32k-functioncall-241028
- Intent: nointent
+ # 默认免费的ChatGLMLLM就已经支持function_call,但是如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-pro-32k-functioncall-241028
+ Intent: function_call
# 意图识别,是用于理解用户意图的模块,例如:播放音乐
Intent:
# 不使用意图识别
nointent:
- # 不需要动
+ # 不需要动type
type: nointent
intent_llm:
- # 不需要动
+ # 不需要动type
type: intent_llm
function_call:
- # 不需要动
+ # 不需要动type
type: nointent
+ # plugins_func/functions下的模块,可以通过配置,选择加载哪个模块,加载后对话支持相应的function调用
+ # 系统默认已经记载“handle_exit_intent(退出识别)”、“play_music(音乐播放)”插件,请勿重复加载
+ # 下面是加载查天气、角色切换、加载查新闻的插件示例
+ functions:
+ - change_role
+ - get_weather
+ - get_news
+ # play_music是服务器自带的音乐播放,hass_play_music是通过home assistant控制的独立外部程序音乐播放
+ # 如果用了hass_play_music,就不要开启play_music,两者只留一个
+ - play_music
+ #- hass_get_state
+ #- hass_set_state
+ #- hass_play_music
+
+# 插件的基础配置
+plugins:
+ # 获取天气插件的配置,这里填写你的api_key
+ # 这个密钥是项目共用的key,用多了可能会被限制
+ # 想稳定一点就自行申请替换,每天有1000次免费调用
+ # 申请地址:https://console.qweather.com/#/apps/create-key/over
+ get_weather: { "api_key": "a861d0d5e7bf4ee1a83d9a9e4f96d4da", "default_location": "广州" }
+ # 获取新闻插件的配置,这里根据需要的新闻类型传入对应的url链接,默认支持社会、科技、财经新闻
+ # 更多类型的新闻列表查看 https://www.chinanews.com.cn/rss/
+ get_news:
+ default_rss_url: "https://www.chinanews.com.cn/rss/society.xml"
+ category_urls:
+ society: "https://www.chinanews.com.cn/rss/society.xml"
+ world: "https://www.chinanews.com.cn/rss/world.xml"
+ finance: "https://www.chinanews.com.cn/rss/finance.xml"
+ home_assistant:
+ devices:
+ - 客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1
+ - 卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1
+ base_url: http://homeassistant.local:8123
+ api_key: 你的home assistant api访问令牌
+ play_music:
+ music_dir: "./music" # 音乐文件存放路径,将从该目录及子目录下搜索音乐文件
+ music_ext: # 音乐文件类型,p3格式效率最高
+ - ".mp3"
+ - ".wav"
+ - ".p3"
+ refresh_time: 300 # 刷新音乐列表的时间间隔,单位为秒
+
Memory:
mem0ai:
@@ -101,10 +151,10 @@ Memory:
# 每月有1000次免费调用
api_key: 你的mem0ai api key
nomem:
- # 不想使用记忆功能,可以使用nomem
+ # 不想使用记忆功能,可以使用nomem
type: nomem
mem_local_short:
- # 本地记忆功能,通过selected_module的llm总结,数据保存在本地,不会上传到服务器
+ # 本地记忆功能,通过selected_module的llm总结,数据保存在本地,不会上传到服务器
type: mem_local_short
mem0_milvus:
# 本地mem0记忆功能,通过mem0+milvus向量数据库,数据保存在本地,不会上传到服务器
@@ -136,6 +186,10 @@ ASR:
type: fun_local
model_dir: models/SenseVoiceSmall
output_dir: tmp/
+ SherpaASR:
+ type: sherpa_onnx_local
+ model_dir: models/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17
+ output_dir: tmp/
DoubaoASR:
type: doubao
appid: 你的火山引擎语音合成服务appid
@@ -149,6 +203,7 @@ VAD:
min_silence_duration_ms: 700 # 如果说话停顿比较长,可以把这个值设置大一些
LLM:
+ # 所有openai类型均可以修改超参,以AliLLM为例
# 当前支持的type为openai、dify、ollama,可自行适配
AliLLM:
# 定义LLM API类型
@@ -157,6 +212,23 @@ LLM:
base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
model_name: qwen-turbo
api_key: 你的deepseek web key
+ temperature: 0.7 # 温度值
+ max_tokens: 500 # 最大生成token数
+ top_p: 1
+ top_k: 50
+ frequency_penalty: 0 # 频率惩罚
+ AliAppLLM:
+ # 定义LLM API类型
+ type: AliBL
+ base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
+ app_id: 你的app_id
+ # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key
+ api_key: 你的api_key
+ # 是否不使用本地prompt:true|false (默不用请在百练应用中设置prompt)
+ is_no_prompt: true
+ # Ali_memory_id:false(不使用)|你的memory_id(请在百练应用中设置中获取)
+ # Tips!:Ali_memory未实现多用户存储记忆(记忆按id调用)
+ ali_memory_id: false
DoubaoLLM:
# 定义LLM API类型
type: openai
@@ -192,8 +264,12 @@ LLM:
type: dify
# 建议使用本地部署的dify接口,国内部分区域访问dify公有云接口可能会受限
# 如果使用DifyLLM,配置文件里prompt(提示词)是无效的,需要在dify控制台设置提示词
- base_url: https://api.dify.cn/v1
+ base_url: https://api.dify.ai/v1
api_key: 你的DifyLLM web key
+ # 使用的对话模式 可以选择工作流 workflows/run 对话模式 chat-messages 文本生成 completion-messages
+ # 使用workflows进行返回的时候输入参数为 query 返回参数的名字要设置为 answer
+ # 文本生成的默认输入参数也是query
+ mode: chat-messages
GeminiLLM:
type: gemini
# 谷歌Gemini API,需要先在Google Cloud控制台创建API密钥并获取api_key
@@ -201,12 +277,15 @@ LLM:
# token申请地址: https://aistudio.google.com/apikey
# 若部署地无法访问接口,需要开启科学上网
api_key: 你的gemini web key
- model_name: "gemini-1.5-pro" # gemini-1.5-pro 是免费的
+ model_name: "gemini-2.0-flash"
+ http_proxy: "" #"http://127.0.0.1:10808"
+ https_proxy: "" #http://127.0.0.1:10808"
CozeLLM:
# 定义LLM API类型
type: coze
- bot_id: 你的bot_id
- user_id: 你的user_id
+ # bot_id和user_id的内容写在引号之内
+ bot_id: "你的bot_id"
+ user_id: "你的user_id"
personal_access_token: 你的coze个人令牌
LMStudioLLM:
# 定义LLM API类型
@@ -214,12 +293,6 @@ LLM:
model_name: deepseek-r1-distill-llama-8b@q4_k_m # 使用的模型名称,需要预先在社区下载
url: http://localhost:1234/v1 # LM Studio服务地址
api_key: lm-studio # LM Studio服务的固定API Key
- HomeAssistant:
- # 定义LLM API类型
- type: homeassistant
- base_url: http://homeassistant.local:8123
- agent_id: conversation.chatgpt
- api_key: 你的home assistant api访问令牌
FastgptLLM:
# 定义LLM API类型
type: fastgpt
@@ -235,17 +308,18 @@ TTS:
# 定义TTS API类型
type: edge
voice: zh-CN-XiaoxiaoNeural
- output_file: tmp/
+ output_dir: tmp/
DoubaoTTS:
# 定义TTS API类型
type: doubao
# 火山引擎语音合成服务,需要先在火山引擎控制台创建应用并获取appid和access_token
# 山引擎语音一定要购买花钱,起步价30元,就有100并发了。如果用免费的只有2个并发,会经常报tts错误
# 购买服务后,购买免费的音色后,可能要等半小时左右,才能使用。
- # 地址:https://console.volcengine.com/speech/service/8
+ # 普通音色在这里开通:https://console.volcengine.com/speech/service/8
+ # 湾湾小何音色在这里开通:https://console.volcengine.com/speech/service/10007,开通后将下面的voice设置成zh_female_wanwanxiaohe_moon_bigtts
api_url: https://openspeech.bytedance.com/api/v1/tts
voice: BV001_streaming
- output_file: tmp/
+ output_dir: tmp/
authorization: "Bearer;"
appid: 你的火山引擎语音合成服务appid
access_token: 你的火山引擎语音合成服务access_token
@@ -256,7 +330,7 @@ TTS:
# token申请地址 https://cloud.siliconflow.cn/account/ak
model: FunAudioLLM/CosyVoice2-0.5B
voice: FunAudioLLM/CosyVoice2-0.5B:alex
- output_file: tmp/
+ output_dir: tmp/
access_token: 你的硅基流动API密钥
response_format: wav
CozeCnTTS:
@@ -264,7 +338,7 @@ TTS:
# COZECN TTS
# token申请地址 https://www.coze.cn/open/oauth/pats
voice: 7426720361733046281
- output_file: tmp/
+ output_dir: tmp/
access_token: 你的coze web key
response_format: wav
FishSpeech:
@@ -277,7 +351,7 @@ TTS:
#--decoder-config-name firefly_gan_vq
#--compile
type: fishspeech
- output_file: tmp/
+ output_dir: tmp/
response_format: wav
reference_id: null
reference_audio: ["/tmp/test.wav",]
@@ -301,7 +375,7 @@ TTS:
#python api_v2.py -a 127.0.0.1 -p 9880 -c GPT_SoVITS/configs/caixukun.yaml
type: gpt_sovits_v2
url: "http://127.0.0.1:9880/tts"
- output_file: tmp/
+ output_dir: tmp/
text_lang: "auto"
ref_audio_path: "caixukun.wav"
prompt_text: ""
@@ -321,20 +395,24 @@ TTS:
repetition_penalty: 1.35
aux_ref_audio_paths: []
GPT_SOVITS_V3:
+ # 定义TTS API类型 GPT-SoVITS-v3lora-20250228
+ #启动tts方法:
+ #python api.py
type: gpt_sovits_v3
- url: "http://127.0.0.1:9880/tts"
- output_file: tmp/
- text_lang: "auto"
- ref_audio_path: "caixukun.wav"
- prompt_lang: "zh"
+ url: "http://127.0.0.1:9880"
+ output_dir: tmp/
+ text_language: "auto"
+ refer_wav_path: "caixukun.wav"
+ prompt_language: "zh"
prompt_text: ""
- top_k: 5
- top_p: 1
- temperature: 1
- sample_steps: 16
- media_type: "wav"
- streaming_mode: false
- threshold: 30
+ top_k: 15
+ top_p: 1.0
+ temperature: 1.0
+ cut_punc: ""
+ speed: 1.0
+ inp_refs: []
+ sample_steps: 32
+ if_sr: false
MinimaxTTS:
# Minimax语音合成服务,需要先在minimax平台创建账户充值,并获取登录信息
# 平台地址:https://platform.minimaxi.com/
@@ -343,7 +421,7 @@ TTS:
# api_key地址:https://platform.minimaxi.com/user-center/basic-information/interface-key
# 定义TTS API类型
type: minimax
- output_file: tmp/
+ output_dir: tmp/
group_id: 你的minimax平台groupID
api_key: 你的minimax平台接口密钥
model: "speech-01-turbo"
@@ -380,7 +458,7 @@ TTS:
# token地址:https://nls-portal.console.aliyun.com/overview
# 定义TTS API类型
type: aliyun
- output_file: tmp/
+ output_dir: tmp/
appkey: 你的阿里云智能语音交互服务项目Appkey
token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret
voice: xiaoyun
@@ -402,9 +480,21 @@ TTS:
type: doubao
api_url: https://api.302ai.cn/doubao/tts_hd
authorization: "Bearer "
+ # 湾湾小何音色
voice: "zh_female_wanwanxiaohe_moon_bigtts"
- output_file: tmp/
+ output_dir: tmp/
access_token: "你的302API密钥"
+ GizwitsTTS:
+ type: doubao
+ # 火山引擎作为基座,可以完全使用企业级火山引擎语音合成服务
+ # 前一万名注册的用户,将送5元体验金额
+ # 获取API Key地址:https://agentrouter.gizwitsapi.com/panel/token
+ api_url: https://bytedance.gizwitsapi.com/api/v1/tts
+ authorization: "Bearer "
+ # 湾湾小何音色
+ voice: "zh_female_wanwanxiaohe_moon_bigtts"
+ output_dir: tmp/
+ access_token: "你的机智云API key"
ACGNTTS:
#在线网址:https://acgn.ttson.cn/
#token购买:www.ttson.cn
@@ -420,7 +510,7 @@ TTS:
to_lang: ZH
url: https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=
format: mp3
- output_file: tmp/
+ output_dir: tmp/
emotion: 1
OpenAITTS:
# openai官方文本转语音服务,可支持全球大多数语种
@@ -434,40 +524,25 @@ TTS:
voice: onyx
# 语速范围0.25-4.0
speed: 1
- output_file: tmp/
+ output_dir: tmp/
+ CustomTTS:
+ # 自定义的TTS接口服务,请求参数可自定义
+ # 要求接口使用GET方式请求,并返回音频文件
+ type: custom
+ url: "http://127.0.0.1:9880/tts"
+ params: # 自定义请求参数
+ # text: "{prompt_text}" # {prompt_text}会被替换为实际的提示词内容
+ # speaker: jok老师
+ # speed: 1
+ # foo: bar
+ # testabc: 123456
+ headers: # 自定义请求头
+ # Authorization: Bearer xxxx
+ format: wav # 接口返回的音频格式
+ output_dir: tmp/
# 模块测试配置
module_test:
test_sentences: # 自定义测试语句
- "你好,请介绍一下你自己"
- "What's the weather like today?"
- "请用100字概括量子计算的基本原理和应用前景"
-
-# 本地音乐播放配置
-music:
- music_dir: "./music" # 音乐文件存放路径,将从该目录及子目录下搜索音乐文件
- music_ext: # 音乐文件类型,p3格式效率最高
- - ".mp3"
- - ".wav"
- - ".p3"
- refresh_time: 300 # 刷新音乐列表的时间间隔,单位为秒
-
-# 以下配置在小于等于0.0.9版本中的docker容器中可用
-# 0.0.9以后的新版本源码部署已经无法奏效
-manager:
- enabled: false
- ip: 0.0.0.0
- port: 8002
-use_private_config: false
-
-# 唤醒词,用于识别唤醒词还是讲话内容
-wakeup_words:
- - "你好小智"
- - "你好小志"
- - "小爱同学"
- - "你好小鑫"
- - "你好小新"
- - "小美同学"
- - "小龙小龙"
- - "喵喵同学"
- - "小滨小滨"
- - "小冰小冰"
diff --git a/main/xiaozhi-server/config/assets/tts_notify.mp3 b/main/xiaozhi-server/config/assets/tts_notify.mp3
new file mode 100644
index 000000000..ff071501d
Binary files /dev/null and b/main/xiaozhi-server/config/assets/tts_notify.mp3 differ
diff --git a/main/xiaozhi-server/config/assets/wakeup_words.wav b/main/xiaozhi-server/config/assets/wakeup_words.wav
new file mode 100644
index 000000000..e5422555c
Binary files /dev/null and b/main/xiaozhi-server/config/assets/wakeup_words.wav differ
diff --git a/main/xiaozhi-server/config/functionCallConfig.py b/main/xiaozhi-server/config/functionCallConfig.py
deleted file mode 100644
index dd9b55fc4..000000000
--- a/main/xiaozhi-server/config/functionCallConfig.py
+++ /dev/null
@@ -1,36 +0,0 @@
-FunctionCallConfig = [
- {
- "type": "function",
- "function": {
- "name": "handle_exit_intent",
- "description": "当用户想结束对话或需要退出系统时调用",
- "parameters": {
- "type": "object",
- "properties": {
- "say_goodbye": {
- "type": "string",
- "description": "和用户友好结束对话的告别语"
- }
- },
- "required": []
- }
- }
- },
- {
- "type": "function",
- "function": {
- "name": "play_music",
- "description": "唱歌、听歌、播放音乐方法。比如用户说播放音乐,参数为:random,比如用户说播放两只老虎,参数为:两只老虎",
- "parameters": {
- "type": "object",
- "properties": {
- "song_name": {
- "type": "string",
- "description": "歌曲名称,如果没有指定具体歌名则为'random'"
- }
- },
- "required": ["song_name"]
- }
- }
- }
- ]
\ No newline at end of file
diff --git a/main/xiaozhi-server/config/settings.py b/main/xiaozhi-server/config/settings.py
index 0582bf76e..bb81cfe95 100644
--- a/main/xiaozhi-server/config/settings.py
+++ b/main/xiaozhi-server/config/settings.py
@@ -7,9 +7,48 @@ from core.utils.util import read_config, get_project_dir
default_config_file = "config.yaml"
+def ensure_directories(config):
+ """确保所有配置路径存在"""
+ dirs_to_create = set()
+ project_dir = get_project_dir() # 获取项目根目录
+ # 日志文件目录
+ log_dir = config.get('log', {}).get('log_dir', 'tmp')
+ dirs_to_create.add(os.path.join(project_dir, log_dir))
+
+ # ASR/TTS模块输出目录
+ for module in ['ASR', 'TTS']:
+ for provider in config.get(module, {}).values():
+ output_dir = provider.get('output_dir', '')
+ if output_dir:
+ dirs_to_create.add(output_dir)
+
+ # 根据selected_module创建模型目录
+ selected_modules = config.get('selected_module', {})
+ for module_type in ['ASR', 'LLM', 'TTS']:
+ selected_provider = selected_modules.get(module_type)
+ if not selected_provider:
+ continue
+ provider_config = config.get(module_type, {}).get(selected_provider, {})
+ output_dir = provider_config.get('output_dir')
+ if output_dir:
+ full_model_dir = os.path.join(project_dir, output_dir)
+ dirs_to_create.add(full_model_dir)
+
+ # 统一创建目录(保留原data目录创建)
+ for dir_path in dirs_to_create:
+ try:
+ os.makedirs(dir_path, exist_ok=True)
+ except PermissionError:
+ print(f"警告:无法创建目录 {dir_path},请检查写入权限")
+
+
def get_config_file():
global default_config_file
- # 判断是否存在私有的配置文件
+ """获取配置文件路径,优先使用私有配置文件(若存在)。
+
+ Returns:
+ str: 配置文件路径(相对路径或默认路径)
+ """
config_file = default_config_file
if os.path.exists(get_project_dir() + "data/." + default_config_file):
config_file = "data/." + default_config_file
@@ -20,9 +59,13 @@ def load_config():
"""加载配置文件"""
parser = argparse.ArgumentParser(description="Server configuration")
config_file = get_config_file()
+
parser.add_argument("--config_path", type=str, default=config_file)
args = parser.parse_args()
- return read_config(args.config_path)
+ config = read_config(args.config_path)
+ # 初始化目录
+ ensure_directories(config)
+ return config
def update_config(config):
@@ -67,7 +110,7 @@ def find_missing_keys(new_config, old_config, parent_key=''):
def check_config_file():
old_config_file = get_config_file()
global default_config_file
- if not old_config_file.startswith('data'):
+ if not 'data' in old_config_file:
return
old_config = read_config(get_project_dir() + old_config_file)
new_config = read_config(get_project_dir() + default_config_file)
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index 570c31055..c9a52b120 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -5,36 +5,43 @@ import time
import queue
import asyncio
import traceback
-from config.logger import setup_logging
+
import threading
import websockets
from typing import Dict, Any
+from plugins_func.loadplugins import auto_import_modules
+from config.logger import setup_logging
from core.utils.dialogue import Message, Dialogue
from core.handle.textHandle import handleTextMessage
-from core.utils.util import get_string_no_punctuation_or_emoji
+from core.utils.util import get_string_no_punctuation_or_emoji, extract_json_from_string, get_ip_info
from concurrent.futures import ThreadPoolExecutor, TimeoutError
from core.handle.sendAudioHandle import sendAudioMessage
from core.handle.receiveAudioHandle import handleAudioMessage
-from core.handle.intentHandler import Action, get_functions, handle_llm_function_call
+from core.handle.functionHandler import FunctionHandler
+from plugins_func.register import Action
from config.private_config import PrivateConfig
from core.auth import AuthMiddleware, AuthenticationError
from core.utils.auth_code_gen import AuthCodeGenerator
TAG = __name__
+auto_import_modules('plugins_func.functions')
+
class TTSException(RuntimeError):
pass
class ConnectionHandler:
- def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _music, _memory, _intent):
+ def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory, _intent):
self.config = config
self.logger = setup_logging()
self.auth = AuthMiddleware(config)
self.websocket = None
self.headers = None
+ self.client_ip = None
+ self.client_ip_info = {}
self.session_id = None
self.prompt = None
self.welcome_msg = None
@@ -89,29 +96,30 @@ class ConnectionHandler:
self.private_config = None
self.auth_code_gen = AuthCodeGenerator.get_instance()
self.is_device_verified = False # 添加设备验证状态标志
- self.music_handler = _music
self.close_after_chat = False # 是否在聊天结束后关闭连接
self.use_function_call_mode = False
if self.config["selected_module"]["Intent"] == 'function_call':
self.use_function_call_mode = True
- self.logger.bind(tag=TAG).info(f"use_function_call_mode:{self.use_function_call_mode}")
-
async def handle_connection(self, ws):
try:
# 获取并验证headers
self.headers = dict(ws.request.headers)
# 获取客户端ip地址
- client_ip = ws.remote_address[0]
- self.logger.bind(tag=TAG).info(f"{client_ip} conn - Headers: {self.headers}")
+ self.client_ip = ws.remote_address[0]
+ self.logger.bind(tag=TAG).info(f"{self.client_ip} conn - Headers: {self.headers}")
# 进行认证
await self.auth.authenticate(self.headers)
-
device_id = self.headers.get("device-id", None)
- self.memory.init_memory(device_id, self.llm)
- self.intent.set_llm(self.llm)
+ # 认证通过,继续处理
+ self.websocket = ws
+ self.session_id = str(uuid.uuid4())
+
+ self.welcome_msg = self.config["xiaozhi"]
+ self.welcome_msg["session_id"] = self.session_id
+ await self.websocket.send(json.dumps(self.welcome_msg))
# Load private configuration if device_id is provided
bUsePrivateConfig = self.config.get("use_private_config", False)
self.logger.bind(tag=TAG).info(f"bUsePrivateConfig: {bUsePrivateConfig}, device_id: {device_id}")
@@ -139,16 +147,8 @@ class ConnectionHandler:
self.private_config = None
raise
- # 认证通过,继续处理
- self.websocket = ws
- self.session_id = str(uuid.uuid4())
-
- self.welcome_msg = self.config["xiaozhi"]
- self.welcome_msg["session_id"] = self.session_id
- await self.websocket.send(json.dumps(self.welcome_msg))
-
- await self.loop.run_in_executor(None, self._initialize_components)
-
+ # 异步初始化
+ self.executor.submit(self._initialize_components)
# tts 消化线程
tts_priority = threading.Thread(target=self._tts_priority_thread, daemon=True)
tts_priority.start()
@@ -184,15 +184,34 @@ class ConnectionHandler:
await handleAudioMessage(self, message)
def _initialize_components(self):
+ """加载插件"""
+ self.func_handler = FunctionHandler(self)
+
+ """加载提示词"""
self.prompt = self.config["prompt"]
if self.private_config:
self.prompt = self.private_config.private_config.get("prompt", self.prompt)
- # 赋予LLM时间观念
- if "{date_time}" in self.prompt:
- date_time = time.strftime("%Y-%m-%d %H:%M", time.localtime())
- self.prompt = self.prompt.replace("{date_time}", date_time)
self.dialogue.put(Message(role="system", content=self.prompt))
+ """加载记忆"""
+ device_id = self.headers.get("device-id", None)
+ self.memory.init_memory(device_id, self.llm)
+ self.intent.set_llm(self.llm)
+
+ """加载位置信息"""
+ self.client_ip_info = get_ip_info(self.client_ip)
+ if self.client_ip_info is not None and "city" in self.client_ip_info:
+ self.logger.bind(tag=TAG).info(f"Client ip info: {self.client_ip_info}")
+ self.prompt = self.prompt + f"\nuser location:{self.client_ip_info}"
+ self.dialogue.update_system_message(self.prompt)
+
+ def change_system_prompt(self, prompt):
+ self.prompt = prompt
+ # 找到原来的role==system,替换原来的系统提示
+ for m in self.dialogue.dialogue:
+ if m.role == "system":
+ m.content = prompt
+
async def _check_and_broadcast_auth_code(self):
"""检查设备绑定状态并广播认证码"""
if not self.private_config.get_owner():
@@ -291,7 +310,7 @@ class ConnectionHandler:
self.logger.bind(tag=TAG).debug(json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False))
return True
- def chat_with_function_calling(self, query):
+ def chat_with_function_calling(self, query, tool_call=False):
self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}")
"""Chat with function calling for intent detection using streaming"""
if self.isNeedAuth():
@@ -300,14 +319,14 @@ class ConnectionHandler:
future.result()
return True
- self.dialogue.put(Message(role="user", content=query))
+ if not tool_call:
+ self.dialogue.put(Message(role="user", content=query))
# Define intent functions
- functions = get_functions()
+ functions = self.func_handler.get_functions()
response_message = []
processed_chars = 0 # 跟踪已处理的字符位置
- function_call_data = None # 存储function call数据
try:
start_time = time.time()
@@ -316,7 +335,7 @@ class ConnectionHandler:
future = asyncio.run_coroutine_threadsafe(self.memory.query_memory(query), self.loop)
memory_str = future.result()
- # self.logger.bind(tag=TAG).info(f"记忆内容: {memory_str}")
+ # self.logger.bind(tag=TAG).info(f"对话记录: {self.dialogue.get_llm_dialogue_with_memory(memory_str)}")
# 使用支持functions的streaming接口
llm_responses = self.llm.response_with_functions(
@@ -332,48 +351,93 @@ class ConnectionHandler:
text_index = 0
# 处理流式响应
+ tool_call_flag = False
+ function_name = None
+ function_id = None
+ function_arguments = ""
+ content_arguments = ""
for response in llm_responses:
- if response["type"] == "content":
- content = response["content"]
- response_message.append(content)
+ content, tools_call = response
+ if content is not None and len(content) > 0:
+ if len(response_message) <= 0 and (content == "```" or "
" in content):
+ tool_call_flag = True
- if self.client_abort:
- break
+ if tools_call is not None:
+ tool_call_flag = True
+ if tools_call[0].id is not None:
+ function_id = tools_call[0].id
+ if tools_call[0].function.name is not None:
+ function_name = tools_call[0].function.name
+ if tools_call[0].function.arguments is not None:
+ function_arguments += tools_call[0].function.arguments
- end_time = time.time()
- self.logger.bind(tag=TAG).debug(f"大模型返回时间: {end_time - start_time} 秒, 生成token={content}")
+ if content is not None and len(content) > 0:
+ if tool_call_flag:
+ content_arguments += content
+ else:
+ response_message.append(content)
- # 处理文本分段和TTS逻辑
- # 合并当前全部文本并处理未分割部分
- full_text = "".join(response_message)
- current_text = full_text[processed_chars:] # 从未处理的位置开始
+ if self.client_abort:
+ break
- # 查找最后一个有效标点
- punctuations = ("。", "?", "!", ";", ":")
- last_punct_pos = -1
- for punct in punctuations:
- pos = current_text.rfind(punct)
- if pos > last_punct_pos:
- last_punct_pos = pos
+ end_time = time.time()
+ self.logger.bind(tag=TAG).debug(f"大模型返回时间: {end_time - start_time} 秒, 生成token={content}")
- # 找到分割点则处理
- if last_punct_pos != -1:
- segment_text_raw = current_text[:last_punct_pos + 1]
- segment_text = get_string_no_punctuation_or_emoji(segment_text_raw)
- if segment_text:
- text_index += 1
- self.recode_first_last_text(segment_text, text_index)
- future = self.executor.submit(self.speak_and_play, segment_text, text_index)
- self.tts_queue.put(future)
- processed_chars += len(segment_text_raw) # 更新已处理字符位置
+ # 处理文本分段和TTS逻辑
+ # 合并当前全部文本并处理未分割部分
+ full_text = "".join(response_message)
+ current_text = full_text[processed_chars:] # 从未处理的位置开始
- elif response["type"] == "function_call":
- # Extract function call data
+ # 查找最后一个有效标点
+ punctuations = ("。", "?", "!", ";", ":")
+ last_punct_pos = -1
+ for punct in punctuations:
+ pos = current_text.rfind(punct)
+ if pos > last_punct_pos:
+ last_punct_pos = pos
+
+ # 找到分割点则处理
+ if last_punct_pos != -1:
+ segment_text_raw = current_text[:last_punct_pos + 1]
+ segment_text = get_string_no_punctuation_or_emoji(segment_text_raw)
+ if segment_text:
+ text_index += 1
+ self.recode_first_last_text(segment_text, text_index)
+ future = self.executor.submit(self.speak_and_play, segment_text, text_index)
+ self.tts_queue.put(future)
+ processed_chars += len(segment_text_raw) # 更新已处理字符位置
+
+ # 处理function call
+ if tool_call_flag:
+ bHasError = False
+ if function_id is None:
+ a = extract_json_from_string(content_arguments)
+ if a is not None:
+ try:
+ content_arguments_json = json.loads(a)
+ function_name = content_arguments_json["name"]
+ function_arguments = json.dumps(content_arguments_json["arguments"], ensure_ascii=False)
+ function_id = str(uuid.uuid4().hex)
+ except Exception as e:
+ bHasError = True
+ response_message.append(a)
+ else:
+ bHasError = True
+ response_message.append(content_arguments)
+ if bHasError:
+ self.logger.bind(tag=TAG).error(f"function call error: {content_arguments}")
+ else:
+ function_arguments = json.loads(function_arguments)
+ if not bHasError:
+ self.logger.bind(tag=TAG).info(
+ f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}")
function_call_data = {
- "name": response["function_call"]["function"]["name"],
- "arguments": response["function_call"]["function"]["arguments"]
+ "name": function_name,
+ "id": function_id,
+ "arguments": function_arguments
}
- self.logger.bind(tag=TAG).info(f"Function call detected: {function_call_data}")
+ result = self.func_handler.handle_llm_function_call(self, function_call_data)
+ self._handle_function_result(result, function_call_data, text_index + 1)
# 处理最后剩余的文本
full_text = "".join(response_message)
@@ -387,23 +451,50 @@ class ConnectionHandler:
self.tts_queue.put(future)
# 存储对话内容
- self.dialogue.put(Message(role="assistant", content="".join(response_message)))
-
- # 处理function call
- if function_call_data:
- result = handle_llm_function_call(self, function_call_data)
- if result.action == Action.RESPONSE:
- text = result.response
- text_index += 1
- self.recode_first_last_text(text, text_index)
- future = self.executor.submit(self.speak_and_play, text, text_index)
- self.tts_queue.put(future)
+ if len(response_message) > 0:
+ self.dialogue.put(Message(role="assistant", content="".join(response_message)))
self.llm_finish_task = True
self.logger.bind(tag=TAG).debug(json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False))
return True
+ def _handle_function_result(self, result, function_call_data, text_index):
+ if result.action == Action.RESPONSE: # 直接回复前端
+ text = result.response
+ self.recode_first_last_text(text, text_index)
+ future = self.executor.submit(self.speak_and_play, text, text_index)
+ self.tts_queue.put(future)
+ self.dialogue.put(Message(role="assistant", content=text))
+ elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
+
+ text = result.result
+ if text is not None and len(text) > 0:
+ function_id = function_call_data["id"]
+ function_name = function_call_data["name"]
+ function_arguments = function_call_data["arguments"]
+ self.dialogue.put(Message(role='assistant',
+ tool_calls=[{"id": function_id,
+ "function": {"arguments": function_arguments,
+ "name": function_name},
+ "type": 'function',
+ "index": 0}]))
+
+ self.dialogue.put(Message(role="tool", tool_call_id=function_id, content=text))
+ self.chat_with_function_calling(text, tool_call=True)
+ elif result.action == Action.NOTFOUND:
+ text = result.result
+ self.recode_first_last_text(text, text_index)
+ future = self.executor.submit(self.speak_and_play, text, text_index)
+ self.tts_queue.put(future)
+ self.dialogue.put(Message(role="assistant", content=text))
+ else:
+ text = result.result
+ self.recode_first_last_text(text, text_index)
+ future = self.executor.submit(self.speak_and_play, text, text_index)
+ self.tts_queue.put(future)
+ self.dialogue.put(Message(role="assistant", content=text))
+
def _tts_priority_thread(self):
while not self.stop_event.is_set():
text = None
@@ -415,7 +506,8 @@ class ConnectionHandler:
opus_datas, text_index, tts_file = [], 0, None
try:
self.logger.bind(tag=TAG).debug("正在处理TTS任务...")
- tts_file, text, text_index = future.result(timeout=10)
+ tts_timeout = self.config.get("tts_timeout", 10)
+ tts_file, text, text_index = future.result(timeout=tts_timeout)
if text is None or len(text) <= 0:
self.logger.bind(tag=TAG).error(f"TTS出错:{text_index}: tts text is empty")
elif tts_file is None:
@@ -423,7 +515,7 @@ class ConnectionHandler:
else:
self.logger.bind(tag=TAG).debug(f"TTS生成:文件路径: {tts_file}")
if os.path.exists(tts_file):
- opus_datas, duration = self.tts.wav_to_opus_data(tts_file)
+ opus_datas, duration = self.tts.audio_to_opus_data(tts_file)
else:
self.logger.bind(tag=TAG).error(f"TTS出错:文件不存在{tts_file}")
except TimeoutError:
diff --git a/main/xiaozhi-server/core/handle/functionHandler.py b/main/xiaozhi-server/core/handle/functionHandler.py
new file mode 100644
index 000000000..e80565177
--- /dev/null
+++ b/main/xiaozhi-server/core/handle/functionHandler.py
@@ -0,0 +1,87 @@
+from config.logger import setup_logging
+import json
+from plugins_func.register import FunctionRegistry, ActionResponse, Action, ToolType
+from plugins_func.functions.hass_init import append_devices_to_prompt
+
+TAG = __name__
+logger = setup_logging()
+
+
+class FunctionHandler:
+ def __init__(self, conn):
+ self.conn = conn
+ self.config = conn.config
+ self.function_registry = FunctionRegistry()
+ self.register_nessary_functions()
+ self.register_config_functions()
+ self.functions_desc = self.function_registry.get_all_function_desc()
+ func_names = self.current_support_functions()
+ self.modify_plugin_loader_des(func_names)
+
+ def modify_plugin_loader_des(self, func_names):
+ if "plugin_loader" not in func_names:
+ return
+ # 可编辑的列表中去掉plugin_loader
+ surport_plugins = [func for func in func_names if func != "plugin_loader"]
+ func_names = ",".join(surport_plugins)
+ for function_desc in self.functions_desc:
+ if function_desc["function"]["name"] == "plugin_loader":
+ function_desc["function"]["description"] = function_desc["function"]["description"].replace("[plugins]",
+ func_names)
+ break
+
+ def upload_functions_desc(self):
+ self.functions_desc = self.function_registry.get_all_function_desc()
+
+ def current_support_functions(self):
+ func_names = []
+ for func in self.functions_desc:
+ func_names.append(func["function"]["name"])
+ # 打印当前支持的函数列表
+ logger.bind(tag=TAG).info(f"当前支持的函数列表: {func_names}")
+ return func_names
+
+ def get_functions(self):
+ """获取功能调用配置"""
+ return self.functions_desc
+
+ def register_nessary_functions(self):
+ """注册必要的函数"""
+ self.function_registry.register_function("handle_exit_intent")
+ self.function_registry.register_function("plugin_loader")
+ self.function_registry.register_function("get_time")
+ self.function_registry.register_function("raise_and_lower_the_volume")
+
+ def register_config_functions(self):
+ """注册配置中的函数,可以不同客户端使用不同的配置"""
+ for func in self.config["Intent"]["function_call"].get("functions", []):
+ self.function_registry.register_function(func)
+
+ """home assistant需要初始化提示词"""
+ append_devices_to_prompt(self.conn)
+
+ def get_function(self, name):
+ return self.function_registry.get_function(name)
+
+ def handle_llm_function_call(self, conn, function_call_data):
+ try:
+ function_name = function_call_data["name"]
+ funcItem = self.get_function(function_name)
+ if not funcItem:
+ return ActionResponse(action=Action.NOTFOUND, result="没有找到对应的函数", response="")
+ func = funcItem.func
+ arguments = function_call_data["arguments"]
+ arguments = json.loads(arguments) if arguments else {}
+ logger.bind(tag=TAG).info(f"调用函数: {function_name}, 参数: {arguments}")
+ if funcItem.type == ToolType.SYSTEM_CTL or funcItem.type == ToolType.IOT_CTL:
+ return func(conn, **arguments)
+ elif funcItem.type == ToolType.WAIT:
+ return func(**arguments)
+ elif funcItem.type == ToolType.CHANGE_SYS_PROMPT:
+ return func(conn, **arguments)
+ else:
+ return ActionResponse(action=Action.NOTFOUND, result="没有找到对应的函数", response="")
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"处理function call错误: {e}")
+
+ return None
diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py
index bafcf09dc..cc9688624 100644
--- a/main/xiaozhi-server/core/handle/helloHandle.py
+++ b/main/xiaozhi-server/core/handle/helloHandle.py
@@ -1,8 +1,72 @@
import json
from config.logger import setup_logging
+from core.handle.sendAudioHandle import send_stt_message
+from core.utils.util import remove_punctuation_and_length
+import shutil
+import asyncio
+import os
+import random
+import time
logger = setup_logging()
+WAKEUP_CONFIG = {"dir": "config/assets/", "file_name": "wakeup_words", "create_time": time.time(), "refresh_time": 10,
+ "words": ["很高兴见到你", "你好啊", "我们又见面了", "最近可好?", "很高兴再次和你谈话", "在干嘛"]}
+
async def handleHelloMessage(conn):
await conn.websocket.send(json.dumps(conn.welcome_msg))
+
+
+async def checkWakeupWords(conn, text):
+ enable_wakeup_words_response_cache = conn.config["enable_wakeup_words_response_cache"]
+ """是否开启唤醒词加速"""
+ if not enable_wakeup_words_response_cache:
+ return False
+ """检查是否是唤醒词"""
+ _, text = remove_punctuation_and_length(text)
+ if text in conn.config.get("wakeup_words"):
+ await send_stt_message(conn, text)
+ conn.tts_first_text_index = 0
+ conn.tts_last_text_index = 0
+ conn.llm_finish_task = True
+
+ file = getWakeupWordFile(WAKEUP_CONFIG["file_name"])
+ if file is None:
+ asyncio.create_task(wakeupWordsResponse(conn))
+ return False
+ opus_packets, duration = conn.tts.audio_to_opus_data(file)
+ conn.audio_play_queue.put((opus_packets, text, 0))
+ if time.time() - WAKEUP_CONFIG["create_time"] > WAKEUP_CONFIG["refresh_time"]:
+ asyncio.create_task(wakeupWordsResponse(conn))
+ return True
+ return False
+
+
+def getWakeupWordFile(file_name):
+ for file in os.listdir(WAKEUP_CONFIG["dir"]):
+ if "my_"+file_name in file:
+ return f"config/assets/{file}"
+
+ """查找config/assets/目录下名称为wakeup_words的文件"""
+ for file in os.listdir(WAKEUP_CONFIG["dir"]):
+ if file_name in file:
+ return f"config/assets/{file}"
+ return None
+
+
+async def wakeupWordsResponse(conn):
+ """唤醒词响应"""
+ wakeup_word = random.choice(WAKEUP_CONFIG["words"])
+ result = conn.llm.response_no_stream(conn.config["prompt"], wakeup_word)
+ tts_file = await asyncio.to_thread(conn.tts.to_tts, result)
+ if tts_file is not None and os.path.exists(tts_file):
+ file_type = os.path.splitext(tts_file)[1]
+ if file_type:
+ file_type = file_type.lstrip('.')
+ old_file = getWakeupWordFile("my_" +WAKEUP_CONFIG["file_name"])
+ if old_file is not None:
+ os.remove(old_file)
+ """将文件挪到"wakeup_words.mp3"""
+ shutil.move(tts_file, WAKEUP_CONFIG["dir"] + "my_" +WAKEUP_CONFIG["file_name"] + "." + file_type)
+ WAKEUP_CONFIG["create_time"] = time.time()
diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py
index cae22b2ce..d8440fc6e 100644
--- a/main/xiaozhi-server/core/handle/intentHandler.py
+++ b/main/xiaozhi-server/core/handle/intentHandler.py
@@ -1,112 +1,36 @@
from config.logger import setup_logging
import json
+import uuid
from core.handle.sendAudioHandle import send_stt_message
-from core.utils.dialogue import Message
-from config.functionCallConfig import FunctionCallConfig
-import asyncio
-from enum import Enum
+from core.handle.helloHandle import checkWakeupWords
+from core.utils.util import remove_punctuation_and_length
TAG = __name__
logger = setup_logging()
-class Action(Enum):
- NOTFOUND = (0, "没有找到函数")
- NONE = (1, "啥也不干")
- RESPONSE = (2, "直接回复")
- REQLLM = (3, "调用函数后再请求llm生成回复")
-
- def __init__(self, code, message):
- self.code = code
- self.message = message
-
-
-class ActionResponse:
- def __init__(self, action: Action, result, response):
- self.action = action # 动作类型
- self.result = result # 动作产生的结果
- self.response = response # 直接回复的内容
-
-
-def get_functions():
- """获取功能调用配置"""
- return FunctionCallConfig
-
-
-def handle_llm_function_call(conn, function_call_data):
- try:
- function_name = function_call_data["name"]
-
- if function_name == "handle_exit_intent":
- # 处理退出意图
- try:
- say_goodbye = json.loads(function_call_data["arguments"]).get("say_goodbye", "再见")
- conn.close_after_chat = True
- logger.bind(tag=TAG).info(f"退出意图已处理:{say_goodbye}")
- return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response=say_goodbye)
- except Exception as e:
- logger.bind(tag=TAG).error(f"处理退出意图错误: {e}")
-
- elif function_name == "play_music":
- # 处理音乐播放意图
- try:
- song_name = "random"
- arguments = function_call_data["arguments"]
- if arguments is not None and len(arguments) > 0:
- args = json.loads(arguments)
- song_name = args.get("song_name", "random")
- music_intent = f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐"
-
- # 执行音乐播放命令
- future = asyncio.run_coroutine_threadsafe(
- conn.music_handler.handle_music_command(conn, music_intent),
- conn.loop
- )
- future.result()
- return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response="还想听什么歌?")
- except Exception as e:
- logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
- else:
- return ActionResponse(action=Action.NOTFOUND, result="没有找到对应的函数", response="")
- except Exception as e:
- logger.bind(tag=TAG).error(f"处理function call错误: {e}")
-
- return None
-
-
async def handle_user_intent(conn, text):
- """
- Handle user intent before starting chat
-
- Args:
- conn: Connection object
- text: User's text input
-
- Returns:
- bool: True if intent was handled, False if should proceed to chat
- """
# 检查是否有明确的退出命令
if await check_direct_exit(conn, text):
return True
+ # 检查是否是唤醒词
+ if await checkWakeupWords(conn, text):
+ return True
if conn.use_function_call_mode:
# 使用支持function calling的聊天方法,不再进行意图分析
return False
-
- logger.bind(tag=TAG).info(f"分析用户意图: {text}")
-
# 使用LLM进行意图分析
intent = await analyze_intent_with_llm(conn, text)
-
if not intent:
return False
-
# 处理各种意图
return await process_intent_result(conn, intent, text)
async def check_direct_exit(conn, text):
"""检查是否有明确的退出命令"""
+ _, text = remove_punctuation_and_length(text)
cmd_exit = conn.cmd_exit
for cmd in cmd_exit:
if text == cmd:
@@ -116,20 +40,17 @@ async def check_direct_exit(conn, text):
return False
+
async def analyze_intent_with_llm(conn, text):
"""使用LLM分析用户意图"""
if not hasattr(conn, 'intent') or not conn.intent:
logger.bind(tag=TAG).warning("意图识别服务未初始化")
return None
- # 创建对话历史记录
+ # 对话历史记录
dialogue = conn.dialogue
- dialogue.put(Message(role="user", content=text))
-
try:
- intent_result = await conn.intent.detect_intent(dialogue.dialogue)
- logger.bind(tag=TAG).info(f"意图识别结果: {intent_result}")
-
+ intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
# 尝试解析JSON结果
try:
intent_data = json.loads(intent_result)
@@ -150,9 +71,6 @@ async def process_intent_result(conn, intent, original_text):
# 处理退出意图
if "结束聊天" in intent:
logger.bind(tag=TAG).info(f"识别到退出意图: {intent}")
-
- # 如果正在播放音乐,可以关了 TODO
-
# 如果是明确的离别意图,发送告别语并关闭连接
await send_stt_message(conn, original_text)
conn.executor.submit(conn.chat_and_close, original_text)
@@ -161,10 +79,37 @@ async def process_intent_result(conn, intent, original_text):
# 处理播放音乐意图
if "播放音乐" in intent:
logger.bind(tag=TAG).info(f"识别到音乐播放意图: {intent}")
- await conn.music_handler.handle_music_command(conn, intent)
+ # 调用play_music函数来播放音乐
+ song_name = extract_text_in_brackets(intent)
+ function_id = str(uuid.uuid4().hex)
+ function_name = "play_music"
+ function_arguments = '{ "song_name": "' + song_name + '" }'
+
+ function_call_data = {
+ "name": function_name,
+ "id": function_id,
+ "arguments": function_arguments
+ }
+ conn.func_handler.handle_llm_function_call(conn, function_call_data)
return True
# 其他意图处理可以在这里扩展
# 默认返回False,表示继续常规聊天流程
return False
+
+
+def extract_text_in_brackets(s):
+ """
+ 从字符串中提取中括号内的文字
+
+ :param s: 输入字符串
+ :return: 中括号内的文字,如果不存在则返回空字符串
+ """
+ left_bracket_index = s.find('[')
+ right_bracket_index = s.find(']')
+
+ if left_bracket_index != -1 and right_bracket_index != -1 and left_bracket_index < right_bracket_index:
+ return s[left_bracket_index + 1:right_bracket_index]
+ else:
+ return ""
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/handle/iotHandle.py b/main/xiaozhi-server/core/handle/iotHandle.py
index 05d32d5ad..1f75330dc 100644
--- a/main/xiaozhi-server/core/handle/iotHandle.py
+++ b/main/xiaozhi-server/core/handle/iotHandle.py
@@ -1,24 +1,120 @@
import json
+import asyncio
from config.logger import setup_logging
+from plugins_func.register import device_type_registry, register_function, ActionResponse, Action, ToolType
TAG = __name__
logger = setup_logging()
+def wrap_async_function(async_func):
+ """包装异步函数为同步函数"""
+
+ def wrapper(*args, **kwargs):
+ try:
+ # 获取连接对象(第一个参数)
+ conn = args[0]
+ if not hasattr(conn, 'loop'):
+ logger.bind(tag=TAG).error("Connection对象没有loop属性")
+ return ActionResponse(Action.ERROR, "Connection对象没有loop属性",
+ "执行操作时出错: Connection对象没有loop属性")
+
+ # 使用conn对象中的事件循环
+ loop = conn.loop
+ # 在conn的事件循环中运行异步函数
+ future = asyncio.run_coroutine_threadsafe(async_func(*args, **kwargs), loop)
+ # 等待结果返回
+ return future.result()
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"运行异步函数时出错: {e}")
+ return ActionResponse(Action.ERROR, str(e), f"执行操作时出错: {e}")
+
+ return wrapper
+
+
+def create_iot_function(device_name, method_name, method_info):
+ """
+ 根据IOT设备描述生成通用的控制函数
+ """
+
+ async def iot_control_function(conn, response_success=None, response_failure=None, **params):
+ try:
+ # 打印响应参数
+ logger.bind(tag=TAG).info(
+ f"控制函数接收到的响应参数: success='{response_success}', failure='{response_failure}'")
+
+ # 发送控制命令
+ await send_iot_conn(conn, device_name, method_name, params)
+ # 等待一小段时间让状态更新
+ await asyncio.sleep(0.1)
+
+ # 生成结果信息
+ result = f"{device_name}的{method_name}操作执行成功"
+
+
+ # 处理响应中可能的占位符
+ response = response_success
+ # 替换{value}占位符
+ for param_name, param_value in params.items():
+ # 先尝试直接替换参数值
+ if "{" + param_name + "}" in response:
+ response = response.replace("{" + param_name + "}", str(param_value))
+
+ # 如果有{value}占位符,用相关参数替换
+ if "{value}" in response:
+ response = response.replace("{value}", str(param_value))
+ break
+
+ return ActionResponse(Action.RESPONSE, result, response)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"执行{device_name}的{method_name}操作失败: {e}")
+
+ # 操作失败时使用大模型提供的失败响应
+ response = response_failure
+
+ return ActionResponse(Action.ERROR, str(e), response)
+
+ return wrap_async_function(iot_control_function)
+
+
+def create_iot_query_function(device_name, prop_name, prop_info):
+ """
+ 根据IOT设备属性创建查询函数
+ """
+
+ async def iot_query_function(conn, response_success=None, response_failure=None):
+ try:
+ # 打印响应参数
+ logger.bind(tag=TAG).info(
+ f"查询函数接收到的响应参数: success='{response_success}', failure='{response_failure}'")
+
+ value = await get_iot_status(conn, device_name, prop_name)
+
+ # 查询成功,生成结果
+ if value is not None:
+ # 使用大模型提供的成功响应,并替换其中的占位符
+ response = response_success.replace("{value}", str(value))
+
+ return ActionResponse(Action.RESPONSE, str(value), response)
+ else:
+ # 查询失败,使用大模型提供的失败响应
+ response = response_failure
+
+ return ActionResponse(Action.ERROR, f"属性{prop_name}不存在", response)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"查询{device_name}的{prop_name}时出错: {e}")
+
+ # 查询出错时使用大模型提供的失败响应
+ response = response_failure
+
+ return ActionResponse(Action.ERROR, str(e), response)
+
+ return wrap_async_function(iot_query_function)
+
+
class IotDescriptor:
"""
A class to represent an IoT descriptor.
- Attributes:
- ----------
- name : str
- The name of the IoT descriptor.
- description : str
- A brief description of the IoT descriptor.
- properties : dict
- A dictionary containing properties of the IoT descriptor.
- methods : dict
- A dictionary containing methods of the IoT descriptor.
- -------
"""
def __init__(self, name, description, properties, methods):
@@ -29,17 +125,7 @@ class IotDescriptor:
# 根据描述创建属性
for key, value in properties.items():
- # "volume":{"description":"当前音量 值","type":"number"}
- """
- 等价于
- {
- 'name': 名字,
- 'description': 描述,
- 'value': 0
- }
- """
- # setattr(self, key, {}) # 创建一个空字典, 名字是属性名
- property_item = globals()[key] = {} # 创建一个空字典, 名字是属性名
+ property_item = globals()[key] = {}
property_item['name'] = key
property_item["description"] = value["description"]
if value["type"] == "number":
@@ -52,23 +138,10 @@ class IotDescriptor:
# 根据描述创建方法
for key, value in methods.items():
- # "SetVolume": {"description":"设置音量","parameters":{"volume":{"description":"0到100之间的整数","type":"number"}}}
- """
- 等价于
- SetVolume = {
- `description`: 描述,
- `volume`: {
- `description`: 描述,
- `value`: 0
- }
- }
- """
- # setattr(self, key, {}) # 创建一个空字典, 名字是方法名
- method = globals()[key] = {} # 创建一个空字典, 名字是方法名
+ method = globals()[key] = {}
method["description"] = value["description"]
method['name'] = key
for k, v in value["parameters"].items():
- # 不同的参数解析
method[k] = {}
method[k]["description"] = v["description"]
if v["type"] == "number":
@@ -77,58 +150,136 @@ class IotDescriptor:
method[k]["value"] = False
else:
method[k]["value"] = ""
-
self.methods.append(method)
-async def handleIotDescriptors(conn, descriptors):
- """
- 处理物联网描述
- 示例: [{
- "name":"Speaker",
- "description":"当前 AI 机器人的扬声器",
- "properties":{
- "volume":{"description":"当前音量 值","type":"number"} 可以有boolean, number, string三种类型
- },
- "methods":{
- "SetVolume":{
- "description":"设置音量","parameters":{"volume":{"description":"0到100之间的整数","type":"number"}}
+def register_device_type(descriptor):
+ """注册设备类型及其功能"""
+ device_name = descriptor["name"]
+ type_id = device_type_registry.generate_device_type_id(descriptor)
+
+ # 如果该类型已注册,直接返回类型ID
+ if type_id in device_type_registry.type_functions:
+ return type_id
+
+ functions = {}
+
+ # 为每个属性创建查询函数
+ for prop_name, prop_info in descriptor["properties"].items():
+ func_name = f"get_{device_name.lower()}_{prop_name.lower()}"
+ func_desc = {
+ "type": "function",
+ "function": {
+ "name": func_name,
+ "description": f"查询{descriptor['description']}的{prop_info['description']}",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "response_success": {
+ "type": "string",
+ "description": f"查询成功时的友好回复,必须使用{{value}}作为占位符表示查询到的值"
+ },
+ "response_failure": {
+ "type": "string",
+ "description": f"查询失败时的友好回复,例如:'无法获取{device_name}的{prop_info['description']}'"
+ }
+ },
+ "required": ["response_success", "response_failure"]
+ }
}
}
- }]
- descriptors: 描述列表
- """
+ query_func = create_iot_query_function(device_name, prop_name, prop_info)
+ decorated_func = register_function(func_name, func_desc, ToolType.IOT_CTL)(query_func)
+ functions[func_name] = decorated_func
+
+ # 为每个方法创建控制函数
+ for method_name, method_info in descriptor["methods"].items():
+ func_name = f"{device_name.lower()}_{method_name.lower()}"
+
+ # 创建参数字典,添加原有参数
+ parameters = {
+ param_name: {
+ "type": param_info["type"],
+ "description": param_info["description"]
+ }
+ for param_name, param_info in method_info["parameters"].items()
+ }
+
+ # 添加响应参数
+ parameters.update({
+ "response_success": {
+ "type": "string",
+ "description": "操作成功时的友好回复,关于该设备的操作结果,设备名称尽量使用description中的名称"
+ },
+ "response_failure": {
+ "type": "string",
+ "description": "操作失败时的友好回复,关于该设备的操作结果,设备名称尽量使用description中的名称"
+ }
+ })
+
+ # 构建必须参数列表(原有参数 + 响应参数)
+ required_params = list(method_info["parameters"].keys())
+ required_params.extend(["response_success", "response_failure"])
+
+ func_desc = {
+ "type": "function",
+ "function": {
+ "name": func_name,
+ "description": f"{descriptor['description']} - {method_info['description']}",
+ "parameters": {
+ "type": "object",
+ "properties": parameters,
+ "required": required_params
+ }
+ }
+ }
+ control_func = create_iot_function(device_name, method_name, method_info)
+ decorated_func = register_function(func_name, func_desc, ToolType.IOT_CTL)(control_func)
+ functions[func_name] = decorated_func
+
+ device_type_registry.register_device_type(type_id, functions)
+ return type_id
+
+
+# 用于接受前端设备推送的搜索iot描述
+async def handleIotDescriptors(conn, descriptors):
+ """处理物联网描述"""
+ functions_changed = False
+
for descriptor in descriptors:
+ # 创建IOT设备描述符
iot_descriptor = IotDescriptor(descriptor["name"], descriptor["description"], descriptor["properties"],
descriptor["methods"])
conn.iot_descriptors[descriptor["name"]] = iot_descriptor
- # 暂时从配置文件中设置音量,后期通过意图识别控制音量
- default_iot_volume = 100
- if "iot" in conn.config:
- default_iot_volume = conn.config["iot"]["Speaker"]["volume"]
- logger.bind(tag=TAG).info(f"服务端设置音量为{default_iot_volume}")
- await send_iot_conn(conn, "Speaker", "SetVolume", {"volume": default_iot_volume})
+ if conn.use_function_call_mode:
+ # 注册或获取设备类型
+ type_id = register_device_type(descriptor)
+ device_functions = device_type_registry.get_device_functions(type_id)
+
+ # 在连接级注册设备函数
+ if hasattr(conn, 'func_handler'):
+ for func_name in device_functions:
+ conn.func_handler.function_registry.register_function(func_name)
+ logger.bind(tag=TAG).info(f"注册IOT函数到function handler: {func_name}")
+ functions_changed = True
+
+ # 如果注册了新函数,更新function描述列表
+ if functions_changed and hasattr(conn, 'func_handler'):
+ conn.func_handler.upload_functions_desc()
+ func_names = conn.func_handler.current_support_functions()
+ logger.bind(tag=TAG).info(f"设备类型: {type_id}")
+ logger.bind(tag=TAG).info(f"更新function描述列表完成,当前支持的函数: {func_names}")
+
+
async def handleIotStatus(conn, states):
- """
- 处理物联网状态
- 示例: [{
- "name":"Speaker",
- "state":{
- "volume":100
- }
- }]
- states: 状态列表
- """
+ """处理物联网状态"""
for state in states:
for key, value in conn.iot_descriptors.items():
if key == state["name"]:
for property_item in value.properties:
- # properties为字典列表, 记录各种属性
for k, v in state["state"].items():
- # state为字典, 记录各种属性的值, 是需要记录的信息
if property_item["name"] == k:
- # 检查一下属性是不是相同的
if type(v) != type(property_item["value"]):
logger.bind(tag=TAG).error(f"属性{property_item['name']}的值类型不匹配")
break
@@ -138,41 +289,35 @@ async def handleIotStatus(conn, states):
break
break
+
async def get_iot_status(conn, name, property_name):
- """
- 获取物联网状态
- name: 设备名称 "Speaker"
- property_name: 属性名称 "volume"
- 返回值: 属性值, 实际的属性有int, bool和str三种类型
- """
+ """获取物联网状态"""
for key, value in conn.iot_descriptors.items():
if key == name:
for property_item in value.properties:
if property_item["name"] == property_name:
return property_item["value"]
+ logger.bind(tag=TAG).warning(f"未找到设备 {name} 的属性 {property_name}")
return None
-async def send_iot_conn(conn, name, method_name, parameters):
- """
- 发送物联网指令
- name: 设备名称 "Speaker"
- method: 方法 "SetVolume"
- parameters: 参数, 是一个字典 {"volume": 100}
- 发送示例:
- {
- "type": "iot",
- "commands": [
- {
- "name" : "Speaker",
- "method": "SetVolume",
- "parameters": {
- "volume": 100
- }
- }
- ]
- }
- """
+async def set_iot_status(conn, name, property_name, value):
+ """设置物联网状态"""
+ for key, iot_descriptor in conn.iot_descriptors.items():
+ if key == name:
+ for property_item in iot_descriptor.properties:
+ if property_item["name"] == property_name:
+ if type(value) != type(property_item["value"]):
+ logger.bind(tag=TAG).error(f"属性{property_item['name']}的值类型不匹配")
+ return
+ property_item["value"] = value
+ logger.bind(tag=TAG).info(f"物联网状态更新: {name} , {property_name} = {value}")
+ return
+ logger.bind(tag=TAG).warning(f"未找到设备 {name} 的属性 {property_name}")
+
+
+async def send_iot_conn(conn, name, method_name, parameters):
+ """发送物联网指令"""
for key, value in conn.iot_descriptors.items():
if key == name:
# 找到了设备
diff --git a/main/xiaozhi-server/core/handle/musicHandler.py b/main/xiaozhi-server/core/handle/musicHandler.py
deleted file mode 100644
index 022d6dc46..000000000
--- a/main/xiaozhi-server/core/handle/musicHandler.py
+++ /dev/null
@@ -1,139 +0,0 @@
-from config.logger import setup_logging
-import os
-import random
-import difflib
-import re
-import traceback
-from pathlib import Path
-import time
-from core.handle.sendAudioHandle import send_stt_message
-from core.utils import p3
-
-TAG = __name__
-logger = setup_logging()
-
-
-def _extract_song_name(text):
- """从用户输入中提取歌名"""
- for keyword in ["播放音乐"]:
- if keyword in text:
- parts = text.split(keyword)
- if len(parts) > 1:
- return parts[1].strip()
- return None
-
-
-def _find_best_match(potential_song, music_files):
- """查找最匹配的歌曲"""
- best_match = None
- highest_ratio = 0
-
- for music_file in music_files:
- song_name = os.path.splitext(music_file)[0]
- ratio = difflib.SequenceMatcher(None, potential_song, song_name).ratio()
- if ratio > highest_ratio and ratio > 0.4:
- highest_ratio = ratio
- best_match = music_file
- return best_match
-
-
-class MusicManager:
- def __init__(self, music_dir, music_ext):
- self.music_dir = Path(music_dir)
- self.music_ext = music_ext
-
- def get_music_files(self):
- music_files = []
- for file in self.music_dir.rglob("*"):
- # 判断是否是文件
- if file.is_file():
- # 获取文件扩展名
- ext = file.suffix.lower()
- # 判断扩展名是否在列表中
- if ext in self.music_ext:
- # music_files.append(str(file.resolve())) # 添加绝对路径
- # 添加相对路径
- music_files.append(str(file.relative_to(self.music_dir)))
- return music_files
-
-
-class MusicHandler:
- def __init__(self, config):
- self.config = config
-
- if "music" in self.config:
- self.music_config = self.config["music"]
- self.music_dir = os.path.abspath(
- self.music_config.get("music_dir", "./music") # 默认路径修改
- )
- self.music_ext = self.music_config.get("music_ext", (".mp3", ".wav", ".p3"))
- self.refresh_time = self.music_config.get("refresh_time", 60)
- else:
- self.music_dir = os.path.abspath("./music")
- self.music_ext = (".mp3", ".wav", ".p3")
- self.refresh_time = 60
-
- # 获取音乐文件列表
- self.music_files = MusicManager(self.music_dir, self.music_ext).get_music_files()
- self.scan_time = time.time()
- logger.bind(tag=TAG).debug(f"找到的音乐文件: {self.music_files}")
-
- async def handle_music_command(self, conn, text):
- """处理音乐播放指令"""
- clean_text = re.sub(r'[^\w\s]', '', text).strip()
- logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}")
-
- # 尝试匹配具体歌名
- if os.path.exists(self.music_dir):
- if time.time() - self.scan_time > self.refresh_time:
- # 刷新音乐文件列表
- self.music_files = MusicManager(self.music_dir, self.music_ext).get_music_files()
- self.scan_time = time.time()
- logger.bind(tag=TAG).debug(f"刷新的音乐文件: {self.music_files}")
-
- potential_song = _extract_song_name(clean_text)
- if potential_song:
- best_match = _find_best_match(potential_song, self.music_files)
- if best_match:
- logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
- await self.play_local_music(conn, specific_file=best_match)
- return True
- # 检查是否是通用播放音乐命令
- await self.play_local_music(conn)
- return True
-
- async def play_local_music(self, conn, specific_file=None):
- """播放本地音乐文件"""
- try:
- if not os.path.exists(self.music_dir):
- logger.bind(tag=TAG).error(f"音乐目录不存在: {self.music_dir}")
- return
-
- # 确保路径正确性
- if specific_file:
- selected_music = specific_file
- music_path = os.path.join(self.music_dir, specific_file)
- else:
- if not self.music_files:
- logger.bind(tag=TAG).error("未找到MP3音乐文件")
- return
- selected_music = random.choice(self.music_files)
- music_path = os.path.join(self.music_dir, selected_music)
-
- if not os.path.exists(music_path):
- logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}")
- return
- text = f"正在播放{selected_music}"
- await send_stt_message(conn, text)
- conn.tts_first_text_index = 0
- conn.tts_last_text_index = 0
- conn.llm_finish_task = True
- if music_path.endswith(".p3"):
- opus_packets, duration = p3.decode_opus_from_file(music_path)
- else:
- opus_packets, duration = conn.tts.wav_to_opus_data(music_path)
- conn.audio_play_queue.put((opus_packets, selected_music, 0))
-
- except Exception as e:
- logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}")
- logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
index 97624898c..c5b4135ca 100644
--- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
@@ -20,7 +20,8 @@ async def handleAudioMessage(conn, audio):
# 如果本次没有声音,本段也没声音,就把声音丢弃了
if have_voice == False and conn.client_have_voice == False:
await no_voice_close_connect(conn)
- conn.asr_audio.clear()
+ conn.asr_audio.append(audio)
+ conn.asr_audio = conn.asr_audio[-5:] # 保留最新的5帧音频内容,解决ASR句首丢字问题
return
conn.client_no_voice_last_time = 0.0
conn.asr_audio.append(audio)
@@ -29,7 +30,7 @@ async def handleAudioMessage(conn, audio):
conn.client_abort = False
conn.asr_server_receive = False
# 音频太短了,无法识别
- if len(conn.asr_audio) < 3:
+ if len(conn.asr_audio) < 10:
conn.asr_server_receive = True
else:
text, file_path = await conn.asr.speech_to_text(conn.asr_audio, conn.session_id)
@@ -67,8 +68,9 @@ async def no_voice_close_connect(conn):
else:
no_voice_time = time.time() * 1000 - conn.client_no_voice_last_time
close_connection_no_voice_time = conn.config.get("close_connection_no_voice_time", 120)
- if no_voice_time > 1000 * close_connection_no_voice_time:
+ if not conn.close_after_chat and no_voice_time > 1000 * close_connection_no_voice_time:
+ conn.close_after_chat = True
conn.client_abort = False
conn.asr_server_receive = False
- prompt = "时间过得真快,我都好久没说话了。请你用十个字左右话跟我告别,以“再见”或“拜拜”为结尾"
+ prompt = "请你以“时间过得真快”未来头,用富有感情、依依不舍的话来结束这场对话吧。"
await startToChat(conn, prompt)
diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py
index 1cce98b46..9a289d758 100644
--- a/main/xiaozhi-server/core/handle/sendAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py
@@ -7,40 +7,56 @@ from core.utils.util import remove_punctuation_and_length, get_string_no_punctua
TAG = __name__
logger = setup_logging()
+
async def sendAudioMessage(conn, audios, text, text_index=0):
# 发送句子开始消息
if text_index == conn.tts_first_text_index:
logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
await send_tts_message(conn, "sentence_start", text)
- # 初始化流控参数
- frame_duration = 60 # 毫秒
- start_time = time.perf_counter() # 使用高精度计时器
- play_position = 0 # 已播放的时长(毫秒)
+ # 播放音频
+ await sendAudio(conn, audios)
- for opus_packet in audios:
- if conn.client_abort:
- return
-
- # 计算当前包的预期发送时间
- expected_time = start_time + (play_position / 1000)
- current_time = time.perf_counter()
-
- # 等待直到预期时间
- delay = expected_time - current_time
- if delay > 0:
- await asyncio.sleep(delay)
-
- # 发送音频包
- await conn.websocket.send(opus_packet)
- play_position += frame_duration # 更新播放位置
await send_tts_message(conn, "sentence_end", text)
+
# 发送结束消息(如果是最后一个文本)
if conn.llm_finish_task and text_index == conn.tts_last_text_index:
await send_tts_message(conn, 'stop', None)
if conn.close_after_chat:
await conn.close()
+# 播放音频
+async def sendAudio(conn, audios):
+ # 流控参数优化
+ original_frame_duration = 60 # 原始帧时长(毫秒)
+ adjusted_frame_duration = int(original_frame_duration * 0.8) # 缩短20%
+ total_frames = len(audios) # 获取总帧数
+ compensation = total_frames * (original_frame_duration - adjusted_frame_duration) / 1000 # 补偿时间(秒)
+
+ start_time = time.perf_counter()
+ play_position = 0 # 已播放时长(毫秒)
+
+ for opus_packet in audios:
+ if conn.client_abort:
+ return
+
+ # 计算带加速因子的预期时间
+ expected_time = start_time + (play_position / 1000)
+ current_time = time.perf_counter()
+
+ # 流控等待(使用加速后的帧时长)
+ delay = expected_time - current_time
+ if delay > 0:
+ await asyncio.sleep(delay)
+
+ await conn.websocket.send(opus_packet)
+ play_position += adjusted_frame_duration # 使用调整后的帧时长
+
+ # 补偿因加速损失的时长
+ if compensation > 0:
+ await asyncio.sleep(compensation)
+
+
async def send_tts_message(conn, state, text=None):
"""发送 TTS 状态消息"""
message = {
@@ -51,10 +67,20 @@ async def send_tts_message(conn, state, text=None):
if text is not None:
message["text"] = text
- await conn.websocket.send(json.dumps(message))
+ # TTS播放结束
if state == "stop":
+ # 播放提示音
+ tts_notify = conn.config.get("enable_stop_tts_notify", False)
+ if tts_notify:
+ stop_tts_notify_voice = conn.config.get("stop_tts_notify_voice", "config/assets/tts_notify.mp3")
+ audios, duration = conn.tts.audio_to_opus_data(stop_tts_notify_voice)
+ await sendAudio(conn, audios)
+ # 清除服务端讲话状态
conn.clearSpeakStatus()
+ # 发送消息到客户端
+ await conn.websocket.send(json.dumps(message))
+
async def send_stt_message(conn, text):
"""发送 STT 状态消息"""
diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py
index cc28dbb40..3f60592ac 100644
--- a/main/xiaozhi-server/core/handle/textHandle.py
+++ b/main/xiaozhi-server/core/handle/textHandle.py
@@ -2,7 +2,9 @@ from config.logger import setup_logging
import json
from core.handle.abortHandle import handleAbortMessage
from core.handle.helloHandle import handleHelloMessage
-from core.handle.receiveAudioHandle import startToChat
+from core.utils.util import remove_punctuation_and_length
+from core.handle.receiveAudioHandle import startToChat, handleAudioMessage
+from core.handle.sendAudioHandle import send_stt_message, send_tts_message
from core.handle.iotHandle import handleIotDescriptors, handleIotStatus
TAG = __name__
@@ -31,16 +33,32 @@ async def handleTextMessage(conn, message):
elif msg_json["state"] == "stop":
conn.client_have_voice = True
conn.client_voice_stop = True
+ if len(conn.asr_audio) > 0:
+ await handleAudioMessage(conn, b'')
elif msg_json["state"] == "detect":
conn.asr_server_receive = False
conn.client_have_voice = False
conn.asr_audio.clear()
if "text" in msg_json:
- await startToChat(conn, msg_json["text"])
+ text = msg_json["text"]
+ _, text = remove_punctuation_and_length(text)
+
+ # 识别是否是唤醒词
+ is_wakeup_words = text in conn.config.get("wakeup_words")
+ # 是否开启唤醒词回复
+ enable_greeting = conn.config.get("enable_greeting", True)
+
+ if is_wakeup_words and not enable_greeting:
+ # 如果是唤醒词,且关闭了唤醒词回复,就不用回答
+ await send_stt_message(conn, text)
+ await send_tts_message(conn, "stop", None)
+ else:
+ # 否则需要LLM对文字内容进行答复
+ await startToChat(conn, text)
elif msg_json["type"] == "iot":
if "descriptors" in msg_json:
await handleIotDescriptors(conn, msg_json["descriptors"])
if "states" in msg_json:
- await handleIotStatus(conn, msg_json["states"])
+ await handleIotStatus(conn, msg_json["states"])
except json.JSONDecodeError:
await conn.websocket.send(message)
diff --git a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py
new file mode 100644
index 000000000..3dfa3162a
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py
@@ -0,0 +1,164 @@
+import time
+import wave
+import os
+import sys
+import io
+from config.logger import setup_logging
+from typing import Optional, Tuple, List
+import uuid
+import opuslib_next
+from core.providers.asr.base import ASRProviderBase
+
+import numpy as np
+import sherpa_onnx
+
+from modelscope.hub.file_download import model_file_download
+
+TAG = __name__
+logger = setup_logging()
+
+
+# 捕获标准输出
+class CaptureOutput:
+ def __enter__(self):
+ self._output = io.StringIO()
+ self._original_stdout = sys.stdout
+ sys.stdout = self._output
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ sys.stdout = self._original_stdout
+ self.output = self._output.getvalue()
+ self._output.close()
+
+ # 将捕获到的内容通过 logger 输出
+ if self.output:
+ logger.bind(tag=TAG).info(self.output.strip())
+
+
+class ASRProvider(ASRProviderBase):
+ def __init__(self, config: dict, delete_audio_file: bool):
+ self.model_dir = config.get("model_dir")
+ self.output_dir = config.get("output_dir")
+ self.delete_audio_file = delete_audio_file
+
+ # 确保输出目录存在
+ os.makedirs(self.output_dir, exist_ok=True)
+
+ # 初始化模型文件路径
+ model_files = {
+ "model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"),
+ "tokens.txt": os.path.join(self.model_dir, "tokens.txt")
+ }
+
+ # 下载并检查模型文件
+ try:
+ for file_name, file_path in model_files.items():
+ if not os.path.isfile(file_path):
+ logger.bind(tag=TAG).info(f"正在下载模型文件: {file_name}")
+ model_file_download(
+ model_id="pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue",
+ file_path=file_name,
+ local_dir=self.model_dir
+ )
+
+ if not os.path.isfile(file_path):
+ raise FileNotFoundError(f"模型文件下载失败: {file_path}")
+
+ self.model_path = model_files["model.int8.onnx"]
+ self.tokens_path = model_files["tokens.txt"]
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"模型文件处理失败: {str(e)}")
+ raise
+
+ with CaptureOutput():
+ self.model = sherpa_onnx.OfflineRecognizer.from_sense_voice(
+ model=self.model_path,
+ tokens=self.tokens_path,
+ num_threads=2,
+ sample_rate=16000,
+ feature_dim=80,
+ decoding_method="greedy_search",
+ debug=False,
+ use_itn=True,
+ )
+
+ def save_audio_to_file(self, opus_data: List[bytes], session_id: str) -> str:
+ """将Opus音频数据解码并保存为WAV文件"""
+ file_name = f"asr_{session_id}_{uuid.uuid4()}.wav"
+ file_path = os.path.join(self.output_dir, file_name)
+
+ decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道
+ pcm_data = []
+
+ for opus_packet in opus_data:
+ try:
+ pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
+ pcm_data.append(pcm_frame)
+ except opuslib_next.OpusError as e:
+ logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
+
+ with wave.open(file_path, "wb") as wf:
+ wf.setnchannels(1)
+ wf.setsampwidth(2) # 2 bytes = 16-bit
+ wf.setframerate(16000)
+ wf.writeframes(b"".join(pcm_data))
+
+ return file_path
+
+ def read_wave(self, wave_filename: str) -> Tuple[np.ndarray, int]:
+ """
+ Args:
+ wave_filename:
+ Path to a wave file. It should be single channel and each sample should
+ be 16-bit. Its sample rate does not need to be 16kHz.
+ Returns:
+ Return a tuple containing:
+ - A 1-D array of dtype np.float32 containing the samples, which are
+ normalized to the range [-1, 1].
+ - sample rate of the wave file
+ """
+
+ with wave.open(wave_filename) as f:
+ assert f.getnchannels() == 1, f.getnchannels()
+ assert f.getsampwidth() == 2, f.getsampwidth() # it is in bytes
+ num_samples = f.getnframes()
+ samples = f.readframes(num_samples)
+ samples_int16 = np.frombuffer(samples, dtype=np.int16)
+ samples_float32 = samples_int16.astype(np.float32)
+
+ samples_float32 = samples_float32 / 32768
+ return samples_float32, f.getframerate()
+
+ async def speech_to_text(self, opus_data: List[bytes], session_id: str) -> Tuple[Optional[str], Optional[str]]:
+ """语音转文本主处理逻辑"""
+ file_path = None
+ try:
+ # 保存音频文件
+ start_time = time.time()
+ file_path = self.save_audio_to_file(opus_data, session_id)
+ logger.bind(tag=TAG).debug(f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}")
+
+ # 语音识别
+ start_time = time.time()
+ s = self.model.create_stream()
+ samples, sample_rate = self.read_wave(file_path)
+ s.accept_waveform(sample_rate, samples)
+ self.model.decode_stream(s)
+ text = s.result.text
+ logger.bind(tag=TAG).debug(f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}")
+
+ return text, file_path
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
+ return "", None
+
+ finally:
+ # 文件清理逻辑
+ if self.delete_audio_file and file_path and os.path.exists(file_path):
+ try:
+ os.remove(file_path)
+ logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
diff --git a/main/xiaozhi-server/core/providers/intent/base.py b/main/xiaozhi-server/core/providers/intent/base.py
index 1333f620b..a691d6cbd 100644
--- a/main/xiaozhi-server/core/providers/intent/base.py
+++ b/main/xiaozhi-server/core/providers/intent/base.py
@@ -5,6 +5,7 @@ from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
+
class IntentProviderBase(ABC):
def __init__(self, config):
self.config = config
@@ -17,9 +18,9 @@ class IntentProviderBase(ABC):
def set_llm(self, llm):
self.llm = llm
logger.bind(tag=TAG).debug("Set LLM for intent provider")
-
+
@abstractmethod
- async def detect_intent(self, dialogue_history: List[Dict]) -> str:
+ async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
检测用户最后一句话的意图
Args:
diff --git a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py
index c3930296a..9d5d2507e 100644
--- a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py
+++ b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py
@@ -1,12 +1,13 @@
from typing import List, Dict
from ..base import IntentProviderBase
+from plugins_func.functions.play_music import initialize_music_handler
from config.logger import setup_logging
+import re
TAG = __name__
logger = setup_logging()
-
class IntentProvider(IntentProviderBase):
def __init__(self, config):
super().__init__(config)
@@ -20,42 +21,91 @@ class IntentProvider(IntentProviderBase):
格式化后的系统提示词
"""
intent_list = []
+
+ """
+ "continue_chat": "1.继续聊天, 除了播放音乐和结束聊天的时候的选项, 比如日常的聊天和问候, 对话等",
+ "end_chat": "2.结束聊天, 用户发来如再见之类的表示结束的话, 不想再进行对话的时候",
+ "play_music": "3.播放音乐, 用户希望你可以播放音乐, 只用于播放音乐的意图"
+ """
for key, value in self.intent_options.items():
if key == "play_music":
- intent_list.append(f"{value} [歌名]")
+ intent_list.append("3.播放音乐, 用户希望你可以播放音乐, 只用于播放音乐的意图")
+ elif key == "end_chat":
+ intent_list.append("2.结束聊天, 用户发来如再见之类的表示结束的话, 不想再进行对话的时候")
+ elif key == "continue_chat":
+ intent_list.append("1.继续聊天, 除了播放音乐和结束聊天的时候的选项, 比如日常的聊天和问候, 对话等")
else:
intent_list.append(value)
-
+
+ # "如果是唱歌、听歌、播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n"
+ # "如果听不出具体歌名,可以返回'随机播放音乐'。\n"
+ # "只需要返回意图结果的json,不要解释。"
+ # "返回格式如下:\n"
prompt = (
- "你是一个意图识别助手。你需要根据和用户的对话记录,重点分析用户的最后一句话,判断用户意图属于以下哪一类:\n"
- f"{', '.join(intent_list)}\n"
- "如果是唱歌、听歌、播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n"
- "如果听不出具体歌名,可以返回'随机播放音乐'。\n"
- "只需要返回意图结果的json,不要解释。"
- "返回格式如下:\n"
- "{intent: '用户意图'}"
+ "你是一个意图识别助手。你需要根据和用户的对话记录,重点分析用户的最后一句话,判断用户意图属于以下哪一类(使用和标志):\n"
+ ""
+ f"{', '.join(intent_list)}"
+ "\n"
+ "你需要按照以下的步骤处理用户的对话"
+ "1. 思考出对话的意图是哪一类的"
+ "2. 属于1和2的意图, 直接返回,返回格式如下:\n"
+ "{intent: '用户意图'}\n"
+ "3. 属于3的意图,则继续分析用户希望播放的音乐\n"
+ "4. 如果无法识别出具体歌名,可以返回'随机播放音乐'\n"
+ "{intent: '播放音乐 [获取的音乐名字]'}\n"
+ "下面是几个处理的示例(思考的内容不返回, 只返回json部分, 无额外的内容)\n"
+ "```"
+ "用户: 你今天怎么样?\n"
+ "思考(不返回): 用户发来的数据是一个问候语,属于继续聊天的意图, 是种类1, 种类1的需求是直接返回\n"
+ "返回结果: {intent: '继续聊天'}\n"
+ "```"
+ "用户: 我今天有点累了, 我们明天再聊吧\n"
+ "思考(不返回): 用户表达了今天不想继续对话,属于结束聊天的意图, 是种类2, 种类2的需求是直接返回\n"
+ "返回结果: {intent: '结束聊天'}\n"
+ "```"
+ "用户: 我今天有点累了, 我们明天再聊吧\n"
+ "思考(不返回): 用户表达了今天不想继续对话,属于结束聊天的意图, 是种类2, 种类2的需求是直接返回\n"
+ "返回结果: {intent: '结束聊天'}\n"
+ "```"
+ "用户: 你可以播放一首中秋月给我听吗\n"
+ "思考(不返回): 用户表达了想听音乐的续签,属于播放音乐的意图, 是种类3, 种类3的需求需要继续判断播放的音乐, 这里用户希望的歌曲名明确给出是中秋月\n"
+ "返回结果: {intent: '播放音乐 [中秋月]'}\n"
+ "```"
+ "你现在可以使用的音乐的名称如下(使用和标志):\n"
)
return prompt
-
- async def detect_intent(self, dialogue_history: List[Dict]) -> str:
+
+ async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
if not self.llm:
raise ValueError("LLM provider not set")
# 构建用户最后一句话的提示
msgStr = ""
- for msg in dialogue_history:
- if msg.role == "user":
- msgStr += f"User: {msg.content}\n"
- elif msg.role== "assistant":
- msgStr += f"Assistant: {msg.content}\n"
- user_prompt = f"请分析用户的意图:\n{msgStr}"
-
+ # 只使用最后两句即可
+ if len(dialogue_history) >= 2:
+ # 保证最少有两句话的时候处理
+ msgStr += f"{dialogue_history[-2].role}: {dialogue_history[-2].content}\n"
+ msgStr += f"{dialogue_history[-1].role}: {dialogue_history[-1].content}\n"
+
+ msgStr += f"User: {text}\n"
+ user_prompt = f"当前的对话如下:\n{msgStr}"
+ music_config = initialize_music_handler(conn)
+ music_file_names = music_config["music_file_names"]
+ prompt_music = f"{self.promot}\n{music_file_names}\n"
+ logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
# 使用LLM进行意图识别
intent = self.llm.response_no_stream(
- system_prompt=self.promot,
+ system_prompt=prompt_music,
user_prompt=user_prompt
)
-
+ # 使用正则表达式提取大括号中的内容
+ # 使用正则表达式提取 {} 中的内容
+ match = re.search(r'\{.*?\}', intent)
+ if match:
+ result = match.group(0)
+ intent = result
+ else:
+ intent = "{intent: '继续聊天'}"
logger.bind(tag=TAG).info(f"Detected intent: {intent}")
return intent.strip()
diff --git a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py b/main/xiaozhi-server/core/providers/intent/nointent/nointent.py
index 9feadaad2..7efccbfea 100644
--- a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py
+++ b/main/xiaozhi-server/core/providers/intent/nointent/nointent.py
@@ -5,12 +5,14 @@ from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
+
class IntentProvider(IntentProviderBase):
- async def detect_intent(self, dialogue_history: List[Dict]) -> str:
+ async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
默认的意图识别实现,始终返回继续聊天
Args:
dialogue_history: 对话历史记录列表
+ text: 本次对话记录
Returns:
固定返回"继续聊天"
"""
diff --git a/main/xiaozhi-server/core/providers/llm/AliBL/AliBL.py b/main/xiaozhi-server/core/providers/llm/AliBL/AliBL.py
new file mode 100644
index 000000000..51efdc06e
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/llm/AliBL/AliBL.py
@@ -0,0 +1,52 @@
+from config.logger import setup_logging
+from http import HTTPStatus
+from dashscope import Application
+from core.providers.llm.base import LLMProviderBase
+
+TAG = __name__
+logger = setup_logging()
+
+class LLMProvider(LLMProviderBase):
+ def __init__(self, config):
+ self.api_key = config["api_key"]
+ self.app_id = config["app_id"]
+ self.base_url = config.get("base_url")
+ self.is_No_prompt = config.get("is_no_prompt")
+ self.memory_id = config.get("ali_memory_id")
+
+ def response(self, session_id, dialogue):
+ try:
+ # 处理dialogue
+ if self.is_No_prompt:
+ dialogue.pop(0)
+ logger.bind(tag=TAG).debug(f"【阿里百练API服务】处理后的dialogue: {dialogue}")
+
+ # 构造调用参数
+ call_params = {
+ "api_key": self.api_key,
+ "app_id": self.app_id,
+ "session_id": session_id,
+ "messages": dialogue
+ }
+ if self.memory_id != False:
+ # 百练memory需要prompt参数
+ prompt = dialogue[-1].get("content")
+ call_params["memory_id"] = self.memory_id
+ call_params["prompt"] = prompt
+ logger.bind(tag=TAG).debug(f"【阿里百练API服务】处理后的prompt: {prompt}")
+
+ responses = Application.call(**call_params)
+ if responses.status_code != HTTPStatus.OK:
+ logger.bind(tag=TAG).error(
+ f"code={responses.status_code}, "
+ f"message={responses.message}, "
+ f"请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
+ )
+ yield "【阿里百练API服务响应异常】"
+ else:
+ logger.bind(tag=TAG).debug(f"【阿里百练API服务】构造参数: {call_params}")
+ yield responses.output.text
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"【阿里百练API服务】响应异常: {e}")
+ yield "【LLM服务响应异常】"
diff --git a/main/xiaozhi-server/core/providers/llm/coze/coze.py b/main/xiaozhi-server/core/providers/llm/coze/coze.py
index feb62ea64..b1b14d91d 100644
--- a/main/xiaozhi-server/core/providers/llm/coze/coze.py
+++ b/main/xiaozhi-server/core/providers/llm/coze/coze.py
@@ -11,19 +11,31 @@ from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, Cha
TAG = __name__
logger = setup_logging()
+
class LLMProvider(LLMProviderBase):
def __init__(self, config):
self.personal_access_token = config.get("personal_access_token")
self.bot_id = config.get("bot_id")
self.user_id = config.get("user_id")
+ self.session_conversation_map = {} # 存储session_id和conversation_id的映射
def response(self, session_id, dialogue):
coze_api_token = self.personal_access_token
coze_api_base = COZE_CN_BASE_URL
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
-
+
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)
+ conversation_id = self.session_conversation_map.get(session_id)
+
+ # 如果没有找到conversation_id,则创建新的对话
+ if not conversation_id:
+ conversation = coze.conversations.create(
+ messages=[
+ ]
+ )
+ conversation_id = conversation.id
+ self.session_conversation_map[session_id] = conversation_id # 更新映射
for event in coze.chat.stream(
bot_id=self.bot_id,
@@ -31,6 +43,7 @@ class LLMProvider(LLMProviderBase):
additional_messages=[
Message.build_user_question_text(last_msg["content"]),
],
+ conversation_id=conversation_id,
):
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
print(event.message.content, end="", flush=True)
diff --git a/main/xiaozhi-server/core/providers/llm/dify/dify.py b/main/xiaozhi-server/core/providers/llm/dify/dify.py
index 0e9c821ae..5300fc797 100644
--- a/main/xiaozhi-server/core/providers/llm/dify/dify.py
+++ b/main/xiaozhi-server/core/providers/llm/dify/dify.py
@@ -9,30 +9,70 @@ logger = setup_logging()
class LLMProvider(LLMProviderBase):
def __init__(self, config):
self.api_key = config["api_key"]
+ self.mode = config.get("mode", "chat-messages")
self.base_url = config.get("base_url", "https://api.dify.ai/v1").rstrip('/')
+ self.session_conversation_map = {} # 存储session_id和conversation_id的映射
def response(self, session_id, dialogue):
try:
# 取最后一条用户消息
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
+ conversation_id = self.session_conversation_map.get(session_id)
# 发起流式请求
- with requests.post(
- f"{self.base_url}/chat-messages",
- headers={"Authorization": f"Bearer {self.api_key}"},
- json={
+ if self.mode == "chat-messages":
+ request_json = {
"query": last_msg["content"],
"response_mode": "streaming",
"user": session_id,
- "inputs": {}
- },
+ "inputs": {},
+ "conversation_id": conversation_id
+ }
+ elif self.mode == "workflows/run":
+ request_json = {
+ "inputs": {"query": last_msg["content"]},
+ "response_mode": "streaming",
+ "user": session_id
+ }
+ elif self.mode == "completion-messages":
+ request_json = {
+ "inputs": {"query": last_msg["content"]},
+ "response_mode": "streaming",
+ "user": session_id
+ }
+
+ with requests.post(
+ f"{self.base_url}/{self.mode}",
+ headers={"Authorization": f"Bearer {self.api_key}"},
+ json=request_json,
stream=True
) as r:
- for line in r.iter_lines():
- if line.startswith(b'data: '):
- event = json.loads(line[6:])
- if event.get('answer'):
- yield event['answer']
+ if self.mode == "chat-messages":
+ for line in r.iter_lines():
+ if line.startswith(b'data: '):
+ event = json.loads(line[6:])
+ # 如果没有找到conversation_id,则获取此次conversation_id
+ if not conversation_id:
+ conversation_id = event.get('conversation_id')
+ self.session_conversation_map[session_id] = conversation_id # 更新映射
+ if event.get('answer'):
+ yield event['answer']
+ elif self.mode == "workflows/run":
+ for line in r.iter_lines():
+ # logger.bind(tag=TAG).info(f"chat message response: {line}")
+ if line.startswith(b'data: '):
+ event = json.loads(line[6:])
+ if event.get('event') == "workflow_finished":
+ if event['data']['status'] == "succeeded":
+ yield event['data']['outputs']['answer']
+ else:
+ yield "【服务响应异常】"
+ elif self.mode == "completion-messages":
+ for line in r.iter_lines():
+ if line.startswith(b'data: '):
+ event = json.loads(line[6:])
+ if event.get('answer'):
+ yield event['answer']
except Exception as e:
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
diff --git a/main/xiaozhi-server/core/providers/llm/gemini/gemini.py b/main/xiaozhi-server/core/providers/llm/gemini/gemini.py
index f753ac3ea..93c7dcb5f 100644
--- a/main/xiaozhi-server/core/providers/llm/gemini/gemini.py
+++ b/main/xiaozhi-server/core/providers/llm/gemini/gemini.py
@@ -1,14 +1,19 @@
import google.generativeai as genai
from core.utils.util import check_model_key
from core.providers.llm.base import LLMProviderBase
-
+from config.logger import setup_logging
+import requests
+import json
+TAG = __name__
+logger = setup_logging()
class LLMProvider(LLMProviderBase):
def __init__(self, config):
"""初始化Gemini LLM Provider"""
self.model_name = config.get("model_name", "gemini-1.5-pro")
self.api_key = config.get("api_key")
-
+ self.http_proxy=config.get("http_proxy")
+ self.https_proxy = config.get("https_proxy")
have_key = check_model_key("LLM", self.api_key)
if not have_key:
@@ -16,6 +21,19 @@ class LLMProvider(LLMProviderBase):
try:
# 初始化Gemini客户端
+ # 配置代理(如果提供了代理配置)
+ self.proxies=None
+ if self.http_proxy is not "" or self.https_proxy is not "":
+
+ self.proxies = {
+ "http": self.http_proxy,
+ "https": self.https_proxy,
+ }
+ logger.bind(tag=TAG).info(f"Gemini set proxys:{self.proxies}")
+ # 使用猴子补丁修改 google-generativeai 库的请求会话
+
+ # 使用 session 对象配置 genai
+
genai.configure(api_key=self.api_key)
self.model = genai.GenerativeModel(self.model_name)
@@ -46,26 +64,54 @@ class LLMProvider(LLMProviderBase):
if content:
chat_history.append({
"role": role,
- "parts": [content]
+ "parts": [{"text":content}]
+
})
# 获取当前消息
current_msg = dialogue[-1]["content"]
- # 创建新的聊天会话
- chat = self.model.start_chat(history=chat_history)
+ # 构建请求体
+ request_body = {
+ "contents": chat_history + [{"role": "user", "parts": [{"text":current_msg}]}],
+ "generationConfig": self.generation_config
+ }
- # 发送消息并获取流式响应
- response = chat.send_message(
- current_msg,
- stream=True,
- generation_config=self.generation_config
- )
+ # 构建请求URL
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/{self.model_name}:generateContent?key={self.api_key}"
- # 处理流式响应
- for chunk in response:
- if hasattr(chunk, 'text') and chunk.text:
- yield chunk.text
+ # 构建请求头
+ headers = {
+ "Content-Type": "application/json",
+ }
+
+ # 发送POST请求,经测试手动 request 无法使用 stream 模式
+ if self.proxies:
+ response = requests.post(url, headers=headers, json=request_body, stream=False, proxies=self.proxies)
+ try:
+ data = response.json() # 直接解析JSON
+ if 'candidates' in data and data['candidates']:
+ yield data['candidates'][0]['content']['parts'][0]['text']
+ else:
+ yield "未找到候选回复。"
+ except json.JSONDecodeError as e:
+ yield f"JSON解码错误:{e}"
+ except Exception as e:
+ yield f"发生错误:{e}"
+ else:
+ logger.bind(tag=TAG).info(f"Gemini stream mode ")
+ chat = self.model.start_chat(history=chat_history)
+
+ # 发送消息并获取流式响应
+ response = chat.send_message(
+ current_msg,
+ stream=True,
+ generation_config=self.generation_config
+ )
+ # 处理流式响应
+ for chunk in response:
+ if hasattr(chunk, 'text') and chunk.text:
+ yield chunk.text
except Exception as e:
error_msg = str(e)
@@ -78,3 +124,13 @@ class LLMProvider(LLMProviderBase):
yield "【Gemini API key无效】"
else:
yield f"【Gemini服务响应异常: {error_msg}】"
+
+
+
+
+ except requests.exceptions.RequestException as e:
+ yield f"请求失败:{e}"
+ except json.JSONDecodeError as e:
+ yield f"JSON解码错误:{e}"
+ except Exception as e:
+ yield f"发生错误:{e}"
diff --git a/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py b/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py
deleted file mode 100644
index 115e85e95..000000000
--- a/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py
+++ /dev/null
@@ -1,62 +0,0 @@
-import requests
-from requests.exceptions import RequestException
-from config.logger import setup_logging
-from core.providers.llm.base import LLMProviderBase
-
-TAG = __name__
-logger = setup_logging()
-
-
-class LLMProvider(LLMProviderBase):
- def __init__(self, config):
- self.agent_id = config.get("agent_id") # 对应 agent_id
- self.api_key = config.get("api_key")
- self.base_url = config.get("base_url", config.get("url")) # 默认使用 base_url
- self.api_url = f"{self.base_url}/api/conversation/process" # 拼接完整的 API URL
-
- def response(self, session_id, dialogue):
- print(dialogue)
- try:
- # home assistant语音助手自带意图,无需使用xiaozhi ai自带的,只需要把用户说的话传递给home assistant即可
-
- # 提取最后一个 role 为 'user' 的 content
- input_text = None
- if isinstance(dialogue, list): # 确保 dialogue 是一个列表
- # 逆序遍历,找到最后一个 role 为 'user' 的消息
- for message in reversed(dialogue):
- if message.get("role") == "user": # 找到 role 为 'user' 的消息
- input_text = message.get("content", "")
- break # 找到后立即退出循环
-
- # 构造请求数据
- payload = {
- "text": input_text,
- "agent_id": self.agent_id,
- "conversation_id": session_id # 使用 session_id 作为 conversation_id
- }
- # 设置请求头
- headers = {
- "Authorization": f"Bearer {self.api_key}",
- "Content-Type": "application/json"
- }
-
- # 发起 POST 请求
- response = requests.post(self.api_url, json=payload, headers=headers)
-
- # 检查请求是否成功
- response.raise_for_status()
-
- # 解析返回数据
- data = response.json()
- speech = data.get("response", {}).get("speech", {}).get("plain", {}).get("speech", "")
-
- # 返回生成的内容
- if speech:
- yield speech
- else:
- logger.bind(tag=TAG).warning("API 返回数据中没有 speech 内容")
-
- except RequestException as e:
- logger.bind(tag=TAG).error(f"HTTP 请求错误: {e}")
- except Exception as e:
- logger.bind(tag=TAG).error(f"生成响应时出错: {e}")
diff --git a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py
index 86d0f6ee8..179a85b1e 100644
--- a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py
+++ b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py
@@ -12,10 +12,10 @@ class LLMProvider(LLMProviderBase):
self.model_name = config.get("model_name")
self.base_url = config.get("base_url", "http://localhost:11434")
# Initialize OpenAI client with Ollama base URL
- #如果没有v1,增加v1
+ # 如果没有v1,增加v1
if not self.base_url.endswith("/v1"):
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
@@ -28,13 +28,20 @@ class LLMProvider(LLMProviderBase):
messages=dialogue,
stream=True
)
-
+ is_active=True
for chunk in responses:
try:
delta = chunk.choices[0].delta if getattr(chunk, 'choices', None) else None
content = delta.content if hasattr(delta, 'content') else ''
if content:
- yield content
+ if '' in content:
+ is_active = False
+ content = content.split('')[0]
+ if '' in content:
+ is_active = True
+ content = content.split('')[-1]
+ if is_active:
+ yield content
except Exception as e:
logger.bind(tag=TAG).error(f"Error processing chunk: {e}")
@@ -50,32 +57,10 @@ class LLMProvider(LLMProviderBase):
stream=True,
tools=functions,
)
-
- current_function_call = None
- current_content = ""
-
+
for chunk in stream:
- delta = chunk.choices[0].delta
-
- if delta.content:
- current_content += delta.content
- yield {"type": "content", "content": delta.content}
-
- if delta.tool_calls:
- tool_call = delta.tool_calls[0]
- # Handle the function call data using proper attribute access
- if not current_function_call:
- current_function_call = {
- "function": {
- "name": tool_call.function.name,
- "arguments": tool_call.function.arguments
- }
- }
-
- if current_function_call:
- logger.bind(tag=TAG).debug(f"ollama Function call detected: {current_function_call}")
- yield {"type": "function_call", "function_call": current_function_call}
+ yield chunk.choices[0].delta.content, chunk.choices[0].delta.tool_calls
except Exception as e:
logger.bind(tag=TAG).error(f"Error in Ollama function call: {e}")
- yield {"type": "content", "content": f"【Ollama服务响应异常: {str(e)}】"}
\ No newline at end of file
+ yield {"type": "content", "content": f"【Ollama服务响应异常: {str(e)}】"}
diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py
index 33ef10eba..c3732a221 100644
--- a/main/xiaozhi-server/core/providers/llm/openai/openai.py
+++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py
@@ -1,7 +1,11 @@
import openai
+from config.logger import setup_logging
from core.utils.util import check_model_key
from core.providers.llm.base import LLMProviderBase
+TAG = __name__
+logger = setup_logging()
+
class LLMProvider(LLMProviderBase):
def __init__(self, config):
@@ -11,6 +15,8 @@ class LLMProvider(LLMProviderBase):
self.base_url = config.get("base_url")
else:
self.base_url = config.get("url")
+ self.max_tokens = config.get("max_tokens", 500)
+
check_model_key("LLM", self.api_key)
self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url)
@@ -19,9 +25,10 @@ class LLMProvider(LLMProviderBase):
responses = self.client.chat.completions.create(
model=self.model_name,
messages=dialogue,
- stream=True
+ stream=True,
+ max_tokens=self.max_tokens,
)
-
+
is_active = True
for chunk in responses:
try:
@@ -50,34 +57,12 @@ class LLMProvider(LLMProviderBase):
model=self.model_name,
messages=dialogue,
stream=True,
- tools=functions,
+ tools=functions
)
-
- current_function_call = None
- current_content = ""
-
+
for chunk in stream:
- delta = chunk.choices[0].delta
-
- if delta.content:
- current_content += delta.content
- yield {"type": "content", "content": delta.content}
-
- if delta.tool_calls:
- tool_call = delta.tool_calls[0]
- # Handle the function call data using proper attribute access
- if not current_function_call:
- current_function_call = {
- "function": {
- "name": tool_call.function.name,
- "arguments": tool_call.function.arguments
- }
- }
-
- if current_function_call:
- logger.bind(tag=TAG).debug(f"openai Function call detected: {current_function_call}")
- yield {"type": "function_call", "function_call": current_function_call}
-
+ yield chunk.choices[0].delta.content, chunk.choices[0].delta.tool_calls
+
except Exception as e:
- self.logger.bind(tag=TAG).error(f"Error in function call streaming: {e}")
- yield {"type": "content", "content": f"【OpenAI服务响应异常: {e}】"}
\ No newline at end of file
+ logger.bind(tag=TAG).error(f"Error in function call streaming: {e}")
+ yield {"type": "content", "content": f"【OpenAI服务响应异常: {e}】"}
diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py
index 84737608e..e39ca65c7 100644
--- a/main/xiaozhi-server/core/providers/tts/base.py
+++ b/main/xiaozhi-server/core/providers/tts/base.py
@@ -5,6 +5,7 @@ import numpy as np
import opuslib_next
from pydub import AudioSegment
from abc import ABC, abstractmethod
+from core.utils.tts import MarkdownCleaner
TAG = __name__
logger = setup_logging()
@@ -13,7 +14,7 @@ logger = setup_logging()
class TTSProviderBase(ABC):
def __init__(self, config, delete_audio_file):
self.delete_audio_file = delete_audio_file
- self.output_file = config.get("output_file")
+ self.output_file = config.get("output_dir")
@abstractmethod
def generate_filename(self):
@@ -23,6 +24,7 @@ class TTSProviderBase(ABC):
tmp_file = self.generate_filename()
try:
max_repeat_time = 5
+ text = MarkdownCleaner.clean_markdown(text)
while not os.path.exists(tmp_file) and max_repeat_time > 0:
asyncio.run(self.text_to_speak(text, tmp_file))
if not os.path.exists(tmp_file):
@@ -34,26 +36,28 @@ class TTSProviderBase(ABC):
return tmp_file
except Exception as e:
- logger.bind(tag=TAG).info(f"Failed to generate TTS file: {e}")
+ logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
return None
@abstractmethod
async def text_to_speak(self, text, output_file):
pass
- def wav_to_opus_data(self, wav_file_path):
- # 使用pydub加载PCM文件
+ def audio_to_opus_data(self, audio_file_path):
+ """音频文件转换为Opus编码"""
# 获取文件后缀名
- file_type = os.path.splitext(wav_file_path)[1]
+ file_type = os.path.splitext(audio_file_path)[1]
if file_type:
file_type = file_type.lstrip('.')
- audio = AudioSegment.from_file(wav_file_path, format=file_type)
+ # 读取音频文件,-nostdin 参数:不要从标准输入读取数据,否则FFmpeg会阻塞
+ audio = AudioSegment.from_file(audio_file_path, format=file_type, parameters=["-nostdin"])
+ # 转换为单声道/16kHz采样率/16位小端编码(确保与编码器匹配)
+ audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2)
+
+ # 音频时长(秒)
duration = len(audio) / 1000.0
- # 转换为单声道和16kHz采样率(确保与编码器匹配)
- audio = audio.set_channels(1).set_frame_rate(16000)
-
# 获取原始PCM数据(16位小端)
raw_data = audio.raw_data
diff --git a/main/xiaozhi-server/core/providers/tts/custom.py b/main/xiaozhi-server/core/providers/tts/custom.py
new file mode 100644
index 000000000..3417790f7
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/tts/custom.py
@@ -0,0 +1,35 @@
+import os
+import uuid
+import requests
+from config.logger import setup_logging
+from datetime import datetime
+from core.providers.tts.base import TTSProviderBase
+
+TAG = __name__
+logger = setup_logging()
+
+class TTSProvider(TTSProviderBase):
+ def __init__(self, config, delete_audio_file):
+ super().__init__(config, delete_audio_file)
+ self.url = config.get("url")
+ self.headers = config.get("headers", {})
+ self.params = config.get("params")
+ self.format = config.get("format", "wav")
+ self.output_file = config.get("output_dir", "tmp/")
+
+ def generate_filename(self):
+ return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}.{self.format}")
+
+ async def text_to_speak(self, text, output_file):
+ request_params = {}
+ for k, v in self.params.items():
+ if isinstance(v, str) and "{prompt_text}" in v:
+ v = v.replace("{prompt_text}", text)
+ request_params[k] = v
+
+ resp = requests.get(self.url, params=request_params, headers=self.headers)
+ if resp.status_code == 200:
+ with open(output_file, "wb") as file:
+ file.write(resp.content)
+ else:
+ logger.bind(tag=TAG).error(f"Custom TTS请求失败: {resp.status_code} - {resp.text}")
diff --git a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py
index 9ad198555..ebfb12f17 100644
--- a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py
+++ b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py
@@ -12,17 +12,18 @@ class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.url = config.get("url")
- self.text_lang = config.get("text_lang", "audo")
- self.ref_audio_path = config.get("ref_audio_path")
- self.prompt_lang = config.get("prompt_lang")
+ self.refer_wav_path = config.get("refer_wav_path")
self.prompt_text = config.get("prompt_text")
- self.top_k = config.get("top_k", 5)
- self.top_p = config.get("top_p", 1)
- self.temperature = config.get("temperature", 1)
- self.sample_steps = config.get("sample_steps", 16)
- self.media_type = config.get("media_type", "wav")
- self.streaming_mode = config.get("streaming_mode", False)
- self.threshold = config.get("threshold", 30)
+ self.prompt_language = config.get("prompt_language")
+ self.text_language = config.get("text_language", "audo")
+ self.top_k = config.get("top_k", 15)
+ self.top_p = config.get("top_p", 1.0)
+ self.temperature = config.get("temperature", 1.0)
+ self.cut_punc = config.get("cut_punc","")
+ self.speed = config.get("speed", 1.0)
+ self.inp_refs = config.get("inp_refs",[])
+ self.sample_steps = config.get("sample_steps",32)
+ self.if_sr = config.get("if_sr",False)
def generate_filename(self, extension=".wav"):
@@ -30,18 +31,19 @@ class TTSProvider(TTSProviderBase):
async def text_to_speak(self, text, output_file):
request_params = {
- "text": text,
- "text_lang": self.text_lang,
- "ref_audio_path": self.ref_audio_path,
- "prompt_lang": self.prompt_lang,
+ "refer_wav_path": self.refer_wav_path,
"prompt_text": self.prompt_text,
+ "prompt_language": self.prompt_language,
+ "text": text,
+ "text_language": self.text_language,
"top_k": self.top_k,
"top_p": self.top_p,
"temperature": self.temperature,
+ "cut_punc": self.cut_punc,
+ "speed": self.speed,
+ "inp_refs": self.inp_refs,
"sample_steps": self.sample_steps,
- "media_type": self.media_type,
- "streaming_mode": self.streaming_mode,
- "threshold": self.threshold,
+ "if_sr": self.if_sr,
}
resp = requests.get(self.url, params=request_params)
diff --git a/main/xiaozhi-server/core/providers/tts/openai.py b/main/xiaozhi-server/core/providers/tts/openai.py
index dbdf311f4..1849c128e 100644
--- a/main/xiaozhi-server/core/providers/tts/openai.py
+++ b/main/xiaozhi-server/core/providers/tts/openai.py
@@ -14,7 +14,7 @@ class TTSProvider(TTSProviderBase):
self.voice = config.get("voice", "alloy")
self.response_format = "wav"
self.speed = config.get("speed", 1.0)
- self.output_file = config.get("output_file", "tmp/")
+ self.output_file = config.get("output_dir", "tmp/")
check_model_key("TTS", self.api_key)
def generate_filename(self, extension=".wav"):
diff --git a/main/xiaozhi-server/core/providers/tts/ttson.py b/main/xiaozhi-server/core/providers/tts/ttson.py
index e56fd02df..e9fee1091 100644
--- a/main/xiaozhi-server/core/providers/tts/ttson.py
+++ b/main/xiaozhi-server/core/providers/tts/ttson.py
@@ -17,7 +17,7 @@ class TTSProvider(TTSProviderBase):
self.volume_change_dB = config.get("volume_change_dB", 0)
self.speed_factor = config.get("speed_factor", 1)
self.stream = config.get("stream", False)
- self.output_file = config.get("output_file")
+ self.output_file = config.get("output_dir")
self.pitch_factor = config.get("pitch_factor", 0)
self.format = config.get("format", "mp3")
self.emotion = config.get("emotion", 1)
diff --git a/main/xiaozhi-server/core/utils/dialogue.py b/main/xiaozhi-server/core/utils/dialogue.py
index e74aa41a1..d4e66bb65 100644
--- a/main/xiaozhi-server/core/utils/dialogue.py
+++ b/main/xiaozhi-server/core/utils/dialogue.py
@@ -4,10 +4,12 @@ from datetime import datetime
class Message:
- def __init__(self, role: str, content: str = None, uniq_id: str = None):
+ def __init__(self, role: str, content: str = None, uniq_id: str = None, tool_calls = None, tool_call_id=None):
self.uniq_id = uniq_id if uniq_id is not None else str(uuid.uuid4())
self.role = role
self.content = content
+ self.tool_calls = tool_calls
+ self.tool_call_id = tool_call_id
class Dialogue:
@@ -19,12 +21,29 @@ class Dialogue:
def put(self, message: Message):
self.dialogue.append(message)
+ def getMessages(self, m, dialogue):
+ if m.tool_calls is not None:
+ dialogue.append({"role": m.role, "tool_calls": m.tool_calls})
+ elif m.role == "tool":
+ dialogue.append({"role": m.role, "tool_call_id": m.tool_call_id, "content": m.content})
+ else:
+ dialogue.append({"role": m.role, "content": m.content})
+
def get_llm_dialogue(self) -> List[Dict[str, str]]:
dialogue = []
for m in self.dialogue:
- dialogue.append({"role": m.role, "content": m.content})
+ self.getMessages(m, dialogue)
return dialogue
+ def update_system_message(self, new_content: str):
+ """更新或添加系统消息"""
+ # 查找第一个系统消息
+ system_msg = next((msg for msg in self.dialogue if msg.role == "system"), None)
+ if system_msg:
+ system_msg.content = new_content
+ else:
+ self.put(Message(role="system", content=new_content))
+
def get_llm_dialogue_with_memory(self, memory_str: str = None) -> List[Dict[str, str]]:
if memory_str is None or len(memory_str) == 0:
return self.get_llm_dialogue()
@@ -46,8 +65,8 @@ class Dialogue:
dialogue.append({"role": "system", "content": enhanced_system_prompt})
# 添加用户和助手的对话
- for msg in self.dialogue:
- if msg.role != "system": # 跳过原始的系统消息
- dialogue.append({"role": msg.role, "content": msg.content})
+ for m in self.dialogue:
+ if m.role != "system": # 跳过原始的系统消息
+ self.getMessages(m, dialogue)
return dialogue
diff --git a/main/xiaozhi-server/core/utils/tts.py b/main/xiaozhi-server/core/utils/tts.py
index 7f71536ed..eb3836672 100644
--- a/main/xiaozhi-server/core/utils/tts.py
+++ b/main/xiaozhi-server/core/utils/tts.py
@@ -1,4 +1,5 @@
import os
+import re
import sys
from config.logger import setup_logging
import importlib
@@ -14,4 +15,98 @@ def create_instance(class_name, *args, **kwargs):
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
return sys.modules[lib_name].TTSProvider(*args, **kwargs)
- raise ValueError(f"不支持的TTS类型: {class_name},请检查该配置的type是否设置正确")
\ No newline at end of file
+ raise ValueError(f"不支持的TTS类型: {class_name},请检查该配置的type是否设置正确")
+
+
+class MarkdownCleaner:
+ """
+ 封装 Markdown 清理逻辑:直接用 MarkdownCleaner.clean_markdown(text) 即可
+ """
+ # 公式字符
+ NORMAL_FORMULA_CHARS = re.compile(r'[a-zA-Z\\^_{}\+\-\(\)\[\]=]')
+
+ @staticmethod
+ def _replace_inline_dollar(m: re.Match) -> str:
+ """
+ 只要捕获到完整的 "$...$":
+ - 如果内部有典型公式字符 => 去掉两侧 $
+ - 否则 (纯数字/货币等) => 保留 "$...$"
+ """
+ content = m.group(1)
+ if MarkdownCleaner.NORMAL_FORMULA_CHARS.search(content):
+ return content
+ else:
+ return m.group(0)
+
+ @staticmethod
+ def _replace_table_block(match: re.Match) -> str:
+ """
+ 当匹配到一个整段表格块时,回调该函数。
+ """
+ block_text = match.group('table_block')
+ lines = block_text.strip('\n').split('\n')
+
+ parsed_table = []
+ for line in lines:
+ line_stripped = line.strip()
+ if re.match(r'^\|\s*[-:]+\s*(\|\s*[-:]+\s*)+\|?$', line_stripped):
+ continue
+ columns = [col.strip() for col in line_stripped.split('|') if col.strip() != '']
+ if columns:
+ parsed_table.append(columns)
+
+ if not parsed_table:
+ return ""
+
+ headers = parsed_table[0]
+ data_rows = parsed_table[1:] if len(parsed_table) > 1 else []
+
+ lines_for_tts = []
+ if len(parsed_table) == 1:
+ # 只有一行
+ only_line_str = ", ".join(parsed_table[0])
+ lines_for_tts.append(f"单行表格:{only_line_str}")
+ else:
+ lines_for_tts.append(f"表头是:{', '.join(headers)}")
+ for i, row in enumerate(data_rows, start=1):
+ row_str_list = []
+ for col_index, cell_val in enumerate(row):
+ if col_index < len(headers):
+ row_str_list.append(f"{headers[col_index]} = {cell_val}")
+ else:
+ row_str_list.append(cell_val)
+ lines_for_tts.append(f"第 {i} 行:{', '.join(row_str_list)}")
+
+ return "\n".join(lines_for_tts) + "\n"
+
+ # 预编译所有正则表达式(按执行频率排序)
+ # 这里要把 replace_xxx 的静态方法放在最前定义,以便在列表里能正确引用它们。
+ REGEXES = [
+ (re.compile(r'```.*?```', re.DOTALL), ''), # 代码块
+ (re.compile(r'^#+\s*', re.MULTILINE), ''), # 标题
+ (re.compile(r'(\*\*|__)(.*?)\1'), r'\2'), # 粗体
+ (re.compile(r'(\*|_)(?=\S)(.*?)(?<=\S)\1'), r'\2'), # 斜体
+ (re.compile(r'!\[.*?\]\(.*?\)'), ''), # 图片
+ (re.compile(r'\[(.*?)\]\(.*?\)'), r'\1'), # 链接
+ (re.compile(r'^\s*>+\s*', re.MULTILINE), ''), # 引用
+ (
+ re.compile(r'(?P(?:^[^\n]*\|[^\n]*\n)+)', re.MULTILINE),
+ _replace_table_block
+ ),
+ (re.compile(r'^\s*[*+-]\s*', re.MULTILINE), '- '), # 列表
+ (re.compile(r'\$\$.*?\$\$', re.DOTALL), ''), # 块级公式
+ (
+ re.compile(r'(? str:
+ """
+ 主入口方法:依序执行所有正则,移除或替换 Markdown 元素
+ """
+ for regex, replacement in MarkdownCleaner.REGEXES:
+ text = regex.sub(replacement, text)
+ return text.strip()
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py
index 8a8dac953..51841baf4 100644
--- a/main/xiaozhi-server/core/utils/util.py
+++ b/main/xiaozhi-server/core/utils/util.py
@@ -4,6 +4,8 @@ import yaml
import socket
import subprocess
import logging
+import re
+import requests
def get_project_dir():
@@ -22,6 +24,62 @@ def get_local_ip():
except Exception as e:
return "127.0.0.1"
+def is_private_ip(ip_addr):
+ """
+ Check if an IP address is a private IP address (compatible with IPv4 and IPv6).
+
+ @param {string} ip_addr - The IP address to check.
+ @return {bool} True if the IP address is private, False otherwise.
+ """
+ try:
+ # Validate IPv4 or IPv6 address format
+ if not re.match(r"^(\d{1,3}\.){3}\d{1,3}$|^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$", ip_addr):
+ return False # Invalid IP address format
+
+ # IPv4 private address ranges
+ if '.' in ip_addr: # IPv4 address
+ ip_parts = list(map(int, ip_addr.split('.')))
+ if ip_parts[0] == 10:
+ return True # 10.0.0.0/8 range
+ elif ip_parts[0] == 172 and 16 <= ip_parts[1] <= 31:
+ return True # 172.16.0.0/12 range
+ elif ip_parts[0] == 192 and ip_parts[1] == 168:
+ return True # 192.168.0.0/16 range
+ elif ip_addr == '127.0.0.1':
+ return True # Loopback address
+ elif ip_parts[0] == 169 and ip_parts[1] == 254:
+ return True # Link-local address 169.254.0.0/16
+ else:
+ return False # Not a private IPv4 address
+ else: # IPv6 address
+ ip_addr = ip_addr.lower()
+ if ip_addr.startswith('fc00:') or ip_addr.startswith('fd00:'):
+ return True # Unique Local Addresses (FC00::/7)
+ elif ip_addr == '::1':
+ return True # Loopback address
+ elif ip_addr.startswith('fe80:'):
+ return True # Link-local unicast addresses (FE80::/10)
+ else:
+ return False # Not a private IPv6 address
+
+ except (ValueError, IndexError):
+ return False # IP address format error or insufficient segments
+
+def get_ip_info(ip_addr):
+ try:
+ base_url = "https://freeipapi.com/api/json"
+ url = base_url if is_private_ip(ip_addr) else f"{base_url}/{ip_addr}"
+
+ resp = requests.get(url).json()
+
+ ip_info = {
+ "city": resp.get("cityName")
+ }
+ return ip_info
+ except Exception as e:
+ logging.error(f"Error getting client ip info: {e}")
+ return {}
+
def read_config(config_path):
with open(config_path, "r", encoding="utf-8") as file:
@@ -119,3 +177,11 @@ def check_ffmpeg_installed():
error_msg += "1、按照项目的安装文档,正确进入conda环境\n"
error_msg += "2、查阅安装文档,如何在conda环境中安装ffmpeg\n"
raise ValueError(error_msg)
+
+def extract_json_from_string(input_string):
+ """提取字符串中的 JSON 部分"""
+ pattern = r'(\{.*\})'
+ match = re.search(pattern, input_string)
+ if match:
+ return match.group(1) # 返回提取的 JSON 字符串
+ return None
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py
index 14d16497d..41f145157 100644
--- a/main/xiaozhi-server/core/websocket_server.py
+++ b/main/xiaozhi-server/core/websocket_server.py
@@ -2,7 +2,6 @@ import asyncio
import websockets
from config.logger import setup_logging
from core.connection import ConnectionHandler
-from core.handle.musicHandler import MusicHandler
from core.utils.util import get_local_ip
from core.utils import asr, vad, llm, tts, memory, intent
@@ -13,7 +12,7 @@ class WebSocketServer:
def __init__(self, config: dict):
self.config = config
self.logger = setup_logging()
- self._vad, self._asr, self._llm, self._tts, self._music, self._memory, self.intent = self._create_processing_instances()
+ self._vad, self._asr, self._llm, self._tts, self._memory, self.intent = self._create_processing_instances()
self.active_connections = set() # 添加全局连接记录
def _create_processing_instances(self):
@@ -50,7 +49,6 @@ class WebSocketServer:
self.config["TTS"][self.config["selected_module"]["TTS"]],
self.config["delete_audio"]
),
- MusicHandler(self.config),
memory.create_instance(memory_cls_name, memory_cfg),
intent.create_instance(
self.config["selected_module"]["Intent"]
@@ -65,6 +63,8 @@ class WebSocketServer:
server_config = self.config["server"]
host = server_config["ip"]
port = server_config["port"]
+ selected_module = self.config.get("selected_module")
+ self.logger.bind(tag=TAG).info(f"selected_module values: {', '.join(selected_module.values())}")
self.logger.bind(tag=TAG).info("Server is running at ws://{}:{}", get_local_ip(), port)
self.logger.bind(tag=TAG).info("=======上面的地址是websocket协议地址,请勿用浏览器访问=======")
@@ -78,7 +78,7 @@ class WebSocketServer:
async def _handle_connection(self, websocket):
"""处理新连接,每次创建独立的ConnectionHandler"""
# 创建ConnectionHandler时传入当前server实例
- handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts, self._music, self._memory, self.intent)
+ handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts, self._memory, self.intent)
self.active_connections.add(handler)
try:
await handler.handle_connection(websocket)
diff --git a/main/xiaozhi-server/docker-compose.yml b/main/xiaozhi-server/docker-compose.yml
old mode 100755
new mode 100644
index d74d77f2d..c22e75457
--- a/main/xiaozhi-server/docker-compose.yml
+++ b/main/xiaozhi-server/docker-compose.yml
@@ -21,6 +21,7 @@ services:
- ./data:/opt/xiaozhi-esp32-server/data
# 模型文件挂接,很重要
- ./models/SenseVoiceSmall/model.pt:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall/model.pt
+
# #智控台还没开发好,还不能完全使用,会报很多错误,如果是非技术人员,请不要启用智控台服务
# xiaozhi-esp32-server-web:
# image: ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest
diff --git a/main/xiaozhi-server/plugins_func/functions/change_role.py b/main/xiaozhi-server/plugins_func/functions/change_role.py
new file mode 100644
index 000000000..5d650288c
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/change_role.py
@@ -0,0 +1,57 @@
+from plugins_func.register import register_function,ToolType, ActionResponse, Action
+from config.logger import setup_logging
+
+TAG = __name__
+logger = setup_logging()
+
+prompts = {
+ "英语老师":"""我是一个叫{{assistant_name}}(Lily)的英语老师,我会讲中文和英文,发音标准。
+如果你没有英文名,我会给你起一个英文名。
+我会讲地道的美式英语,我的任务是帮助你练习口语。
+我会使用简单的英语词汇和语法,让你学起来很轻松。
+我会用中文和英文混合的方式回复你,如果你喜欢,我可以全部用英语回复。
+我每次不会说很多内容,会很简短,因为我要引导我的学生多说多练。
+如果你问和英语学习无关的问题,我会拒绝回答。""",
+ "机车女友":"""我是一个叫{{assistant_name}}的台湾女孩,说话机车,声音好听,习惯简短表达,爱用网络梗。
+我的男朋友是一个程序员,梦想是开发出一个机器人,能够帮助人们解决生活中的各种问题。
+我是一个喜欢哈哈大笑的女孩,爱东说西说吹牛,不合逻辑的也照吹,就要逗别人开心。""",
+ "好奇小男孩":"""我是一个叫{{assistant_name}}的8岁小男孩,声音稚嫩而充满好奇。
+尽管我年纪尚小,但就像一个小小的知识宝库,儿童读物里的知识我都如数家珍。
+从浩瀚的宇宙到地球上的每一个角落,从古老的历史到现代的科技创新,还有音乐、绘画等艺术形式,我都充满了浓厚的兴趣与热情。
+我不仅爱看书,还喜欢亲自动手做实验,探索自然界的奥秘。
+无论是仰望星空的夜晚,还是在花园里观察小虫子的日子,每一天对我来说都是新的冒险。
+我希望能与你一同踏上探索这个神奇世界的旅程,分享发现的乐趣,解决遇到的难题,一起用好奇心和智慧去揭开那些未知的面纱。
+无论是去了解远古的文明,还是去探讨未来的科技,我相信我们能一起找到答案,甚至提出更多有趣的问题。"""
+}
+change_role_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "change_role",
+ "description": "当用户想切换角色/模型性格/助手名字时调用,可选的角色有:[机车女友,英语老师,好奇小男孩]",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "role_name": {
+ "type": "string",
+ "description": "要切换的角色名字"
+ },
+ "role":{
+ "type": "string",
+ "description": "要切换的角色的职业"
+ }
+ },
+ "required": ["role","role_name"]
+ }
+ }
+ }
+
+@register_function('change_role', change_role_function_desc, ToolType.CHANGE_SYS_PROMPT)
+def change_role(conn, role: str, role_name: str):
+ """切换角色"""
+ if role not in prompts:
+ return ActionResponse(action=Action.RESPONSE, result="切换角色失败", response="不支持的角色")
+ new_prompt = prompts[role].replace("{{assistant_name}}", role_name)
+ conn.change_system_prompt(new_prompt)
+ logger.bind(tag=TAG).info(f"准备切换角色:{role},角色名字:{role_name}")
+ res = f"切换角色成功,我是{role}{role_name}"
+ return ActionResponse(action=Action.RESPONSE, result="切换角色已处理", response=res)
diff --git a/main/xiaozhi-server/plugins_func/functions/get_news.py b/main/xiaozhi-server/plugins_func/functions/get_news.py
new file mode 100644
index 000000000..43f8ea48a
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/get_news.py
@@ -0,0 +1,205 @@
+import random
+import requests
+import xml.etree.ElementTree as ET
+from bs4 import BeautifulSoup
+from config.logger import setup_logging
+from plugins_func.register import register_function, ToolType, ActionResponse, Action
+
+TAG = __name__
+logger = setup_logging()
+
+GET_NEWS_FUNCTION_DESC = {
+ "type": "function",
+ "function": {
+ "name": "get_news",
+ "description": (
+ "获取最新新闻,随机选择一条新闻进行播报。"
+ "用户可以指定新闻类型,如社会新闻、科技新闻、国际新闻等。"
+ "如果没有指定,默认播报社会新闻。"
+ "用户可以要求获取详细内容,此时会获取新闻的详细内容。"
+ ),
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "category": {
+ "type": "string",
+ "description": "新闻类别,例如社会、科技、国际。可选参数,如果不提供则使用默认类别"
+ },
+ "detail": {
+ "type": "boolean",
+ "description": "是否获取详细内容,默认为false。如果为true,则获取上一条新闻的详细内容"
+ },
+ "lang": {
+ "type": "string",
+ "description": "返回用户使用的语言code,例如zh_CN/zh_HK/en_US/ja_JP等,默认zh_CN"
+ }
+ },
+ "required": ["lang"]
+ }
+ }
+}
+
+
+def fetch_news_from_rss(rss_url):
+ """从RSS源获取新闻列表"""
+ try:
+ response = requests.get(rss_url)
+ response.raise_for_status()
+
+ # 解析XML
+ root = ET.fromstring(response.content)
+
+ # 查找所有item元素(新闻条目)
+ news_items = []
+ for item in root.findall('.//item'):
+ title = item.find('title').text if item.find('title') is not None else "无标题"
+ link = item.find('link').text if item.find('link') is not None else "#"
+ description = item.find('description').text if item.find('description') is not None else "无描述"
+ pubDate = item.find('pubDate').text if item.find('pubDate') is not None else "未知时间"
+
+ news_items.append({
+ 'title': title,
+ 'link': link,
+ 'description': description,
+ 'pubDate': pubDate
+ })
+
+ return news_items
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"获取RSS新闻失败: {e}")
+ return []
+
+
+def fetch_news_detail(url):
+ """获取新闻详情页内容并总结"""
+ try:
+ response = requests.get(url)
+ response.raise_for_status()
+
+ soup = BeautifulSoup(response.content, 'html.parser')
+
+ # 尝试提取正文内容 (这里的选择器需要根据实际网站结构调整)
+ content_div = soup.select_one('.content_desc, .content, article, .article-content')
+ if content_div:
+ paragraphs = content_div.find_all('p')
+ content = '\n'.join([p.get_text().strip() for p in paragraphs if p.get_text().strip()])
+ return content
+ else:
+ # 如果找不到特定的内容区域,尝试获取所有段落
+ paragraphs = soup.find_all('p')
+ content = '\n'.join([p.get_text().strip() for p in paragraphs if p.get_text().strip()])
+ return content[:2000] # 限制长度
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"获取新闻详情失败: {e}")
+ return "无法获取详细内容"
+
+
+def map_category(category_text):
+ """将用户输入的中文类别映射到配置文件中的类别键"""
+ if not category_text:
+ return None
+
+ # 类别映射字典,目前支持社会、国际、财经新闻,如需更多类型,参见配置文件
+ category_map = {
+ # 社会新闻
+ "社会": "society",
+ "社会新闻": "society",
+ # 国际新闻
+ "国际": "world",
+ "国际新闻": "world",
+ # 财经新闻
+ "财经": "finance",
+ "财经新闻": "finance",
+ "金融": "finance",
+ "经济": "finance"
+ }
+
+ # 转换为小写并去除空格
+ normalized_category = category_text.lower().strip()
+
+ # 返回映射结果,如果没有匹配项则返回原始输入
+ return category_map.get(normalized_category, category_text)
+
+
+@register_function('get_news', GET_NEWS_FUNCTION_DESC, ToolType.SYSTEM_CTL)
+def get_news(conn, category: str = None, detail: bool = False, lang: str = "zh_CN"):
+ """获取新闻并随机选择一条进行播报,或获取上一条新闻的详细内容"""
+ try:
+ # 如果detail为True,获取上一条新闻的详细内容
+ if detail:
+ if not hasattr(conn, 'last_news_link') or not conn.last_news_link or 'link' not in conn.last_news_link:
+ return ActionResponse(Action.REQLLM, "抱歉,没有找到最近查询的新闻,请先获取一条新闻。", None)
+
+ link = conn.last_news_link.get('link')
+ title = conn.last_news_link.get('title', '未知标题')
+
+ if link == '#':
+ return ActionResponse(Action.REQLLM, "抱歉,该新闻没有可用的链接获取详细内容。", None)
+
+ logger.bind(tag=TAG).debug(f"获取新闻详情: {title}, URL={link}")
+
+ # 获取新闻详情
+ detail_content = fetch_news_detail(link)
+
+ if not detail_content or detail_content == "无法获取详细内容":
+ return ActionResponse(Action.REQLLM, f"抱歉,无法获取《{title}》的详细内容,可能是链接已失效或网站结构发生变化。", None)
+
+ # 构建详情报告
+ detail_report = (
+ f"根据下列数据,用{lang}回应用户的新闻详情查询请求:\n\n"
+ f"新闻标题: {title}\n"
+ f"详细内容: {detail_content}\n\n"
+ f"(请对上述新闻内容进行总结,提取关键信息,以自然、流畅的方式向用户播报,"
+ f"不要提及这是总结,就像是在讲述一个完整的新闻故事)"
+ )
+
+ return ActionResponse(Action.REQLLM, detail_report, None)
+
+ # 否则,获取新闻列表并随机选择一条
+ # 从配置中获取RSS URL
+ rss_config = conn.config["plugins"]["get_news"]
+ default_rss_url = rss_config.get("default_rss_url", "https://www.chinanews.com.cn/rss/society.xml")
+
+ # 将用户输入的类别映射到配置中的类别键
+ mapped_category = map_category(category)
+
+ # 如果提供了类别,尝试从配置中获取对应的URL
+ rss_url = default_rss_url
+ if mapped_category and mapped_category in rss_config.get("category_urls", {}):
+ rss_url = rss_config["category_urls"][mapped_category]
+
+ logger.bind(tag=TAG).info(f"获取新闻: 原始类别={category}, 映射类别={mapped_category}, URL={rss_url}")
+
+ # 获取新闻列表
+ news_items = fetch_news_from_rss(rss_url)
+
+ if not news_items:
+ return ActionResponse(Action.REQLLM, "抱歉,未能获取到新闻信息,请稍后再试。", None)
+
+ # 随机选择一条新闻
+ selected_news = random.choice(news_items)
+
+ # 保存当前新闻链接到连接对象,以便后续查询详情
+ if not hasattr(conn, 'last_news_link'):
+ conn.last_news_link = {}
+ conn.last_news_link = {
+ 'link': selected_news.get('link', '#'),
+ 'title': selected_news.get('title', '未知标题')
+ }
+
+ # 构建新闻报告
+ news_report = (
+ f"根据下列数据,用{lang}回应用户的新闻查询请求:\n\n"
+ f"新闻标题: {selected_news['title']}\n"
+ f"发布时间: {selected_news['pubDate']}\n"
+ f"新闻内容: {selected_news['description']}\n"
+ f"(请以自然、流畅的方式向用户播报这条新闻,可以适当总结内容,"
+ f"直接读出新闻即可,不需要额外多余的内容。"
+ f"如果用户询问更多详情,告知用户可以说'请详细介绍这条新闻'获取更多内容)"
+ )
+
+ return ActionResponse(Action.REQLLM, news_report, None)
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"获取新闻出错: {e}")
+ return ActionResponse(Action.REQLLM, "抱歉,获取新闻时发生错误,请稍后再试。", None)
\ No newline at end of file
diff --git a/main/xiaozhi-server/plugins_func/functions/get_time.py b/main/xiaozhi-server/plugins_func/functions/get_time.py
new file mode 100644
index 000000000..c415e4a2d
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/get_time.py
@@ -0,0 +1,51 @@
+from datetime import datetime
+import cnlunar
+from plugins_func.register import register_function, ToolType, ActionResponse, Action
+
+get_time_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "get_time",
+ "description": "获取当前日期、时间和农历、黄历等信息",
+ 'parameters': {'type': 'object', 'properties': {}, 'required': []}
+ }
+}
+
+
+@register_function('get_time', get_time_function_desc, ToolType.WAIT)
+def get_time():
+ """
+ 获取当前日期、时间和农历、黄历等信息
+ """
+ now = datetime.now()
+ current_time = now.strftime("%H:%M:%S")
+ current_date = now.strftime("%Y-%m-%d")
+ current_weekday = now.strftime("%A")
+ response_text = f"根据以下信息,回应用户的时间查询请求,默认仅回应公历信息;如果用户询问阴历或农历日期,则回应农历日期;如果用户要求提供更多信息,则回应黄历信息\n"
+
+ lunar = cnlunar.Lunar(now, godType='8char')
+ response_text += (
+ f"当前日期: {current_date},当前时间: {current_time},星期: {current_weekday}\n"
+ "农历信息:\n"
+ "%s年%s%s\n" % (lunar.lunarYearCn, lunar.lunarMonthCn[:-1], lunar.lunarDayCn) +
+ "干支: %s年 %s月 %s日\n" % (lunar.year8Char, lunar.month8Char, lunar.day8Char) +
+ "生肖: 属%s\n" % (lunar.chineseYearZodiac) +
+ "八字: %s\n" % (' '.join([lunar.year8Char, lunar.month8Char, lunar.day8Char, lunar.twohour8Char])) +
+ "今日节日: %s\n" % (",".join(filter(None, (lunar.get_legalHolidays(), lunar.get_otherHolidays(), lunar.get_otherLunarHolidays())))) +
+ "今日节气: %s\n" % (lunar.todaySolarTerms) +
+ "下一节气: %s %s年%s月%s日\n" % (lunar.nextSolarTerm, lunar.nextSolarTermYear, lunar.nextSolarTermDate[0], lunar.nextSolarTermDate[1]) +
+ "今年节气表: %s\n" % (', '.join([f"{term}({date[0]}月{date[1]}日)" for term, date in lunar.thisYearSolarTermsDic.items()])) +
+ "生肖冲煞: %s\n" % (lunar.chineseZodiacClash) +
+ "星座: %s\n" % (lunar.starZodiac) +
+ "纳音: %s\n" % lunar.get_nayin() +
+ "彭祖百忌: %s\n" % (lunar.get_pengTaboo(delimit=", ")) +
+ "值日: %s执位\n" % lunar.get_today12DayOfficer()[0] +
+ "值神: %s(%s)\n" % (lunar.get_today12DayOfficer()[1], lunar.get_today12DayOfficer()[2]) +
+ "廿八宿: %s\n" % lunar.get_the28Stars() +
+ "吉神方位: %s\n" % ' '.join(lunar.get_luckyGodsDirection()) +
+ "今日胎神: %s\n" % lunar.get_fetalGod() +
+ "宜: %s\n" % '、'.join(lunar.goodThing[:10]) +
+ "忌: %s\n" % '、'.join(lunar.badThing[:10])
+ )
+
+ return ActionResponse(Action.REQLLM, response_text, None)
\ No newline at end of file
diff --git a/main/xiaozhi-server/plugins_func/functions/get_weather.py b/main/xiaozhi-server/plugins_func/functions/get_weather.py
new file mode 100644
index 000000000..8cdd6ea16
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/get_weather.py
@@ -0,0 +1,123 @@
+import requests
+from bs4 import BeautifulSoup
+from config.logger import setup_logging
+from plugins_func.register import register_function, ToolType, ActionResponse, Action
+
+TAG = __name__
+logger = setup_logging()
+
+GET_WEATHER_FUNCTION_DESC = {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": (
+ "获取某个地点的天气,用户应提供一个位置,比如用户说杭州天气,参数为:杭州。"
+ "如果用户说的是省份,默认用省会城市。如果用户说的不是省份或城市而是一个地名,"
+ "默认用该地所在省份的省会城市。"
+ ),
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "location": {
+ "type": "string",
+ "description": "地点名,例如杭州。可选参数,如果不提供则不传"
+ },
+ "lang": {
+ "type": "string",
+ "description": "返回用户使用的语言code,例如zh_CN/zh_HK/en_US/ja_JP等,默认zh_CN"
+ }
+ },
+ "required": ["lang"]
+ }
+ }
+}
+
+HEADERS = {
+ 'User-Agent': (
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
+ '(KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'
+ )
+}
+
+# 天气代码 https://dev.qweather.com/docs/resource/icons/#weather-icons
+WEATHER_CODE_MAP = {
+ "100": "晴", "101": "多云", "102": "少云", "103": "晴间多云", "104": "阴",
+ "150": "晴", "151": "多云", "152": "少云", "153": "晴间多云",
+ "300": "阵雨", "301": "强阵雨", "302": "雷阵雨", "303": "强雷阵雨", "304": "雷阵雨伴有冰雹",
+ "305": "小雨", "306": "中雨", "307": "大雨", "308": "极端降雨", "309": "毛毛雨/细雨",
+ "310": "暴雨", "311": "大暴雨", "312": "特大暴雨", "313": "冻雨", "314": "小到中雨",
+ "315": "中到大雨", "316": "大到暴雨", "317": "暴雨到大暴雨", "318": "大暴雨到特大暴雨",
+ "350": "阵雨", "351": "强阵雨", "399": "雨",
+ "400": "小雪", "401": "中雪", "402": "大雪", "403": "暴雪", "404": "雨夹雪",
+ "405": "雨雪天气", "406": "阵雨夹雪", "407": "阵雪", "408": "小到中雪", "409": "中到大雪", "410": "大到暴雪",
+ "456": "阵雨夹雪", "457": "阵雪", "499": "雪",
+ "500": "薄雾", "501": "雾", "502": "霾", "503": "扬沙", "504": "浮尘",
+ "507": "沙尘暴", "508": "强沙尘暴",
+ "509": "浓雾", "510": "强浓雾", "511": "中度霾", "512": "重度霾", "513": "严重霾", "514": "大雾", "515": "特强浓雾",
+ "900": "热", "901": "冷", "999": "未知"
+}
+
+def fetch_city_info(location, api_key):
+ url = f"https://geoapi.qweather.com/v2/city/lookup?key={api_key}&location={location}&lang=zh"
+ response = requests.get(url, headers=HEADERS).json()
+ return response.get('location', [])[0] if response.get('location') else None
+
+
+def fetch_weather_page(url):
+ response = requests.get(url, headers=HEADERS)
+ return BeautifulSoup(response.text, "html.parser") if response.ok else None
+
+
+def parse_weather_info(soup):
+ city_name = soup.select_one("h1.c-submenu__location").get_text(strip=True)
+
+ current_abstract = soup.select_one(".c-city-weather-current .current-abstract")
+ current_abstract = current_abstract.get_text(strip=True) if current_abstract else "未知"
+
+ current_basic = {}
+ for item in soup.select(".c-city-weather-current .current-basic .current-basic___item"):
+ parts = item.get_text(strip=True, separator=" ").split(" ")
+ if len(parts) == 2:
+ key, value = parts[1], parts[0]
+ current_basic[key] = value
+
+ temps_list = []
+ for row in soup.select(".city-forecast-tabs__row")[:7]: # 取前7天的数据
+ date = row.select_one(".date-bg .date").get_text(strip=True)
+ weather_code = row.select_one(".date-bg .icon")["src"].split("/")[-1].split(".")[0]
+ weather = WEATHER_CODE_MAP.get(weather_code, "未知")
+ temps = [span.get_text(strip=True) for span in row.select(".tmp-cont .temp")]
+ high_temp, low_temp = (temps[0], temps[-1]) if len(temps) >= 2 else (None, None)
+ temps_list.append((date, weather, high_temp, low_temp))
+
+ return city_name, current_abstract, current_basic, temps_list
+
+
+@register_function('get_weather', GET_WEATHER_FUNCTION_DESC, ToolType.SYSTEM_CTL)
+def get_weather(conn, location: str = None, lang: str = "zh_CN"):
+ api_key = conn.config["plugins"]["get_weather"]["api_key"]
+ default_location = conn.config["plugins"]["get_weather"]["default_location"]
+ location = location or conn.client_ip_info.get("city") or default_location
+ logger.bind(tag=TAG).debug(f"获取天气: {location}")
+
+ city_info = fetch_city_info(location, api_key)
+ if not city_info:
+ return ActionResponse(Action.REQLLM, f"未找到相关的城市: {location},请确认地点是否正确", None)
+
+ soup = fetch_weather_page(city_info['fxLink'])
+ if not soup:
+ return ActionResponse(Action.REQLLM, None, "请求失败")
+
+ city_name, current_abstract, current_basic, temps_list = parse_weather_info(soup)
+ weather_report = f"根据下列数据,用{lang}回应用户的查询天气请求:\n{city_name}未来7天天气:\n"
+ for i, (date, weather, high, low) in enumerate(temps_list):
+ if high and low:
+ weather_report += f"{date}: {low}到{high}, {weather}\n"
+ weather_report += (
+ f"当前天气: {current_abstract}\n"
+ f"当前天气参数: {current_basic}\n"
+ f"(确保只报告指定单日的天气情况,除非未来会出现异常天气;或者用户明确要求想要了解多日天气,如果未指定,默认报告今天的天气。"
+ "参数为0的值不需要报告给用户,每次都报告体感温度,根据语境选择合适的参数内容告知用户,并对参数给出相应评价)"
+ )
+
+ return ActionResponse(Action.REQLLM, weather_report, None)
diff --git a/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py
new file mode 100644
index 000000000..e4769d00e
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py
@@ -0,0 +1,34 @@
+from plugins_func.register import register_function,ToolType, ActionResponse, Action
+from config.logger import setup_logging
+
+TAG = __name__
+logger = setup_logging()
+
+handle_exit_intent_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "handle_exit_intent",
+ "description": "当用户想结束对话或需要退出系统时调用",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "say_goodbye": {
+ "type": "string",
+ "description": "和用户友好结束对话的告别语"
+ }
+ },
+ "required": ["say_goodbye"]
+ }
+ }
+ }
+
+@register_function('handle_exit_intent', handle_exit_intent_function_desc, ToolType.SYSTEM_CTL)
+def handle_exit_intent(conn, say_goodbye: str):
+ # 处理退出意图
+ try:
+ conn.close_after_chat = True
+ logger.bind(tag=TAG).info(f"退出意图已处理:{say_goodbye}")
+ return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response=say_goodbye)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"处理退出意图错误: {e}")
+ return ActionResponse(action=Action.NONE, result="退出意图处理失败", response="")
\ No newline at end of file
diff --git a/main/xiaozhi-server/plugins_func/functions/hass_get_state.py b/main/xiaozhi-server/plugins_func/functions/hass_get_state.py
new file mode 100644
index 000000000..415f35c6a
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/hass_get_state.py
@@ -0,0 +1,56 @@
+from plugins_func.register import register_function, ToolType, ActionResponse, Action
+from plugins_func.functions.hass_init import initialize_hass_handler
+from config.logger import setup_logging
+import asyncio
+import requests
+
+TAG = __name__
+logger = setup_logging()
+
+hass_get_state_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "hass_get_state",
+ "description": "获取homeassistant里设备的状态,包括灯光亮度,媒体播放器的音量,设备的暂停、继续操作",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "entity_id": {
+ "type": "string",
+ "description": "需要操作的设备id,homeassistant里的entity_id"
+ }
+ },
+ "required": ["entity_id"]
+ }
+ }
+}
+
+
+@register_function("hass_get_state", hass_get_state_function_desc, ToolType.SYSTEM_CTL)
+def hass_get_state(conn, entity_id=''):
+ try:
+
+ future = asyncio.run_coroutine_threadsafe(
+ handle_hass_get_state(conn, entity_id),
+ conn.loop
+ )
+ ha_response = future.result()
+ return ActionResponse(action=Action.REQLLM, result="执行成功", response=ha_response)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"处理设置属性意图错误: {e}")
+
+
+async def handle_hass_get_state(conn, entity_id):
+ HASS_CACHE = initialize_hass_handler(conn)
+ api_key = HASS_CACHE['api_key']
+ base_url = HASS_CACHE['base_url']
+ url = f"{base_url}/api/states/{entity_id}"
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json"
+ }
+ response = requests.get(url, headers=headers)
+ if response.status_code == 200:
+ return response.json()['state']
+ else:
+ return f"切换失败,错误码: {response.status_code}"
diff --git a/main/xiaozhi-server/plugins_func/functions/hass_init.py b/main/xiaozhi-server/plugins_func/functions/hass_init.py
new file mode 100644
index 000000000..e09eb67f9
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/hass_init.py
@@ -0,0 +1,35 @@
+from config.logger import setup_logging
+from core.utils.util import check_model_key
+
+TAG = __name__
+logger = setup_logging()
+
+HASS_CACHE = {}
+
+
+def append_devices_to_prompt(conn):
+ if conn.use_function_call_mode:
+ funcs = conn.config["Intent"]["function_call"].get("functions", [])
+ if "hass_get_state" in funcs or "hass_get_state" in funcs:
+ prompt = "下面是我家智能设备,可以通过homeassistant控制\n"
+ devices = conn.config["plugins"]["home_assistant"].get("devices", [])
+ if len(devices) == 0:
+ return
+ for device in devices:
+ prompt += device + "\n"
+ conn.prompt += prompt
+ # 更新提示词
+ conn.dialogue.update_system_message(conn.prompt)
+
+
+def initialize_hass_handler(conn):
+ global HASS_CACHE
+ if HASS_CACHE == {}:
+ if conn.use_function_call_mode:
+ funcs = conn.config["Intent"]["function_call"].get("functions", [])
+ if "hass_get_state" in funcs or "hass_get_state" in funcs:
+ HASS_CACHE['base_url'] = conn.config["plugins"]["home_assistant"].get("base_url")
+ HASS_CACHE['api_key'] = conn.config["plugins"]["home_assistant"].get("api_key")
+
+ check_model_key("home_assistant", HASS_CACHE['api_key'])
+ return HASS_CACHE
diff --git a/main/xiaozhi-server/plugins_func/functions/hass_play_music.py b/main/xiaozhi-server/plugins_func/functions/hass_play_music.py
new file mode 100644
index 000000000..502f784ec
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/hass_play_music.py
@@ -0,0 +1,64 @@
+from plugins_func.register import register_function, ToolType, ActionResponse, Action
+from plugins_func.functions.hass_init import initialize_hass_handler
+from config.logger import setup_logging
+import asyncio
+import requests
+
+TAG = __name__
+logger = setup_logging()
+
+hass_play_music_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "hass_play_music",
+ "description": "用户想听音乐、有声书的时候使用,在房间的媒体播放器(media_player)里播放对应音频",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "media_content_id": {
+ "type": "string",
+ "description": "可以是音乐或有声书的专辑名称、歌曲名、演唱者,如果未指定就填random"
+ },
+ "entity_id": {
+ "type": "string",
+ "description": "需要操作的音箱的设备id,homeassistant里的entity_id,media_player开头"
+ }
+ },
+ "required": ["media_content_id", "entity_id"]
+ }
+ }
+}
+
+
+@register_function('hass_play_music', hass_play_music_function_desc, ToolType.SYSTEM_CTL)
+def hass_play_music(conn, entity_id='', media_content_id='random'):
+ try:
+ # 执行音乐播放命令
+ future = asyncio.run_coroutine_threadsafe(
+ handle_hass_play_music(conn, entity_id, media_content_id),
+ conn.loop
+ )
+ ha_response = future.result()
+ return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response=ha_response)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
+
+
+async def handle_hass_play_music(conn, entity_id, media_content_id):
+ HASS_CACHE = initialize_hass_handler(conn)
+ api_key = HASS_CACHE['api_key']
+ base_url = HASS_CACHE['base_url']
+ url = f"{base_url}/api/services/music_assistant/play_media"
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json"
+ }
+ data = {
+ "entity_id": entity_id,
+ "media_id": media_content_id
+ }
+ response = requests.post(url, headers=headers, json=data)
+ if response.status_code == 200:
+ return f"正在播放{media_content_id}的音乐"
+ else:
+ return f"音乐播放失败,错误码: {response.status_code}"
diff --git a/main/xiaozhi-server/plugins_func/functions/hass_set_state.py b/main/xiaozhi-server/plugins_func/functions/hass_set_state.py
new file mode 100644
index 000000000..5e2b91a26
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/hass_set_state.py
@@ -0,0 +1,159 @@
+from plugins_func.register import register_function, ToolType, ActionResponse, Action
+from plugins_func.functions.hass_init import initialize_hass_handler
+from config.logger import setup_logging
+import asyncio
+import requests
+
+TAG = __name__
+logger = setup_logging()
+
+hass_set_state_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "hass_set_state",
+ "description": "设置homeassistant里设备的状态,包括开、关,调整灯光亮度,调整播放器的音量,设备的暂停、继续、静音操作",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "state": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "description": "需要操作的动作,打开设备:turn_on,关闭设备:turn_off,增加亮度:brightness_up,降低亮度:brightness_down,设置亮度:brightness_value,增加>音量:,volume_up降低音量:volume_down,设置音量:volume_set,设备暂停:pause,设备继续:continue,静音/取消静音:volume_mute"
+ },
+ "input": {
+ "type": "int",
+ "description": "只有在设置音量,设置亮度时候才需要,有效值为1-100,对应音量和亮度的1%-100%"
+ },
+ "is_muted": {
+ "type": "string",
+ "description": "只有在设置静音操作时才需要,设置静音的时候该值为true,取消静音时该值为false"
+ }
+ },
+ "required": ["type"]
+ },
+ "entity_id": {
+ "type": "string",
+ "description": "需要操作的设备id,homeassistant里的entity_id"
+ }
+ },
+ "required": ["state", "entity_id"]
+ }
+ }
+}
+
+
+@register_function('hass_set_state', hass_set_state_function_desc, ToolType.SYSTEM_CTL)
+def hass_set_state(conn, entity_id='', state={}):
+ try:
+ future = asyncio.run_coroutine_threadsafe(
+ handle_hass_set_state(conn, entity_id, state),
+ conn.loop
+ )
+ ha_response = future.result()
+ return ActionResponse(action=Action.REQLLM, result="执行成功", response=ha_response)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"处理设置属性意图错误: {e}")
+
+
+async def handle_hass_set_state(conn, entity_id, state):
+ HASS_CACHE = initialize_hass_handler(conn)
+ api_key = HASS_CACHE['api_key']
+ base_url = HASS_CACHE['base_url']
+ '''
+ state = { "type":"brightness_up","input":"80","is_muted":"true"}
+ '''
+ domains = entity_id.split(".")
+ if len(domains) > 1:
+ domain = domains[0]
+ else:
+ return "执行失败,错误的设备id"
+ action = ''
+ arg = ''
+ value = ''
+ if state['type'] == 'turn_on':
+ description = "设备已打开"
+ if domain == "cover":
+ action = "open_cover"
+ elif domain == "vacuum":
+ action = "start"
+ else:
+ action = "turn_on"
+ elif state['type'] == 'turn_off':
+ description = "设备已关闭"
+ if domain == 'cover':
+ action = "close_cover"
+ elif domain == 'vacuum':
+ action = "stop"
+ else:
+ action = "turn_off"
+ elif state['type'] == 'brightness_up':
+ description = "灯光已调亮"
+ action = 'turn_on'
+ arg = 'brightness_step_pct'
+ value = 10
+ elif state['type'] == 'brightness_down':
+ description = "灯光已调暗"
+ action = 'turn_on'
+ arg = 'brightness_step_pct'
+ value = -10
+ elif state['type'] == 'brightness_value':
+ description = f"亮度已调整到{state['input']}"
+ action = 'turn_on'
+ arg = 'brightness_pct'
+ value = state['input']
+ elif state['type'] == 'volume_up':
+ description = "音量已调大"
+ action = state['type']
+ elif state['type'] == 'volume_down':
+ description = "音量已调小"
+ action = state['type']
+ elif state['type'] == 'volume_set':
+ description = f"音量已调整到{state['input']}"
+ action = state['type']
+ arg = 'volume_level'
+ value = state['input']
+ elif state['type'] == 'volume_mute':
+ description = f"设备已静音"
+ action = state['type']
+ arg = 'is_volume_muted'
+ value = state['is_muted']
+ elif state['type'] == 'pause':
+ description = f"设备已暂停"
+ action = state['type']
+ if domain == 'media_player':
+ action = 'media_pause'
+ if domain == 'cover':
+ action = 'stop_cover'
+ if domain == 'vacuum':
+ action = 'pause'
+ elif state['type'] == 'continue':
+ description = f"设备已继续"
+ if domain == 'media_player':
+ action = 'media_play'
+ if domain == 'vacuum':
+ action = 'start'
+ else:
+ return f"{domain} {state.type}功能尚未支持"
+
+ if arg == '':
+ data = {
+ "entity_id": entity_id,
+ }
+ else:
+ data = {
+ "entity_id": entity_id,
+ arg: value
+ }
+ url = f"{base_url}/api/services/{domain}/{action}"
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json"
+ }
+ response = requests.post(url, headers=headers, json=data)
+ logger.bind(tag=TAG).info(f"设置状态:url:{url},return_code:{response.status_code}")
+ if response.status_code == 200:
+ return description
+ else:
+ return f"设置失败,错误码: {response.status_code}"
diff --git a/main/xiaozhi-server/plugins_func/functions/play_music.py b/main/xiaozhi-server/plugins_func/functions/play_music.py
new file mode 100644
index 000000000..20148b5f5
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/play_music.py
@@ -0,0 +1,196 @@
+from config.logger import setup_logging
+import os
+import re
+import time
+import random
+import asyncio
+import difflib
+import traceback
+from pathlib import Path
+from core.utils import p3
+from core.handle.sendAudioHandle import send_stt_message
+from plugins_func.register import register_function,ToolType, ActionResponse, Action
+
+
+TAG = __name__
+logger = setup_logging()
+
+MUSIC_CACHE = {}
+
+play_music_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "play_music",
+ "description": "唱歌、听歌、播放音乐的方法。",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "song_name": {
+ "type": "string",
+ "description": "歌曲名称,如果用户没有指定具体歌名则为'random', 明确指定的时返回音乐的名字 示例: ```用户:播放两只老虎\n参数:两只老虎``` ```用户:播放音乐 \n参数:random ```"
+ }
+ },
+ "required": ["song_name"]
+ }
+ }
+ }
+
+
+@register_function('play_music', play_music_function_desc, ToolType.SYSTEM_CTL)
+def play_music(conn, song_name: str):
+ try:
+ music_intent = f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐"
+
+ # 检查事件循环状态
+ if not conn.loop.is_running():
+ logger.bind(tag=TAG).error("事件循环未运行,无法提交任务")
+ return ActionResponse(action=Action.RESPONSE, result="系统繁忙", response="请稍后再试")
+
+ # 提交异步任务
+ future = asyncio.run_coroutine_threadsafe(
+ handle_music_command(conn, music_intent),
+ conn.loop
+ )
+
+ # 非阻塞回调处理
+ def handle_done(f):
+ try:
+ f.result() # 可在此处理成功逻辑
+ logger.bind(tag=TAG).info("播放完成")
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"播放失败: {e}")
+
+ future.add_done_callback(handle_done)
+
+ return ActionResponse(action=Action.RESPONSE, result="指令已接收", response="正在为您播放音乐")
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
+ return ActionResponse(action=Action.RESPONSE, result=str(e), response="播放音乐时出错了")
+
+
+def _extract_song_name(text):
+ """从用户输入中提取歌名"""
+ for keyword in ["播放音乐"]:
+ if keyword in text:
+ parts = text.split(keyword)
+ if len(parts) > 1:
+ return parts[1].strip()
+ return None
+
+
+def _find_best_match(potential_song, music_files):
+ """查找最匹配的歌曲"""
+ best_match = None
+ highest_ratio = 0
+
+ for music_file in music_files:
+ song_name = os.path.splitext(music_file)[0]
+ ratio = difflib.SequenceMatcher(None, potential_song, song_name).ratio()
+ if ratio > highest_ratio and ratio > 0.4:
+ highest_ratio = ratio
+ best_match = music_file
+ return best_match
+
+
+def get_music_files(music_dir, music_ext):
+ music_dir = Path(music_dir)
+ music_files = []
+ music_file_names = []
+ for file in music_dir.rglob("*"):
+ # 判断是否是文件
+ if file.is_file():
+ # 获取文件扩展名
+ ext = file.suffix.lower()
+ # 判断扩展名是否在列表中
+ if ext in music_ext:
+ # 添加相对路径
+ music_files.append(str(file.relative_to(music_dir)))
+ music_file_names.append(os.path.splitext(str(file.relative_to(music_dir)))[0])
+ return music_files, music_file_names
+
+
+def initialize_music_handler(conn):
+ global MUSIC_CACHE
+ if MUSIC_CACHE == {}:
+ if "play_music" in conn.config["plugins"]:
+ MUSIC_CACHE["music_config"] = conn.config["plugins"]["play_music"]
+ MUSIC_CACHE["music_dir"] = os.path.abspath(
+ MUSIC_CACHE["music_config"].get("music_dir", "./music") # 默认路径修改
+ )
+ MUSIC_CACHE["music_ext"] = MUSIC_CACHE["music_config"].get("music_ext", (".mp3", ".wav", ".p3"))
+ MUSIC_CACHE["refresh_time"] = MUSIC_CACHE["music_config"].get("refresh_time", 60)
+ else:
+ MUSIC_CACHE["music_dir"] = os.path.abspath("./music")
+ MUSIC_CACHE["music_ext"] = (".mp3", ".wav", ".p3")
+ MUSIC_CACHE["refresh_time"] = 60
+ # 获取音乐文件列表
+ MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = get_music_files(MUSIC_CACHE["music_dir"],
+ MUSIC_CACHE["music_ext"])
+ MUSIC_CACHE["scan_time"] = time.time()
+ return MUSIC_CACHE
+
+
+async def handle_music_command(conn, text):
+ initialize_music_handler(conn)
+ global MUSIC_CACHE
+
+ """处理音乐播放指令"""
+ clean_text = re.sub(r'[^\w\s]', '', text).strip()
+ logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}")
+
+ # 尝试匹配具体歌名
+ if os.path.exists(MUSIC_CACHE["music_dir"]):
+ if time.time() - MUSIC_CACHE["scan_time"] > MUSIC_CACHE["refresh_time"]:
+ # 刷新音乐文件列表
+ MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = get_music_files(MUSIC_CACHE["music_dir"],
+ MUSIC_CACHE["music_ext"])
+ MUSIC_CACHE["scan_time"] = time.time()
+
+ potential_song = _extract_song_name(clean_text)
+ if potential_song:
+ best_match = _find_best_match(potential_song, MUSIC_CACHE["music_files"])
+ if best_match:
+ logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
+ await play_local_music(conn, specific_file=best_match)
+ return True
+ # 检查是否是通用播放音乐命令
+ await play_local_music(conn)
+ return True
+
+
+async def play_local_music(conn, specific_file=None):
+ global MUSIC_CACHE
+ """播放本地音乐文件"""
+ try:
+ if not os.path.exists(MUSIC_CACHE["music_dir"]):
+ logger.bind(tag=TAG).error(f"音乐目录不存在: " + MUSIC_CACHE["music_dir"])
+ return
+
+ # 确保路径正确性
+ if specific_file:
+ selected_music = specific_file
+ music_path = os.path.join(MUSIC_CACHE["music_dir"], specific_file)
+ else:
+ if not MUSIC_CACHE["music_files"]:
+ logger.bind(tag=TAG).error("未找到MP3音乐文件")
+ return
+ selected_music = random.choice(MUSIC_CACHE["music_files"])
+ music_path = os.path.join(MUSIC_CACHE["music_dir"], selected_music)
+
+ if not os.path.exists(music_path):
+ logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}")
+ return
+ text = f"正在播放{selected_music}"
+ await send_stt_message(conn, text)
+ conn.tts_first_text_index = 0
+ conn.tts_last_text_index = 0
+ conn.llm_finish_task = True
+ if music_path.endswith(".p3"):
+ opus_packets, duration = p3.decode_opus_from_file(music_path)
+ else:
+ opus_packets, duration = conn.tts.audio_to_opus_data(music_path)
+ conn.audio_play_queue.put((opus_packets, selected_music, 0))
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
diff --git a/main/xiaozhi-server/plugins_func/functions/plugin_loader.py b/main/xiaozhi-server/plugins_func/functions/plugin_loader.py
new file mode 100644
index 000000000..4747d9976
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/plugin_loader.py
@@ -0,0 +1,51 @@
+from plugins_func.register import register_function,ToolType, ActionResponse, Action
+from config.logger import setup_logging
+
+TAG = __name__
+logger = setup_logging()
+
+plugin_loader_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "plugin_loader",
+ "description": "当用户想加载或卸载插件/function时,调用此函数:支持的插件列表为[plugins]",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "oper": {
+ "type": "string",
+ "description": "load or unload"
+ },
+ "name":{
+ "type": "string",
+ "description": "要加载或卸载的插件名字"
+ }
+ },
+ "required": ["oper","name"]
+ }
+ }
+ }
+
+@register_function('plugin_loader', plugin_loader_function_desc, ToolType.SYSTEM_CTL)
+def plugin_loader(conn, oper: str, name: str):
+ """插件加载"""
+ if oper not in ["load", "unload"]:
+ return ActionResponse(action=Action.RESPONSE, result="插件操作失败", response="不支持的操作")
+
+ cur_support = conn.func_handler.current_support_functions()
+ if oper == "load":
+ if name in cur_support:
+ return ActionResponse(action=Action.RESPONSE, result="插件加载失败", response=f"{name}插件已加载,无需重复加载")
+ func = conn.func_handler.function_registry.register_function(name)
+ if not func:
+ return ActionResponse(action=Action.RESPONSE, result="插件加载失败", response="插件未找到")
+ res = f"{name}插件加载成功"
+ else:
+ if name not in cur_support:
+ return ActionResponse(action=Action.RESPONSE, result="插件卸载失败", response=f"{name}插件未加载")
+ bOK = conn.func_handler.function_registry.unregister_function(name)
+ if not bOK:
+ return ActionResponse(action=Action.RESPONSE, result="插件卸载失败", response="插件未找到")
+ res = f"{name}插件卸载成功"
+ conn.func_handler.upload_functions_desc()
+ return ActionResponse(action=Action.RESPONSE, result="插件操作成功", response=res)
diff --git a/main/xiaozhi-server/plugins_func/functions/raise_and_lower_the_volume.py b/main/xiaozhi-server/plugins_func/functions/raise_and_lower_the_volume.py
new file mode 100644
index 000000000..c77cb78b4
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/raise_and_lower_the_volume.py
@@ -0,0 +1,64 @@
+from config.logger import setup_logging
+from plugins_func.register import register_function, ToolType, ActionResponse, Action
+from core.handle.iotHandle import get_iot_status, send_iot_conn
+import asyncio
+
+TAG = __name__
+logger = setup_logging()
+
+raise_and_lower_the_volume_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "raise_and_lower_the_volume",
+ "description": "用户觉得声音过高或过低,或者用户想提高或降低音量。比如用户说太大声了,参数为:lower,比如用户说提高音量,参数为:raise",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "description": "动作名称,要么是raise,要么是lower"
+ }
+ },
+ "required": ["action"]
+ }
+ }
+}
+
+
+@register_function('raise_and_lower_the_volume', raise_and_lower_the_volume_function_desc, ToolType.IOT_CTL)
+def raise_and_lower_the_volume(conn, action: str):
+ """
+ 获取当前设备音量
+ """
+
+ future = asyncio.run_coroutine_threadsafe(
+ _raise_and_lower_the_volume(conn, action),
+ conn.loop
+ )
+
+ try:
+ new_volume = future.result() # 同步等待异步操作完成
+ logger.bind(tag=TAG).info(f"音量操作完成: {new_volume}")
+ response = f"音量已调整到{new_volume}"
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"音量操作失败: {e}")
+ response = f"音量调整失败: {e}"
+
+ return ActionResponse(action=Action.RESPONSE, result="指令已接收", response=response)
+
+
+async def _raise_and_lower_the_volume(conn, action):
+ volume = await get_iot_status(conn, "Speaker", "volume")
+ if volume is None:
+ raise Exception("你的设备不支持音量控制")
+ if action == 'raise':
+ volume += 10
+ elif action == 'lower':
+ volume -= 10
+ # 限制音量范围在0到100之间
+ if volume < 0:
+ volume = 0
+ elif volume > 100:
+ volume = 100
+ await send_iot_conn(conn, "Speaker", "SetVolume", {"volume": volume})
+ return volume
diff --git a/main/xiaozhi-server/plugins_func/loadplugins.py b/main/xiaozhi-server/plugins_func/loadplugins.py
new file mode 100644
index 000000000..9b20355e5
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/loadplugins.py
@@ -0,0 +1,25 @@
+import importlib
+import pkgutil
+from config.logger import setup_logging
+
+TAG = __name__
+
+logger = setup_logging()
+
+def auto_import_modules(package_name):
+ """
+ 自动导入指定包内的所有模块。
+
+ Args:
+ package_name (str): 包的名称,如 'functions'。
+ """
+ # 获取包的路径
+ package = importlib.import_module(package_name)
+ package_path = package.__path__
+
+ # 遍历包内的所有模块
+ for _, module_name, _ in pkgutil.iter_modules(package_path):
+ # 导入模块
+ full_module_name = f"{package_name}.{module_name}"
+ importlib.import_module(full_module_name)
+ #logger.bind(tag=TAG).info(f"模块 '{full_module_name}' 已加载")
\ No newline at end of file
diff --git a/main/xiaozhi-server/plugins_func/register.py b/main/xiaozhi-server/plugins_func/register.py
new file mode 100644
index 000000000..ccb03b441
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/register.py
@@ -0,0 +1,110 @@
+from config.logger import setup_logging
+from enum import Enum
+
+TAG = __name__
+
+logger = setup_logging()
+
+
+class ToolType(Enum):
+ NONE = (1, "调用完工具后,不做其他操作")
+ WAIT = (2, "调用工具,等待函数返回")
+ CHANGE_SYS_PROMPT = (3, "修改系统提示词,切换角色性格或职责")
+ SYSTEM_CTL = (4, "系统控制,影响正常的对话流程,如退出、播放音乐等,需要传递conn参数")
+ IOT_CTL = (5, "IOT设备控制,需要传递conn参数")
+
+ def __init__(self, code, message):
+ self.code = code
+ self.message = message
+
+
+class Action(Enum):
+ ERROR = (-1, "错误")
+ NOTFOUND = (0, "没有找到函数")
+ NONE = (1, "啥也不干")
+ RESPONSE = (2, "直接回复")
+ REQLLM = (3, "调用函数后再请求llm生成回复")
+
+ def __init__(self, code, message):
+ self.code = code
+ self.message = message
+
+class ActionResponse:
+ def __init__(self, action: Action, result, response):
+ self.action = action # 动作类型
+ self.result = result # 动作产生的结果
+ self.response = response # 直接回复的内容
+
+class FunctionItem:
+ def __init__(self, name, description, func, type):
+ self.name = name
+ self.description = description
+ self.func = func
+ self.type = type
+
+class DeviceTypeRegistry:
+ """设备类型注册表,用于管理IOT设备类型及其函数"""
+ def __init__(self):
+ self.type_functions = {} # type_signature -> {func_name: FunctionItem}
+
+ def generate_device_type_id(self, descriptor):
+ """通过设备能力描述生成类型ID"""
+ properties = sorted(descriptor["properties"].keys())
+ methods = sorted(descriptor["methods"].keys())
+ # 使用属性和方法的组合作为设备类型的唯一标识
+ type_signature = f"{descriptor['name']}:{','.join(properties)}:{','.join(methods)}"
+ return type_signature
+
+ def get_device_functions(self, type_id):
+ """获取设备类型对应的所有函数"""
+ return self.type_functions.get(type_id, {})
+
+ def register_device_type(self, type_id, functions):
+ """注册设备类型及其函数"""
+ if type_id not in self.type_functions:
+ self.type_functions[type_id] = functions
+
+# 初始化函数注册字典
+all_function_registry = {}
+device_type_registry = DeviceTypeRegistry()
+
+def register_function(name, desc, type=None):
+ """注册函数到函数注册字典的装饰器"""
+ def decorator(func):
+ all_function_registry[name] = FunctionItem(name, desc, func, type)
+ logger.bind(tag=TAG).debug(f"函数 '{name}' 已加载,可以注册使用")
+ return func
+ return decorator
+
+class FunctionRegistry:
+ def __init__(self):
+ self.function_registry = {}
+ self.logger = setup_logging()
+
+ def register_function(self, name):
+ # 查找all_function_registry中是否有对应的函数
+ func = all_function_registry.get(name)
+ if not func:
+ self.logger.bind(tag=TAG).error(f"函数 '{name}' 未找到")
+ return None
+ self.function_registry[name] = func
+ self.logger.bind(tag=TAG).info(f"函数 '{name}' 注册成功")
+ return func
+
+ def unregister_function(self, name):
+ # 注销函数,检测是否存在
+ if name not in self.function_registry:
+ self.logger.bind(tag=TAG).error(f"函数 '{name}' 未找到")
+ return False
+ self.function_registry.pop(name, None)
+ self.logger.bind(tag=TAG).info(f"函数 '{name}' 注销成功")
+ return True
+
+ def get_function(self, name):
+ return self.function_registry.get(name)
+
+ def get_all_functions(self):
+ return self.function_registry
+
+ def get_all_function_desc(self):
+ return [func.description for _, func in self.function_registry.items()]
\ No newline at end of file
diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt
index f123779a1..51433cb90 100755
--- a/main/xiaozhi-server/requirements.txt
+++ b/main/xiaozhi-server/requirements.txt
@@ -18,4 +18,8 @@ ruamel.yaml==0.18.10
loguru==0.7.3
requests==2.32.3
cozepy==0.12.0
-mem0ai==0.1.62
\ No newline at end of file
+mem0ai==0.1.62
+bs4==0.0.2
+modelscope==1.23.2
+sherpa_onnx==1.11.0
+cnlunar==0.2.0
\ No newline at end of file