mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
feat: 支持dify的多轮对话, chat工作流支持持久化conversation_id #296
This commit is contained in:
parent
a8f06f5718
commit
eb2c35c4f3
1 changed files with 8 additions and 1 deletions
|
|
@ -10,11 +10,13 @@ class LLMProvider(LLMProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self.api_key = config["api_key"]
|
self.api_key = config["api_key"]
|
||||||
self.base_url = config.get("base_url", "https://api.dify.ai/v1").rstrip('/')
|
self.base_url = config.get("base_url", "https://api.dify.ai/v1").rstrip('/')
|
||||||
|
self.session_conversation_map = {} # 存储session_id和conversation_id的映射
|
||||||
|
|
||||||
def response(self, session_id, dialogue):
|
def response(self, session_id, dialogue):
|
||||||
try:
|
try:
|
||||||
# 取最后一条用户消息
|
# 取最后一条用户消息
|
||||||
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")
|
||||||
|
conversation_id = self.session_conversation_map.get(session_id)
|
||||||
|
|
||||||
# 发起流式请求
|
# 发起流式请求
|
||||||
with requests.post(
|
with requests.post(
|
||||||
|
|
@ -24,13 +26,18 @@ class LLMProvider(LLMProviderBase):
|
||||||
"query": last_msg["content"],
|
"query": last_msg["content"],
|
||||||
"response_mode": "streaming",
|
"response_mode": "streaming",
|
||||||
"user": session_id,
|
"user": session_id,
|
||||||
"inputs": {}
|
"inputs": {},
|
||||||
|
"conversation_id": conversation_id
|
||||||
},
|
},
|
||||||
stream=True
|
stream=True
|
||||||
) as r:
|
) as r:
|
||||||
for line in r.iter_lines():
|
for line in r.iter_lines():
|
||||||
if line.startswith(b'data: '):
|
if line.startswith(b'data: '):
|
||||||
event = json.loads(line[6:])
|
event = json.loads(line[6:])
|
||||||
|
# 如果没有找到conversation_id,则获取此次conversation_id
|
||||||
|
if not conversation_id:
|
||||||
|
conversation_id = event.get('conversation_id')
|
||||||
|
self.session_conversation_map[session_id] = conversation_id # 更新映射
|
||||||
if event.get('answer'):
|
if event.get('answer'):
|
||||||
yield event['answer']
|
yield event['answer']
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue