"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(grounding): bind document percentages to explicit source units
Haozhe Wue7c550567f21
diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.pyindex 0d22297f8..2652ce5ba 100644--- a/agent/src/agent/grounding/evidence.py+++ b/agent/src/agent/grounding/evidence.py@@ -709,6 +709,51 @@ def _is_price_kind(record: EvidenceRecord) -> bool:)+_PERCENT_HEADER = re.compile(r"(?:^[%%]$|[((]\s*[%%]\s*[))]$)")+_NUMERIC_CELL = re.compile(r"[+−-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?")+++def _document_percent_cells(text: str) -> str:+ """Attach an explicit column unit to numeric cells before evidence scanning.++ A PDF reader may flatten a table to whitespace. Only carry its header+ across contiguous, equal-width numeric rows with a leading row label.+ Preserve empty cells in delimited tables and reset on any ambiguous row.+ """+ if "%" not in text and "%" not in text:+ return text+ lines = text.splitlines(keepends=True)+ columns: tuple[int, ...] = ()+ layout = ("", 0)+ for i, line in enumerate(lines):+ row = line.rstrip("\r\n").strip(" ")+ sep = "|" if "|" in row else "\t" if "\t" in row else ""+ if sep == "|":+ row = row.removeprefix("|").removesuffix("|")+ if not sep:+ row = row.strip()+ delimiter = re.escape(sep) if sep else r"\s+"+ parts = re.split(f"({delimiter})", row)+ cells = [part.strip() for part in parts[::2]]+ shape = (sep, len(cells))+ if columns and shape == layout:+ if sep == "|" and all(re.fullmatch(r":?-{2,}:?", c) for c in cells):+ continue+ if cells[0] and all(_NUMERIC_CELL.fullmatch(c) or c in {"", "—", "-"} for c in cells[1:]):+ # Odd parts are the original delimiters.+ for col in columns:+ pos = 2 * col+ if _NUMERIC_CELL.fullmatch(parts[pos].strip()):+ parts[pos] = parts[pos].rstrip() + "%"+ lines[i] = line.replace(row, "".join(parts), 1)+ continue+ columns = tuple(j for j, c in enumerate(cells) if j and _PERCENT_HEADER.search(c))+ if any(_NUMERIC_CELL.fullmatch(c) for c in cells):+ columns = ()+ layout = shape+ return "".join(lines)++def _document_field(figure: Figure) -> str:"""The evidence field a document's figure is recorded under.@@ -1558,6 +1603,7 @@ class _EvidenceMixin:if room <= 0:returnseen: set[tuple[float, bool, str | None]] = set()+ text = _document_percent_cells(text)for figure in scan_figures(text, parse_figures_block(text)):if room <= 0:returndiff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.pyindex 4d76c1916..cf4b25bdc 100644--- a/agent/src/agent/grounding/policies.py+++ b/agent/src/agent/grounding/policies.py@@ -547,6 +547,19 @@ class _PolicyMixin:declaration = block.match(figure.value, figure.percent, figure.digits, figure.point_marked)+ if declaration is None and figure.percent:+ # A bare observation can restate a percentage only if the+ # declaration's own source explicitly provided the unit.+ for item in block.declarations:+ if item.role != "observed" or item.percent or item.value != figure.value:+ continue+ scoped = self._referenced(item.ref, None, figure)+ if scoped and any(+ record.field == "document.ratio" and record.source == "document"+ and record.value == figure.value for record in scoped[0]+ ):+ declaration = item+ breaksymbol = self._figure_symbol(content,figure,diff --git a/agent/tests/test_grounding_document_figures.py b/agent/tests/test_grounding_document_figures.pyindex cf38c62fc..8ce295cd7 100644--- a/agent/tests/test_grounding_document_figures.py+++ b/agent/tests/test_grounding_document_figures.py@@ -77,6 +77,26 @@ def _declared(prose: str, *lines: str) -> str:return prose + "\n\n```figures\n" + "\n".join(lines) + "\n```"[email protected](("source", "valid"), [+ ("营业收入同比 +17.10%。", True),+ ("项目 金额 同比(%)\n营业收入 124.20 17.10", True),+ ("| 项目 | 金额 | 同比 (%) |\n|---|---|---|\n| 营业收入 | 124.20 | 17.10 |", True),+ ("| 项目 | 金额 | 同比 (%) |\n| 营业收入 | 17.10 | 9.36 |", False),+ ("项目 金额 同比(%)\n营业收入 17.10", False),+ ("成品平均重量为 17.10 千克。", False),+ ("营业收入 7,747,346,892 17.10 20,817,866,218 10.56", False),+])+def test_percent_declaration_needs_a_unit_in_its_own_document(tmp_path, source, valid):+ ledger, document = _ledger_with_upload(tmp_path)+ _read_document(ledger, document, "doc-1", source)+ _read_document(ledger, document.with_name("other.pdf"), "doc-2", "占比 17.10%。")+ for declaration in ("17.10", "17.10%"):+ result = ledger.validate_final_answer(_declared(+ "营收同比增长 +17.10%。", f"{declaration} | observed | 营收同比 | doc-1",+ ))+ assert result.valid is valid, result.issues++def test_a_document_figure_grounds_the_answer_that_quotes_it(tmp_path: Path) -> None:ledger, document = _ledger_with_upload(tmp_path)_read_document(ledger, document, "doc-1")