接入dify工作流内容
This commit is contained in:
@@ -135,7 +135,8 @@ class DifyChat:
|
|||||||
# 准备请求头
|
# 准备请求头
|
||||||
headers = {
|
headers = {
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json",
|
||||||
|
"Accept": "text/event-stream" # 指定接受事件流
|
||||||
}
|
}
|
||||||
|
|
||||||
# 准备请求数据
|
# 准备请求数据
|
||||||
@@ -161,17 +162,59 @@ class DifyChat:
|
|||||||
|
|
||||||
# 发送请求
|
# 发送请求
|
||||||
url = f"{self.base_url}/chat-messages"
|
url = f"{self.base_url}/chat-messages"
|
||||||
response = requests.post(url, headers=headers, json=data, proxies=proxies)
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 使用流式请求
|
||||||
|
with requests.post(url, headers=headers, json=data, proxies=proxies, stream=True) as response:
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
self.LOG.error(f"Dify API请求失败: {response.status_code} {response.text}")
|
self.LOG.error(f"Dify API请求失败: {response.status_code} {response.text}")
|
||||||
return f"请求失败,状态码: {response.status_code}"
|
return f"请求失败,状态码: {response.status_code}"
|
||||||
|
|
||||||
# 解析响应
|
answer = ""
|
||||||
result = response.json()
|
total_tokens = 0
|
||||||
|
|
||||||
# 提取回复内容
|
# 处理流式响应
|
||||||
answer = result.get("answer", "")
|
for line in response.iter_lines():
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 解析事件流数据
|
||||||
|
line_text = line.decode('utf-8')
|
||||||
|
if not line_text.startswith('data: '):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 提取JSON数据部分
|
||||||
|
json_str = line_text[6:] # 去掉 "data: " 前缀
|
||||||
|
|
||||||
|
try:
|
||||||
|
event_data = json.loads(json_str)
|
||||||
|
event_type = event_data.get("event")
|
||||||
|
|
||||||
|
# 处理不同类型的事件
|
||||||
|
if event_type == "workflow_finished":
|
||||||
|
# 工作流完成事件,可以获取总token数
|
||||||
|
data_obj = event_data.get("data", {})
|
||||||
|
total_tokens = data_obj.get("total_tokens", 0)
|
||||||
|
|
||||||
|
elif event_type == "node_finished":
|
||||||
|
# 节点完成事件,可以获取节点输出和token使用情况
|
||||||
|
data_obj = event_data.get("data", {})
|
||||||
|
outputs = data_obj.get("outputs", {})
|
||||||
|
|
||||||
|
# 从outputs中提取回答内容
|
||||||
|
if outputs and isinstance(outputs, dict):
|
||||||
|
for key, value in outputs.items():
|
||||||
|
if isinstance(value, str) and value.strip():
|
||||||
|
answer += value
|
||||||
|
|
||||||
|
# 获取token使用情况
|
||||||
|
execution_metadata = data_obj.get("execution_metadata", {})
|
||||||
|
if "total_tokens" in execution_metadata:
|
||||||
|
total_tokens = execution_metadata.get("total_tokens", 0)
|
||||||
|
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
self.LOG.error(f"解析事件流数据失败: {line_text}")
|
||||||
|
continue
|
||||||
|
|
||||||
# 更新会话历史
|
# 更新会话历史
|
||||||
self.conversations[session_id].append({
|
self.conversations[session_id].append({
|
||||||
@@ -189,8 +232,7 @@ class DifyChat:
|
|||||||
self.conversations[session_id] = self.conversations[session_id][-self.max_history_length * 2:]
|
self.conversations[session_id] = self.conversations[session_id][-self.max_history_length * 2:]
|
||||||
|
|
||||||
# 统计token使用情况
|
# 统计token使用情况
|
||||||
if "usage" in result and "total_tokens" in result["usage"]:
|
if total_tokens > 0:
|
||||||
total_tokens = result["usage"]["total_tokens"]
|
|
||||||
if user_id in self.token_usage:
|
if user_id in self.token_usage:
|
||||||
self.token_usage[user_id] += total_tokens
|
self.token_usage[user_id] += total_tokens
|
||||||
else:
|
else:
|
||||||
@@ -200,6 +242,10 @@ class DifyChat:
|
|||||||
|
|
||||||
return answer
|
return answer
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.LOG.error(f"处理Dify流式响应时出错: {str(e)}")
|
||||||
|
return f"处理响应时出错: {str(e)}"
|
||||||
|
|
||||||
def _cleanup_expired_conversations(self) -> None:
|
def _cleanup_expired_conversations(self) -> None:
|
||||||
"""清理过期的会话"""
|
"""清理过期的会话"""
|
||||||
current_time = time.time()
|
current_time = time.time()
|
||||||
|
|||||||
Reference in New Issue
Block a user