mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge 6e1ab09738 into 242a701984
This commit is contained in:
commit
fbab23cf69
3 changed files with 240 additions and 11 deletions
|
|
@ -23,10 +23,21 @@ class LLMProvider(LLMProviderBase):
|
|||
self.bot_id = str(config.get("bot_id"))
|
||||
self.user_id = str(config.get("user_id"))
|
||||
self.session_conversation_map = {} # 存储session_id和conversation_id的映射
|
||||
# session_id -> (conversation_id, chat_id):上一轮没跑完的 chat。
|
||||
# 客户端打断时上游的 chat 还占着会话,下一轮开始前要把它取消掉。
|
||||
self.pending_chats = {}
|
||||
model_key_msg = check_model_key("CozeLLM", self.personal_access_token)
|
||||
if model_key_msg:
|
||||
logger.bind(tag=TAG).error(model_key_msg)
|
||||
|
||||
def _cancel_chat(self, coze, conversation_id, chat_id, reason):
|
||||
"""取消一个还在跑的 coze chat,把会话释放出来"""
|
||||
try:
|
||||
coze.chat.cancel(conversation_id=conversation_id, chat_id=chat_id)
|
||||
logger.bind(tag=TAG).info(f"{reason},已取消 coze chat {chat_id}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).warning(f"取消 coze chat 失败: {e}")
|
||||
|
||||
def response(self, session_id, dialogue, **kwargs):
|
||||
coze_api_token = self.personal_access_token
|
||||
coze_api_base = COZE_CN_BASE_URL
|
||||
|
|
@ -36,23 +47,61 @@ class LLMProvider(LLMProviderBase):
|
|||
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)
|
||||
conversation_id = self.session_conversation_map.get(session_id)
|
||||
|
||||
# 上一轮被客户端打断时,上游的 chat 还占着这个会话,这一轮开始前先把它
|
||||
# 取消掉,否则会撞上 4016 Conversation occupied
|
||||
pending = self.pending_chats.pop(session_id, None)
|
||||
if pending:
|
||||
self._cancel_chat(
|
||||
coze, pending[0], pending[1], "上一轮对话没有正常结束"
|
||||
)
|
||||
|
||||
# 如果没有找到conversation_id,则创建新的对话
|
||||
if not conversation_id:
|
||||
conversation = coze.conversations.create(messages=[])
|
||||
conversation_id = conversation.id
|
||||
self.session_conversation_map[session_id] = conversation_id # 更新映射
|
||||
|
||||
for event in coze.chat.stream(
|
||||
bot_id=self.bot_id,
|
||||
user_id=self.user_id,
|
||||
additional_messages=[
|
||||
Message.build_user_question_text(last_msg["content"]),
|
||||
],
|
||||
conversation_id=conversation_id,
|
||||
):
|
||||
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
|
||||
print(event.message.content, end="", flush=True)
|
||||
yield event.message.content
|
||||
chat_id = None
|
||||
chat_finished = False
|
||||
try:
|
||||
for event in coze.chat.stream(
|
||||
bot_id=self.bot_id,
|
||||
user_id=self.user_id,
|
||||
additional_messages=[
|
||||
Message.build_user_question_text(last_msg["content"]),
|
||||
],
|
||||
conversation_id=conversation_id,
|
||||
):
|
||||
# conversation.chat.created 事件里带着本次 chat 的 id
|
||||
if event.chat is not None and event.chat.id:
|
||||
chat_id = event.chat.id
|
||||
self.pending_chats[session_id] = (conversation_id, chat_id)
|
||||
if event.event == ChatEventType.CONVERSATION_CHAT_COMPLETED:
|
||||
chat_finished = True
|
||||
pending = self.pending_chats.get(session_id)
|
||||
if pending and pending[1] == chat_id:
|
||||
self.pending_chats.pop(session_id, None)
|
||||
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
|
||||
print(event.message.content, end="", flush=True)
|
||||
yield event.message.content
|
||||
except Exception as e:
|
||||
# 4016:同一个会话里上一轮 chat 还占着(上一轮被客户端打断时没结束干净),
|
||||
# 这里把本地记的会话 id 清掉,下一轮重新建会话,避免一直卡住
|
||||
if "4016" in str(e) or "Conversation occupied" in str(e):
|
||||
logger.bind(tag=TAG).error(
|
||||
"Coze 会话被占用,已清除本地会话 id,下一轮重新创建会话"
|
||||
)
|
||||
self.session_conversation_map.pop(session_id, None)
|
||||
raise
|
||||
finally:
|
||||
# 客户端打断时这个生成器会被提前关闭(GeneratorExit),上游的 chat
|
||||
# 还占着会话,下一轮请求就会撞上 4016。这里主动取消掉,且保留
|
||||
# conversation_id,上下文不会丢。
|
||||
if chat_id and not chat_finished:
|
||||
pending = self.pending_chats.get(session_id)
|
||||
if pending and pending[1] == chat_id:
|
||||
self.pending_chats.pop(session_id, None)
|
||||
self._cancel_chat(coze, conversation_id, chat_id, "对话被打断")
|
||||
|
||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
|
||||
|
|
|
|||
0
main/xiaozhi-server/tests/core/providers/llm/__init__.py
Normal file
0
main/xiaozhi-server/tests/core/providers/llm/__init__.py
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
"""Coze provider 的会话收尾测试。
|
||||
|
||||
覆盖 #2076:客户端打断后上一轮 chat 还占着 coze 会话,下一轮请求撞上
|
||||
4016 Conversation occupied,整轮对话直接卡死。
|
||||
|
||||
- 客户端打断 → 生成器被提前关闭 → 主动取消上游 chat,但保留 conversation_id
|
||||
(上下文不丢)
|
||||
- 正常说完 → 不需要取消
|
||||
- 真的撞上 4016 → 清掉本地会话 id,下一轮重新建会话,不再一直卡住
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from cozepy import ChatEventType
|
||||
|
||||
from core.providers.llm.coze import coze as coze_module
|
||||
from core.providers.llm.coze.coze import LLMProvider as CozeProvider
|
||||
|
||||
CONVERSATION_ID = "conv-new"
|
||||
|
||||
|
||||
def _delta(content):
|
||||
return SimpleNamespace(
|
||||
event=ChatEventType.CONVERSATION_MESSAGE_DELTA,
|
||||
chat=None,
|
||||
message=SimpleNamespace(content=content),
|
||||
)
|
||||
|
||||
|
||||
def _chat_created(chat_id="chat-1"):
|
||||
return SimpleNamespace(
|
||||
event=ChatEventType.CONVERSATION_CHAT_CREATED,
|
||||
chat=SimpleNamespace(id=chat_id),
|
||||
message=None,
|
||||
)
|
||||
|
||||
|
||||
def _chat_completed(chat_id="chat-1"):
|
||||
return SimpleNamespace(
|
||||
event=ChatEventType.CONVERSATION_CHAT_COMPLETED,
|
||||
chat=SimpleNamespace(id=chat_id),
|
||||
message=None,
|
||||
)
|
||||
|
||||
|
||||
def _install_fake_coze(monkeypatch, events, error=None):
|
||||
"""把 coze 模块里的 Coze 换成假实现,返回记录调用状态的 dict"""
|
||||
state = {"cancelled": [], "created": []}
|
||||
|
||||
class FakeChat:
|
||||
def stream(self, **kwargs):
|
||||
for event in events:
|
||||
yield event
|
||||
if error is not None:
|
||||
raise error
|
||||
|
||||
def cancel(self, conversation_id, chat_id):
|
||||
state["cancelled"].append((conversation_id, chat_id))
|
||||
|
||||
class FakeConversations:
|
||||
def create(self, messages=None):
|
||||
state["created"].append(messages)
|
||||
return SimpleNamespace(id=CONVERSATION_ID)
|
||||
|
||||
class FakeCoze:
|
||||
def __init__(self, auth=None, base_url=None):
|
||||
self.chat = FakeChat()
|
||||
self.conversations = FakeConversations()
|
||||
|
||||
monkeypatch.setattr(coze_module, "Coze", FakeCoze)
|
||||
return state
|
||||
|
||||
|
||||
def _provider():
|
||||
return CozeProvider(
|
||||
{
|
||||
"personal_access_token": "pat-test",
|
||||
"bot_id": "bot-1",
|
||||
"user_id": "user-1",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _dialogue():
|
||||
return [{"role": "user", "content": "你好"}]
|
||||
|
||||
|
||||
def test_completed_chat_is_not_cancelled(monkeypatch):
|
||||
state = _install_fake_coze(
|
||||
monkeypatch, [_chat_created(), _delta("你好"), _chat_completed()]
|
||||
)
|
||||
|
||||
provider = _provider()
|
||||
result = list(provider.response("s1", _dialogue()))
|
||||
|
||||
assert result == ["你好"]
|
||||
assert state["cancelled"] == []
|
||||
|
||||
|
||||
def test_interrupted_chat_is_cancelled(monkeypatch):
|
||||
state = _install_fake_coze(monkeypatch, [_chat_created(), _delta("你好")])
|
||||
|
||||
provider = _provider()
|
||||
responses = provider.response("s1", _dialogue())
|
||||
assert next(responses) == "你好"
|
||||
|
||||
# 客户端打断:core/connection.py 跳出流式循环后生成器被关闭
|
||||
responses.close()
|
||||
|
||||
assert state["cancelled"] == [(CONVERSATION_ID, "chat-1")]
|
||||
|
||||
|
||||
def test_interrupted_chat_keeps_conversation_id(monkeypatch):
|
||||
"""取消上游 chat,但不能把会话 id 丢掉,否则上下文就没了"""
|
||||
_install_fake_coze(monkeypatch, [_chat_created(), _delta("你好")])
|
||||
|
||||
provider = _provider()
|
||||
responses = provider.response("s1", _dialogue())
|
||||
next(responses)
|
||||
responses.close()
|
||||
|
||||
assert provider.session_conversation_map["s1"] == CONVERSATION_ID
|
||||
|
||||
|
||||
def test_occupied_conversation_is_reset(monkeypatch):
|
||||
error = Exception(
|
||||
'error event: {"code":4016,"msg":"Conversation occupied: Another chat '
|
||||
'is currently active."}'
|
||||
)
|
||||
_install_fake_coze(monkeypatch, [_chat_created()], error=error)
|
||||
|
||||
provider = _provider()
|
||||
provider.session_conversation_map["s1"] = "conv-old"
|
||||
|
||||
with pytest.raises(Exception):
|
||||
list(provider.response("s1", _dialogue()))
|
||||
|
||||
# 本地记的会话 id 被清掉,下一轮会重新建会话
|
||||
assert "s1" not in provider.session_conversation_map
|
||||
|
||||
|
||||
def test_other_errors_keep_conversation_id(monkeypatch):
|
||||
error = Exception("error event: {\"code\":5000}")
|
||||
_install_fake_coze(monkeypatch, [_chat_created()], error=error)
|
||||
|
||||
provider = _provider()
|
||||
provider.session_conversation_map["s1"] = "conv-old"
|
||||
|
||||
with pytest.raises(Exception):
|
||||
list(provider.response("s1", _dialogue()))
|
||||
|
||||
assert provider.session_conversation_map["s1"] == "conv-old"
|
||||
|
||||
|
||||
def test_next_turn_cancels_leftover_chat(monkeypatch):
|
||||
"""上一轮遗留的 chat,这一轮开始前先取消掉,不会撞上 4016"""
|
||||
state = _install_fake_coze(monkeypatch, [_chat_created(), _delta("你好")])
|
||||
|
||||
provider = _provider()
|
||||
# 模拟「上一轮被打断、没走完收尾」:会话 id 还留着,chat 还占着
|
||||
provider.session_conversation_map["s1"] = CONVERSATION_ID
|
||||
provider.pending_chats["s1"] = (CONVERSATION_ID, "chat-stale")
|
||||
|
||||
list(provider.response("s1", _dialogue()))
|
||||
|
||||
assert (CONVERSATION_ID, "chat-stale") in state["cancelled"]
|
||||
# 会话 id 保留,上下文不丢
|
||||
assert provider.session_conversation_map["s1"] == CONVERSATION_ID
|
||||
|
||||
|
||||
def test_completed_chat_leaves_no_pending(monkeypatch):
|
||||
_install_fake_coze(
|
||||
monkeypatch, [_chat_created(), _delta("你好"), _chat_completed()]
|
||||
)
|
||||
|
||||
provider = _provider()
|
||||
list(provider.response("s1", _dialogue()))
|
||||
|
||||
assert provider.pending_chats == {}
|
||||
Loading…
Reference in a new issue