modify the provider and test it

This commit is contained in:
Yibin Jiang 2026-01-25 14:11:21 +08:00
parent 9265a9e32d
commit 58602ff4df
3 changed files with 155 additions and 3 deletions

View file

@ -10,12 +10,14 @@ 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
@ -141,6 +143,11 @@ 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 = {}
@ -788,6 +795,52 @@ 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}")
@ -872,6 +925,15 @@ 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:

View file

@ -156,6 +156,26 @@ def _build_tool_context(messages: List[Dict]) -> str:
return "\n".join(lines) 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: 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
@ -175,6 +195,9 @@ class _CodexSession:
self.export_api_key = bool(config.get("export_api_key", False)) self.export_api_key = bool(config.get("export_api_key", False))
self.env_overrides = config.get("env", {}) or {} self.env_overrides = config.get("env", {}) or {}
self.runtime_config = config.get("runtime_config", {}) 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.proc: Optional[subprocess.Popen] = None
self.q: Optional[queue.Queue] = None self.q: Optional[queue.Queue] = None
@ -272,6 +295,14 @@ class _CodexSession:
except Exception as exc: except Exception as exc:
logger.bind(tag=TAG).warning(f"codex config write failed: {key} ({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} thread_params = {"model": self.model, "cwd": self.workspace, "sandbox": self.thread_sandbox}
if self.approval_policy: if self.approval_policy:
thread_params["approvalPolicy"] = self.approval_policy thread_params["approvalPolicy"] = self.approval_policy
@ -353,7 +384,7 @@ class _CodexSession:
return last_user return last_user
def _stream_turn(self, prompt_text: str, **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,
@ -385,6 +416,7 @@ class _CodexSession:
saw_tokens = False saw_tokens = False
final_text = None final_text = None
thinking_buffer = ""
try: try:
while True: while True:
@ -405,6 +437,32 @@ class _CodexSession:
saw_tokens = True saw_tokens = True
yield delta 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": if method == "item/completed":
item = params.get("item", {}) or {} item = params.get("item", {}) or {}
if item.get("type") == "agentMessage": if item.get("type") == "agentMessage":
@ -423,7 +481,10 @@ class _CodexSession:
prompt_text = self._compose_prompt(dialogue) prompt_text = self._compose_prompt(dialogue)
if not prompt_text: if not prompt_text:
return 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 yield token
@ -472,4 +533,7 @@ class LLMProvider(LLMProviderBase):
def response_with_functions(self, session_id, dialogue, functions=None, **kwargs): def response_with_functions(self, session_id, dialogue, functions=None, **kwargs):
for token in self.response(session_id, dialogue, **kwargs): for token in self.response(session_id, dialogue, **kwargs):
if isinstance(token, dict):
yield token
else:
yield token, None yield token, None

View file

@ -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()