chatview优化

This commit is contained in:
runny committed 2026-05-14 17:52:21 +08:00
1 parent e2510c0565
commit bf5f735404
3 files changed
+155 -44

No files matched your search

+27 -5
View File
@@ -24,6 +24,7 @@ chat.py (/api/chat/completions)
"""
import json
import time
import uuid
from typing import Any, List, Optional
import requests
@@ -37,6 +38,26 @@ from app.services.integration_api import IntegrationApiService
class DifyService:
"""Dify service wrapper."""
@staticmethod
def _normalize_dify_conversation_id(conversation_id: str | None) -> str:
"""
Dify 只接受标准 UUID 会话 ID。
本项目里 ERP Text2SQL 会生成 `erp_xxx` 形式的本地会话号,
这类值不能继续透传给 Dify,否则会触发 400 invalid_param。
"""
value = str(conversation_id or "").strip()
if not value:
return ""
try:
return str(uuid.UUID(value))
except (ValueError, TypeError, AttributeError):
if current_app:
current_app.logger.warning(
"[chat-stream] ignore non-uuid conversation_id for dify: %s",
value,
)
return ""
@staticmethod
def _build_chat_messages_url(base_url: str) -> str:
"""
@@ -90,6 +111,7 @@ class DifyService:
# Prefer agent-specific base URL; fallback to global config.
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
url = DifyService._build_chat_messages_url(base_url)
normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id)
headers = {
'Authorization': f'Bearer {agent.dify_api_key}',
@@ -99,7 +121,7 @@ class DifyService:
'inputs': {},
'query': query,
'response_mode': 'streaming',
'conversation_id': conversation_id or '',
'conversation_id': normalized_conversation_id,
'user': str(user_id),
}
@@ -110,7 +132,7 @@ class DifyService:
getattr(agent, 'id', None),
base_url,
len(query or ''),
conversation_id,
normalized_conversation_id or conversation_id,
)
start_time = time.time()
@@ -161,7 +183,7 @@ class DifyService:
event,
len(data.get('answer', '') or ''),
bool(data.get('metadata')),
data.get('conversation_id') or conversation_id,
data.get('conversation_id') or normalized_conversation_id,
)
if event == 'message':
@@ -196,7 +218,7 @@ class DifyService:
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
conversation_id=data.get('conversation_id') or conversation_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=''.join(full_answer),
tokens=usage.get('total_tokens', 0),
@@ -209,7 +231,7 @@ class DifyService:
if current_app:
current_app.logger.info(
"[chat-stream] message_end logged conversation_id=%s answer_len=%s resources=%s attribution=%s latency_ms=%s",
data.get('conversation_id') or conversation_id,
data.get('conversation_id') or normalized_conversation_id,
len(''.join(full_answer)),
len(retriever_resources),
len(attribution_parts),