diff --git a/main/xiaozhi-server/config/assets/wakeup_words/ed76d459636c2481aec828516c1b4f54.wav b/main/xiaozhi-server/config/assets/wakeup_words/ed76d459636c2481aec828516c1b4f54.wav index b4bf64848..6ce02eea2 100644 Binary files a/main/xiaozhi-server/config/assets/wakeup_words/ed76d459636c2481aec828516c1b4f54.wav and b/main/xiaozhi-server/config/assets/wakeup_words/ed76d459636c2481aec828516c1b4f54.wav differ diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index c8a4de5e0..da13949d5 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -2,6 +2,7 @@ import os import sys import copy import json +from urllib import response import uuid import time import queue @@ -795,7 +796,7 @@ class ConnectionHandler: def _send_llm_event_message(self, text, event=None, phase=None): if not self.websocket or not self.loop: return - payload = {"type": "llm", "text": text, "session_id": self.session_id} + payload = {"type": "stt", "text": text, "session_id": self.session_id} if event is not None: payload["event"] = event if phase is not None: @@ -928,143 +929,192 @@ class ConnectionHandler: self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") return None - # 处理流式响应 + # 处理流式响应(满足:非 action、未产 content、0.5s 无信息增加 => thinking) tool_call_flag = False - # 支持多个并行工具调用 - 使用列表存储 tool_calls_list = [] # 格式: [{"id": "", "name": "", "arguments": ""}] content_arguments = "" self.client_abort = False emotion_flag = True + thinking_event_sent = False thinking_event_done = False - for response in llm_responses: - if self.client_abort: - break - if isinstance(response, dict): - kind = response.get("kind") - if kind == "thinking": - if not thinking_event_sent: - self._send_llm_event_message( - "[Thinking]", event="thinking", phase="start" - ) - thinking_event_sent = True - self._start_thinking_pulse() - continue - if kind == "action": - phase = response.get("phase") - if phase == "start": - label = "[Action Started]" - self._start_action_pulse() - elif phase == "done": - label = "[Action Finished]" - self._stop_action_pulse() + + # --- idle -> thinking 状态变量 --- + IDLE_TO_THINKING_SEC = 0.5 + last_progress_t = [time.monotonic()] # “信息增加”的最后时间(只在增量有意义时更新) + action_in_progress = threading.Event() # True: action(start) 后未 done + content_started = threading.Event() # True: 真实 content 已开始输出 + watchdog_stop = threading.Event() + + def mark_progress(): + last_progress_t[0] = time.monotonic() + + def ensure_thinking_running(): + """只有在:非 action、未产 content、且 thinking 未结束 时,启动/维持 thinking pulse""" + nonlocal thinking_event_sent, thinking_event_done + if thinking_event_done: + return + if action_in_progress.is_set() or content_started.is_set(): + return + if not thinking_event_sent: + self._send_llm_event_message("[Thinking]", event="thinking", phase="start") + thinking_event_sent = True + self._start_thinking_pulse() + + def finish_thinking_once(): + """第一次拿到真实 content 时,结束 thinking""" + nonlocal thinking_event_done + if thinking_event_sent and not thinking_event_done: + self._stop_thinking_pulse() + self._send_llm_event_message("[Thinking Finished]", event="thinking", phase="done") + thinking_event_done = True + + def pause_thinking_pulse_only(): + """action 期间暂停 thinking pulse,但不发 Thinking Finished""" + if thinking_event_sent and not thinking_event_done: + self._stop_thinking_pulse() + + def emit_action_event(phase): + """action 事件出现时:暂停 thinking、跑 action pulse,并维护 action_in_progress 状态""" + if phase == "start": + action_in_progress.set() + pause_thinking_pulse_only() + self._start_action_pulse() + label = "[Action Started]" + elif phase == "done": + action_in_progress.clear() + self._stop_action_pulse() + label = "[Action Finished]" + else: + label = "[Action]" + self._send_llm_event_message(label, event="action", phase=phase) + + def is_toolcall_payload(prefix: str) -> bool: + s = (prefix or "").lstrip() + return s.startswith("") + + def _watchdog(): + # 规则:非 action、未产 content、且 0.5s 无信息增加 => thinking + while not watchdog_stop.is_set(): + if (not action_in_progress.is_set()) and (not content_started.is_set()) and (not thinking_event_done): + idle = time.monotonic() - last_progress_t[0] + if idle >= IDLE_TO_THINKING_SEC: + ensure_thinking_running() + watchdog_stop.wait(0.05) # 50ms tick + + threading.Thread(target=_watchdog, daemon=True).start() + + try: + for response in llm_responses: + if self.client_abort: + break + + # ---------- 1) 归一化:拆出 event / text_delta / tools_call ---------- + event = None + text_delta = None + tools_call = None + + if isinstance(response, dict): + # 注意:有些 provider 用 dict 承载 {"content":..., "tools_call":...} + if "content" in response: + text_delta = response.get("content") + tools_call = response.get("tools_call") else: - label = "[Action]" - self._send_llm_event_message( - label, - event="action", - phase=phase, - ) - continue - continue - if self.intent_type == "function_call" and functions is not None: - content, tools_call = response - if "content" in response: - content = response["content"] - tools_call = None - if isinstance(content, dict): - kind = content.get("kind") - if kind == "thinking": - if not thinking_event_sent: - self._send_llm_event_message( - "[Thinking]", event="thinking", phase="start" - ) - thinking_event_sent = True - self._start_thinking_pulse() - continue - if kind == "action": - phase = content.get("phase") - if phase == "start": - label = "[Action Started]" - self._start_action_pulse() - elif phase == "done": - label = "[Action Finished]" - self._stop_action_pulse() + event = response + else: + if self.intent_type == "function_call" and functions is not None: + if isinstance(response, tuple) and len(response) == 2: + text_delta, tools_call = response else: - label = "[Action]" - self._send_llm_event_message( - label, - event="action", - phase=phase, - ) - continue - if ( - thinking_event_sent - and not thinking_event_done - and isinstance(content, str) - and content.strip() - ): - self._stop_thinking_pulse() - self._send_llm_event_message( - "[Thinking Finished]", - event="thinking", - phase="done", - ) - thinking_event_done = True - if content is not None and len(content) > 0: - content_arguments += content + text_delta = response + else: + text_delta = response - if not tool_call_flag and content_arguments.startswith(""): - # print("content_arguments", content_arguments) - tool_call_flag = True + # ---------- 2) 处理 event(dict) ---------- + if event is not None: + # event 算“信息增加”(你能看见/能用于状态判断) + mark_progress() + kind = event.get("kind") + if kind == "action": + emit_action_event(event.get("phase")) + elif kind == "thinking": + # 模型显式发 thinking:立即进入 thinking(不等 0.5s) + ensure_thinking_running() + # 其它 event:不立刻进入 thinking,交给 watchdog(看 idle) + continue + + # text_delta 也可能是 dict(kind=...) + if isinstance(text_delta, dict): + mark_progress() + kind = text_delta.get("kind") + if kind == "action": + emit_action_event(text_delta.get("phase")) + elif kind == "thinking": + ensure_thinking_running() + continue + + # ---------- 3) tools_call(算信息增加) ---------- if tools_call is not None and len(tools_call) > 0: + mark_progress() tool_call_flag = True self._merge_tool_calls(tool_calls_list, tools_call) - else: - content = response - if ( - thinking_event_sent - and not thinking_event_done - and isinstance(content, str) - and content.strip() - ): - self._stop_thinking_pulse() - self._send_llm_event_message( - "[Thinking Finished]", - event="thinking", - phase="done", - ) - thinking_event_done = True - # 在llm回复中获取情绪表情,一轮对话只在开头获取一次 - if emotion_flag and content is not None and content.strip(): - asyncio.run_coroutine_threadsafe( - textUtils.get_emotion(self, content), - self.loop, + # ---------- 4) 处理文本增量 ---------- + if text_delta is None: + # 没信息增加 -> 不 mark_progress,watchdog 会在 idle 后触发 thinking + continue + if isinstance(text_delta, str) and text_delta == "": + # 空串不算信息增加 -> watchdog 触发 thinking + continue + + content = str(text_delta) + if content: + mark_progress() + + # 情绪表情:一轮只做一次 + if emotion_flag and content.strip(): + asyncio.run_coroutine_threadsafe( + textUtils.get_emotion(self, content), + self.loop, + ) + emotion_flag = False + + # 累积用于 tool_call 判断与后续解析 + content_arguments += content + + if not tool_call_flag and is_toolcall_payload(content_arguments): + tool_call_flag = True + + if tool_call_flag: + # tool_call 阶段不算“真实 content”,由 watchdog 负责 idle->thinking + continue + + # 真正用户可见 content:开始输出后结束 thinking + if content.strip(): + content_started.set() + finish_thinking_once() + + response_message.append(content) + self.tts.tts_text_queue.put( + TTSMessageDTO( + sentence_id=self.sentence_id, + sentence_type=SentenceType.MIDDLE, + content_type=ContentType.TEXT, + content_detail=content, + ) ) - emotion_flag = False - if content is not None and len(content) > 0: - if not tool_call_flag: - response_message.append(content) - self.tts.tts_text_queue.put( - TTSMessageDTO( - sentence_id=self.sentence_id, - sentence_type=SentenceType.MIDDLE, - content_type=ContentType.TEXT, - content_detail=content, - ) - ) - # 处理function call + finally: + watchdog_stop.set() + + # 流结束:如果曾经进入 thinking 但没结束,收尾 if thinking_event_sent and not thinking_event_done: self._stop_thinking_pulse() - self._send_llm_event_message( - "[Thinking Finished]", - event="thinking", - phase="done", - ) + self._send_llm_event_message("[Thinking Finished]", event="thinking", phase="done") thinking_event_done = True + + if tool_call_flag: bHasError = False # 处理基于文本的工具调用格式 diff --git a/main/xiaozhi-server/core/providers/llm/codex/codex.py b/main/xiaozhi-server/core/providers/llm/codex/codex.py index 20181d308..c83cefcde 100644 --- a/main/xiaozhi-server/core/providers/llm/codex/codex.py +++ b/main/xiaozhi-server/core/providers/llm/codex/codex.py @@ -211,6 +211,7 @@ class _CodexSession: self.emit_events = bool(config.get("emit_events", False)) self.thinking_mode = (config.get("thinking_mode") or "off").lower() self.show_actions = bool(config.get("show_actions", False)) + self.thinking_debug = bool(config.get("thinking_debug", False)) # ---- Stream logging toggles ---- # log_stream: enables writing stream output to file + end-of-turn info log @@ -219,6 +220,8 @@ class _CodexSession: self.stream_debug = bool(config.get("stream_debug", False)) # log_events: also write emitted event dicts (thinking/action) into SAME log file self.log_events = bool(config.get("log_events", True)) + # raw_stream_log: write raw app-server messages to a separate file + self.raw_stream_log = bool(config.get("raw_stream_log", False)) # event_max_chars: truncate long event JSON payloads (0 = no truncation) self.event_max_chars = int(config.get("event_max_chars", 8000)) @@ -227,6 +230,11 @@ class _CodexSession: ) self.stream_log_path = config.get("stream_log_path", default_stream_log_path) self._stream_flush_bytes = int(config.get("stream_flush_bytes", 4096)) + default_raw_log_path = str( + Path(self.workspace) / f"codex_stream_raw_{_safe_filename(session_key)}.log" + ) + self.raw_stream_log_path = config.get("raw_stream_log_path", default_raw_log_path) + self._raw_stream_flush_bytes = int(config.get("raw_stream_flush_bytes", 8192)) self.proc: Optional[subprocess.Popen] = None self.q: Optional[queue.Queue] = None @@ -254,6 +262,17 @@ class _CodexSession: except Exception as exc: logger.bind(tag=TAG).warning(f"codex stream log write failed: {exc}") + def _append_raw_log(self, text: str) -> None: + """Append to per-session raw log file (best-effort).""" + if not self.raw_stream_log or not self.raw_stream_log_path or not text: + return + try: + Path(self.raw_stream_log_path).parent.mkdir(parents=True, exist_ok=True) + with open(self.raw_stream_log_path, "a", encoding="utf-8") as f: + f.write(text) + except Exception as exc: + logger.bind(tag=TAG).warning(f"codex raw log write failed: {exc}") + def _pump_stderr(self) -> None: if not self.proc or not self.proc.stderr: return @@ -465,6 +484,7 @@ class _CodexSession: # ---- file buffering (assistant text + event lines) ---- file_buf = "" + raw_buf = "" def file_append(s: str) -> None: nonlocal file_buf @@ -481,6 +501,21 @@ class _CodexSession: self._append_stream_log(file_buf) file_buf = "" + def raw_append(s: str) -> None: + nonlocal raw_buf + if not self.raw_stream_log or not s: + return + raw_buf += s + if len(raw_buf.encode("utf-8", errors="ignore")) >= self._raw_stream_flush_bytes: + self._append_raw_log(raw_buf) + raw_buf = "" + + def raw_flush() -> None: + nonlocal raw_buf + if raw_buf: + self._append_raw_log(raw_buf) + raw_buf = "" + def file_event(event_obj: Dict) -> None: """ Write an event line into the SAME log file, with timestamp. @@ -500,6 +535,12 @@ class _CodexSession: # Ensure event starts on a new line and ends with newline. file_append(f"\n[{_ts()}] [EVENT] {payload}\n") + def file_thinking_debug(method: str, delta: str) -> None: + if not (self.log_stream and self.thinking_debug): + return + safe_delta = delta.replace("\r", "\\r").replace("\n", "\\n") + file_append(f"\n[{_ts()}] [THINKING_DEBUG] {method}: {safe_delta}\n") + # Log turn start if self.log_stream: file_append(f"[{_ts()}] [TURN_START] session={self.session_key} thread={self.thread_id} turn={turn_id}\n") @@ -512,6 +553,12 @@ class _CodexSession: try: while True: msg = _read_one(self.q, timeout=None) + if self.raw_stream_log: + try: + raw_payload = json.dumps(msg, ensure_ascii=False) + except Exception: + raw_payload = str(msg) + raw_append(f"[{_ts()}] raw_{raw_payload}\n") if _is_server_request(msg): _accept_server_request(self.proc, msg, self.auto_approve) continue @@ -521,7 +568,7 @@ class _CodexSession: method = msg.get("method") params = msg.get("params", {}) or {} - + # --- assistant text stream --- if method == "item/agentMessage/delta": delta = params.get("delta", "") @@ -547,6 +594,7 @@ class _CodexSession: thinking_buffer += delta evt = {"kind": "thinking", "mode": "summary", "delta": delta, "turn_id": turn_id} file_event(evt) + file_thinking_debug(method, delta) if self.log_stream and self.stream_debug: tlog.debug("codex_thinking_summary_delta", delta=_short(delta, 400)) yield {"kind": "thinking", "text": thinking_buffer} @@ -557,9 +605,15 @@ class _CodexSession: thinking_buffer += delta evt = {"kind": "thinking", "mode": "raw", "delta": delta, "turn_id": turn_id} file_event(evt) + file_thinking_debug(method, delta) if self.log_stream and self.stream_debug: tlog.debug("codex_thinking_raw_delta", delta=_short(delta, 400)) yield {"kind": "thinking", "text": thinking_buffer} + else: + if method in ("item/reasoning/summaryTextDelta", "item/reasoning/textDelta"): + delta = params.get("delta", "") + if delta: + file_thinking_debug(method, delta) if emit_events and self.show_actions and method in ("item/started", "item/completed"): item = params.get("item", {}) or {} @@ -599,6 +653,7 @@ class _CodexSession: file_append(f"\n[{_ts()}] [TURN_END] chars={len(out_buffer)}\n\n--- turn_end ---\n\n") file_flush() + raw_flush() if self.log_stream: tlog.info( diff --git a/main/xiaozhi-server/test_codex_provider_action.py b/main/xiaozhi-server/test_codex_provider_action.py index 28644a90d..9963db095 100644 --- a/main/xiaozhi-server/test_codex_provider_action.py +++ b/main/xiaozhi-server/test_codex_provider_action.py @@ -9,7 +9,7 @@ cfg = { "log_events":True, # 把 thinking/action 事件写进同一个 log "event_max_chars": 0, # 可选:事件 JSON 太长就截断;设 0 表示不截断 "model_name": "gpt-5.2", - "workspace": r"C:\Users\yibinjiang\Documents\GitHub\codex_app_server", + "workspace": "C:/Users/yibinjiang/Documents/GitHub/codex_edu/", "auto_approve": True, "network_access": True, "emit_events": True, diff --git a/test_codex.ipynb b/test_codex.ipynb new file mode 100644 index 000000000..1f7eb79a7 --- /dev/null +++ b/test_codex.ipynb @@ -0,0 +1,249 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "38e24e24", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\u001b[32m260130 16:36:51\u001b[0m[0.8.11_00000000000000][\u001b[94mcore.providers.llm.codex.codex\u001b[0m]-\u001b[1mINFO\u001b[0m-\u001b[92mcodex_action\u001b[0m\n", + "{'kind': 'action', 'text': 'commandExecution cmd=\"C:\\\\\\\\WINDOWS\\\\\\\\System32\\\\\\\\WindowsPowerShell\\\\\\\\v1.0\\\\\\\\powershell.exe\" -Command \\'Get-Content .codex/skills/repo-bootstrap/SKILL.md\\'', 'phase': 'start'}\n", + "\u001b[32m260130 16:36:51\u001b[0m[0.8.11_00000000000000][\u001b[94mcore.providers.llm.codex.codex\u001b[0m]-\u001b[1mINFO\u001b[0m-\u001b[92mcodex_action\u001b[0m\n", + "{'kind': 'action', 'text': 'commandExecution cmd=\"C:\\\\\\\\WINDOWS\\\\\\\\System32\\\\\\\\WindowsPowerShell\\\\\\\\v1.0\\\\\\\\powershell.exe\" -Command \\'Get-Content .codex/skills/repo-bootstrap/SKILL.md\\'', 'phase': 'done'}\n", + "\u001b[32m260130 16:37:01\u001b[0m[0.8.11_00000000000000][\u001b[94mcore.providers.llm.codex.codex\u001b[0m]-\u001b[1mINFO\u001b[0m-\u001b[92mcodex_action\u001b[0m\n", + "{'kind': 'action', 'text': 'commandExecution cmd=\"C:\\\\\\\\WINDOWS\\\\\\\\System32\\\\\\\\WindowsPowerShell\\\\\\\\v1.0\\\\\\\\powershell.exe\" -Command Get-ChildItem', 'phase': 'start'}\n", + "\u001b[32m260130 16:37:01\u001b[0m[0.8.11_00000000000000][\u001b[94mcore.providers.llm.codex.codex\u001b[0m]-\u001b[1mINFO\u001b[0m-\u001b[92mcodex_action\u001b[0m\n", + "{'kind': 'action', 'text': 'commandExecution cmd=\"C:\\\\\\\\WINDOWS\\\\\\\\System32\\\\\\\\WindowsPowerShell\\\\\\\\v1.0\\\\\\\\powershell.exe\" -Command Get-ChildItem', 'phase': 'done'}\n", + "同\n", + "学\n", + "你好\n", + ",我\n", + "是\n", + "小\n", + "智\n", + ",\n", + "先\n", + "确认\n", + "一下\n", + "你\n", + "现在\n", + "做\n", + "的\n", + "实验\n", + "名称\n", + "是什么\n", + "、\n", + "进行\n", + "到\n", + "哪\n", + "一步\n", + "了\n", + "?\n", + "仓\n", + "库\n", + "根\n", + "目录\n", + "目前\n", + "包括\n", + " `.\n", + "cod\n", + "ex\n", + "`\n", + " \n", + "目录\n", + "(\n", + "存\n", + "放\n", + " Cod\n", + "ex\n", + " 技\n", + "能\n", + "与\n", + "配置\n", + ",用\n", + "来\n", + "约\n", + "束\n", + "和\n", + "加载\n", + "化\n", + "学\n", + "助\n", + "教\n", + "行为\n", + ")、\n", + "`\n", + "data\n", + "`\n", + " \n", + "目录\n", + "(\n", + "保存\n", + "教学\n", + "资料\n", + "等\n", + "实验\n", + "数据\n", + ",\n", + "按\n", + "规定\n", + "默认\n", + "只\n", + "读\n", + ")、\n", + "`\n", + "AG\n", + "ENTS\n", + ".md\n", + ":\n", + "1\n", + "`\n", + "(\n", + "详细\n", + "说明\n", + "助\n", + "教\n", + "身份\n", + "、\n", + "互动\n", + "和\n", + "安全\n", + "要求\n", + ")、\n", + "`\n", + "cod\n", + "ex\n", + "_stream\n", + "_raw\n", + "_test\n", + "_session\n", + ".log\n", + ":\n", + "1\n", + "`\n", + "(\n", + "调\n", + "试\n", + "或\n", + "演\n", + "练\n", + "过程\n", + "的\n", + "原\n", + "始\n", + "日志\n", + ",\n", + "便\n", + "于\n", + "完整\n", + "追\n", + "踪\n", + ")、\n", + "`\n", + "cod\n", + "ex\n", + "_stream\n", + "_test\n", + "_session\n", + ".log\n", + ":\n", + "1\n", + "`\n", + "(\n", + "提\n", + "炼\n", + "后的\n", + "测试\n", + "日志\n", + ",\n", + "快速\n", + "定位\n", + "最近\n", + "的\n", + "交\n", + "互\n", + "结果\n", + ")。\n", + "需要\n", + "我\n", + "进一步\n", + "查看\n", + "或\n", + "整理\n", + "这些\n", + "内容\n", + "就\n", + "告诉\n", + "我\n", + "。\n", + "\u001b[32m260130 16:37:18\u001b[0m[0.8.11_00000000000000][\u001b[94mcore.providers.llm.codex.codex\u001b[0m]-\u001b[1mINFO\u001b[0m-\u001b[92mcodex_stream_turn_completed\u001b[0m\n" + ] + } + ], + "source": [ + "import sys\n", + "sys.path.append(r\"C:\\Users\\yibinjiang\\Documents\\GitHub\\xiaozhi-esp32-server\\main\\xiaozhi-server\")\n", + "\n", + "from core.providers.llm.codex.codex import LLMProvider\n", + "\n", + "config = {\n", + " \"type\": \"codex\",\n", + " \"codex_bin\": \"codex.cmd\",\n", + " \"model_name\": \"gpt-5.1-codex\",\n", + " \"workspace\": r\"C:\\Users\\yibinjiang\\Documents\\GitHub\\codex_edu\",\n", + " \"auto_approve\": True,\n", + " \"network_access\": True,\n", + " \"effort\": \"high\",\n", + " \"emit_events\": True,\n", + " \"thinking_mode\": \"summary\",\n", + " \"show_actions\": True,\n", + " \"raw_stream_log\": True,\n", + " \"runtime_config\": {\"hide_agent_reasoning\": False},\n", + "}\n", + "config[\"summary\"] = \"detailed\"\n", + "\n", + "llm = LLMProvider(config)\n", + "\n", + "dialogue = [\n", + " {\"role\": \"user\", \"content\": \"请列出这个仓库顶层文件,并解释每个文件的作用。\"}\n", + "]\n", + "\n", + "for token in llm.response(session_id=\"test_session\", dialogue=dialogue, summary=\"detailed\"):\n", + " print(token)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b9c4f649", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "xiaozhi-esp32-server", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.19" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}