output_presenter.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. import json
  2. import logging
  3. from constants import DEVICE_INVALID_MESSAGE
  4. logger = logging.getLogger(__name__)
  5. # Builds AI-safe MCP results for the explicitly supported tool set.
  6. class OutputPresenter:
  7. TABLE_TOOLS = frozenset((
  8. 'query_order_exact',
  9. 'query_track',
  10. 'query_customs_declaration_files',
  11. ))
  12. OPTION_TOOLS = frozenset((
  13. 'list_order_filter_options',
  14. 'list_pending_outbound_export_filter_options',
  15. ))
  16. EXPORT_TOOLS = frozenset((
  17. 'export_pending_outbound_orders',
  18. 'export_out_of_province_port_data',
  19. ))
  20. SAFE_TOOLS = TABLE_TOOLS | OPTION_TOOLS | EXPORT_TOOLS
  21. TABLE_COLUMNS = {
  22. 'query_order_exact': {
  23. 'order_number': ('订单号',),
  24. 'reference_number': ('客户参考号',),
  25. 'status_txt_name': ('状态',),
  26. 'check_status_txt_name': ('是否已查验',),
  27. 'customer_name': ('客户名称',),
  28. 'customer_account_type_name': ('客户属性',),
  29. 'inbound_date': ('入库时间',),
  30. 'wo_num': ('未完成工单',),
  31. 'product_name': ('物流产品',),
  32. 'inbound_pieces': ('件数',),
  33. 'inbound_volume': ('体积(CBM)',),
  34. 'inbound_weight': ('重量(KG)',),
  35. 'pro_cn_name': ('品名',),
  36. 'export_declaration_type': ('报关方式',),
  37. 'merge_declare_number': ('合并报关单号',),
  38. 'delivery_address': ('派送地址',),
  39. 'container_code': ('柜号',),
  40. 'out_status_txt': ('排舱单状态',),
  41. 'hinge_of_destination': ('目的港',),
  42. 'etd': ('ETD',),
  43. 'atd': ('ATD',),
  44. 'eta': ('ETA',),
  45. 'ata': ('ATA',),
  46. 'release_time': ('清关放行时间',),
  47. 'oversea_inbound_date': ('海外入库时间',),
  48. 'appt_time': ('APPT时间',),
  49. 'est_loading_time': ('预计装柜时间',),
  50. 'pickup_time': ('海外提柜时间',),
  51. 'delivery_way_title': ('派送方式',),
  52. 'tracking_number': ('快递单号', '承运商跟踪号码'),
  53. 'shipment_id': ('Shipment ID',),
  54. 'goods_attribute': ('商品属性',),
  55. 'sku': ('SKU',),
  56. 'sales_user': ('商务经理',),
  57. 'service_user': ('客户经理',),
  58. 'department_name': ('事业部',),
  59. 'remark': ('订单备注',),
  60. 'importer_name': ('进口商',),
  61. 'warehouse_name': ('交货仓库',),
  62. 'paid_status_name': ('付款状态',),
  63. },
  64. 'query_track': {
  65. 'status': ('轨迹节点', '轨迹状态,如:开始集港、离港放行、清关、配送等'),
  66. 'location': ('轨迹地点', '发生地点'),
  67. 'time': ('时间', '轨迹发生时间(已转换为用户时区)'),
  68. 'content': ('轨迹内容', '详细描述'),
  69. 'tracking_number': ('跟踪号', '快递单号'),
  70. 'shipment_id': ('Shipment ID', '包裹ID'),
  71. },
  72. 'query_customs_declaration_files': {
  73. 'outbound_number': ('排舱单号',),
  74. 'order_number': ('订单号',),
  75. 'file_name': ('文件名',),
  76. 'file_type': ('文件类型',),
  77. 'file_url': ('文件链接',),
  78. },
  79. }
  80. FIELD_LABELS = {
  81. 'query_order_exact': {
  82. 'order_number': '订单号',
  83. 'order_numbers': '订单号',
  84. 'reference_number': '客户参考号',
  85. 'reference_numbers': '客户参考号',
  86. 'tracking_number': '快递单号',
  87. 'tracking_numbers': '快递单号',
  88. 'outbound_number': '排舱单号',
  89. 'outbound_numbers': '排舱单号',
  90. 'container_code': '柜号',
  91. 'container_codes': '柜号',
  92. 'so_number': 'SO号',
  93. 'so_numbers': 'SO号',
  94. 'shipment_id': 'Shipment ID',
  95. 'receiver_country': '收货国家',
  96. 'product_ids': '物流产品',
  97. 'customer_ids': '客户',
  98. 'sales_id': '销售人员',
  99. 'warehouse_ids': '仓库',
  100. 'department_id': '事业部',
  101. 'inbound_date_start': '入库开始日期',
  102. 'inbound_date_end': '入库结束日期',
  103. 'outbound_date_start': '出库开始日期',
  104. 'outbound_date_end': '出库结束日期',
  105. 'page': '页码',
  106. 'limit': '每页数量',
  107. },
  108. 'query_track': {
  109. 'order_id': '订单ID',
  110. 'order_number': '订单号',
  111. 'tracking_number': '快递单号',
  112. 'page': '页码',
  113. 'limit': '每页数量',
  114. },
  115. 'query_customs_declaration_files': {
  116. 'outbound_numbers': '排舱单号',
  117. 'order_numbers': '订单号',
  118. 'page': '页码',
  119. 'limit': '每页数量',
  120. },
  121. 'list_order_filter_options': {
  122. 'filter_type': '筛选项类型',
  123. 'keyword': '关键词',
  124. 'page': '页码',
  125. 'limit': '每页数量',
  126. },
  127. 'list_pending_outbound_export_filter_options': {
  128. 'filter_type': '筛选项类型',
  129. 'product_type_id': '产品分类',
  130. 'keyword': '关键词',
  131. 'page': '页码',
  132. 'limit': '每页数量',
  133. },
  134. 'export_pending_outbound_orders': {
  135. 'number': '单号',
  136. 'product_type_id': '产品分类',
  137. 'product_id': '物流产品',
  138. 'order_warehouse_id': '集货仓库',
  139. 'receiver_country': '目的国',
  140. 'is_remove': '是否装柜剔除',
  141. 'address': '派送地址',
  142. 'inbound_date': '入库时间',
  143. 'status': '订单状态',
  144. 'merge_declare_number': '合并报关单号',
  145. 'importer_id': '进口商',
  146. 'packing_type': '货物类型',
  147. 'is_battery': '带电属性',
  148. 'is_magnetic': '带磁属性',
  149. 'is_wood': '带木属性',
  150. 'is_other': '其他商品属性',
  151. 'is_fda': 'FDA产品属性',
  152. 'is_toy': '玩具属性',
  153. 'is_ultra_limit': '超长超重属性',
  154. 'is_sensitive': '敏感货属性',
  155. 'is_food': '食品属性',
  156. 'no_property': '无属性',
  157. },
  158. 'export_out_of_province_port_data': {
  159. 'outbound_numbers': '排舱单号',
  160. 'container_codes': '柜号',
  161. 'bl_numbers': '提单号',
  162. 'so_numbers': 'SO号',
  163. 'file_type': '资料类型',
  164. },
  165. }
  166. ERROR_MESSAGES = {
  167. 'MCP_1101': '设备配置已失效,请重新生成配置',
  168. 'MCP_1102': '设备会话已过期,请重新连接',
  169. 'MCP_1103': '员工账号不可用,请联系管理员',
  170. 'MCP_1104': '身份信息已失效,请重新登录或重新生成设备配置',
  171. 'MCP_1201': '工具当前不可用',
  172. 'MCP_1202': '工具当前不可用',
  173. 'MCP_1301': '没有权限使用此工具',
  174. 'MCP_1501': '目标数据不可用',
  175. 'MCP_1502': '结果过多,请缩小查询范围',
  176. 'MCP_1601': '没有可导出的数据',
  177. 'MCP_9001': '工具调用失败,请稍后重试',
  178. }
  179. NON_RETRYABLE_CODES = frozenset((
  180. 'MCP_1101',
  181. 'MCP_1102',
  182. 'MCP_1103',
  183. 'MCP_1104',
  184. 'MCP_1201',
  185. 'MCP_1202',
  186. 'MCP_1301',
  187. 'MCP_1401',
  188. 'MCP_1501',
  189. 'MCP_1502',
  190. 'MCP_1601',
  191. ))
  192. def handles(self, tool_name):
  193. return isinstance(tool_name, str) and tool_name in self.SAFE_TOOLS
  194. # Convert a backend envelope into text and structured display data.
  195. def present(self, tool_name, tool_result):
  196. if not self.handles(tool_name) or not isinstance(tool_result, dict):
  197. return self._format_error()
  198. code = str(tool_result.get('code') or '').strip()
  199. meta = self._build_meta(tool_result.get('meta'))
  200. if code not in ('MCP_0000', '0'):
  201. return self._business_error(
  202. tool_name,
  203. code or 'MCP_9001',
  204. tool_result.get('msg'),
  205. meta,
  206. )
  207. data = tool_result.get('data')
  208. if not isinstance(data, dict):
  209. return self._format_error(meta)
  210. if tool_name in self.TABLE_TOOLS:
  211. return self._present_table(
  212. tool_name,
  213. data,
  214. tool_result.get('meta'),
  215. meta,
  216. )
  217. if tool_name in self.OPTION_TOOLS:
  218. return self._present_options(data, tool_result.get('meta'), meta)
  219. return self._present_export(data, meta)
  220. # Map local tool exceptions without exposing internal error details.
  221. def present_exception(self, tool_name, exception):
  222. if not self.handles(tool_name):
  223. return self._format_error()
  224. message = str(exception or '').strip()
  225. if isinstance(exception, ValueError):
  226. label = self._find_field_label(tool_name, message)
  227. return self._error_result(
  228. 'MCP_1401',
  229. self._parameter_message(label),
  230. False,
  231. )
  232. if message == DEVICE_INVALID_MESSAGE:
  233. return self._error_result('MCP_1101', DEVICE_INVALID_MESSAGE, False)
  234. if message.lower().startswith('tool disabled'):
  235. return self._error_result('MCP_1202', '工具当前不可用', False)
  236. return self._error_result(
  237. 'MCP_9001',
  238. '工具调用失败,请稍后重试',
  239. True,
  240. )
  241. def _present_table(self, tool_name, data, raw_meta, meta):
  242. columns = data.get('columns')
  243. records = data.get('records')
  244. if not isinstance(columns, list) or not columns or not isinstance(records, list):
  245. return self._format_error(meta)
  246. allowed_columns = self.TABLE_COLUMNS.get(tool_name)
  247. if not isinstance(allowed_columns, dict):
  248. return self._format_error(meta)
  249. headers = []
  250. keys = []
  251. for column in columns:
  252. if not isinstance(column, dict):
  253. return self._format_error(meta)
  254. key = column.get('key')
  255. label = column.get('name')
  256. if not isinstance(key, str) or not key.strip():
  257. return self._format_error(meta)
  258. if not isinstance(label, str) or not label.strip():
  259. return self._format_error(meta)
  260. key = key.strip()
  261. definition = allowed_columns.get(key)
  262. if not isinstance(definition, tuple) or not definition:
  263. return self._format_error(meta)
  264. keys.append(key)
  265. header = {'label': definition[0]}
  266. if len(definition) > 1:
  267. header['description'] = definition[1]
  268. headers.append(header)
  269. rows = []
  270. for record in records:
  271. if not isinstance(record, dict):
  272. return self._format_error(meta)
  273. rows.append([
  274. '' if record.get(key) is None else record.get(key, '')
  275. for key in keys
  276. ])
  277. content = {
  278. 'summary': self._safe_text(data.get('summary')),
  279. 'headers': headers,
  280. 'rows': rows,
  281. }
  282. tips = self._safe_tips(data.get('tips'))
  283. if tips:
  284. content['tips'] = tips
  285. pagination = self._build_pagination(raw_meta)
  286. if pagination:
  287. content['pagination'] = pagination
  288. return self._success_result(content, self._render_table(content), meta)
  289. def _present_options(self, data, raw_meta, meta):
  290. records = data.get('records')
  291. if not isinstance(records, list):
  292. return self._format_error(meta)
  293. rows = []
  294. for record in records:
  295. if not isinstance(record, dict):
  296. return self._format_error(meta)
  297. rows.append([
  298. record.get('value', ''),
  299. self._safe_text(record.get('label')),
  300. self._safe_text(record.get('code')),
  301. ])
  302. content = {
  303. 'headers': [
  304. {'label': '可传值'},
  305. {'label': '显示名称'},
  306. {'label': '业务编码'},
  307. ],
  308. 'rows': rows,
  309. }
  310. pagination = self._build_pagination(raw_meta)
  311. if pagination:
  312. content['pagination'] = pagination
  313. return self._success_result(content, self._render_table(content), meta)
  314. def _present_export(self, data, meta):
  315. url = data.get('file_url')
  316. if not isinstance(url, str) or not url.strip():
  317. return self._format_error(meta)
  318. content = {
  319. 'message': '文件已生成',
  320. 'files': [{'label': '导出文件', 'url': url.strip()}],
  321. }
  322. text = '文件已生成\n- 导出文件: {0}'.format(url.strip())
  323. return self._success_result(content, text, meta)
  324. def _business_error(self, tool_name, code, raw_message, meta):
  325. if code not in self.ERROR_MESSAGES and code != 'MCP_1401':
  326. logger.warning(
  327. 'Unknown MCP business error code',
  328. extra={
  329. 'request_id': meta.get('request_id', ''),
  330. 'tool_code': tool_name,
  331. 'backend_code': code,
  332. 'response_code': 'MCP_9001',
  333. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  334. },
  335. )
  336. code = 'MCP_9001'
  337. if code == 'MCP_1401':
  338. label = self._find_field_label(tool_name, raw_message)
  339. message = self._parameter_message(label)
  340. else:
  341. message = self.ERROR_MESSAGES[code]
  342. retryable = code not in self.NON_RETRYABLE_CODES
  343. return self._error_result(code, message, retryable, meta)
  344. def _find_field_label(self, tool_name, raw_message):
  345. message = str(raw_message or '')
  346. fields = self.FIELD_LABELS.get(tool_name, {})
  347. for field in sorted(fields, key=len, reverse=True):
  348. if field in message:
  349. return fields[field]
  350. return ''
  351. @staticmethod
  352. def _parameter_message(label):
  353. return '{0}参数不正确'.format(label) if label else '工具参数不正确,请检查后重试'
  354. @staticmethod
  355. def _build_meta(raw_meta):
  356. if not isinstance(raw_meta, dict):
  357. return {}
  358. request_id = raw_meta.get('request_id')
  359. if not isinstance(request_id, str) or not request_id.strip():
  360. return {}
  361. return {'request_id': request_id.strip()}
  362. @staticmethod
  363. def _build_pagination(raw_meta):
  364. if not isinstance(raw_meta, dict):
  365. return {}
  366. return {
  367. key: raw_meta[key]
  368. for key in ('page', 'limit', 'has_more', 'total')
  369. if key in raw_meta
  370. }
  371. @staticmethod
  372. def _safe_text(value):
  373. if value is None:
  374. return ''
  375. return str(value).strip()
  376. @classmethod
  377. def _safe_tips(cls, value):
  378. if not isinstance(value, list):
  379. return []
  380. return [cls._safe_text(item) for item in value if cls._safe_text(item)]
  381. @classmethod
  382. def _render_table(cls, content):
  383. headers = content.get('headers') or []
  384. rows = content.get('rows') or []
  385. lines = []
  386. summary = cls._safe_text(content.get('summary'))
  387. if summary:
  388. lines.append(summary)
  389. lines.append('表头共 {0} 列:'.format(len(headers)))
  390. for index, header in enumerate(headers, start=1):
  391. lines.append('{0}. {1}'.format(index, header['label']))
  392. for index, row in enumerate(rows, start=1):
  393. lines.append('记录 {0}:'.format(index))
  394. for header, value in zip(headers, row):
  395. if isinstance(value, (dict, list)):
  396. value = json.dumps(value, ensure_ascii=False)
  397. lines.append('- {0}: {1}'.format(header['label'], value))
  398. tips = content.get('tips') or []
  399. if tips:
  400. lines.append('提示:{0}'.format(';'.join(tips)))
  401. return '\n'.join(lines)
  402. @staticmethod
  403. def _success_result(content, text, meta):
  404. return {
  405. 'structured_content': content,
  406. 'text': text,
  407. 'is_error': False,
  408. 'meta': meta,
  409. }
  410. @staticmethod
  411. def _error_result(code, message, retryable, meta=None):
  412. return {
  413. 'structured_content': {
  414. 'code': code,
  415. 'message': message,
  416. 'retryable': retryable,
  417. },
  418. 'text': '{0}: {1}'.format(code, message),
  419. 'is_error': True,
  420. 'meta': meta or {},
  421. }
  422. @classmethod
  423. def _format_error(cls, meta=None):
  424. return cls._error_result(
  425. 'MCP_9001',
  426. '工具返回格式异常',
  427. True,
  428. meta,
  429. )