diff --git a/dify/dify_chat.py b/dify/dify_chat.py index 152366d..06f2f67 100644 --- a/dify/dify_chat.py +++ b/dify/dify_chat.py @@ -166,7 +166,10 @@ class DifyChat: # 发送请求 url = f"{self.base_url}/workflows/run" - + + self.LOG.info(f"发送请求到Dify API: {url}") + self.LOG.info(f"请求数据: {json.dumps(data, ensure_ascii=False)}") + try: # 使用流式请求 with requests.post(url, headers=headers, json=data, proxies=proxies, stream=True) as response: @@ -192,24 +195,47 @@ class DifyChat: try: event_data = json.loads(json_str) + if not event_data: + continue + event_type = event_data.get("event") - + if not event_type: + continue + # 处理不同类型的事件 if event_type == "workflow_finished": # 工作流完成事件,可以获取总token数 data_obj = event_data.get("data", {}) - total_tokens = data_obj.get("total_tokens", 0) + if data_obj: + total_tokens = data_obj.get("total_tokens", 0) elif event_type == "node_finished": # 节点完成事件,可以获取节点输出和token使用情况 data_obj = event_data.get("data", {}) + if not data_obj: + continue + 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 + elif isinstance(value, dict): + # 处理嵌套字典的情况 + for sub_key, sub_value in value.items(): + if isinstance(sub_value, str) and sub_value.strip(): + answer += sub_value + elif isinstance(value, list): + # 处理列表的情况 + for item in value: + if isinstance(item, str) and item.strip(): + answer += item + elif isinstance(item, dict): + # 处理列表中的字典 + for item_key, item_value in item.items(): + if isinstance(item_value, str) and item_value.strip(): + answer += item_value # 获取token使用情况 execution_metadata = data_obj.get("execution_metadata", {})