From 58602ff4df9c5ae13c0d41f2ae8c6a03d6a0a195 Mon Sep 17 00:00:00 2001 From: Yibin Jiang <44966246+chemyibinjiang@users.noreply.github.com> Date: Sun, 25 Jan 2026 14:11:21 +0800 Subject: [PATCH] modify the provider and test it --- main/xiaozhi-server/core/connection.py | 62 ++++++++++++++++ .../core/providers/llm/codex/codex.py | 70 ++++++++++++++++++- .../test_codex_provider_action.py | 26 +++++++ 3 files changed, 155 insertions(+), 3 deletions(-) create mode 100644 main/xiaozhi-server/test_codex_provider_action.py diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 449fbd2db..23f0bfb72 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -10,12 +10,14 @@ import threading import traceback import subprocess import websockets +import math from core.utils.util import ( extract_json_from_string, check_vad_update, check_asr_update, filter_sensitive_info, + pcm_to_data_stream, ) from typing import Dict, Any from collections import deque @@ -141,6 +143,11 @@ class ConnectionHandler: self.sentence_id = None # 处理TTS响应没有文本返回 self.tts_MessageText = "" + self._silent_opus_cache = {} + self._status_event_state = { + "thinking": {"last_time": 0.0, "last_len": 0, "last_text": ""}, + "action": {"last_time": 0.0, "last_len": 0, "last_text": ""}, + } # iot相关变量 self.iot_descriptors = {} @@ -788,6 +795,52 @@ class ConnectionHandler: # 更新系统prompt至上下文 self.dialogue.update_system_message(self.prompt) + def _get_silent_opus_frames(self, duration_ms): + frame_ms = 60 + duration_ms = max(frame_ms, int(duration_ms)) + frame_count = int(math.ceil(duration_ms / frame_ms)) + cached = self._silent_opus_cache.get(frame_count) + if cached is not None: + return cached + raw_len = frame_count * 960 * 2 + raw_data = b"\x00" * raw_len + frames = [] + pcm_to_data_stream(raw_data, is_opus=True, callback=frames.append) + self._silent_opus_cache[frame_count] = frames + return frames + + def _maybe_send_silent_status(self, kind, text, phase=None): + if not text or self.tts is None: + return + state = self._status_event_state.get(kind) + if state is None: + return + now = time.time() + min_interval = int(self.config.get("silent_status_interval_ms", 400)) / 1000.0 + min_chars = int(self.config.get("silent_status_min_chars", 40)) + + if kind != "action": + if ( + len(text) - state["last_len"] < min_chars + and now - state["last_time"] < min_interval + ): + return + + display_text = text + if kind == "action" and phase: + display_text = f"{phase}: {text}" + + silent_ms = int(self.config.get("silent_tts_ms", 120)) + frames = self._get_silent_opus_frames(silent_ms) + # ensure a fresh start/stop pair for each status update + self.tts.tts_audio_first_sentence = True + self.tts.tts_audio_queue.put((SentenceType.FIRST, frames, display_text)) + self.tts.tts_audio_queue.put((SentenceType.LAST, [], None)) + + state["last_time"] = now + state["last_len"] = len(text) + state["last_text"] = text + def chat(self, query, depth=0): if query is not None: self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}") @@ -872,6 +925,15 @@ class ConnectionHandler: for response in llm_responses: if self.client_abort: break + if isinstance(response, dict) and response.get("kind"): + event_kind = response.get("kind") + if event_kind in ("thinking", "action"): + self._maybe_send_silent_status( + event_kind, + response.get("text", ""), + response.get("phase"), + ) + continue if self.intent_type == "function_call" and functions is not None: content, tools_call = response if "content" in response: diff --git a/main/xiaozhi-server/core/providers/llm/codex/codex.py b/main/xiaozhi-server/core/providers/llm/codex/codex.py index abfb019d2..cde0c9ee2 100644 --- a/main/xiaozhi-server/core/providers/llm/codex/codex.py +++ b/main/xiaozhi-server/core/providers/llm/codex/codex.py @@ -156,6 +156,26 @@ def _build_tool_context(messages: List[Dict]) -> str: return "\n".join(lines) +def _short(text: Optional[str], limit: int = 240) -> str: + if not text: + return "" + text = text.replace("\r\n", "\n") + return text if len(text) <= limit else text[:limit] + " ..." + + +def _format_action_desc(item: Dict) -> str: + desc = item.get("type") or "item" + if "command" in item: + desc += f" cmd={_short(str(item['command']))}" + if "path" in item: + desc += f" path={_short(str(item['path']))}" + if "tool" in item: + desc += f" tool={_short(str(item['tool']))}" + if "name" in item: + desc += f" name={_short(str(item['name']))}" + return desc + + class _CodexSession: def __init__(self, config: Dict, session_key: str) -> None: self.session_key = session_key @@ -175,6 +195,9 @@ class _CodexSession: self.export_api_key = bool(config.get("export_api_key", False)) self.env_overrides = config.get("env", {}) or {} self.runtime_config = config.get("runtime_config", {}) or {} + 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.proc: Optional[subprocess.Popen] = None self.q: Optional[queue.Queue] = None @@ -272,6 +295,14 @@ class _CodexSession: except Exception as exc: logger.bind(tag=TAG).warning(f"codex config write failed: {key} ({exc})") + if self.emit_events and self.thinking_mode != "off" and "hide_agent_reasoning" not in self.runtime_config: + try: + self._write_config("hide_agent_reasoning", False) + except Exception as exc: + logger.bind(tag=TAG).warning( + f"codex config write failed: hide_agent_reasoning ({exc})" + ) + thread_params = {"model": self.model, "cwd": self.workspace, "sandbox": self.thread_sandbox} if self.approval_policy: thread_params["approvalPolicy"] = self.approval_policy @@ -353,7 +384,7 @@ class _CodexSession: return last_user - def _stream_turn(self, prompt_text: str, **kwargs): + def _stream_turn(self, prompt_text: str, emit_events: bool, **kwargs): self.start() turn_params = { "threadId": self.thread_id, @@ -385,6 +416,7 @@ class _CodexSession: saw_tokens = False final_text = None + thinking_buffer = "" try: while True: @@ -405,6 +437,32 @@ class _CodexSession: saw_tokens = True yield delta + if emit_events and self.thinking_mode != "off": + if ( + self.thinking_mode == "summary" + and method == "item/reasoning/summaryTextDelta" + ): + delta = params.get("delta", "") + if delta: + thinking_buffer += delta + yield {"kind": "thinking", "text": thinking_buffer} + if self.thinking_mode == "raw" and method == "item/reasoning/textDelta": + delta = params.get("delta", "") + if delta: + thinking_buffer += delta + yield {"kind": "thinking", "text": thinking_buffer} + + if emit_events and self.show_actions and method in ("item/started", "item/completed"): + item = params.get("item", {}) or {} + item_type = item.get("type") + if item_type not in ("userMessage", "reasoning", "agentMessage"): + phase = "start" if method == "item/started" else "done" + yield { + "kind": "action", + "text": _format_action_desc(item), + "phase": phase, + } + if method == "item/completed": item = params.get("item", {}) or {} if item.get("type") == "agentMessage": @@ -423,7 +481,10 @@ class _CodexSession: prompt_text = self._compose_prompt(dialogue) if not prompt_text: return - for token in self._stream_turn(prompt_text, **kwargs): + emit_events = kwargs.pop("emit_events", self.emit_events) + for token in self._stream_turn(prompt_text, emit_events=emit_events, **kwargs): + if isinstance(token, dict) and not emit_events: + continue yield token @@ -472,4 +533,7 @@ class LLMProvider(LLMProviderBase): def response_with_functions(self, session_id, dialogue, functions=None, **kwargs): for token in self.response(session_id, dialogue, **kwargs): - yield token, None + if isinstance(token, dict): + yield token + else: + yield token, None diff --git a/main/xiaozhi-server/test_codex_provider_action.py b/main/xiaozhi-server/test_codex_provider_action.py new file mode 100644 index 000000000..fe32bc6a2 --- /dev/null +++ b/main/xiaozhi-server/test_codex_provider_action.py @@ -0,0 +1,26 @@ +from core.providers.llm.codex.codex import LLMProvider + +cfg = { + "type": "codex", + "codex_bin": "codex.cmd", + "model_name": "gpt-5.2", + "workspace": r"C:\Users\yibinjiang\Documents\GitHub\codex_app_server", + "auto_approve": True, + "network_access": True, + "emit_events": True, + "thinking_mode": "summary", # 或 "raw" + "show_actions": True, + "summary": "detailed", # 建议加,方便出 reasoning +} +p = LLMProvider(cfg) +dialogue = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "请列出当前目录文件名,并说明你做了哪些操作。然后回答 1+1=?"}, +] + +for chunk in p.response("probe", dialogue, emit_events=True): + if isinstance(chunk, dict): + print("[EVENT]", chunk) + else: + print(chunk, end="", flush=True) +print() \ No newline at end of file