From 5dc45ee24752630db5bb01eb6320ae38bcd6aef6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E4=BA=9A=E9=B9=8F?= <1480083907@qq.com> Date: Mon, 30 Nov 2026 17:31:54 +0800 Subject: [PATCH] update --- .../work_assistant/submission_advice.py | 112 +++++++++++++++--- 1 file changed, 93 insertions(+), 19 deletions(-) diff --git a/app/modules/work_assistant/submission_advice.py b/app/modules/work_assistant/submission_advice.py index e2f2974..7eeef3d 100644 --- a/app/modules/work_assistant/submission_advice.py +++ b/app/modules/work_assistant/submission_advice.py @@ -1,9 +1,11 @@ """Evidence-bound advice for submission; never approves or blocks a transaction.""" import re +import time +from copy import deepcopy from decimal import Decimal from typing import Literal from pydantic import BaseModel, ConfigDict, Field, model_validator -from app.modules.work_assistant.model_gateway import complete_json +from app.modules.work_assistant.model_gateway import complete_json, ModelUnavailable class Record(BaseModel): model_config = ConfigDict(extra='forbid') @@ -36,8 +38,9 @@ class AdviceRequest(BaseModel): raise ValueError('重复材料编号') if sum(len(r.content) for r in self.records) > 48000: raise ValueError('材料超出本次核对范围') - if sum(bool(r.image) for r in self.records) > 2: - raise ValueError('最多提供两张附件画面') + image_limit = 24 if self.mode == 'expense' else 2 + if sum(bool(r.image) for r in self.records) > image_limit: + raise ValueError(f'单次核对最多提供{image_limit}页附件画面') for r in self.records: if r.claimed_amount and not re.fullmatch(r'\d{1,15}(?:\.\d{1,2})?', r.claimed_amount): raise ValueError('无效的明细金额') @@ -80,6 +83,7 @@ class PlanResult(BaseModel): class Invoice(BaseModel): model_config = ConfigDict(extra='forbid') id: str + invoice_number: str = Field(default='', max_length=64) title: str = Field(max_length=100) item: str = Field(max_length=180) gross_total: str = Field(max_length=32) @@ -117,7 +121,10 @@ status:明确问题 warning;确实无法判断的事项 insufficient;无 """ EXPENSE_FIELDS = EXPENSE_TEXT_FIELDS + """ -每份 id 含 -invoice- 的附件在 invoices 返回一条(包括无法识别的附件),只按同组原费用类别、描述及 claimed_amount 核对。 +每份 id 含 -invoice- 的材料在 invoices 返回一条(包括无法识别的附件),只按同组原费用类别及描述核对票面项目。 +descriptions 仅评价备注和费用描述,不在其中评价发票或比较金额;发票判断统一放在 invoices。 +同一附件可能拆为多页,每个页编号必须分别返回,不得只处理最后一页。invoice_number 只抄清楚可见的发票号码,不用车次、订单号或文件名替代;看不清留空。 +match 和 reason 只判断费用类别、业务内容与票面项目是否相符,禁止用单张或单页金额与整条申请金额比较;多页金额由程序收齐后汇总比较。 title/item 逐字抄票面票种和实际商品服务名;gross_total 取整票价税合计小写或实际总额(元),amount_quote 抄含总额及金额标识的原句;不能用申请金额、税额或不含税额替代。不清楚、多票总额不明则留空。 match=match/mismatch/unknown,reason 一句说明具体依据;费用类别与票面服务明确冲突必须 mismatch,即使描述笼统。收据、订单、行程截图不能当成发票;不假定公司允许的票种。文件名、申请描述、上传状态不是票面证据。缺失内容留空,不猜金额、票据真伪。金额加总比较由程序完成,不推断差额原因。 """ @@ -141,6 +148,7 @@ def invoice_tips(entry: AdviceRequest, invoices: list[Invoice]) -> list[dict]: for line in (r for r in entry.records if r.claimed_amount): amounts = [] amount_limits = [] + seen_numbers = {} files = [r for r in attached.values() if r.group == line.group] for order, r in enumerate(files, 1): i = by_id[r.id] @@ -157,15 +165,26 @@ def invoice_tips(entry: AdviceRequest, invoices: list[Invoice]) -> list[dict]: and re.fullmatch(r'-?\d{1,15}(?:\.\d{1,2})?', i.gross_total) and Decimal(i.gross_total) in quoted): amount = Decimal(i.gross_total) - if amount is not None: + number = i.invoice_number.strip() if on_invoice(i.invoice_number) else '' + repeated = bool(number and number in seen_numbers) + if repeated and amount is not None and seen_numbers[number] != amount: + amount_limits.append('同一发票号码的票面金额识别不一致') + if amount is not None and not repeated: amounts.append(amount) + if number: + seen_numbers[number] = amount if amount is None: amount_limits.append(f'附件{order}的票面金额未识别') if r.partial: amount_limits.append(f'附件{order}只读取到部分票面') - status = 'warning' if i.match == 'mismatch' and (title or item) else ( - 'no_issue' if title and item and amount is not None and not r.partial and i.match == 'match' else 'insufficient') - finding = (f'附件{order}:票种「{title or "未识别"}」,票面项目「{item or "未识别"}」,' + # 模型不能把一页的金额与整条申请金额比较;金额结论只采用下方完整汇总。 + amount_reason = bool(re.search(r'金额|票价|合计|总额|差额|[0-9]\s*元', i.reason)) + match = 'unknown' if i.match == 'mismatch' and amount_reason else i.match + status = 'warning' if match == 'mismatch' and (title or item) and not r.partial else ( + 'no_issue' if title and item and amount is not None and not r.partial and match == 'match' else 'insufficient') + page_ref = re.search(r'-invoice-(\d+)(?:-page-(\d+))?$', r.id) + label = (f'附件{page_ref[1]}' + (f'第{page_ref[2]}页' if page_ref[2] else '')) if page_ref else f'附件{order}' + finding = (f'{label}:票种「{title or "未识别"}」,票面项目「{item or "未识别"}」,' + ('票面合计未核实。' if amount is None else f'票面合计 ¥{amount:.2f}。')) fee = line.fee_label clear_conflict = (any(word in fee for word in ('打车', '出租车', '劳动保护', '劳保')) @@ -179,9 +198,11 @@ def invoice_tips(entry: AdviceRequest, invoices: list[Invoice]) -> list[dict]: finding += '请确认该凭证是否满足本次申请的票据要求。' if r.partial: finding += '仅获取部分票面,需核对原件。' - if i.reason and not clear_conflict and (i.match == 'mismatch' or status == 'no_issue'): + if repeated: + finding += '相同发票号码已计入,不重复累加。' + if i.reason and not amount_reason and not r.partial and not clear_conflict and (match == 'mismatch' or status == 'no_issue'): finding += i.reason - elif not clear_conflict and (i.match == 'unknown' or not item): + elif not clear_conflict and (match == 'unknown' or not item): finding += '费用类别与票面项目是否相符尚待确认。' checks.append(dict(group=line.group, status=status, finding=finding, suggestion='', basis=[dict(id=r.id, quote=next((v for v in (i.amount_quote, title, item) if v and v in r.content), '' if r.image else r.content[:100]))])) @@ -268,6 +289,10 @@ def review_advice(entry: AdviceRequest) -> dict: if entry.mode == 'expense': r['review_scope'] = ('overall_application' if entry.records[i].group == 'application' else 'line_expense' if entry.records[i].claimed_amount else 'line_invoice') + if entry.records[i].claimed_amount: + # 整条申请金额只用于程序汇总比对,避免模型拿单页金额作错误比较。 + r.pop('claimed_amount', None) + r['content'] = re.sub(r';金额:[^;]*', '', r.get('content', '')) # Accept older Java payloads during rollout, but never forward payment fields. for legacy_field in tuple(r): if legacy_field.startswith('payee_'): @@ -330,12 +355,61 @@ def review_advice(entry: AdviceRequest) -> dict: tips.append(dict(**d.model_dump(), aspect='description', basis=[dict(id=source.id, quote=source.content[:150])])) tips.extend(invoice_tips(entry, parsed.invoices)) return dict(summary='逐条核对结果', tips=tips, expense_version=2) - raw = complete_json(instruction, content, schema, timeout_seconds=65, max_tokens=2400, - **({'images': images} if images else {})) - try: - return checked(raw) - except (ValueError, TypeError) as exc: - corrected = complete_json(instruction, {'materials': content, 'candidate': raw, - 'correction': str(exc)}, schema, timeout_seconds=50, max_tokens=2400, - **({'images': images} if images else {})) - return checked(corrected) + # 保持在 Java 调用方的125秒等待窗口内;超时不能把已完成的部分页当成完整结果。 + deadline = time.monotonic() + 115 + def remaining(limit): + seconds = deadline - time.monotonic() + if seconds < 1: + raise ModelUnavailable('submission_advice_deadline') + return min(limit, seconds) + + def invoke(materials, contract, rules, pictures, validate): + raw = complete_json(rules, materials, contract, timeout_seconds=remaining(65), max_tokens=2400, + **({'images': pictures} if pictures else {})) + try: + return validate(raw) + except (ValueError, TypeError) as exc: + corrected = complete_json(rules, {'materials': materials, 'candidate': raw, + 'correction': str(exc)}, contract, timeout_seconds=remaining(50), max_tokens=2400, + **({'images': pictures} if pictures else {})) + return validate(corrected) + + invoice_records = [r for r in entry.records if '-invoice-' in r.id] + if expense and (len(images) > 2 or len(invoice_records) > 4): + # 网关每次最多接收两张图。只分批提取票面,收齐所有批次后才做一次金额汇总。 + batches, batch, image_count = [], [], 0 + for r in invoice_records: + if batch and (image_count + bool(r.image) > 2 or len(batch) >= 4): + batches.append(batch) + batch, image_count = [], 0 + batch.append(r) + image_count += bool(r.image) + if batch: + batches.append(batch) + merged = dict(descriptions=[], invoices=[]) + for index, batch in enumerate(batches): + ids = {r.id for r in batch} + part = deepcopy(content) + part['records'] = [r for r in part['records'] if '-invoice-' not in r['id'] or r['id'] in ids] + expected_groups = required_groups if index == 0 else [] + part['required_description_groups'] = expected_groups + contract = deepcopy(schema) + contract['properties']['descriptions'].update(minItems=len(expected_groups), maxItems=len(expected_groups)) + contract['properties']['invoices'].update(minItems=len(ids), maxItems=len(ids)) + contract['$defs']['Invoice']['properties']['id']['enum'] = [r.id for r in batch] + pictures = [(n + 1, r.image) for n, r in enumerate(entry.records) if r.id in ids and r.image] + + def checked_part(raw): + parsed = ExpenseResult.model_validate(raw) + if len(parsed.invoices) != len(ids) or {i.id for i in parsed.invoices} != ids: + raise ValueError('本批次必须逐页返回全部发票材料,不能遗漏或重复页编号') + if (len(parsed.descriptions) != len(expected_groups) + or {d.group for d in parsed.descriptions} != set(expected_groups)): + raise ValueError('descriptions 必须与本批 required_description_groups 一一对应') + return parsed.model_dump() + + parsed = invoke(part, contract, instruction, pictures, checked_part) + merged['descriptions'].extend(parsed['descriptions']) + merged['invoices'].extend(parsed['invoices']) + return checked(merged) + return invoke(content, schema, instruction, images, checked)