"""A bounded grammar for formal metric questions, separate from evidence proof. Only understood product/period/stage/field tokens produce a request. Unknown scope or analysis words leave the native analysis path in charge. This module never obtains metrics, interprets model prose, or reuses historical evidence. """ from __future__ import annotations import copy import re from typing import Any from nao_evidence_report import _filters _MONTH = re.compile(r'(? bool: return bool(_FRESH.search(question)) def is_history_restatement(question: str) -> bool: return (not requires_fresh_query(question) and bool(re.search(r'再说一遍|再讲一遍|复述|总结|重复', question)) and bool(_RESTATE.fullmatch(question.strip()))) def frozen_metric_frame(context: Any) -> dict[str, Any]: """Only user-visible query dimensions bind inheritance; prose is not state.""" value = context if isinstance(context, dict) else {} selected = value.get('period') or value.get('currentPeriod') or value selected = selected if isinstance(selected, dict) else {} frame = {'filters': copy.deepcopy(_filters(value.get('filters') if isinstance(value.get('filters'), dict) else value))} bound_task = value.get('_agentTask') if isinstance(bound_task, dict) and isinstance(bound_task.get('filters'), dict) and 'columnFilters' in bound_task['filters']: frame['filters']['columnFilters'] = copy.deepcopy(bound_task['filters'].get('columnFilters') or []) elif isinstance(value.get('filters'), dict) and 'columnFilters' in value['filters']: frame['filters']['columnFilters'] = copy.deepcopy(value['filters'].get('columnFilters') or []) for name, period in (('period', selected), ('comparisonPeriod', value.get('comparisonPeriod'))): if isinstance(period, dict): parsed = {key: period[key] for key in ('year', 'month', 'quarter', 'monthStart', 'monthEnd') if period.get(key) is not None} if parsed: frame[name] = parsed if value.get('stage') in ('black', 'bright'): frame['stage'] = value['stage'] if value.get('releaseId'): frame['releaseId'] = value['releaseId'] return frame def _valid_request(value: Any) -> bool: if not isinstance(value, dict): return False periods = value.get('periods') return (isinstance(value.get('product'), str) and bool(value['product']) and isinstance(value.get('filters'), dict) and value['filters'].get('product') == value['product'] and isinstance(periods, list) and len(periods) == 2 and periods[0] != periods[1] and all(isinstance(p, dict) and set(p) == {'year', 'month'} and type(p['year']) is int and 1900 <= p['year'] <= 2200 and type(p['month']) is int and 1 <= p['month'] <= 12 for p in periods) and isinstance(value.get('stages'), list) and bool(value['stages']) and all(isinstance(item, str) for item in value['stages']) and set(value['stages']) <= set(_STAGES) and isinstance(value.get('fields'), list) and bool(value['fields']) and all(isinstance(item, str) for item in value['fields']) and set(value['fields']) <= set(_FIELDS)) def resolve_metric_request(question: str, context: Any = None, previous: Any = None) -> dict[str, Any] | None: """Resolve a complete request, optionally inheriting a verified prior intent. The caller controls whether previous belongs to the same session and frozen input frame. Missing dimensions are not guessed from result rows or prose. """ if not isinstance(question, str) or is_history_restatement(question): return None text = question.strip() prior = previous if _valid_request(previous) else {} frozen = frozen_metric_frame(context) periods = [] years = {p['year'] for p in prior.get('periods', [])} year = next(iter(years)) if len(years) == 1 else None if year is None and isinstance(frozen.get('period'), dict): year = frozen['period'].get('year') for match in _MONTH.finditer(text): year = int(match.group(1)) if match.group(1) else year if type(year) is not int or not 1900 <= year <= 2200: return None periods.append({'year': year, 'month': int(match.group(2))}) text = _MONTH.sub('', text) text = re.sub(r'该规格|这个规格|该产品|这个产品', '', text) products = [] # Explicit markers support Unicode names; bare identifiers support the usual # dimension/specification notation without treating arbitrary prose as a name. marked = re.compile(r'(?:只看|仅看|仅针对|针对|换成|换为|改成|规格|产品)\s*(?:规格|产品)?\s*' r'([A-Za-z0-9][A-Za-z0-9.+*/×_-]*|[「“\"]([^」”\"]+)[」”\"]|[^,,;;。!?!?、::\s的在]+)') def product_token(match): value = match.group(2) or match.group(1) # Reference words must inherit a verified intent, never become a product. if value in ('该规格', '这个规格', '该产品', '这个产品', '黑片', '亮片'): return match.group(0) products.append(value) return '' text = marked.sub(product_token, text) def bare_product(match): value = match.group(1) if not re.search(r'\d', value) or not re.search(r'[A-Za-z×]', value): return value products.append(value); return '' text = _BARE_PRODUCT.sub(bare_product, text) if len(products) > 1 or products and len(products[0]) > 100: return None product = products[0] if products else prior.get('product') or frozen['filters'].get('product') stages, fields = [], [] for name, tokens in _STAGES.items(): if any(token in text for token in tokens): stages.append(name) for token in tokens: text = text.replace(token, '') for name, tokens in _FIELDS.items(): if any(token in text for token in tokens): fields.append(name) for token in tokens: text = text.replace(token, '') if not _REMAINDER.fullmatch(text): return None if not periods: if prior: periods = copy.deepcopy(prior['periods']) elif all(isinstance(frozen.get(key), dict) for key in ('period', 'comparisonPeriod')): periods = [frozen['period'], frozen['comparisonPeriod']] stages = stages or prior.get('stages') or ([frozen['stage']] if frozen.get('stage') else []) fields = fields or prior.get('fields') or [] request = {'product': product, 'filters': {**frozen['filters'], 'product': product}, 'periods': periods, 'stages': list(stages), 'fields': list(fields)} if not _valid_request(request): return None request['periods'] = sorted(periods, key=lambda period: (period['year'], period['month']), reverse=True) return request def metric_request(question: str, context: Any = None) -> dict[str, Any] | None: """Use a runtime-resolved intent only for its exact question and frame.""" from nao_agent_task import task_from_context task = task_from_context(context, question) if task is not None: if task['kind'] != 'metrics': return None request = {'product': task['filters'].get('product'), 'filters': task['filters'], 'periods': [task.get('period'), task.get('comparisonPeriod')], 'stages': task['stages'], 'fields': task['fields']} return copy.deepcopy(request) if _valid_request(request) else None frozen = context if isinstance(context, dict) else {} resolved = frozen.get('_resolvedMetricRequest') if (isinstance(resolved, dict) and resolved.get('question') == question and resolved.get('frame') == frozen_metric_frame(frozen) and _valid_request(resolved.get('request'))): return copy.deepcopy(resolved['request']) return resolve_metric_request(question, context) def prepare_metric_context(question: str, context: Any, previous_record: Any = None) -> tuple[Any, dict[str, Any] | None]: """Bind the current goal and only inherit across an unchanged input frame.""" base = dict(context) if isinstance(context, dict) else {} base.pop('_resolvedMetricRequest', None) previous = previous_record if isinstance(previous_record, dict) else {} prior = previous.get('metricRequest') if previous.get('baseMetricFrame') == frozen_metric_frame(base) else None request = resolve_metric_request(question, base, prior) if not request: return context, None # An explicit new product/period is the current local goal; every other # frozen filter is retained. The release stays exactly as supplied. bound = {**base, 'period': request['periods'][0], 'comparisonPeriod': request['periods'][1], 'filters': copy.deepcopy(request['filters'])} for key in ('year', 'month', 'quarter', 'monthStart', 'monthEnd', 'currentPeriod', 'stage'): bound.pop(key, None) if len(request['stages']) == 1: bound['stage'] = request['stages'][0] bound['_resolvedMetricRequest'] = {'question': question, 'frame': frozen_metric_frame(bound), 'request': copy.deepcopy(request)} return bound, request