Merge branch 'dev' into hugo-shipping-notice

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/shipping_notice/chat_actions.py
This commit is contained in:
hugo committed 2026-07-03 17:18:10 +08:00
commit 7a9c36d16b
17 files changed
+1014 -357

No files matched your search

+26
View File
@@ -67,6 +67,19 @@ def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_b
}
def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy) -> bool:
"""
判断固资管理里的当前问题是否应当切断上游 Dify 会话上下文。
核心逻辑:
- 仅对“固资管理”Agent 生效;
- 仅当用户本轮问题可脱离上一轮上下文独立完成时触发;
- 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。
"""
from app.services.text2sql import Text2SQLService
return Text2SQLService._should_reset_provider_conversation(query, agent_proxy)
def _session_title_from_text(text: str) -> str:
value = str(text or '').strip()
if not value:
@@ -1187,6 +1200,19 @@ def chat_completions():
status='running',
)
external_conversation_id = session.external_conversation_id
if external_conversation_id and _should_reset_provider_conversation_for_asset_query(query, agent_proxy):
current_app.logger.info(
'[chat-api] reset provider conversation for asset query request_id=%s session_id=%s old_provider_conversation_id=%s query=%s',
request_id,
session.session_id,
external_conversation_id,
query,
)
session.external_conversation_id = None
session.updated_at = datetime.utcnow()
session.last_active_at = datetime.utcnow()
db.session.commit()
external_conversation_id = None
else:
session = _ensure_chat_session(
user_id,
+40 -119
View File
@@ -63,31 +63,6 @@ def _ok(payload: dict):
return ok(payload, request_id=getattr(g, 'request_id', None))
def _notice_file_type(upload) -> str | None:
"""提取上传文件 MIME type;为空时返回 None,保持响应字段稳定。"""
return str(getattr(upload, 'mimetype', '') or '').strip() or None
def _build_notice_file_summary(
*,
total_files: int,
accepted_files: list[dict],
rejected_files: list[dict],
) -> dict[str, object]:
"""
构建工作台批量上传预检摘要。
核心逻辑:把可建任务文件与被拒文件统一汇总到 file_summary,供前端回显和测试断言使用。
"""
return {
'total_files': total_files,
'accepted_count': len(accepted_files),
'rejected_count': len(rejected_files),
'accepted_files': accepted_files,
'rejected_files': rejected_files,
}
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks():
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
@@ -123,77 +98,27 @@ def workspace_create_shipping_batch_from_notices():
raise ValidationError('files is required')
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import (
build_notice_file_summary,
cleanup_temp_notice_uploads,
extract_notice_text,
guess_source_type,
max_notice_chars,
save_temp_notice_upload,
intake_temp_notice_uploads,
)
conversation_id = str(request.form.get('conversation_id') or '').strip()
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
notice_items: list[dict] = []
accepted_files: list[dict] = []
rejected_files: list[dict] = []
try:
for index, upload in enumerate(uploads, start=1):
raw = upload.read() or b''
filename = upload.filename or 'notice'
source_type = guess_source_type(filename)
source_file_type = _notice_file_type(upload)
text = ''
warnings: list[str] = []
try:
saved_path = save_temp_notice_upload(temp_request_id, index, filename, raw)
text, meta = extract_notice_text(saved_path)
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
except Exception as exc:
warnings = [f'notice_extract_failed:{exc}']
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
warnings.append(f'notice_text_truncated:{limit}')
notice_items.append(
{
'source_type': source_type,
'source_file_name': filename,
'source_file_type': source_file_type,
'raw_text': text,
'warnings': warnings,
}
)
accepted_files.append(
{
'filename': filename,
'source_type': source_type,
'source_file_type': source_file_type,
'text_length': len(text),
'warnings': warnings,
}
)
continue
rejected_files.append(
{
'filename': filename,
'source_type': source_type,
'source_file_type': source_file_type,
'reason': 'empty_text',
'message': 'notice text is empty after extraction',
'warnings': warnings,
}
)
accepted, rejected = intake_temp_notice_uploads(temp_request_id, uploads)
finally:
cleanup_temp_notice_uploads(temp_request_id)
file_summary = _build_notice_file_summary(
file_summary = build_notice_file_summary(
total_files=len(uploads),
accepted_files=accepted_files,
rejected_files=rejected_files,
accepted=accepted,
rejected=rejected,
)
notice_items = [item.to_notice_item() for item in accepted]
if not notice_items:
raise ValidationError(
'all uploaded files failed extraction or contained no parseable text',
details={'rejected_files': rejected_files, 'file_summary': file_summary},
details={'rejected_files': file_summary['rejected_files'], 'file_summary': file_summary},
)
payload = {
@@ -327,8 +252,11 @@ def workspace_create_shipping_task_from_notice():
if not upload:
raise ValidationError('file is required')
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
source_type = guess_source_type(upload.filename or '')
from app.services.shipping_notice.notice_upload import guess_source_type, intake_notice_attachment, notice_source_file_type
filename = upload.filename or 'notice'
raw = upload.read() or b''
source_file_type = notice_source_file_type(upload)
source_type = guess_source_type(filename)
conversation_id = str(request.form.get('conversation_id') or '').strip()
payload = {'user_id': user.id, 'source_type': source_type}
if conversation_id:
@@ -337,29 +265,25 @@ def workspace_create_shipping_task_from_notice():
task_id = str(created.get('task_id') or '').strip()
if not task_id:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500)
raw = upload.read() or b''
saved_path = save_task_notice_upload(task_id, upload.filename or 'notice', raw)
text, meta = extract_notice_text(saved_path)
if not text:
intake = intake_notice_attachment(
filename=filename,
raw=raw,
source_file_type=source_file_type,
storage='task',
task_no=task_id,
)
if not intake.accepted:
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': {'filename': upload.filename or '', **meta}}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
meta.setdefault('warnings', []).append(f'notice_text_truncated:{limit}')
task = ShippingTask.query.filter_by(task_no=task_id).first()
if task:
task.raw_content = text
db.session.commit()
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
task = ShippingTask.query.filter_by(task_no=task_id).first()
if task:
task.source_file_name = str(upload.filename or '').strip() or task.source_file_name
task.source_file_type = str(getattr(upload, 'mimetype', '') or '').strip() or task.source_file_type
task.raw_content = intake.text
task.source_file_name = intake.filename or task.source_file_name
task.source_file_type = intake.source_file_type or task.source_file_type
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id)
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': {'filename': upload.filename or '', **meta}, 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
def workspace_replace_shipping_task_notice(task_no: str):
@@ -372,28 +296,25 @@ def workspace_replace_shipping_task_notice(task_no: str):
if not upload:
raise ValidationError('file is required')
from app.services.shipping_notice import task_workflow
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
raw = upload.read() or b''
filename = upload.filename or 'notice'
saved_path = save_task_notice_upload(task.task_no, filename, raw)
text, meta = extract_notice_text(saved_path)
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
warnings.append(f'notice_text_truncated:{limit}')
task.source_type = guess_source_type(filename) or task.source_type
from app.services.shipping_notice.notice_upload import intake_notice_attachment, notice_source_file_type
intake = intake_notice_attachment(
filename=upload.filename or 'notice',
raw=upload.read() or b'',
source_file_type=notice_source_file_type(upload),
storage='task',
task_no=task.task_no,
)
task.source_type = intake.source_type or task.source_type
result = task_workflow.replace_task_notice(
task,
raw_text=text,
source_file_name=filename,
source_file_type=str(getattr(upload, 'mimetype', '') or '').strip(),
warnings=warnings,
raw_text=intake.text,
source_file_name=intake.filename,
source_file_type=intake.source_file_type,
warnings=list(intake.warnings),
)
data = result.setdefault('data', {})
if isinstance(data, dict):
data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})}
data['notice_upload'] = intake.to_notice_upload_meta()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
-1
View File
@@ -40,7 +40,6 @@ from app.models import ChatLog
from app.services.chat_perf import ChatPerfTracker, chat_perf_enabled
from app.services.integration_api import IntegrationApiService
class DifyService:
"""Dify service wrapper."""
VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on")
+101 -31
View File
@@ -617,12 +617,83 @@ INSERT INTO fixed_assets (
return normalized_tokens[:5]
@classmethod
def _build_where_clause(cls, query: str, user_context: dict[str, Any] | None = None) -> tuple[str, list[str]]:
def _build_generic_keyword_match_clause(cls, keyword: str) -> tuple[str, list[str]]:
"""为宽泛资产关键词查询构造更严格的直连字段匹配条件。
AI 触发时机:当用户只输入“资讯有哪些资产”“电脑有哪些资产”这类宽泛关键词时,
不能再把 `remark_normalized` 这类兜底字段也纳入匹配,否则容易把仅备注命中的低质量记录一起带出。
Args:
keyword: 已抽取的资产关键词。
Returns:
tuple[str, list[str]]: SQL 条件片段与对应参数。
"""
like_keyword = f"%{keyword.upper()}%"
clause = (
"("
"UPPER(COALESCE(asset_name, '')) LIKE ? "
"OR UPPER(COALESCE(asset_name2, '')) LIKE ? "
"OR UPPER(COALESCE(specification, '')) LIKE ? "
"OR UPPER(COALESCE(location_name, '')) LIKE ? "
"OR UPPER(COALESCE(custodian_name, '')) LIKE ? "
"OR UPPER(COALESCE(department_name, '')) LIKE ? "
"OR UPPER(COALESCE(vendor_name, '')) LIKE ?"
")"
)
return clause, [like_keyword] * 7
@classmethod
def _generic_result_quality_guard_sql(cls) -> str:
"""过滤仅命中名称但关键业务列几乎全空的低质量快照记录。
AI 触发时机:宽泛关键词查询会返回很多候选记录,其中一部分只有资产名称,
其余关键字段(编号、保管人、部门、账套、供应商、状态、数量、取得日期)全部为空。
这类记录即使展示出来也无法支撑业务判断,应在快照层直接剔除。
"""
informative_fields = (
"asset_no",
"custodian_name",
"department_name",
"operating_center_code",
"vendor_name",
"asset_status",
"quantity",
"acquisition_date",
)
checks = [f"TRIM(COALESCE({field}, '')) <> ''" for field in informative_fields]
return "(" + " OR ".join(checks) + ")"
@classmethod
def _generic_result_quality_score_sql(cls) -> str:
"""为宽泛关键词查询生成字段完整度评分,便于优先展示高质量记录。"""
informative_fields = (
"asset_no",
"custodian_name",
"department_name",
"operating_center_code",
"vendor_name",
"asset_status",
"quantity",
"acquisition_date",
)
return " + ".join(
f"CASE WHEN TRIM(COALESCE({field}, '')) <> '' THEN 1 ELSE 0 END"
for field in informative_fields
)
@classmethod
def _build_where_clause(
cls,
query: str,
user_context: dict[str, Any] | None = None,
) -> tuple[str, list[str], dict[str, Any]]:
"""根据用户问句生成本地快照过滤条件。"""
from app.services.text2sql import Text2SQLService
clauses: list[str] = []
params: list[str] = []
query_profile = {"uses_generic_keyword_search": False}
advanced_conds = Text2SQLService._extract_advanced_asset_conditions(query)
asset_code = advanced_conds.get("asset_code") or Text2SQLService._extract_asset_code(query)
@@ -681,31 +752,10 @@ INSERT INTO fixed_assets (
params.append(f"%{explicit_department.upper()}%")
if should_use_generic_keyword_search:
normalized_keyword = cls._normalize_search_text(asset_name)
clauses.append(
"("
"UPPER(COALESCE(asset_name, '')) LIKE ? "
"OR UPPER(COALESCE(asset_name2, '')) LIKE ? "
"OR UPPER(COALESCE(specification, '')) LIKE ? "
"OR UPPER(COALESCE(location_name, '')) LIKE ? "
"OR UPPER(COALESCE(custodian_name, '')) LIKE ? "
"OR UPPER(COALESCE(department_name, '')) LIKE ? "
"OR UPPER(COALESCE(vendor_name, '')) LIKE ? "
"OR UPPER(COALESCE(remark_normalized, '')) LIKE ?"
")"
)
params.extend(
[
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{asset_name.upper()}%",
f"%{normalized_keyword}%",
]
)
generic_clause, generic_params = cls._build_generic_keyword_match_clause(asset_name)
clauses.append(generic_clause)
params.extend(generic_params)
query_profile["uses_generic_keyword_search"] = True
normalized_user = user_context or {}
if Text2SQLService._is_self_asset_query(query):
@@ -730,7 +780,7 @@ INSERT INTO fixed_assets (
params.append(f"%{token}%")
where_sql = " AND ".join(clauses) if clauses else "1=1"
return where_sql, params
return where_sql, params, query_profile
@classmethod
def query_assets(
@@ -745,7 +795,7 @@ INSERT INTO fixed_assets (
if not cls.is_snapshot_available():
return ["Error"], [("固定资产快照尚未生成,请稍后重试。",)], 0
where_sql, params = cls._build_where_clause(query, user_context=user_context)
where_sql, params, query_profile = cls._build_where_clause(query, user_context=user_context)
deduped_assets_cte = """
WITH deduped_assets AS (
SELECT *
@@ -764,6 +814,24 @@ WITH deduped_assets AS (
WHERE dedupe_rn = 1
)
""".strip()
filtered_assets_cte = ""
result_source_name = "deduped_assets"
order_by_sql = "asset_no"
if query_profile.get("uses_generic_keyword_search"):
filtered_assets_cte = f"""
, filtered_assets AS (
SELECT *,
{cls._generic_result_quality_score_sql()} AS quality_score
FROM deduped_assets
WHERE {cls._generic_result_quality_guard_sql()}
)
""".rstrip()
result_source_name = "filtered_assets"
order_by_sql = (
"quality_score DESC, "
"CASE WHEN TRIM(COALESCE(asset_no, '')) = '' THEN 1 ELSE 0 END, "
"asset_no, asset_name"
)
visible_select = """
asset_no AS "资产编号",
asset_name AS "资产名称",
@@ -784,15 +852,17 @@ accounting_date AS "入账日期"
""".strip()
list_sql = f"""
{deduped_assets_cte}
{filtered_assets_cte}
SELECT {visible_select}
FROM deduped_assets
FROM {result_source_name}
WHERE {where_sql}
ORDER BY asset_no
ORDER BY {order_by_sql}
LIMIT ? OFFSET ?
""".strip()
count_sql = f"""
{deduped_assets_cte}
SELECT COUNT(*) FROM deduped_assets WHERE {where_sql}
{filtered_assets_cte}
SELECT COUNT(*) FROM {result_source_name} WHERE {where_sql}
""".strip()
conn = sqlite3.connect(cls._latest_db_path())
@@ -11,6 +11,7 @@ from app.services.shipping_notice.state_machine import (
ALL_ACTION_IDS,
ALL_CHECKPOINT_IDS,
CHECKPOINT_REGISTRY,
CP_INVENTORY_SOURCE_REVIEW,
TaskTransition,
TaskUiState,
action_buttons_for_checkpoint,
@@ -21,6 +22,7 @@ from app.services.shipping_notice.state_machine import (
human_options_for_checkpoint,
human_options_for_task,
human_options_for_task_or_checkpoint,
inventory_source_action_buttons,
resolve_task_ui_state,
ui_state_for_checkpoint,
upload_req_options_for_task,
@@ -1,9 +1,10 @@
"""
services/shipping_notice/notice_upload.py
用途:管理发货通知附件上传、文本抽取、OCR/文档解析与文件落盘。
用途:管理发货通知附件上传、文本抽取、截断与统一接入结果模型。
依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、export._storage_root、Flask current_app 配置。
逻辑:由 workspace_shipping_notice 和 task_workflow 上游入口调用本文件,把原始附件转成可解析文本后交给 extract/task_workflow;批量上传的预检临时文件也在这里统一落盘和清理。
逻辑:workspace 单票建单、批量建单、重新上传三条入口均经 intake_notice_attachment / intake_temp_notice_uploads
收敛抽取与失败分流;下游 extract/task_workflow 只消费 NoticeIntakeResult。
"""
from __future__ import annotations
@@ -11,10 +12,11 @@ from __future__ import annotations
import base64
import re
import shutil
from dataclasses import dataclass, field
from email import policy
from email.parser import BytesParser
from pathlib import Path
from typing import Any
from typing import Any, Literal, Sequence
from flask import current_app
@@ -228,3 +230,237 @@ def max_notice_chars() -> int:
except Exception:
value = 0
return value if value > 0 else 200000
EMPTY_TEXT_REJECT_MESSAGE = "notice text is empty after extraction"
@dataclass(frozen=True)
class NoticeIntakeResult:
"""
发货通知附件统一接入结果。
三条工作台入口(单票建单 / 批量建单 / 重新上传)共用本模型,避免抽取、截断与失败分流行为漂移。
"""
filename: str
source_type: str
source_file_type: str | None
text: str
warnings: list[str] = field(default_factory=list)
meta: dict[str, Any] = field(default_factory=dict)
status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text"
saved_path: Path | None = None
@property
def accepted(self) -> bool:
"""抽取成功且正文非空。"""
return self.status == "accepted"
def to_notice_item(self) -> dict[str, Any]:
"""批量建单 notice_items 载荷项。"""
return {
"source_type": self.source_type,
"source_file_name": self.filename,
"source_file_type": self.source_file_type,
"raw_text": self.text,
"warnings": list(self.warnings),
}
def to_accepted_file_summary(self) -> dict[str, Any]:
"""批量预检 accepted_files 摘要项。"""
return {
"filename": self.filename,
"source_type": self.source_type,
"source_file_type": self.source_file_type,
"text_length": len(self.text),
"warnings": list(self.warnings),
}
def to_rejected_file_summary(self) -> dict[str, Any]:
"""批量预检 rejected_files 摘要项。"""
return {
"filename": self.filename,
"source_type": self.source_type,
"source_file_type": self.source_file_type,
"reason": "empty_text",
"message": EMPTY_TEXT_REJECT_MESSAGE,
"warnings": list(self.warnings),
}
def to_notice_upload_meta(self) -> dict[str, Any]:
"""API data.notice_upload 响应字段。"""
payload = dict(self.meta) if isinstance(self.meta, dict) else {}
payload["filename"] = self.filename
payload["warnings"] = list(self.warnings)
return payload
def notice_source_file_type(upload: Any) -> str | None:
"""从 Flask/Werkzeug 上传对象提取 MIME type;为空时返回 None。"""
return str(getattr(upload, "mimetype", "") or "").strip() or None
def truncate_notice_text(text: str, warnings: list[str] | None = None) -> tuple[str, list[str]]:
"""
按配置上限截断发货通知正文,并追加统一 warning 标记。
Args:
text: 抽取后的原始正文。
warnings: 已有 warnings,截断时会追加 notice_text_truncated 项。
Returns:
tuple[str, list[str]]: (截断后正文, 更新后的 warnings)。
"""
ws = list(warnings or [])
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
ws.append(f"notice_text_truncated:{limit}")
return text, ws
def intake_notice_attachment(
*,
filename: str,
raw: bytes,
source_file_type: str | None = None,
storage: Literal["task", "temp"] = "task",
task_no: str | None = None,
temp_request_id: str | None = None,
temp_index: int = 1,
) -> NoticeIntakeResult:
"""
单份发货通知附件的统一接入:落盘 → 抽取 → 截断 → 失败分流。
核心逻辑:三条工作台入口均调用本函数,保证 empty_text / extract_failed 与 warnings 语义一致。
Args:
filename: 原始文件名。
raw: 文件字节流。
source_file_type: MIME type,可为空。
storage: task 为任务级持久化目录;temp 为批量预检临时目录。
task_no: storage=task 时必填。
temp_request_id: storage=temp 时必填。
temp_index: storage=temp 时文件序号,避免同名覆盖。
Returns:
NoticeIntakeResult: 含 accepted / empty_text / extract_failed 状态与截断后正文。
"""
name = str(filename or "").strip() or "notice"
source_type = guess_source_type(name)
saved_path: Path | None = None
text = ""
meta: dict[str, Any] = {}
warnings: list[str] = []
status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text"
try:
if storage == "task":
if not task_no:
raise ValueError("task_no is required for task storage")
saved_path = save_task_notice_upload(task_no, name, raw or b"")
else:
if not temp_request_id:
raise ValueError("temp_request_id is required for temp storage")
saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw or b"")
text, meta = extract_notice_text(saved_path)
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
except Exception as exc:
warnings = [f"notice_extract_failed:{exc}"]
status = "extract_failed"
return NoticeIntakeResult(
filename=name,
source_type=source_type,
source_file_type=source_file_type,
text="",
warnings=warnings,
meta=meta if isinstance(meta, dict) else {},
status=status,
saved_path=saved_path,
)
if not str(text or "").strip():
return NoticeIntakeResult(
filename=name,
source_type=source_type,
source_file_type=source_file_type,
text="",
warnings=warnings,
meta=meta if isinstance(meta, dict) else {},
status="empty_text",
saved_path=saved_path,
)
text, warnings = truncate_notice_text(text, warnings)
return NoticeIntakeResult(
filename=name,
source_type=source_type,
source_file_type=source_file_type,
text=text,
warnings=warnings,
meta=meta if isinstance(meta, dict) else {},
status="accepted",
saved_path=saved_path,
)
def intake_temp_notice_uploads(
temp_request_id: str,
uploads: Sequence[Any],
) -> tuple[list[NoticeIntakeResult], list[NoticeIntakeResult]]:
"""
批量建单入口:逐份附件接入并在 finally 外由调用方清理临时目录。
Args:
temp_request_id: 请求级临时目录 ID。
uploads: Flask request.files 中的上传对象序列。
Returns:
tuple[list, list]: (accepted 结果列表, rejected 结果列表)。
"""
accepted: list[NoticeIntakeResult] = []
rejected: list[NoticeIntakeResult] = []
for index, upload in enumerate(uploads, start=1):
raw = upload.read() or b""
result = intake_notice_attachment(
filename=upload.filename or "notice",
raw=raw,
source_file_type=notice_source_file_type(upload),
storage="temp",
temp_request_id=temp_request_id,
temp_index=index,
)
if result.accepted:
accepted.append(result)
else:
rejected.append(result)
return accepted, rejected
def build_notice_file_summary(
*,
total_files: int,
accepted: Sequence[NoticeIntakeResult],
rejected: Sequence[NoticeIntakeResult],
) -> dict[str, Any]:
"""
构建批量上传预检摘要,供前端回显与测试断言。
Args:
total_files: 请求内附件总数。
accepted: 接入成功的结果列表。
rejected: 接入失败的结果列表。
Returns:
dict: total/accepted/rejected 计数与文件明细。
"""
accepted_files = [item.to_accepted_file_summary() for item in accepted]
rejected_files = [item.to_rejected_file_summary() for item in rejected]
return {
"total_files": total_files,
"accepted_count": len(accepted_files),
"rejected_count": len(rejected_files),
"accepted_files": accepted_files,
"rejected_files": rejected_files,
}
+107
View File
@@ -151,6 +151,51 @@ class Text2SQLService:
"当前登录用户",
"登录用户",
)
_ASSET_CONTEXT_DEPENDENT_MARKERS = (
"这个",
"这个资产",
"该资产",
"这台",
"这个设备",
"这个人",
"这个部门",
"这些",
"上述",
"上面",
"前面",
"刚才",
"上一条",
"上一个",
"同一个",
"它",
"它的",
"其",
"他的",
"她的",
)
_ASSET_RESET_SAFE_INTENT_MARKERS = (
"明细",
"列表",
"统计",
"查询",
"查下",
"看下",
"看看",
"有多少",
"多少",
"多少台",
"状态",
"规格",
"型号",
"账套",
"保管人",
"保管部门",
"存放位置",
"位置",
"供应商",
"取得日期",
"入账日期",
)
_ASSET_CODE_HINT_PATTERN = re.compile(
r"(?:资产编号|财产编号|资产编码|设备编号|编号|设备|资产|固资|固定资产)\s*(?:为|是|=|:|:)?\s*([A-Za-z][A-Za-z0-9_-]{4,30})",
re.IGNORECASE,
@@ -547,6 +592,68 @@ class Text2SQLService:
or any(marker.lower() in sql_text.lower() for marker in cls._ASSET_TABLE_MARKERS)
)
@classmethod
def _is_context_dependent_asset_query(cls, query: str) -> bool:
"""判断固资问句是否依赖上一轮上下文。
AI 触发时机:当用户说“这个资产”“上面那条”“它的状态”等省略表达时,
不能贸然重置 provider conversation,否则会把真正依赖上下文的追问切断。
"""
text = cls._strip_asset_query_prefix(query)
if not text:
return False
if cls._extract_asset_code(text):
return False
if cls._has_explicit_asset_scope(text) or cls._is_self_asset_query(text):
return False
if cls._extract_advanced_asset_conditions(text):
return False
if cls._extract_explicit_asset_name(text):
return False
if cls._extract_asset_name_combo_keyword(text):
return False
if cls._extract_asset_name_keyword(text):
return False
return any(marker in text for marker in cls._ASSET_CONTEXT_DEPENDENT_MARKERS)
@classmethod
def _should_reset_provider_conversation(cls, query: str, agent=None) -> bool:
"""判断固资查询是否应主动切断上游会话上下文。
AI 触发时机:固资管理中的多数查询本质上都是“本轮文本可独立完成”的单轮检索。
当上一轮返回超大结果时,继续复用 Dify 会话容易把 token 撑爆;此时应保留本地历史会话,
但把上游 provider conversation 重置为空,让当前这轮按独立查询执行。
Args:
query: 用户当前输入的问题文本。
agent: 当前会话 Agent,仅固资管理 Agent 会进入该策略。
Returns:
bool: True 表示当前问题可脱离旧上下文独立执行,应切断上游会话;
False 表示当前问题明显依赖上一轮上下文,或根本不是固资管理问题。
"""
text = cls._strip_asset_query_prefix(query)
if not text or not cls._is_asset_management_agent(agent):
return False
if not cls._looks_like_asset_query(text):
return False
if cls._is_context_dependent_asset_query(text):
return False
if cls._extract_asset_code(text):
return True
if cls._has_explicit_asset_scope(text) or cls._is_self_asset_query(text):
return True
if cls._extract_advanced_asset_conditions(text):
return True
if cls._extract_explicit_asset_name(text):
return True
if cls._extract_asset_name_combo_keyword(text):
return True
if cls._extract_asset_name_keyword(text):
return True
return any(marker in text for marker in cls._ASSET_RESET_SAFE_INTENT_MARKERS)
@staticmethod
def _normalize_user_context(user) -> dict:
if user is None: