diff --git a/.gitignore b/.gitignore index c09248c59..62f841200 100644 --- a/.gitignore +++ b/.gitignore @@ -132,6 +132,9 @@ dmypy.json # Pyre type checker .pyre/ +# music directory +music/ + # pytype static type analyzer .pytype/ @@ -146,3 +149,4 @@ tmp .private_config.yaml .env.development docker-compose.yml +web/vue/node_modules diff --git a/README.md b/README.md index a0f6c4f1c..fc1cb425f 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,22 @@ + + + + + + 自定义音色 + + + + + + + 播放音乐 + + + @@ -66,7 +82,7 @@ - + --- @@ -91,7 +107,8 @@ 1、本项目为开源软件,本软件与对接的任何第三方API服务商(包括但不限于语音识别、大模型、语音合成等平台)均不存在商业合作关系,不为其服务质量及资金安全提供任何形式的担保。 建议使用者优先选择持有相关业务牌照的服务商,并仔细阅读其服务协议及隐私政策。本软件不托管任何账户密钥、不参与资金流转、不承担充值资金损失风险。 -2、本项目成立时间较短,还未通过网络安全测评,请勿在生产环境中使用。 如果您在公网环境中部署学习本项目,请务必在配置文件 `config.yaml` 中开启防护: +2、本项目成立时间较短,还未通过网络安全测评,请勿在生产环境中使用。 如果您在公网环境中部署学习本项目,请务必在配置文件 +`config.yaml` 中开启防护: ```yaml server: @@ -177,6 +194,14 @@ server: --- +### Memory + +| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | +|:------:|:------:|:----:|:----:|:--:| +| Memory | mem0ai | 接口调用 | 免费 | | + +--- + ## 使用方式 🚀 ### 一、[部署文档](./docs/Deployment.md) diff --git a/config.yaml b/config.yaml index d0217deb0..6d9cd989b 100644 --- a/config.yaml +++ b/config.yaml @@ -80,7 +80,15 @@ selected_module: LLM: ChatGLMLLM # TTS将根据配置名称对应的type调用实际的TTS适配器 TTS: EdgeTTS + Memory: mem0ai +Memory: + mem0ai: + type: mem0ai + # https://app.mem0.ai/dashboard/api-keys + # 每月有1000次免费调用 + api_key: 你的mem0ai api key + ASR: FunASR: type: fun_local diff --git a/core/connection.py b/core/connection.py index 5532e3a1a..588a3a2c0 100644 --- a/core/connection.py +++ b/core/connection.py @@ -22,8 +22,12 @@ from core.utils.auth_code_gen import AuthCodeGenerator TAG = __name__ +class TTSException(RuntimeError): + pass + + class ConnectionHandler: - def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _music): + def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _music, _memory): self.config = config self.logger = setup_logging() self.auth = AuthMiddleware(config) @@ -50,7 +54,7 @@ class ConnectionHandler: self.asr = _asr self.llm = _llm self.tts = _tts - self.dialogue = None + self.memory = _memory # vad相关变量 self.client_audio_buffer = bytes() @@ -68,10 +72,8 @@ class ConnectionHandler: self.dialogue = Dialogue() # tts相关变量 - self.tts_first_text = None - self.tts_last_text = None - self.tts_start_speak_time = None - self.tts_duration = 0 + self.tts_first_text_index = -1 + self.tts_last_text_index = -1 # iot相关变量 self.iot_descriptors = {} @@ -99,6 +101,7 @@ class ConnectionHandler: await self.auth.authenticate(self.headers) device_id = self.headers.get("device-id", None) + self.memory.set_role_id(device_id) # Load private configuration if device_id is provided bUsePrivateConfig = self.config.get("use_private_config", False) @@ -161,6 +164,8 @@ class ConnectionHandler: self.logger.bind(tag=TAG).error(f"Connection error: {str(e)}-{stack_trace}") await ws.close() return + finally: + await self.memory.save_memory(self.dialogue.dialogue) async def _route_message(self, message): """消息路由""" @@ -199,15 +204,12 @@ class ConnectionHandler: return False return not self.is_device_verified + def chat(self, query): if self.isNeedAuth(): self.llm_finish_task = True - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - loop.run_until_complete(self._check_and_broadcast_auth_code()) - finally: - loop.close() + future = asyncio.run_coroutine_threadsafe(self._check_and_broadcast_auth_code(), self.loop) + future.result() return True self.dialogue.put(Message(role="user", content=query)) @@ -215,12 +217,21 @@ class ConnectionHandler: processed_chars = 0 # 跟踪已处理的字符位置 try: start_time = time.time() - llm_responses = self.llm.response(self.session_id, self.dialogue.get_llm_dialogue()) + # 使用带记忆的对话 + 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}") + llm_responses = self.llm.response( + self.session_id, + self.dialogue.get_llm_dialogue_with_memory(memory_str) + ) except Exception as e: self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") return None self.llm_finish_task = False + text_index = 0 for content in llm_responses: response_message.append(content) if self.client_abort: @@ -234,7 +245,7 @@ class ConnectionHandler: current_text = full_text[processed_chars:] # 从未处理的位置开始 # 查找最后一个有效标点 - punctuations = ("。", "?", "!", "?", "!", ";", ";", ":", ":", ",") + punctuations = ("。", "?", "!", "?", "!", ";", ";", ":", ":") last_punct_pos = -1 for punct in punctuations: pos = current_text.rfind(punct) @@ -246,8 +257,12 @@ class ConnectionHandler: segment_text_raw = current_text[:last_punct_pos + 1] segment_text = get_string_no_punctuation_or_emoji(segment_text_raw) if segment_text: - self.recode_first_last_text(segment_text) - future = self.executor.submit(self.speak_and_play, segment_text) + # 强制设置空字符,测试TTS出错返回语音的健壮性 + # if text_index % 2 == 0: + # 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) # 更新已处理字符位置 @@ -257,8 +272,9 @@ class ConnectionHandler: if remaining_text: segment_text = get_string_no_punctuation_or_emoji(remaining_text) if segment_text: - self.recode_first_last_text(segment_text) - future = self.executor.submit(self.speak_and_play, 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) self.llm_finish_task = True @@ -274,30 +290,28 @@ class ConnectionHandler: if future is None: continue text = None + opus_datas, text_index, tts_file = [], 0, None try: self.logger.bind(tag=TAG).debug("正在处理TTS任务...") - tts_file, text = future.result(timeout=10) + tts_file, text, text_index = future.result(timeout=10) if text is None or len(text) <= 0: - continue - if tts_file is None: - self.logger.bind(tag=TAG).error(f"TTS文件生成失败: {text}") - continue - 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) + self.logger.bind(tag=TAG).error(f"TTS出错:{text_index}: tts text is empty") + elif tts_file is None: + self.logger.bind(tag=TAG).error(f"TTS出错: file is empty: {text_index}: {text}") else: - self.logger.bind(tag=TAG).error(f"TTS文件不存在: {tts_file}") - opus_datas = [] + 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) + else: + self.logger.bind(tag=TAG).error(f"TTS出错:文件不存在{tts_file}") except TimeoutError: - self.logger.bind(tag=TAG).error("TTS 任务超时") - continue + self.logger.bind(tag=TAG).error("TTS超时") except Exception as e: - self.logger.bind(tag=TAG).error(f"TTS 任务出错: {e}") - continue + self.logger.bind(tag=TAG).error(f"TTS出错: {e}") if not self.client_abort: # 如果没有中途打断就发送语音 - self.audio_play_queue.put((opus_datas, text)) - if self.tts.delete_audio_file and os.path.exists(tts_file): + self.audio_play_queue.put((opus_datas, text, text_index)) + if self.tts.delete_audio_file and tts_file is not None and os.path.exists(tts_file): os.remove(tts_file) except Exception as e: self.logger.bind(tag=TAG).error(f"TTS任务处理错误: {e}") @@ -306,42 +320,41 @@ class ConnectionHandler: self.websocket.send(json.dumps({"type": "tts", "state": "stop", "session_id": self.session_id})), self.loop ) - self.logger.bind(tag=TAG).error(f"tts_priority priority_thread: {text}{e}") + self.logger.bind(tag=TAG).error(f"tts_priority priority_thread: {text} {e}") def _audio_play_priority_thread(self): while not self.stop_event.is_set(): text = None try: - opus_datas, text = self.audio_play_queue.get() - future = asyncio.run_coroutine_threadsafe(sendAudioMessage(self, opus_datas, text), self.loop) + opus_datas, text, text_index = self.audio_play_queue.get() + future = asyncio.run_coroutine_threadsafe(sendAudioMessage(self, opus_datas, text, text_index), + self.loop) future.result() except Exception as e: - self.logger.bind(tag=TAG).error(f"audio_play_priority priority_thread: {text}{e}") + self.logger.bind(tag=TAG).error(f"audio_play_priority priority_thread: {text} {e}") - def speak_and_play(self, text): + def speak_and_play(self, text, text_index=0): if text is None or len(text) <= 0: self.logger.bind(tag=TAG).info(f"无需tts转换,query为空,{text}") - return None, text + return None, text, text_index tts_file = self.tts.to_tts(text) if tts_file is None: self.logger.bind(tag=TAG).error(f"tts转换失败,{text}") - return None, text + return None, text, text_index self.logger.bind(tag=TAG).debug(f"TTS 文件生成完毕: {tts_file}") - return tts_file, text + return tts_file, text, text_index def clearSpeakStatus(self): self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态") self.asr_server_receive = True - self.tts_last_text = None - self.tts_first_text = None - self.tts_duration = 0 - self.tts_start_speak_time = None + self.tts_last_text_index = -1 + self.tts_first_text_index = -1 - def recode_first_last_text(self, text): - if not self.tts_first_text: + def recode_first_last_text(self, text, text_index=0): + if self.tts_first_text_index == -1: self.logger.bind(tag=TAG).info(f"大模型说出第一句话: {text}") - self.tts_first_text = text - self.tts_last_text = text + self.tts_first_text_index = text_index + self.tts_last_text_index = text_index async def close(self): """资源清理方法""" diff --git a/core/handle/musicHandler.py b/core/handle/musicHandler.py index 93283fe6d..e380704f9 100644 --- a/core/handle/musicHandler.py +++ b/core/handle/musicHandler.py @@ -385,14 +385,14 @@ class MusicHandler: return text = f"正在本地播放{selected_music}" await send_stt_message(conn, text) - conn.tts_first_text = selected_music - conn.tts_last_text = selected_music + 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)) + conn.audio_play_queue.put((opus_packets, selected_music, 0)) except Exception as e: logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") diff --git a/core/handle/sendAudioHandle.py b/core/handle/sendAudioHandle.py index 07b24fb95..d0dcb82f4 100644 --- a/core/handle/sendAudioHandle.py +++ b/core/handle/sendAudioHandle.py @@ -15,11 +15,10 @@ async def isLLMWantToFinish(last_text): return False -async def sendAudioMessage(conn, audios, text): +async def sendAudioMessage(conn, audios, text, text_index=0): # 发送句子开始消息 - if text == conn.tts_first_text: + if text_index == conn.tts_first_text_index: logger.bind(tag=TAG).info(f"发送第一段语音: {text}") - conn.tts_start_speak_time = time.perf_counter() await send_tts_message(conn, "sentence_start", text) # 初始化流控参数 @@ -45,7 +44,7 @@ async def sendAudioMessage(conn, audios, text): play_position += frame_duration # 更新播放位置 await send_tts_message(conn, "sentence_end", text) # 发送结束消息(如果是最后一个文本) - if conn.llm_finish_task and text == conn.tts_last_text: + if conn.llm_finish_task and text_index == conn.tts_last_text_index: await send_tts_message(conn, 'stop', None) if await isLLMWantToFinish(text): await conn.close() diff --git a/core/providers/memory/base.py b/core/providers/memory/base.py new file mode 100644 index 000000000..00ab6650c --- /dev/null +++ b/core/providers/memory/base.py @@ -0,0 +1,23 @@ +from abc import ABC, abstractmethod +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + +class MemoryProviderBase(ABC): + def __init__(self, config): + self.config = config + self.role_id = None + + @abstractmethod + async def save_memory(self, msgs): + """Save a new memory for specific role and return memory ID""" + print("this is base func", msgs) + + @abstractmethod + async def query_memory(self, query: str) -> str: + """Query memories for specific role based on similarity""" + return "please implement query method" + + def set_role_id(self, role_id: str): + self.role_id = role_id \ No newline at end of file diff --git a/core/providers/memory/mem0ai/mem0ai.py b/core/providers/memory/mem0ai/mem0ai.py new file mode 100644 index 000000000..482c0bc29 --- /dev/null +++ b/core/providers/memory/mem0ai/mem0ai.py @@ -0,0 +1,74 @@ +from ..base import MemoryProviderBase, logger +from mem0 import MemoryClient + +TAG = __name__ + +class MemoryProvider(MemoryProviderBase): + def __init__(self, config): + super().__init__(config) + self.api_key = config.get("api_key", "") + self.api_version = config.get("api_version", "v1.1") + if len(self.api_key) == 0 or "你" in self.api_key: + logger.bind(tag=TAG).error("你还没配置Mem0ai的密钥,请在配置文件中配置密钥,否则无法提供记忆服务") + self.use_mem0 = False + return + else: + self.use_mem0 = True + self.client = MemoryClient(api_key=self.api_key) + + async def save_memory(self, msgs): + if not self.use_mem0: + return None + if len(msgs) < 2: + return None + + try: + # Format the content as a message list for mem0 + messages = [ + {"role": message.role, "content": message.content} + for message in msgs if message.role != "system" + ] + result = self.client.add(messages, user_id=self.role_id, output_format=self.api_version) + logger.bind(tag=TAG).debug(f"Save memory result: {result}") + except Exception as e: + logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}") + return None + + async def query_memory(self, query: str)-> str: + if not self.use_mem0: + return "" + try: + results = self.client.search( + query, + user_id=self.role_id, + output_format=self.api_version + ) + if not results or 'results' not in results: + return "" + + # Format each memory entry with its update time up to minutes + memories = [] + for entry in results['results']: + timestamp = entry.get('updated_at', '') + if timestamp: + try: + # Parse and reformat the timestamp + dt = timestamp.split('.')[0] # Remove milliseconds + formatted_time = dt.replace('T', ' ') + except: + formatted_time = timestamp + memory = entry.get('memory', '') + if timestamp and memory: + # Store tuple of (timestamp, formatted_string) for sorting + memories.append((timestamp, f"[{formatted_time}] {memory}")) + + # Sort by timestamp in descending order (newest first) + memories.sort(key=lambda x: x[0], reverse=True) + + # Extract only the formatted strings + memories_str = "\n".join(f"- {memory[1]}" for memory in memories) + logger.bind(tag=TAG).debug(f"Query results: {memories_str}") + return memories_str + except Exception as e: + logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}") + return "" \ No newline at end of file diff --git a/core/utils/dialogue.py b/core/utils/dialogue.py index 703f12c00..ed5e27fee 100644 --- a/core/utils/dialogue.py +++ b/core/utils/dialogue.py @@ -24,3 +24,27 @@ class Dialogue: for m in self.dialogue: dialogue.append({"role": m.role, "content": m.content}) return dialogue + + def get_llm_dialogue_with_memory(self, memory_str: str = None) -> List[Dict[str, str]]: + # 构建带记忆的对话 + dialogue = [] + + # 添加系统提示和记忆 + system_message = next( + (msg for msg in self.dialogue if msg.role == "system"), None + ) + + + if system_message: + enhanced_system_prompt = ( + f"{system_message.content}\n\n" + f"相关记忆:\n{memory_str}" + ) + 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}) + + return dialogue diff --git a/core/utils/memory.py b/core/utils/memory.py new file mode 100644 index 000000000..c750e9aa7 --- /dev/null +++ b/core/utils/memory.py @@ -0,0 +1,17 @@ +import os +import sys +import importlib +from config.logger import setup_logging +from core.utils.util import read_config, get_project_dir + +logger = setup_logging() + +def create_instance(class_name, *args, **kwargs): + if os.path.exists(os.path.join('core', 'providers', 'memory', class_name, f'{class_name}.py')): + lib_name = f'core.providers.memory.{class_name}.{class_name}' + if lib_name not in sys.modules: + sys.modules[lib_name] = importlib.import_module(f'{lib_name}') + return sys.modules[lib_name].MemoryProvider(*args, **kwargs) + + raise ValueError(f"不支持的记忆服务类型: {class_name}") + diff --git a/core/websocket_server.py b/core/websocket_server.py index 907ef22ff..41629932f 100644 --- a/core/websocket_server.py +++ b/core/websocket_server.py @@ -4,7 +4,7 @@ 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 +from core.utils import asr, vad, llm, tts, memory TAG = __name__ @@ -13,10 +13,14 @@ 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._create_processing_instances() + self._vad, self._asr, self._llm, self._tts, self._music, self._memory = self._create_processing_instances() self.active_connections = set() # 添加全局连接记录 def _create_processing_instances(self): + memory_cls_name = self.config["selected_module"].get("Memory", "mem0ai") # 默认使用mem0ai + has_memory_cfg = self.config.get("Memory") and memory_cls_name in self.config["Memory"] + memory_cfg = self.config["Memory"][memory_cls_name] if has_memory_cfg else {} + """创建处理模块实例""" return ( vad.create_instance( @@ -46,7 +50,8 @@ class WebSocketServer: self.config["TTS"][self.config["selected_module"]["TTS"]], self.config["delete_audio"] ), - MusicHandler(self.config) + MusicHandler(self.config), + memory.create_instance(memory_cls_name, memory_cfg), ) async def start(self): @@ -66,7 +71,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) + handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts, self._music, self._memory) self.active_connections.add(handler) try: await handler.handle_connection(websocket) diff --git a/docs/Deployment.md b/docs/Deployment.md index 81c4d7f96..8f5b4f914 100644 --- a/docs/Deployment.md +++ b/docs/Deployment.md @@ -231,9 +231,10 @@ python app.py 如果你的`项目目录`目录没有`data`,你需要创建`data`目录。 如果你的`data`下面没有`.config.yaml`文件,你可以把源码目录下的`config.yaml`文件复制一份,重命名为`.config.yaml` -修改`项目目录`下`data`目录下的`.config.yaml`文件,配置本项目所需的各种参数。默认的LLM使用的是`ChatGLMLLM` -,你需要配置密钥,因为他们的模型,虽然有免费的,但是仍要去[官网](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)注册密钥,才能启动。 -默认的TTS使用的是`EdgeTTS`,这个无需配置,如果你需要更换成`豆包TTS`,则需要配置密钥。 +修改`项目目录`下`data`目录下的`.config.yaml`文件,配置本项目必须的两个配置。 + +- 默认的LLM使用的是`ChatGLMLLM`,你需要配置密钥,因为他们的模型,虽然有免费的,但是仍要去[官网](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)注册密钥,才能启动。 +- 默认的记忆层`mem0ai`,你需要配置密钥,因为他们的API,虽然有免费额度,但是仍要去[官网](https://app.mem0.ai/dashboard/api-keys)注册密钥,才能启动。 配置说明:这里是各个功能使用的默认组件,例如LLM默认使用`ChatGLMLLM`模型。如果需要切换模型,就是改对应的名称。 本项目的默认配置仅是成本最低配置(`glm-4-flash`和`EdgeTTS`都是免费的),如果需要更优的更快的搭配,需要自己结合部署环境切换各组件的使用。 diff --git a/docs/images/demo6.png b/docs/images/demo6.png new file mode 100644 index 000000000..18d8f5f36 Binary files /dev/null and b/docs/images/demo6.png differ diff --git a/docs/images/demo7.png b/docs/images/demo7.png new file mode 100644 index 000000000..ed7a3557c Binary files /dev/null and b/docs/images/demo7.png differ diff --git a/requirements.txt b/requirements.txt index 1ed089bcb..3edafe34b 100755 --- a/requirements.txt +++ b/requirements.txt @@ -19,3 +19,4 @@ loguru==0.7.3 requests==2.32.3 cozepy==0.12.0 miniaudio==1.61 +mem0ai==0.1.62 \ No newline at end of file