Skip to content

Build and run agents you can see, understand and trust.

fix(rag): keep text inside nested Word tables (#2759)

ydflow9222291acff8
diff --git a/src/agentscope/rag/_parser/_word.py b/src/agentscope/rag/_parser/_word.py
index de1f05e3c..33bbece37 100644
--- a/src/agentscope/rag/_parser/_word.py
+++ b/src/agentscope/rag/_parser/_word.py
@@ -90,7 +90,8 @@ def _extract_table_data(table: DocxTable) -> list[list[str]]:
row_data: list[str] = []
for tc in tr.findall(qn("w:tc")):
paragraphs: list[str] = []
- for p_elem in tc.findall(qn("w:p")):
+ # Include paragraphs of tables nested in this cell.
+ for p_elem in tc.xpath("./w:p | ./w:tbl//w:tc/w:p"):
text_parts: list[str] = []
for element in p_elem.iter():
if element.tag == text_tag and element.text:
diff --git a/tests/rag_parser_test.py b/tests/rag_parser_test.py
index 9ef6b81c5..4684e0cb2 100644
--- a/tests/rag_parser_test.py
+++ b/tests/rag_parser_test.py
@@ -248,6 +248,31 @@ def _make_docx_with_table() -> bytes:
return buffer.getvalue()
+def _make_docx_with_nested_table() -> bytes:
+ """Build a DOCX whose outer table cell contains a nested table.
+
+ A nested ``w:tbl`` lives inside the outer ``w:tc``, so its paragraphs are
+ not direct children of that cell.
+ """
+ from docx import Document as DocxDocument
+
+ doc = DocxDocument()
+ doc.add_paragraph("Before table")
+
+ outer = doc.add_table(rows=1, cols=1)
+ outer_cell = outer.cell(0, 0)
+ outer_cell.text = "Outer cell"
+
+ nested = outer_cell.add_table(rows=1, cols=1)
+ nested.cell(0, 0).text = "Nested cell"
+
+ doc.add_paragraph("After table")
+
+ buffer = io.BytesIO()
+ doc.save(buffer)
+ return buffer.getvalue()
+
+
def _make_docx_with_special_table_cells() -> bytes:
"""Build a DOCX table with pipes and a multi-line cell."""
from docx import Document as DocxDocument
@@ -1556,6 +1581,32 @@ class WordParserTest(IsolatedAsyncioTestCase):
],
)
+ async def test_nested_table_text_is_kept(self) -> None:
+ """Text inside a table nested in another cell must survive parsing."""
+ docx_bytes = _make_docx_with_nested_table()
+ parser = WordParser(include_image=False, separate_table=False)
+ sections = await parser.parse(docx_bytes, "nested.docx")
+
+ self.assertListEqual(
+ [section.model_dump() for section in sections],
+ [
+ {
+ "content": {
+ "type": "text",
+ "text": "Before table\n"
+ "| Outer cell<br>Nested cell |\n"
+ "| --- |\n\n"
+ "After table",
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ "source": "nested.docx",
+ "metadata": {},
+ },
+ ],
+ )
+
async def test_table_separated(self) -> None:
"""``separate_table=True`` isolates the table from surrounding
paragraphs."""