mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
complete codex api but need to play with the connection part.
This commit is contained in:
parent
58602ff4df
commit
c2d10b524e
3 changed files with 146 additions and 71 deletions
|
|
@ -10,14 +10,12 @@ import threading
|
||||||
import traceback
|
import traceback
|
||||||
import subprocess
|
import subprocess
|
||||||
import websockets
|
import websockets
|
||||||
import math
|
|
||||||
|
|
||||||
from core.utils.util import (
|
from core.utils.util import (
|
||||||
extract_json_from_string,
|
extract_json_from_string,
|
||||||
check_vad_update,
|
check_vad_update,
|
||||||
check_asr_update,
|
check_asr_update,
|
||||||
filter_sensitive_info,
|
filter_sensitive_info,
|
||||||
pcm_to_data_stream,
|
|
||||||
)
|
)
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
from collections import deque
|
from collections import deque
|
||||||
|
|
@ -143,11 +141,6 @@ class ConnectionHandler:
|
||||||
self.sentence_id = None
|
self.sentence_id = None
|
||||||
# 处理TTS响应没有文本返回
|
# 处理TTS响应没有文本返回
|
||||||
self.tts_MessageText = ""
|
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相关变量
|
# iot相关变量
|
||||||
self.iot_descriptors = {}
|
self.iot_descriptors = {}
|
||||||
|
|
@ -795,52 +788,6 @@ class ConnectionHandler:
|
||||||
# 更新系统prompt至上下文
|
# 更新系统prompt至上下文
|
||||||
self.dialogue.update_system_message(self.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):
|
def chat(self, query, depth=0):
|
||||||
if query is not None:
|
if query is not None:
|
||||||
self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
|
self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
|
||||||
|
|
@ -925,15 +872,6 @@ class ConnectionHandler:
|
||||||
for response in llm_responses:
|
for response in llm_responses:
|
||||||
if self.client_abort:
|
if self.client_abort:
|
||||||
break
|
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:
|
if self.intent_type == "function_call" and functions is not None:
|
||||||
content, tools_call = response
|
content, tools_call = response
|
||||||
if "content" in response:
|
if "content" in response:
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,10 @@
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import queue
|
import queue
|
||||||
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import threading
|
import threading
|
||||||
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, List, Optional, Tuple
|
from typing import Dict, List, Optional, Tuple
|
||||||
|
|
||||||
|
|
@ -13,6 +15,11 @@ TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
def _ts() -> str:
|
||||||
|
"""ISO timestamp with timezone, milliseconds."""
|
||||||
|
return datetime.now().astimezone().isoformat(timespec="milliseconds")
|
||||||
|
|
||||||
|
|
||||||
def _send(proc: subprocess.Popen, obj: Dict) -> None:
|
def _send(proc: subprocess.Popen, obj: Dict) -> None:
|
||||||
proc.stdin.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
proc.stdin.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
||||||
proc.stdin.flush()
|
proc.stdin.flush()
|
||||||
|
|
@ -176,6 +183,12 @@ def _format_action_desc(item: Dict) -> str:
|
||||||
return desc
|
return desc
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_filename(s: str) -> str:
|
||||||
|
s = str(s or "session")
|
||||||
|
s = re.sub(r"[^a-zA-Z0-9._-]+", "_", s)
|
||||||
|
return s[:120] if len(s) > 120 else s
|
||||||
|
|
||||||
|
|
||||||
class _CodexSession:
|
class _CodexSession:
|
||||||
def __init__(self, config: Dict, session_key: str) -> None:
|
def __init__(self, config: Dict, session_key: str) -> None:
|
||||||
self.session_key = session_key
|
self.session_key = session_key
|
||||||
|
|
@ -199,6 +212,22 @@ class _CodexSession:
|
||||||
self.thinking_mode = (config.get("thinking_mode") or "off").lower()
|
self.thinking_mode = (config.get("thinking_mode") or "off").lower()
|
||||||
self.show_actions = bool(config.get("show_actions", False))
|
self.show_actions = bool(config.get("show_actions", False))
|
||||||
|
|
||||||
|
# ---- Stream logging toggles ----
|
||||||
|
# log_stream: enables writing stream output to file + end-of-turn info log
|
||||||
|
self.log_stream = bool(config.get("log_stream", True))
|
||||||
|
# stream_debug: enables per-token debug logs (config-only gate)
|
||||||
|
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))
|
||||||
|
# event_max_chars: truncate long event JSON payloads (0 = no truncation)
|
||||||
|
self.event_max_chars = int(config.get("event_max_chars", 8000))
|
||||||
|
|
||||||
|
default_stream_log_path = str(
|
||||||
|
Path(self.workspace) / f"codex_stream_{_safe_filename(session_key)}.log"
|
||||||
|
)
|
||||||
|
self.stream_log_path = config.get("stream_log_path", default_stream_log_path)
|
||||||
|
self._stream_flush_bytes = int(config.get("stream_flush_bytes", 4096))
|
||||||
|
|
||||||
self.proc: Optional[subprocess.Popen] = None
|
self.proc: Optional[subprocess.Popen] = None
|
||||||
self.q: Optional[queue.Queue] = None
|
self.q: Optional[queue.Queue] = None
|
||||||
self.thread_id: Optional[str] = None
|
self.thread_id: Optional[str] = None
|
||||||
|
|
@ -214,6 +243,17 @@ class _CodexSession:
|
||||||
self._req_id += 1
|
self._req_id += 1
|
||||||
return rid
|
return rid
|
||||||
|
|
||||||
|
def _append_stream_log(self, text: str) -> None:
|
||||||
|
"""Append to per-session stream log file (best-effort)."""
|
||||||
|
if not self.log_stream or not self.stream_log_path or not text:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
Path(self.stream_log_path).parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with open(self.stream_log_path, "a", encoding="utf-8") as f:
|
||||||
|
f.write(text)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.bind(tag=TAG).warning(f"codex stream log write failed: {exc}")
|
||||||
|
|
||||||
def _pump_stderr(self) -> None:
|
def _pump_stderr(self) -> None:
|
||||||
if not self.proc or not self.proc.stderr:
|
if not self.proc or not self.proc.stderr:
|
||||||
return
|
return
|
||||||
|
|
@ -386,6 +426,7 @@ class _CodexSession:
|
||||||
|
|
||||||
def _stream_turn(self, prompt_text: str, emit_events: bool, **kwargs):
|
def _stream_turn(self, prompt_text: str, emit_events: bool, **kwargs):
|
||||||
self.start()
|
self.start()
|
||||||
|
|
||||||
turn_params = {
|
turn_params = {
|
||||||
"threadId": self.thread_id,
|
"threadId": self.thread_id,
|
||||||
"input": [{"type": "text", "text": prompt_text}],
|
"input": [{"type": "text", "text": prompt_text}],
|
||||||
|
|
@ -414,9 +455,59 @@ class _CodexSession:
|
||||||
turn_id = str(result["turn"]["id"])
|
turn_id = str(result["turn"]["id"])
|
||||||
self._active_turn_id = turn_id
|
self._active_turn_id = turn_id
|
||||||
|
|
||||||
|
# Turn logger
|
||||||
|
tlog = logger.bind(
|
||||||
|
tag=TAG,
|
||||||
|
session_key=self.session_key,
|
||||||
|
thread_id=self.thread_id,
|
||||||
|
turn_id=turn_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---- file buffering (assistant text + event lines) ----
|
||||||
|
file_buf = ""
|
||||||
|
|
||||||
|
def file_append(s: str) -> None:
|
||||||
|
nonlocal file_buf
|
||||||
|
if not self.log_stream or not s:
|
||||||
|
return
|
||||||
|
file_buf += s
|
||||||
|
if len(file_buf.encode("utf-8", errors="ignore")) >= self._stream_flush_bytes:
|
||||||
|
self._append_stream_log(file_buf)
|
||||||
|
file_buf = ""
|
||||||
|
|
||||||
|
def file_flush() -> None:
|
||||||
|
nonlocal file_buf
|
||||||
|
if file_buf:
|
||||||
|
self._append_stream_log(file_buf)
|
||||||
|
file_buf = ""
|
||||||
|
|
||||||
|
def file_event(event_obj: Dict) -> None:
|
||||||
|
"""
|
||||||
|
Write an event line into the SAME log file, with timestamp.
|
||||||
|
We log the *emitted* event dicts (thinking/action), not every raw app-server message.
|
||||||
|
"""
|
||||||
|
if not (self.log_stream and self.log_events):
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
payload = json.dumps(event_obj, ensure_ascii=False)
|
||||||
|
except Exception:
|
||||||
|
payload = str(event_obj)
|
||||||
|
|
||||||
|
if self.event_max_chars and len(payload) > self.event_max_chars:
|
||||||
|
payload = payload[: self.event_max_chars] + " ..."
|
||||||
|
|
||||||
|
# Ensure event starts on a new line and ends with newline.
|
||||||
|
file_append(f"\n[{_ts()}] [EVENT] {payload}\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")
|
||||||
|
|
||||||
saw_tokens = False
|
saw_tokens = False
|
||||||
final_text = None
|
final_text = None
|
||||||
thinking_buffer = ""
|
thinking_buffer = ""
|
||||||
|
out_buffer = ""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
|
|
@ -431,25 +522,43 @@ class _CodexSession:
|
||||||
method = msg.get("method")
|
method = msg.get("method")
|
||||||
params = msg.get("params", {}) or {}
|
params = msg.get("params", {}) or {}
|
||||||
|
|
||||||
|
# --- assistant text stream ---
|
||||||
if method == "item/agentMessage/delta":
|
if method == "item/agentMessage/delta":
|
||||||
delta = params.get("delta", "")
|
delta = params.get("delta", "")
|
||||||
if delta:
|
if delta:
|
||||||
saw_tokens = True
|
saw_tokens = True
|
||||||
|
out_buffer += delta
|
||||||
|
|
||||||
|
# write assistant text as-is to the log file (streaming)
|
||||||
|
if self.log_stream:
|
||||||
|
file_append(delta)
|
||||||
|
|
||||||
|
# per-token debug (config-only gate)
|
||||||
|
if self.log_stream and self.stream_debug:
|
||||||
|
tlog.debug("codex_stream_delta", delta=_short(delta, 400))
|
||||||
|
|
||||||
yield delta
|
yield delta
|
||||||
|
|
||||||
|
# --- emitted events (thinking/action) ---
|
||||||
if emit_events and self.thinking_mode != "off":
|
if emit_events and self.thinking_mode != "off":
|
||||||
if (
|
if self.thinking_mode == "summary" and method == "item/reasoning/summaryTextDelta":
|
||||||
self.thinking_mode == "summary"
|
|
||||||
and method == "item/reasoning/summaryTextDelta"
|
|
||||||
):
|
|
||||||
delta = params.get("delta", "")
|
delta = params.get("delta", "")
|
||||||
if delta:
|
if delta:
|
||||||
thinking_buffer += delta
|
thinking_buffer += delta
|
||||||
|
evt = {"kind": "thinking", "mode": "summary", "delta": delta, "turn_id": turn_id}
|
||||||
|
file_event(evt)
|
||||||
|
if self.log_stream and self.stream_debug:
|
||||||
|
tlog.debug("codex_thinking_summary_delta", delta=_short(delta, 400))
|
||||||
yield {"kind": "thinking", "text": thinking_buffer}
|
yield {"kind": "thinking", "text": thinking_buffer}
|
||||||
|
|
||||||
if self.thinking_mode == "raw" and method == "item/reasoning/textDelta":
|
if self.thinking_mode == "raw" and method == "item/reasoning/textDelta":
|
||||||
delta = params.get("delta", "")
|
delta = params.get("delta", "")
|
||||||
if delta:
|
if delta:
|
||||||
thinking_buffer += delta
|
thinking_buffer += delta
|
||||||
|
evt = {"kind": "thinking", "mode": "raw", "delta": delta, "turn_id": turn_id}
|
||||||
|
file_event(evt)
|
||||||
|
if self.log_stream and self.stream_debug:
|
||||||
|
tlog.debug("codex_thinking_raw_delta", delta=_short(delta, 400))
|
||||||
yield {"kind": "thinking", "text": thinking_buffer}
|
yield {"kind": "thinking", "text": thinking_buffer}
|
||||||
|
|
||||||
if emit_events and self.show_actions and method in ("item/started", "item/completed"):
|
if emit_events and self.show_actions and method in ("item/started", "item/completed"):
|
||||||
|
|
@ -457,12 +566,16 @@ class _CodexSession:
|
||||||
item_type = item.get("type")
|
item_type = item.get("type")
|
||||||
if item_type not in ("userMessage", "reasoning", "agentMessage"):
|
if item_type not in ("userMessage", "reasoning", "agentMessage"):
|
||||||
phase = "start" if method == "item/started" else "done"
|
phase = "start" if method == "item/started" else "done"
|
||||||
yield {
|
desc = _format_action_desc(item)
|
||||||
"kind": "action",
|
evt = {"kind": "action", "phase": phase, "text": desc, "turn_id": turn_id}
|
||||||
"text": _format_action_desc(item),
|
file_event(evt)
|
||||||
"phase": phase,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if self.log_stream:
|
||||||
|
tlog.info("codex_action", phase=phase, action=desc)
|
||||||
|
|
||||||
|
yield {"kind": "action", "text": desc, "phase": phase}
|
||||||
|
|
||||||
|
# --- final text fallback ---
|
||||||
if method == "item/completed":
|
if method == "item/completed":
|
||||||
item = params.get("item", {}) or {}
|
item = params.get("item", {}) or {}
|
||||||
if item.get("type") == "agentMessage":
|
if item.get("type") == "agentMessage":
|
||||||
|
|
@ -471,11 +584,30 @@ class _CodexSession:
|
||||||
if method == "turn/completed":
|
if method == "turn/completed":
|
||||||
break
|
break
|
||||||
|
|
||||||
|
# fallback if the server didn't stream deltas but gave final text
|
||||||
if not saw_tokens and final_text:
|
if not saw_tokens and final_text:
|
||||||
|
out_buffer += final_text
|
||||||
|
if self.log_stream:
|
||||||
|
file_append(final_text)
|
||||||
yield final_text
|
yield final_text
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
self._active_turn_id = None
|
self._active_turn_id = None
|
||||||
|
|
||||||
|
# Log turn end
|
||||||
|
if self.log_stream:
|
||||||
|
file_append(f"\n[{_ts()}] [TURN_END] chars={len(out_buffer)}\n\n--- turn_end ---\n\n")
|
||||||
|
|
||||||
|
file_flush()
|
||||||
|
|
||||||
|
if self.log_stream:
|
||||||
|
tlog.info(
|
||||||
|
"codex_stream_turn_completed",
|
||||||
|
chars=len(out_buffer),
|
||||||
|
preview=_short(out_buffer, 2000),
|
||||||
|
stream_log_path=self.stream_log_path,
|
||||||
|
)
|
||||||
|
|
||||||
def stream_response(self, dialogue: List[Dict], **kwargs):
|
def stream_response(self, dialogue: List[Dict], **kwargs):
|
||||||
with self._lock:
|
with self._lock:
|
||||||
prompt_text = self._compose_prompt(dialogue)
|
prompt_text = self._compose_prompt(dialogue)
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,11 @@ from core.providers.llm.codex.codex import LLMProvider
|
||||||
cfg = {
|
cfg = {
|
||||||
"type": "codex",
|
"type": "codex",
|
||||||
"codex_bin": "codex.cmd",
|
"codex_bin": "codex.cmd",
|
||||||
|
"effort": "medium",
|
||||||
|
"log_stream": True,
|
||||||
|
"stream_debug": True,
|
||||||
|
"log_events":True, # 把 thinking/action 事件写进同一个 log
|
||||||
|
"event_max_chars": 0, # 可选:事件 JSON 太长就截断;设 0 表示不截断
|
||||||
"model_name": "gpt-5.2",
|
"model_name": "gpt-5.2",
|
||||||
"workspace": r"C:\Users\yibinjiang\Documents\GitHub\codex_app_server",
|
"workspace": r"C:\Users\yibinjiang\Documents\GitHub\codex_app_server",
|
||||||
"auto_approve": True,
|
"auto_approve": True,
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue