mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
添加 使用 coze 会话。 (#282)
历史消息在coze 上可配置历史消息的轮次。 同个会话id,coze 上自动带历史上下文。 会话和当前session关联。一次连接一个会话,断开后,重连是新会话无历史消息。
This commit is contained in:
parent
0ce189b9a2
commit
beb707d074
1 changed files with 14 additions and 1 deletions
|
|
@ -11,19 +11,31 @@ from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, Cha
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class LLMProvider(LLMProviderBase):
|
class LLMProvider(LLMProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self.personal_access_token = config.get("personal_access_token")
|
self.personal_access_token = config.get("personal_access_token")
|
||||||
self.bot_id = config.get("bot_id")
|
self.bot_id = config.get("bot_id")
|
||||||
self.user_id = config.get("user_id")
|
self.user_id = config.get("user_id")
|
||||||
|
self.session_conversation_map = {} # 存储session_id和conversation_id的映射
|
||||||
|
|
||||||
def response(self, session_id, dialogue):
|
def response(self, session_id, dialogue):
|
||||||
coze_api_token = self.personal_access_token
|
coze_api_token = self.personal_access_token
|
||||||
coze_api_base = COZE_CN_BASE_URL
|
coze_api_base = COZE_CN_BASE_URL
|
||||||
|
|
||||||
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
||||||
|
|
||||||
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)
|
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)
|
||||||
|
conversation_id = self.session_conversation_map.get(session_id)
|
||||||
|
|
||||||
|
# 如果没有找到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(
|
for event in coze.chat.stream(
|
||||||
bot_id=self.bot_id,
|
bot_id=self.bot_id,
|
||||||
|
|
@ -31,6 +43,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
additional_messages=[
|
additional_messages=[
|
||||||
Message.build_user_question_text(last_msg["content"]),
|
Message.build_user_question_text(last_msg["content"]),
|
||||||
],
|
],
|
||||||
|
conversation_id=conversation_id,
|
||||||
):
|
):
|
||||||
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
|
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
|
||||||
print(event.message.content, end="", flush=True)
|
print(event.message.content, end="", flush=True)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue