fix: FunASR 识别结果以 JSON 原样进入对话历史 (#3411)

FunASR 返回 {"content","language","emotion"} 时,startToChat 只在含 speaker
字段时才解包,否则整段 JSON 字符串会作为用户消息交给 LLM 并写入对话历史。
现在没有 speaker 时只取 content。
This commit is contained in:
korexil 2026-10-13 17:44:13 +09:00 committed by GitHub
parent dc86a780a2
commit 4445aa7510
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 77 additions and 0 deletions

View file

@ -61,6 +61,10 @@ async def startToChat(conn: "ConnectionHandler", text):
actual_text = text
else:
actual_text = actual_content
elif "content" in data:
# FunASR 等返回 {"content","language","emotion"}:只把识别正文交给 LLM,
# 否则整段 JSON 会进入对话历史
actual_text = str(data["content"])
except (json.JSONDecodeError, KeyError):
# 如果解析失败,继续使用原始文本
pass

View file

@ -0,0 +1,73 @@
"""startToChat must hand the recognized text, not the ASR JSON, to the LLM."""
import json
import logging
from types import SimpleNamespace
import pytest
import core.handle.receiveAudioHandle as receive
class _Executor:
def __init__(self):
self.calls = []
def submit(self, fn, *args):
self.calls.append(args)
def _conn():
logger = logging.getLogger("test")
return SimpleNamespace(
logger=SimpleNamespace(bind=lambda **_: logger),
introduced_speakers=set(),
current_speaker=None,
need_bind=False,
max_output_size=0,
client_is_speaking=False,
client_listen_mode="auto",
client_abort=True,
executor=_Executor(),
chat=lambda text: None,
)
@pytest.fixture(autouse=True)
def _no_side_effects(monkeypatch):
async def not_handled(conn, text):
return False
async def ignore(*args, **kwargs):
return None
monkeypatch.setattr(receive, "handle_user_intent", not_handled)
monkeypatch.setattr(receive, "send_stt_message", ignore)
async def test_funasr_payload_without_speaker_passes_only_content():
conn = _conn()
payload = json.dumps({"content": "今日は寒いね。", "language": "ja", "emotion": "😶"}, ensure_ascii=False)
await receive.startToChat(conn, payload)
assert conn.executor.calls == [("今日は寒いね。",)]
assert conn.current_speaker is None
async def test_first_speaker_payload_still_keeps_json_once():
conn = _conn()
payload = json.dumps({"speaker": "Alice", "content": "hello"}, ensure_ascii=False)
await receive.startToChat(conn, payload)
await receive.startToChat(conn, payload)
assert conn.executor.calls == [(payload,), ("hello",)]
assert conn.current_speaker == "Alice"
async def test_plain_text_is_unchanged():
conn = _conn()
await receive.startToChat(conn, "你好")
assert conn.executor.calls == [("你好",)]