修复:DSH 自主查询、图片直显与报告稳定性

允许 Agent 在循环中查目录、修正查询和提问,保留实时权限检查及模型原始回答。
统一相同查询证据与图表资源;排名补齐阶段指标,修正 OR 重量筛选,并限制模型明细输入。
增加运行恢复、图表自适应坐标轴与两位小数,修复报告主图选择、重复图及边缘标签。

验证:独立副本通过 162 项 Python、73 项前端及 21 项后端测试,前端构建通过。
线上已用原 8 题复测,并追加两轮双期对比;TOP100 与组合筛选分别核对 100 行和 20 行。
This commit is contained in:
2026-11-12 16:14:20 +08:00
parent f1a2fbd494
commit bc19475b29
35 changed files with 983 additions and 114 deletions
+74 -12
View File
@@ -168,6 +168,12 @@ def _current_source_catalog(state, release_id):
def prepare_step(arguments, task, state, *, source_catalog=None):
"""Make a proposal, never an authorization. The server resolves every scope."""
args = copy.deepcopy(arguments)
agent_driven = task.get('agentDriven') is True
if agent_driven:
# 意图提示不锁定实际查询;每个新范围仍须由服务端签发。
task = copy.deepcopy(task)
task['filters'] = {}
task['stages'] = []
# Some providers encode object arguments as JSON strings. Decode only the
# declared period objects before comparing them with the authorized frame.
for key in ('period', 'comparisonPeriod'):
@@ -178,8 +184,14 @@ def prepare_step(arguments, task, state, *, source_catalog=None):
raise QualityToolError(key+'必须是期间对象,例如{year:2026,month:10}。', code='invalid_arguments') from None
if not isinstance(args[key], dict):
raise QualityToolError(key+'必须是期间对象。', code='invalid_arguments')
if agent_driven:
for key in ('period', 'comparisonPeriod'):
if key in args:
task[key] = args[key]
if 'groupBy' in args:
args['view'] = args.pop('groupBy')
if agent_driven and args.get('mode') == 'query' and args.get('comparisonPeriod') is not None:
args['mode'] = 'compare'
mode = args.get('mode')
if mode == 'details':
# The native protocol records complete, pageable investigation responses;
@@ -201,18 +213,21 @@ def prepare_step(arguments, task, state, *, source_catalog=None):
scope_was_explicit='scope' in args)
if not root.get('includeUnassigned') and filters.get('includeUnassigned') is False:
filters.pop('includeUnassigned', None)
if supplied_columns != columns or ('columnFilters' in args and args['columnFilters'] != (columns or [])):
if not agent_driven and (supplied_columns != columns or ('columnFilters' in args and args['columnFilters'] != (columns or []))):
raise QualityToolError('调查不能修改已确认原表列条件。')
if columns is not None:
filters['columnFilters'] = columns
args['columnFilters'] = copy.deepcopy(columns)
elif agent_driven and supplied_columns is not None:
filters['columnFilters'] = supplied_columns
args['columnFilters'] = copy.deepcopy(supplied_columns)
args.pop('scope', None)
for key in ('period', 'comparisonPeriod'):
required = task.get(key)
if key == 'comparisonPeriod' and mode not in ('compare', 'changes', 'defects', 'investigate'):
continue
if required is not None:
if key in args and args[key] != required:
if not agent_driven and key in args and args[key] != required:
from nao_period import normalize_period, expected_months
try:
supplied_period = normalize_period(args[key])
@@ -239,12 +254,15 @@ def prepare_step(arguments, task, state, *, source_catalog=None):
# A verified earlier parent scope can supply more than one inherited filter.
candidates = [entry for entry in state.get('scopes', [])
if entry.get('queryIds') and all(filters.get(k) == v for k, v in entry['filters'].items())]
if candidates:
if candidates and not agent_driven:
parent = max(candidates, key=lambda entry: len(entry['filters']))
if len(parent['filters']) > len(parent_filters):
parent_filters = parent['filters']
parent_ids = parent['queryIds']
extras = {k: v for k, v in filters.items() if k not in parent_filters}
if agent_driven:
extras = {}
parent_ids = []
if set(extras) - {'department', 'group', 'product', 'projectGroup'} or len(extras) > 1:
raise QualityToolError('请先取得父范围证据,再沿授权目录逐层下钻;不能一次增加未核验的多层条件。')
selector = {'kind': 'base'}
@@ -258,6 +276,8 @@ def prepare_step(arguments, task, state, *, source_catalog=None):
# redundant selector, not permission to change the root stage frame.
args.pop('stage', None)
view = args.get('view', 'overall')
if mode == 'query':
args['view'] = view
if view not in ('overall','department','group','product') or mode == 'compare' and view != 'overall':
raise QualityToolError('query支持overall总体、department产业部、group业务分组、product产品批量汇总;compare只比较总体。')
if mode == 'compare':
@@ -265,6 +285,12 @@ def prepare_step(arguments, task, state, *, source_catalog=None):
node.update(purpose='trend' if mode == 'query' and task.get('trendRequired') else 'metrics',
fields=list(task.get('fields') or ['rate']), stages=list(task.get('stages') or []),
comparisonRequired=mode == 'compare')
if agent_driven and 'fields' in args:
selected = args.pop('fields')
if (not isinstance(selected, list) or not selected
or any(field not in ('rate','scrapRate','totalWeight','scrapWeight') for field in selected)):
raise QualityToolError('query.fields只能选择rate/scrapRate/totalWeight/scrapWeight,请修正后继续。',code='invalid_arguments')
node['fields'] = list(dict.fromkeys(selected))
if not node['stages'] and node['fields'] != ['rate']:
node['stages'] = ['black', 'bright']
if mode == 'query' and view != 'overall':
@@ -294,6 +320,10 @@ def prepare_step(arguments, task, state, *, source_catalog=None):
dimension=args.get('dimension', 'defect'), fields=[args['metric']] if mode == 'rank' else ['scrapWeight'],
stages=[stage] if stage else [], limit=args.get('limit', 10),
comparisonRequired=mode == 'defects' and bool(args.get('comparisonPeriod')))
if mode == 'rank' and agent_driven:
selected = args.pop('fields', [])
if not isinstance(selected, list) or any(field not in ('rate','totalWeight','scrapWeight') for field in selected):
raise QualityToolError('rank.fields仅支持rate/totalWeight/scrapWeight。',code='invalid_arguments')
if mode == 'rank' and stage:
node['fields'] = list(dict.fromkeys([*node['fields'],
*[field for field in task.get('fields', []) if field in ('totalWeight', 'scrapWeight')]]))
@@ -341,10 +371,14 @@ def prepare_step(arguments, task, state, *, source_catalog=None):
# Response caching below still uses the complete page arguments.
scope_arguments.pop('offset', None)
scope_arguments.pop('limit', None)
if agent_driven:
scope_arguments = {'arguments': scope_arguments, 'fields': node.get('fields'), 'stages': node.get('stages')}
request_key = hashlib.sha256(json.dumps(scope_arguments, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
node['nodeId'] = 'e' + request_key[:24]
return args, {'requestKey': request_key,
'node': node, 'parentQueryIds': parent_ids}
proposal = {'requestKey': request_key, 'node': node, 'parentQueryIds': parent_ids}
if agent_driven:
proposal['frame'] = {key: copy.deepcopy(args[key]) for key in ('period','comparisonPeriod','filters') if key in args}
return args, proposal
class NativeExplorationTools:
@@ -363,7 +397,7 @@ class NativeExplorationTools:
return {**result, 'investigationCoverage': {
'scopeComplete': bool(rows) and all(row.get('complete') is True for row in rows),
'missingEvidence': bounded(gap for row in rows for gap in row.get('missingEvidence', [])),
'rootGoalGaps': bounded(snapshot.get('rootGoalGaps', [])),
'rootGoalGaps': [] if self.task.get('agentDriven') else bounded(snapshot.get('rootGoalGaps', [])),
'meaning': '正式结论须使用完整范围证据;未完整细项可换为明确已提供的具体字段查询,不能把缺失值当零。'}}
def quality_data(self, arguments):
@@ -375,6 +409,10 @@ class NativeExplorationTools:
fresh = arguments.pop('freshQuery', False)
if type(fresh) is not bool:
raise QualityToolError('freshQuery必须是布尔值,仅明确重查时使用。')
# A published release is immutable within this execution. A model's
# refresh flag cannot produce newer data; a new turn has its own cache.
if self.task.get('agentDriven'):
fresh = False
# Even an in-turn cache hit must reauthorize the current turn.
self.delegated.call('/api/analysis/model-authorization', method='GET')
with _file_lock(self.state_path.with_suffix('.lock'), blocking=True):
@@ -382,7 +420,7 @@ class NativeExplorationTools:
if state.get('executionId') != self.identity['executionId']:
state = {'executionId': self.identity['executionId'], 'releaseId': self.identity['releaseId'],
'cache': {}, 'scopes': [], 'noProgress': 0, 'readCount': 0}
if state.get('halted'):
if state.get('halted') and not self.task.get('agentDriven'):
raise QualityToolError('连续三次未取得新证据,已停止调查并保留已核实结果。')
scoped = None
try:
@@ -390,6 +428,25 @@ class NativeExplorationTools:
key = 'catalog-' + hashlib.sha256(json.dumps(arguments, sort_keys=True).encode()).hexdigest()
if key in state['cache'] and not fresh:
return {**copy.deepcopy(state['cache'][key]), 'reusedEvidence': True}
if arguments.get('dimension') in ('product','department','group','projectGroup'):
dimension = arguments['dimension']
search = arguments.get('search', '')
limit = arguments.get('limit', 100)
if not isinstance(search, str) or len(search)>256 or type(limit) is not int or not 1<=limit<=100:
raise QualityToolError('catalog的search为短文本,limit为1到100整数。',code='invalid_arguments')
directory = self.delegated.call('/api/options?releaseId='+state['releaseId'],method='GET')
from nao_product_identification import _normalized, identify_products
match = identify_products(search, directory).get('productMatch', {}) if dimension=='product' and search else {}
candidates = [item['name'] for item in match.get('candidates', [])]
if not candidates:
candidates = [name for name in directory.get({'product':'products','department':'departments','group':'groups','projectGroup':'projectGroups'}[dimension], [])
if isinstance(name,str) and _normalized(search) in _normalized(name)]
result = {'kind':'quality_catalog_members','releaseId':state['releaseId'],'dimension':dimension,
'search':search,'candidateCount':len(candidates),'truncated':len(candidates)>limit,
'items':[{'name':name} for name in candidates[:limit]],
'guidance':'候选均来自当前账号可访问目录;多个不同完整规格时向用户提问,不猜选或合并。'}
state['cache'][key] = copy.deepcopy(result)
return result
result = QualityTools(api_factory=lambda: self.delegated,
evidence_dir=self.evidence_dir,
catalog_metadata_only=True).quality_data(arguments)
@@ -401,12 +458,15 @@ class NativeExplorationTools:
args, proposal = prepare_step(arguments, self.task, state, source_catalog=source_catalog)
QualityTools(api_factory=lambda: self.delegated,
evidence_dir=self.evidence_dir)._validate_arguments(args)
key = hashlib.sha256(json.dumps(args, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
cache_frame = {'arguments': args,
'fields': sorted(proposal['node'].get('fields', [])),
'stages': sorted(proposal['node'].get('stages', []))}
key = hashlib.sha256(json.dumps(cache_frame, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
if key in state['cache'] and not fresh:
if state['cache'][key].get('status') == 'no_data':
return {**copy.deepcopy(state['cache'][key]), 'reusedEvidence':True}
state['noProgress'] += 1
state['halted'] = state['noProgress'] >= 3
state['halted'] = state['noProgress'] >= 3 and not self.task.get('agentDriven')
return self.active_result({**self.observation_coverage(copy.deepcopy(state['cache'][key])), 'reusedEvidence': True,
'investigationNotice': '复用本轮相同查询证据;请依据结果换调查方向或结束答复。'})
registrations = state.setdefault('registrations', {})
@@ -450,7 +510,7 @@ class NativeExplorationTools:
state['scopes'].append({'nodeId': registered['nodeId'], 'scopeId': registered['scopeId'],
'filters': child['filters'], 'queryIds': proof_ids})
state['noProgress'] = state['noProgress'] + 1 if same_content else 0
state['halted'] = state['noProgress'] >= 3
state['halted'] = state['noProgress'] >= 3 and not self.task.get('agentDriven')
if same_content:
result['investigationNotice'] = '已明确重查,但正式响应没有新增内容;请依据已有结果换调查方向或结束。'
return self.active_result(self.observation_coverage(result))
@@ -474,7 +534,7 @@ class NativeExplorationTools:
return result
except Exception as error:
state['noProgress'] += 1
state['halted'] = state['noProgress'] >= 3
state['halted'] = state['noProgress'] >= 3 and not self.task.get('agentDriven')
from nao_quality_runtime import RuntimeErrorSafe
safe = str(error)[:600] if isinstance(error, (RuntimeErrorSafe, QualityToolError, ValueError)) else type(error).__name__
state.setdefault('errors', []).append({'type': type(error).__name__, 'message': safe})
@@ -482,7 +542,9 @@ class NativeExplorationTools:
if isinstance(error, RuntimeErrorSafe):
code = ('forbidden' if error.http_status in (401,403) else
'invalid_arguments' if error.http_status in (400,409,422) else 'unavailable')
raise QualityToolError(safe, code=code) from None
wrapped = QualityToolError(safe, code=code)
wrapped.http_status = error.http_status
raise wrapped from None
raise
finally:
if scoped is not None: state['readCount'] = scoped.read_count