Skip to content

Feat: agentic search framework - #16859

Merged
yingfeng merged 13 commits into
infiniflow:mainfrom
KevinHuSh:feat/agentic_search1
Jul 15, 2026
Merged

yingfeng merged 13 commits into
infiniflow:mainfrom
KevinHuSh:feat/agentic_search1

Conversation

@KevinHuSh

@KevinHuSh KevinHuSh commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Agentic search

image

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 🌈 python Pull requests that update Python code 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 13, 2026
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change adds an agentic RAG harness with configurable retrieval tools, claim planning, sufficiency evaluation, citation-aware synthesis, and streamed graph execution. Chat completions now use rag_agent, while tool schemas support Google-style docs and per-tool timeouts.

Changes

Agentic RAG execution

Layer / File(s) Summary
Harness contracts and tool runtime
rag/advanced_rag/harness/types.py, rag/advanced_rag/harness/config.py, rag/advanced_rag/harness/tools/*, rag/llm/tool_decorator.py
Defines orchestration contracts, thinking modes, tool registration and gating, execution tracing, schema generation, and timeout overrides.
Retrieval capabilities and tool implementations
rag/advanced_rag/agentic_rag.py, rag/advanced_rag/harness/tools/*, rag/prompts/*, rag/utils/es_conn.py
Adds KB, web, structured, navigation, inspection, document-summary, keyword narrowing, evidence handling, and retrieval prompt capabilities.
Agentic orchestration and answer synthesis
rag/advanced_rag/agentic_rag_graph.py, rag/advanced_rag/harness/*, rag/advanced_rag/harness/prompts/*
Adds routing, planning, retrieval strategies, agent loops, sufficiency scoring, replanning, LangGraph execution, and streamed answer generation.
Chat completion integration
api/db/services/dialog_service.py, api/apps/restful_apis/chat_api.py, api/db/services/llm_service.py, rag/llm/chat_model.py
Routes completion paths through rag_agent, preserves SSE/JSON formatting, disables the previous research branch, and updates tool-call streaming behavior.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant chat_api
  participant rag_agent
  participant RAGTools
  participant AgenticGraph
  participant RetrievalTools
  participant ChatModel
  Client->>chat_api: submit completion request
  chat_api->>rag_agent: start response generation
  rag_agent->>RAGTools: initialize retrieval capabilities
  rag_agent->>AgenticGraph: run agentic workflow
  AgenticGraph->>RetrievalTools: execute routed retrieval tools
  RetrievalTools-->>AgenticGraph: return evidence and document aggregates
  AgenticGraph->>ChatModel: generate evidence-backed answer
  ChatModel-->>AgenticGraph: stream answer tokens
  AgenticGraph-->>rag_agent: answer and citation pool
  rag_agent-->>chat_api: formatted SSE or JSON response
  chat_api-->>Client: completion response
Loading

Possibly related PRs

Suggested reviewers: yuzhichang

Poem

A rabbit hops through tools and text,
Finds cited crumbs and checks what’s next.
Claims are planned, answers stream,
Evidence guides the rabbit’s dream.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The Summary section exists, but it is far too brief and lacks the required background and purpose details. Expand the Summary with the problem being solved, why it is needed, and a concise overview of the main changes.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly matches the main change: introducing an agentic search framework.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (2)
rag/advanced_rag/agentic_rag.py (1)

479-499: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add lifecycle logging around the new agentic-RAG entry point.

Log start, successful completion, and failure without recording the user’s question.

As per coding guidelines, “**/*.py: Add logging for new flows”.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 479 - 499, Add lifecycle
logging to the rag method around run_agentic_rag: log when processing starts,
when it completes successfully, and when it fails. Wrap the streaming execution
in appropriate exception handling, log failure details, and re-raise the
exception; do not include the question or other user-provided content in any log
entry.

Source: Coding guidelines

rag/llm/chat_model.py (1)

1928-1928: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Avoid dumping full history at INFO every round.

{history=} serializes the entire conversation (system prompt, user content, tool results) into the log on each tool-calling round, which is noisy and can leak user/PII content. Consider logging at debug and/or only the count/last message.

Proposed change
-                    logging.info(f"HAS TOOL:{len(self.tools)}\n{history=}")
+                    logging.info("HAS TOOL: %d; history_len=%d", len(self.tools), len(history))
+                    logging.debug("history=%s", history)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/llm/chat_model.py` at line 1928, Update the logging statement in the
tool-calling flow to avoid serializing the full history at INFO level. Use
debug-level logging and report only non-sensitive summary data such as the tool
count and history size or last-message metadata, without including conversation
contents.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/db/services/dialog_service.py`:
- Around line 718-719: Remove the disabled DeepResearcher branch beginning at
the `if False` condition, including its unreachable body and stale commented-out
condition. Collapse the corresponding `else` into the surrounding flow so only
the active non-reasoning behavior remains in the dialog service.
- Around line 1908-1913: Remove the unused run_agentic_rag import from the
surrounding dialog-service branch, and rewrite the adjacent comment to
accurately describe the bound-tools flow: the rag tool populates
rag_tools.kbinfos, after which decorate_answer processes the result rather than
streaming a direct agentic graph response.

In `@rag/advanced_rag/agentic_rag_graph.py`:
- Around line 441-445: Update the conditional-edge mapping in the graph
construction around route_sufficiency so the "select_documents" route targets
the select_documents node instead of retrieve, preserving the intended follow-up
path through query_keywords and document-scope normalization.

In `@rag/advanced_rag/agentic_rag.py`:
- Around line 448-467: Stop the outer pagination loop in the chunk retrieval
flow once adding a chunk would exceed self.chat_mdl.max_length. Track this
exhaustion condition from the inner loop and break the surrounding offset loop
after processing the current page, while preserving normal pagination when the
context budget remains available.
- Around line 200-218: Remove the unconditional return None at the start of
pick_documents so the existing kb_ids validation, metadata filtering via
_filter_by_metadata, and title selection via _select_by_titles execute and
return the derived document scope.
- Around line 542-549: The _collect_doc_titles method incorrectly returns None
when max_docs is reached, causing _select_by_titles to skip title selection.
Return the accumulated result immediately once the cap is reached, preserving
the collected documents and existing behavior for smaller catalogues.
- Around line 501-514: Update the summarize_document tool declaration to use an
explicit timeout matching the realistic timeout configured for the rag tool,
while preserving its existing function behavior and signature.

In `@rag/llm/tool_decorator.py`:
- Around line 140-180: Update the reST field handling around _PARAM_RE so
non-parameter directives such as :returns: clear current_param before their
continuation can be processed. Preserve parameter parsing and continuation
behavior for actual :param: fields, while ensuring subsequent indented
non-parameter field text is not appended to the preceding parameter.

---

Nitpick comments:
In `@rag/advanced_rag/agentic_rag.py`:
- Around line 479-499: Add lifecycle logging to the rag method around
run_agentic_rag: log when processing starts, when it completes successfully, and
when it fails. Wrap the streaming execution in appropriate exception handling,
log failure details, and re-raise the exception; do not include the question or
other user-provided content in any log entry.

In `@rag/llm/chat_model.py`:
- Line 1928: Update the logging statement in the tool-calling flow to avoid
serializing the full history at INFO level. Use debug-level logging and report
only non-sensitive summary data such as the tool count and history size or
last-message metadata, without including conversation contents.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6b5efe67-516d-4836-afde-adc4b2be3318

📥 Commits

Reviewing files that changed from the base of the PR and between 2a482f3 and 21e1458.

📒 Files selected for processing (10)
  • api/apps/restful_apis/chat_api.py
  • api/db/services/dialog_service.py
  • api/db/services/llm_service.py
  • rag/advanced_rag/agentic_rag.py
  • rag/advanced_rag/agentic_rag_graph.py
  • rag/llm/chat_model.py
  • rag/llm/tool_decorator.py
  • rag/prompts/generator.py
  • rag/prompts/sufficiency_select.md
  • rag/utils/es_conn.py

Comment thread api/db/services/dialog_service.py Outdated
Comment on lines +718 to +719
# replaced by extension of reasoning: 0, 1, 2
if False: #prompt_config.get("reasoning", False) or kwargs.get("reasoning"):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Remove the disabled DeepResearcher branch instead of gating with if False.

if False: #prompt_config.get("reasoning", ...) disables the whole branch (lines ~720-754) as dead/commented-out code. Since deep research is being disabled in this PR, delete the branch and collapse the else rather than leaving a disabled shim.

As per coding guidelines: "Prefer deletion over compatibility shims, deprecated branches... Remove dead tests, commented-out code, stale documentation."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/db/services/dialog_service.py` around lines 718 - 719, Remove the
disabled DeepResearcher branch beginning at the `if False` condition, including
its unreachable body and stale commented-out condition. Collapse the
corresponding `else` into the surrounding flow so only the active non-reasoning
behavior remains in the dialog service.

Source: Coding guidelines

Comment thread api/db/services/dialog_service.py Resolved
Comment thread rag/advanced_rag/agentic_rag_graph.py Outdated
Comment on lines +441 to +445
g.add_conditional_edges(
"check_sufficiency",
route_sufficiency,
{"select_documents": "retrieve", "formalize_answer": "formalize_answer"},
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

sed -n '1,260p' rag/advanced_rag/agentic_rag_graph.py && printf '\n---CUT---\n' && sed -n '260,520p' rag/advanced_rag/agentic_rag_graph.py

Repository: infiniflow/ragflow

Length of output: 22306


🏁 Script executed:

ast-grep outline rag/advanced_rag/agentic_rag_graph.py --view expanded

Repository: infiniflow/ragflow

Length of output: 1182


🏁 Script executed:

python3 - <<'PY'
from pathlib import Path
import re

path = Path("rag/advanced_rag/agentic_rag_graph.py")
text = path.read_text()

for needle in [
    'active.append({"q": q, "keywords": f.get("query", []), "doc_scope": None})',
    'def route_sufficiency(state: AgenticState) -> str:',
    'nxt = "formalize_answer" if state.get("sufficient") else "select_documents"',
    '{"select_documents": "retrieve", "formalize_answer": "formalize_answer"}',
]:
    i = text.find(needle)
    print(f"\n--- {needle} ---")
    print(text[max(0, i-120): i+len(needle)+120])

# Minimal behavioral summary from the source
route = "select_documents"
mapped = {"select_documents": "retrieve", "formalize_answer": "formalize_answer"}[route]
print("\nroute_sufficiency(non-sufficient) =>", route)
print("conditional edge target =>", mapped)
print("follow-up initializer => keywords is f.get('query', []), doc_scope is None")
PY

Repository: infiniflow/ragflow

Length of output: 1868


Route non-sufficient results back through select_documents.

route_sufficiency() returns "select_documents", but the conditional edge maps that label to retrieve, so the follow-up loop bypasses both select_documents and query_keywords. That leaves generated follow-ups without doc_scope normalization and with keywords passed through as-is. Map "select_documents" to select_documents, or rename the router/log/docstring to match the direct jump.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag_graph.py` around lines 441 - 445, Update the
conditional-edge mapping in the graph construction around route_sufficiency so
the "select_documents" route targets the select_documents node instead of
retrieve, preserving the intended follow-up path through query_keywords and
document-scope normalization.

Comment on lines +200 to +218
async def pick_documents(self, question: str) -> List[str] | None:
"""Narrow the search to a document subset for ``question``.

Uses document metadata when the bound KBs carry any (mirrors the old
``filter_docs_by_metadata``); otherwise asks an LLM to pick relevant
titles (mirrors the old ``select_documents``). Returns ``None`` when
no useful scope can be derived, meaning "search everything".
"""
return None
if not self.kb_ids:
return None

metas = await self._get_cached_metas()
if metas:
ids = await self._filter_by_metadata(question, metas)
return ids or None

ids = await self._select_by_titles(question)
return ids or None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Remove the unconditional return that disables document scoping.

Line 208 makes all metadata and title-based selection unreachable, so every retrieval searches the full bound KB set.

Proposed fix
-        return None
         if not self.kb_ids:
             return None

As per coding guidelines, remove dead branches and converge on the current implementation path.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async def pick_documents(self, question: str) -> List[str] | None:
"""Narrow the search to a document subset for ``question``.
Uses document metadata when the bound KBs carry any (mirrors the old
``filter_docs_by_metadata``); otherwise asks an LLM to pick relevant
titles (mirrors the old ``select_documents``). Returns ``None`` when
no useful scope can be derived, meaning "search everything".
"""
return None
if not self.kb_ids:
return None
metas = await self._get_cached_metas()
if metas:
ids = await self._filter_by_metadata(question, metas)
return ids or None
ids = await self._select_by_titles(question)
return ids or None
async def pick_documents(self, question: str) -> List[str] | None:
"""Narrow the search to a document subset for ``question``.
Uses document metadata when the bound KBs carry any (mirrors the old
``filter_docs_by_metadata``); otherwise asks an LLM to pick relevant
titles (mirrors the old ``select_documents``). Returns ``None`` when
no useful scope can be derived, meaning "search everything".
"""
if not self.kb_ids:
return None
metas = await self._get_cached_metas()
if metas:
ids = await self._filter_by_metadata(question, metas)
return ids or None
ids = await self._select_by_titles(question)
return ids or None
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 200 - 218, Remove the
unconditional return None at the start of pick_documents so the existing kb_ids
validation, metadata filtering via _filter_by_metadata, and title selection via
_select_by_titles execute and return the derived document scope.

Source: Coding guidelines

Comment on lines +448 to +467
for offset in range(0, 10000, 128):
chunks = await thread_pool_exec(
settings.retriever.chunk_list,
doc_id,
tenant_id,
[kb_id],
max_count=offset + 128,
offset=offset,
fields=["content_with_weight", "docnm_kwd", "doc_id"],
sort_by_position=True,
retrieve_all=False,
)
if not chunks:
break
for ck in chunks:
num = num_tokens_from_string(str(ck["content_with_weight"]))
if tokens + num > self.chat_mdl.max_length:
break
tokens += num
cks.append(ck)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Stop pagination once the context budget is exhausted.

Breaking only the inner loop causes subsequent pages to be fetched even though their content generally cannot fit, increasing latency and making summary timeouts more likely.

Proposed fix
         cks = []
         tokens = 0
+        budget_exhausted = False
         for offset in range(0, 10000, 128):
             chunks = await thread_pool_exec(
                 ...
             )
             if not chunks:
                 break
             for ck in chunks:
                 num = num_tokens_from_string(str(ck["content_with_weight"]))
                 if tokens + num > self.chat_mdl.max_length:
+                    budget_exhausted = True
                     break
                 tokens += num
                 cks.append(ck)
+            if budget_exhausted:
+                break
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for offset in range(0, 10000, 128):
chunks = await thread_pool_exec(
settings.retriever.chunk_list,
doc_id,
tenant_id,
[kb_id],
max_count=offset + 128,
offset=offset,
fields=["content_with_weight", "docnm_kwd", "doc_id"],
sort_by_position=True,
retrieve_all=False,
)
if not chunks:
break
for ck in chunks:
num = num_tokens_from_string(str(ck["content_with_weight"]))
if tokens + num > self.chat_mdl.max_length:
break
tokens += num
cks.append(ck)
cks = []
tokens = 0
budget_exhausted = False
for offset in range(0, 10000, 128):
chunks = await thread_pool_exec(
settings.retriever.chunk_list,
doc_id,
tenant_id,
[kb_id],
max_count=offset + 128,
offset=offset,
fields=["content_with_weight", "docnm_kwd", "doc_id"],
sort_by_position=True,
retrieve_all=False,
)
if not chunks:
break
for ck in chunks:
num = num_tokens_from_string(str(ck["content_with_weight"]))
if tokens + num > self.chat_mdl.max_length:
budget_exhausted = True
break
tokens += num
cks.append(ck)
if budget_exhausted:
break
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 448 - 467, Stop the outer
pagination loop in the chunk retrieval flow once adding a chunk would exceed
self.chat_mdl.max_length. Track this exhaustion condition from the inner loop
and break the surrounding offset loop after processing the current page, while
preserving normal pagination when the context budget remains available.

Comment on lines +501 to +514
@tool
async def summarize_document(self, doc_id: str) -> list[str]:
"""Return a single document's content, position-ordered, ready to summarise.

Call ONLY for an explicit summary request about a specific document.
For general Q&A use the `rag` tool instead.

:param doc_id: a 32-character lowercase hex document ID that some
other tool returned in this turn. Never invent one.

:returns: formatted chunk blocks (document order) fitting the model's
context budget, prefixed with the citation rules to apply.
"""
kbinfos = await self.fetch_full_document(doc_id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Configure a realistic timeout for document summarization.

Bare @tool inherits the 10-second session default, but this flow may execute many sequential document-page queries before returning. Give it an explicit timeout like the rag tool.

-    `@tool`
+    `@tool`(timeout=180)
     async def summarize_document(self, doc_id: str) -> list[str]:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@tool
async def summarize_document(self, doc_id: str) -> list[str]:
"""Return a single document's content, position-ordered, ready to summarise.
Call ONLY for an explicit summary request about a specific document.
For general Q&A use the `rag` tool instead.
:param doc_id: a 32-character lowercase hex document ID that some
other tool returned in this turn. Never invent one.
:returns: formatted chunk blocks (document order) fitting the model's
context budget, prefixed with the citation rules to apply.
"""
kbinfos = await self.fetch_full_document(doc_id)
`@tool`(timeout=180)
async def summarize_document(self, doc_id: str) -> list[str]:
"""Return a single document's content, position-ordered, ready to summarise.
Call ONLY for an explicit summary request about a specific document.
For general Q&A use the `rag` tool instead.
:param doc_id: a 32-character lowercase hex document ID that some
other tool returned in this turn. Never invent one.
:returns: formatted chunk blocks (document order) fitting the model's
context budget, prefixed with the citation rules to apply.
"""
kbinfos = await self.fetch_full_document(doc_id)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 501 - 514, Update the
summarize_document tool declaration to use an explicit timeout matching the
realistic timeout configured for the rag tool, while preserving its existing
function behavior and signature.

Comment on lines +542 to +549
def _collect_doc_titles(self, max_docs: int = 512) -> list[tuple[str, str]] | None:
result: list[tuple[str, str]] = []
for kb_id in self.kb_ids:
for doc in DocumentService.query(kb_id=kb_id):
result.append((doc.id, doc.name))
if len(result) >= max_docs:
return None
return result

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Return the capped catalogue instead of discarding it.

When the 512th document is collected, this returns None; _select_by_titles then treats the KB as having no documents and skips title selection.

                 result.append((doc.id, doc.name))
                 if len(result) >= max_docs:
-                    return None
+                    return result
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _collect_doc_titles(self, max_docs: int = 512) -> list[tuple[str, str]] | None:
result: list[tuple[str, str]] = []
for kb_id in self.kb_ids:
for doc in DocumentService.query(kb_id=kb_id):
result.append((doc.id, doc.name))
if len(result) >= max_docs:
return None
return result
def _collect_doc_titles(self, max_docs: int = 512) -> list[tuple[str, str]] | None:
result: list[tuple[str, str]] = []
for kb_id in self.kb_ids:
for doc in DocumentService.query(kb_id=kb_id):
result.append((doc.id, doc.name))
if len(result) >= max_docs:
return result
return result
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 542 - 549, The
_collect_doc_titles method incorrectly returns None when max_docs is reached,
causing _select_by_titles to skip title selection. Return the accumulated result
immediately once the cap is reached, preserving the collected documents and
existing behavior for smaller catalogues.

Comment thread rag/llm/tool_decorator.py
Comment on lines +140 to +180
# reST :param: line — works in any state, resets it.
m = _PARAM_RE.match(line)
if m:
param_docs[m.group("name")] = m.group("desc")
elif not param_docs:
current_param = m.group("name")
current_indent = line_indent
param_docs[current_param] = m.group("desc").strip()
state = "rst_param"
after_first_param = True
continue

# Google section headers.
if _GOOGLE_ARGS_HDR_RE.match(stripped):
state = "google_args"
current_param = None
after_first_param = True
continue
if _GOOGLE_SECTION_HDR_RE.match(stripped):
state = "other_section"
current_param = None
after_first_param = True
continue

# Google `` name: desc`` entry inside an Args block.
if state == "google_args":
gm = _GOOGLE_PARAM_RE.match(line)
if gm:
current_param = gm.group("name")
current_indent = line_indent
param_docs[current_param] = gm.group("desc").strip()
continue

# Continuation line for the most recent reST or Google param.
if state in ("rst_param", "google_args") and current_param and stripped:
if line_indent > current_indent:
_append_continuation(current_param, stripped)
continue

# Blank line ends the current param's continuation but stays in-state.
if not stripped:
current_param = None
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Clear the active parameter when leaving a reST field.

A directive such as :returns: does not reset current_param. Its indented continuation can therefore be appended to the preceding parameter description.

Proposed fix
         if state in ("rst_param", "google_args") and current_param and stripped:
             if line_indent > current_indent:
                 _append_continuation(current_param, stripped)
                 continue
+            current_param = None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# reST :param: line — works in any state, resets it.
m = _PARAM_RE.match(line)
if m:
param_docs[m.group("name")] = m.group("desc")
elif not param_docs:
current_param = m.group("name")
current_indent = line_indent
param_docs[current_param] = m.group("desc").strip()
state = "rst_param"
after_first_param = True
continue
# Google section headers.
if _GOOGLE_ARGS_HDR_RE.match(stripped):
state = "google_args"
current_param = None
after_first_param = True
continue
if _GOOGLE_SECTION_HDR_RE.match(stripped):
state = "other_section"
current_param = None
after_first_param = True
continue
# Google `` name: desc`` entry inside an Args block.
if state == "google_args":
gm = _GOOGLE_PARAM_RE.match(line)
if gm:
current_param = gm.group("name")
current_indent = line_indent
param_docs[current_param] = gm.group("desc").strip()
continue
# Continuation line for the most recent reST or Google param.
if state in ("rst_param", "google_args") and current_param and stripped:
if line_indent > current_indent:
_append_continuation(current_param, stripped)
continue
# Blank line ends the current param's continuation but stays in-state.
if not stripped:
current_param = None
continue
# Continuation line for the most recent reST or Google param.
if state in ("rst_param", "google_args") and current_param and stripped:
if line_indent > current_indent:
_append_continuation(current_param, stripped)
continue
current_param = None
# Blank line ends the current param's continuation but stays in-state.
if not stripped:
current_param = None
continue
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/llm/tool_decorator.py` around lines 140 - 180, Update the reST field
handling around _PARAM_RE so non-parameter directives such as :returns: clear
current_param before their continuation can be processed. Preserve parameter
parsing and continuation behavior for actual :param: fields, while ensuring
subsequent indented non-parameter field text is not appended to the preceding
parameter.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 13

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
rag/advanced_rag/agentic_rag.py (1)

550-557: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

_collect_doc_titles still discards the capped catalogue.

Line 556 returns None when max_docs is reached, causing _select_by_titles to treat the KB as having no documents. This was flagged in a previous review and remains unresolved.

🐛 Proposed fix
                 result.append((doc.id, doc.name))
                 if len(result) >= max_docs:
-                    return None
+                    return result
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 550 - 557, Update
_collect_doc_titles so reaching max_docs returns the accumulated result rather
than None. Preserve the existing catalogue entries and return result immediately
at the cap, while retaining the normal result return when fewer documents are
found.
♻️ Duplicate comments (3)
rag/advanced_rag/agentic_rag.py (3)

457-478: 🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Pagination still continues after context budget is exhausted.

The inner break at line 476 only exits the for ck in chunks loop; the outer for offset loop keeps fetching pages even though no more content can fit. This was flagged in a previous review and remains unresolved.

🚀 Proposed fix
         cks = []
         tokens = 0
+        budget_exhausted = False
         for offset in range(0, 10000, 128):
             chunks = await thread_pool_exec(
                 ...
             )
             if not chunks:
                 break
             for ck in chunks:
                 num = num_tokens_from_string(str(ck["content_with_weight"]))
                 if tokens + num > self.chat_mdl.max_length:
+                    budget_exhausted = True
                     break
                 tokens += num
                 cks.append(ck)
+            if budget_exhausted:
+                break
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 457 - 478, Update the
pagination logic surrounding the inner ck loop so exhausting
self.chat_mdl.max_length also terminates the outer offset loop. Track whether
the token budget was reached, then stop fetching additional pages while
preserving collection of all fitting chunks.

211-229: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Unconditional return None still disables document scoping.

Line 219 returns None unconditionally, making lines 220–229 (metadata filtering and title selection) unreachable. This was flagged in a previous review and remains unresolved.

🐛 Proposed fix
     return None
-        if not self.kb_ids:
-            return None
-
-        metas = await self._get_cached_metas()
-        if metas:
-            ids = await self._filter_by_metadata(question, metas)
-            return ids or None
-
-        ids = await self._select_by_titles(question)
-        return ids or None
+        if not self.kb_ids:
+            return None
+
+        metas = await self._get_cached_metas()
+        if metas:
+            ids = await self._filter_by_metadata(question, metas)
+            return ids or None
+
+        ids = await self._select_by_titles(question)
+        return ids or None
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 211 - 229, Remove the
unconditional return None at the start of pick_documents so document scoping
executes. Preserve the existing flow: return None when kb_ids is empty, use
_filter_by_metadata when cached metadata exists, otherwise use
_select_by_titles, and return None only when those strategies produce no IDs.

512-513: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

summarize_document still lacks an explicit timeout.

Bare @tool inherits the 10-second session default, but this flow may execute many sequential document-page queries. The rag tool uses @tool(timeout=180). This was flagged in a previous review and remains unresolved.

🩺 Proposed fix
-    `@tool`
+    `@tool`(timeout=180)
     async def summarize_document(self, doc_id: str) -> list[str]:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 512 - 513, Update the
summarize_document method’s tool declaration to use an explicit 180-second
timeout, matching the rag tool’s configured timeout, while preserving its
existing async behavior and signature.
🧹 Nitpick comments (4)
rag/advanced_rag/harness/planner.py (1)

65-67: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

prompt.split("输出格式", 1) couples planner to prompt wording.

The system/user message split relies on the literal string "输出格式" appearing in every decompose prompt. If a prompt omits or renames this marker, split returns a single-element list and unpacking raises ValueError, silently falling back to a direct plan. Consider defining system and user sections as separate constants or using a structured delimiter.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/planner.py` around lines 65 - 67, Decouple planner
message construction from the literal “输出格式” marker in the prompt-splitting
logic. Update the planner’s prompt handling around the system/user assignment to
use separately defined system and user sections or a structured delimiter,
ensuring prompts without that wording do not raise ValueError or trigger
direct-plan fallback.
rag/advanced_rag/harness/types.py (1)

161-162: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

record_fallback is a no-op — implement or remove.

A method body of just pass gives the false impression of functionality. Per coding guidelines, dead code and stale stubs should be removed. If fallback tracking is needed, implement it with logging for observability.

♻️ Proposed fix — implement with logging or remove

Option A: Implement with logging (recommended for observability)

 def record_fallback(self, tool_name: str, fallback_from: str | None = None):
-    pass
+    import logging
+    _log = logging.getLogger(__name__)
+    _log.info("fallback: tool=%s from=%s", tool_name, fallback_from or "unknown")
+    self.history.append({"event": "fallback", "tool": tool_name, "from": fallback_from})

Option B: Remove entirely if unused

-    def record_fallback(self, tool_name: str, fallback_from: str | None = None):
-        pass
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/types.py` around lines 161 - 162, Resolve the no-op
record_fallback method in the relevant class: if fallback tracking is used,
implement it with appropriate logging that includes tool_name and fallback_from;
otherwise remove the method and update any callers or references. Do not leave
the pass-only stub in place.

Source: Coding guidelines

rag/advanced_rag/__init__.py (1)

22-31: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Sort __all__ to satisfy Ruff RUF022.

Ruff flags the __all__ list as unsorted. Apply isort-style sorting.

♻️ Proposed fix
 __all__ = [
+    "ClaimTarget",
     "DeepResearcher",
-    "THINKING_MODES",
-    "get_mode",
-    "RouteDecision",
     "ExecutionStrategy",
-    "ClaimTarget",
-    "WorkflowPlan",
+    "RouteDecision",
     "SufficiencyVerdict",
+    "THINKING_MODES",
+    "WorkflowPlan",
+    "get_mode",
 ]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/__init__.py` around lines 22 - 31, Sort the __all__ entries
in rag/advanced_rag/__init__.py using isort-style ordering to satisfy Ruff
RUF022, while preserving all existing exported symbols.

Source: Linters/SAST tools

rag/advanced_rag/harness/tools/exploration.py (1)

8-30: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Placeholder tools delegate to hybrid_search — consider implementing or removing from the active tool surface.

Both graph_explore and wiki_query are TODO placeholders that delegate to hybrid_search. Since they're registered in TOOL_REGISTRY and referenced in gating.py SEARCH_PHASES, the LLM may select them expecting graph/wiki-specific retrieval but gets generic hybrid search instead, which could mislead the agent's search strategy.

Would you like me to help implement the actual KG walk and wiki lookup, or should these be removed from the registry until ready?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/exploration.py` around lines 8 - 30, Remove
graph_explore and wiki_query from the active tool surface until their
graph-specific and wiki-specific implementations are available. Update
TOOL_REGISTRY and the SEARCH_PHASES references in gating.py, and remove or
disable the placeholder functions so they cannot be selected while delegating to
generic hybrid_search.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rag/advanced_rag/agentic_rag_graph.py`:
- Around line 168-190: Update formalize_answer to read chunks safely with
kbinfos.get("chunks", []) wherever kbinfos["chunks"] is accessed, including the
logging count and empty-result condition, while preserving the existing fallback
behavior.

In `@rag/advanced_rag/harness/agent.py`:
- Around line 137-141: Guard the fallback loop in the priority-based tool
selection flow so it runs only when tool_name is found in priority. When
current_idx is -1, skip fallback entirely; preserve the existing behavior of
iterating priority[current_idx + 1:] for recognized tools.

In `@rag/advanced_rag/harness/orchestrator/agentic.py`:
- Around line 141-146: Remove the unused evidence-collection loop over
ctx.claims and its seen_evidence updates, since it produces no output or side
effects used by the current implementation. Preserve the surrounding
orchestration logic and any independently required evidence handling.

In `@rag/advanced_rag/harness/orchestrator/decompose.py`:
- Around line 15-83: Add observability logging inside decompose_and_search using
the existing _LOG logger: record each orchestration cycle and the computed
verdict/action, matching the established agentic_research logging style where
applicable. Keep the existing search and routing behavior unchanged.

In `@rag/advanced_rag/harness/orchestrator/direct.py`:
- Around line 43-44: Update the fallback in _chunk_key to derive a deterministic
content-based key from the chunk dictionary instead of str(id(ck)). Preserve
chunk_id and id precedence, and ensure equivalent dictionaries without either
field produce the same key for deduplication.

In `@rag/advanced_rag/harness/sufficiency.py`:
- Around line 61-73: Update the entity validation loop in the cross-check logic
to append a successful entity lookup to matches, mirroring the number path,
while retaining mismatches for absent entities. Normalize extracted numbers
before text comparison so integral floats such as 3.0 are formatted as “3” while
non-integral values retain their decimal representation; use this normalized
value in the number messages and lookup.

In `@rag/advanced_rag/harness/tools/gating.py`:
- Around line 108-112: Update get_gated_tools to create independent copies of
each selected function_schema before assigning x_phase and x_phase_hint, rather
than mutating TOOL_REGISTRY entries. Preserve the existing filtering and
metadata values, and ensure _default_defs also cannot expose phase metadata left
by earlier calls.
- Around line 62-70: Update compilation_available to retrieve compilation_type
via tool.get("compilation_type") and return False when it is missing or falsy,
before checking compilation_map values. Keep the existing behavior for tools
that do not require compilation and valid compilation types unchanged.

In `@rag/advanced_rag/harness/tools/inspector.py`:
- Around line 38-39: Update grep_within’s re.search call to escape the untrusted
pattern before matching, preserving case-insensitive literal keyword search and
preventing regex interpretation or catastrophic backtracking.
- Around line 9-19: Update open_context to honor its width parameter instead of
always returning the fixed idx-2 through idx+3 chunk window. Define the window
behavior from width consistently with the schema’s expansion-character contract,
while preserving collection bounds, missing-chunk handling, logging, and doc
aggregation; keep the corresponding tool schema aligned with the implementation.

In `@rag/advanced_rag/harness/tools/navigation.py`:
- Around line 30-35: Rename the mindmap_navigate parameter from concept to topic
and update its logging and hybrid_search query usage accordingly, matching the
topic field produced by _navigate_schema so executor calls with topic succeed.

In `@rag/advanced_rag/harness/tools/registry.py`:
- Line 71: Update the _inspector_schema parameter annotation from an implicitly
optional dict to the explicit Python 3.13 union type dict | None, while keeping
its default value and function behavior unchanged.
- Around line 71-87: Update _inspector_schema to accept an explicit required
parameter and use it for the schema’s required fields instead of treating every
property as required. Update the open_context and request_adjacent registrations
in __init__.py to pass only ["chunk_id"], while preserving the existing default
behavior for callers that do not provide required.

---

Outside diff comments:
In `@rag/advanced_rag/agentic_rag.py`:
- Around line 550-557: Update _collect_doc_titles so reaching max_docs returns
the accumulated result rather than None. Preserve the existing catalogue entries
and return result immediately at the cap, while retaining the normal result
return when fewer documents are found.

---

Duplicate comments:
In `@rag/advanced_rag/agentic_rag.py`:
- Around line 457-478: Update the pagination logic surrounding the inner ck loop
so exhausting self.chat_mdl.max_length also terminates the outer offset loop.
Track whether the token budget was reached, then stop fetching additional pages
while preserving collection of all fitting chunks.
- Around line 211-229: Remove the unconditional return None at the start of
pick_documents so document scoping executes. Preserve the existing flow: return
None when kb_ids is empty, use _filter_by_metadata when cached metadata exists,
otherwise use _select_by_titles, and return None only when those strategies
produce no IDs.
- Around line 512-513: Update the summarize_document method’s tool declaration
to use an explicit 180-second timeout, matching the rag tool’s configured
timeout, while preserving its existing async behavior and signature.

---

Nitpick comments:
In `@rag/advanced_rag/__init__.py`:
- Around line 22-31: Sort the __all__ entries in rag/advanced_rag/__init__.py
using isort-style ordering to satisfy Ruff RUF022, while preserving all existing
exported symbols.

In `@rag/advanced_rag/harness/planner.py`:
- Around line 65-67: Decouple planner message construction from the literal
“输出格式” marker in the prompt-splitting logic. Update the planner’s prompt
handling around the system/user assignment to use separately defined system and
user sections or a structured delimiter, ensuring prompts without that wording
do not raise ValueError or trigger direct-plan fallback.

In `@rag/advanced_rag/harness/tools/exploration.py`:
- Around line 8-30: Remove graph_explore and wiki_query from the active tool
surface until their graph-specific and wiki-specific implementations are
available. Update TOOL_REGISTRY and the SEARCH_PHASES references in gating.py,
and remove or disable the placeholder functions so they cannot be selected while
delegating to generic hybrid_search.

In `@rag/advanced_rag/harness/types.py`:
- Around line 161-162: Resolve the no-op record_fallback method in the relevant
class: if fallback tracking is used, implement it with appropriate logging that
includes tool_name and fallback_from; otherwise remove the method and update any
callers or references. Do not leave the pass-only stub in place.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 063317fc-f90b-4d83-829f-0cc149a107ab

📥 Commits

Reviewing files that changed from the base of the PR and between 21e1458 and 0aeb88a.

📒 Files selected for processing (28)
  • rag/advanced_rag/__init__.py
  • rag/advanced_rag/agentic_rag.py
  • rag/advanced_rag/agentic_rag_graph.py
  • rag/advanced_rag/harness/__init__.py
  • rag/advanced_rag/harness/agent.py
  • rag/advanced_rag/harness/config.py
  • rag/advanced_rag/harness/orchestrator/__init__.py
  • rag/advanced_rag/harness/orchestrator/agentic.py
  • rag/advanced_rag/harness/orchestrator/decompose.py
  • rag/advanced_rag/harness/orchestrator/direct.py
  • rag/advanced_rag/harness/pipeline.py
  • rag/advanced_rag/harness/planner.py
  • rag/advanced_rag/harness/prompts/__init__.py
  • rag/advanced_rag/harness/prompts/decompose_prompts.py
  • rag/advanced_rag/harness/prompts/report_prompt.py
  • rag/advanced_rag/harness/prompts/research_agent_prompt.py
  • rag/advanced_rag/harness/prompts/route_prompt.py
  • rag/advanced_rag/harness/prompts/sufficiency_prompt.py
  • rag/advanced_rag/harness/route.py
  • rag/advanced_rag/harness/sufficiency.py
  • rag/advanced_rag/harness/tools/__init__.py
  • rag/advanced_rag/harness/tools/exploration.py
  • rag/advanced_rag/harness/tools/gating.py
  • rag/advanced_rag/harness/tools/inspector.py
  • rag/advanced_rag/harness/tools/navigation.py
  • rag/advanced_rag/harness/tools/registry.py
  • rag/advanced_rag/harness/tools/search.py
  • rag/advanced_rag/harness/types.py

Comment thread rag/advanced_rag/agentic_rag_graph.py Resolved
Comment on lines +137 to +141
current_idx = next(
(i for i, t in enumerate(priority) if t == tool_name),
-1,
)
for fallback_name in priority[current_idx + 1 :]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Fallback restarts from the top when the tool isn't in tools_priority.

When tool_name is absent from priority, current_idx is -1, so priority[current_idx + 1:] becomes priority[0:] and re-executes every priority tool, potentially re-running the just-failed tool. Skip fallback (or guard) when the tool isn't found.

🐛 Proposed guard
     current_idx = next(
         (i for i, t in enumerate(priority) if t == tool_name),
         -1,
     )
-    for fallback_name in priority[current_idx + 1 :]:
+    start = current_idx + 1 if current_idx >= 0 else len(priority)
+    for fallback_name in priority[start:]:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
current_idx = next(
(i for i, t in enumerate(priority) if t == tool_name),
-1,
)
for fallback_name in priority[current_idx + 1 :]:
current_idx = next(
(i for i, t in enumerate(priority) if t == tool_name),
-1,
)
start = current_idx + 1 if current_idx >= 0 else len(priority)
for fallback_name in priority[start:]:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/agent.py` around lines 137 - 141, Guard the fallback
loop in the priority-based tool selection flow so it runs only when tool_name is
found in priority. When current_idx is -1, skip fallback entirely; preserve the
existing behavior of iterating priority[current_idx + 1:] for recognized tools.

Comment on lines +141 to +146
# Collect evidence chunks from agent results
for c in ctx.claims:
if c.agent_result and c.agent_result.evidence_ids:
for eid in c.agent_result.evidence_ids:
if eid not in seen_evidence:
seen_evidence.add(eid)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Dead evidence-collection loop.

The comment says "Collect evidence chunks from agent results," but the loop only populates seen_evidence and discards it — no chunks are gathered or merged anywhere. Either implement the intended merge or remove the block.

As per coding guidelines: remove dead code "when it is not required by the current implementation."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/orchestrator/agentic.py` around lines 141 - 146,
Remove the unused evidence-collection loop over ctx.claims and its seen_evidence
updates, since it produces no output or side effects used by the current
implementation. Preserve the surrounding orchestration logic and any
independently required evidence handling.

Source: Coding guidelines

Comment on lines +15 to +83
_LOG = logging.getLogger(__name__)


async def decompose_and_search(state: dict, tools) -> dict:
"""Decompose → parallel search → merge → sufficiency check → iterate."""
question = state.get("question", "")
claims_raw = state.get("claims", [])
mode_label = state.get("route", {}).thinking_mode if state.get("route") else "medium"
mode = get_mode(mode_label)

claims = [ClaimTarget(**c) if isinstance(c, dict) else c for c in claims_raw]
ctx = OrchestratorContext(question=question, claims=claims, mode=mode_label)

for cycle in range(mode.max_orchestrator_cycles):
ctx.iteration = cycle
unverified = [c for c in ctx.claims if not c.is_verified]
if not unverified:
break

# Parallel search on unverified claims
tasks = []
for c in unverified:
tasks.append(hybrid_search(tools, query=c.description))
results = await asyncio.gather(*tasks)

for c, result in zip(unverified, results):
if result.get("chunks"):
c.is_verified = True
c.confidence = 0.8
c.agent_result = AgentResult(
claim_id=c.claim_id,
report=_summarize(result),
is_verified=True,
confidence=0.8,
evidence_ids=list(range(len(result.get("chunks", [])))),
)
_merge_kbinfos(tools, result)
else:
c.agent_result = AgentResult(
claim_id=c.claim_id,
report="",
is_verified=False,
confidence=0.0,
)

all_chunks = {i: c for i, c in enumerate(tools.kbinfos.get("chunks", []))}
agent_results = [c.agent_result for c in ctx.claims if c.agent_result]
cross_results = [cross_check_claim(r, all_chunks) for r in agent_results]

verdict = compute_fusion_score(agent_results, cross_results, mode)

action, should_continue = route_sufficiency_verdict(
verdict,
mode_label,
cycle,
mode.max_orchestrator_cycles,
)

if action in ("ANSWER", "ANSWER_PARTIAL"):
return {
"verdict": verdict.__dict__,
"partial_answer": action == "ANSWER_PARTIAL",
"kbinfos": tools.kbinfos,
}
if action == "ABSTAIN":
tools.kbinfos["chunks"] = []
return {"verdict": verdict.__dict__, "abstain": True}

return {"kbinfos": tools.kbinfos}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add logging to the decompose flow.

_LOG is declared (Line 15) but decompose_and_search emits no logs, unlike the sibling agentic_research orchestrator. Add cycle/verdict logging for observability and to satisfy the repo's logging requirement for new flows.

As per coding guidelines: "Add logging for new flows".

🧰 Tools
🪛 Ruff (0.15.20)

[warning] 40-40: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)


[warning] 66-66: Unpacked variable should_continue is never used

Prefix it with an underscore or any other dummy variable pattern

(RUF059)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/orchestrator/decompose.py` around lines 15 - 83, Add
observability logging inside decompose_and_search using the existing _LOG
logger: record each orchestration cycle and the computed verdict/action,
matching the established agentic_research logging style where applicable. Keep
the existing search and routing behavior unchanged.

Source: Coding guidelines

Comment on lines +43 to +44
def _chunk_key(ck: dict) -> str:
return ck.get("chunk_id") or ck.get("id") or str(id(ck))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

_chunk_key fallback to str(id(ck)) breaks deduplication.

id(ck) returns the CPython memory address, not a content-based identifier. Two distinct dict objects with identical content will get different keys, so chunks without chunk_id or id fields are never deduplicated — duplicate evidence silently accumulates in kbinfos.

🛡️ Proposed fix: use content-based fallback
 def _chunk_key(ck: dict) -> str:
-    return ck.get("chunk_id") or ck.get("id") or str(id(ck))
+    import json
+    return ck.get("chunk_id") or ck.get("id") or json.dumps(ck, sort_keys=True, ensure_ascii=False)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _chunk_key(ck: dict) -> str:
return ck.get("chunk_id") or ck.get("id") or str(id(ck))
def _chunk_key(ck: dict) -> str:
import json
return ck.get("chunk_id") or ck.get("id") or json.dumps(ck, sort_keys=True, ensure_ascii=False)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/orchestrator/direct.py` around lines 43 - 44, Update
the fallback in _chunk_key to derive a deterministic content-based key from the
chunk dictionary instead of str(id(ck)). Preserve chunk_id and id precedence,
and ensure equivalent dictionaries without either field produce the same key for
deduplication.

Comment on lines +38 to +39
content = c.get("content_with_weight", c.get("text", ""))
if re.search(pattern, content, re.IGNORECASE):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

grep_within passes an untrusted pattern to re.search — ReDoS risk.

The pattern comes from the LLM tool call and is used directly in re.search. A crafted or inefficient pattern can cause catastrophic backtracking on large chunk content. The tool description says "精确搜索关键词" (precisely search keywords), indicating literal search is intended — so re.escape() is the appropriate fix.

🔒 Proposed fix — escape pattern for literal search
-        if re.search(pattern, content, re.IGNORECASE):
+        if re.search(re.escape(pattern), content, re.IGNORECASE):
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
content = c.get("content_with_weight", c.get("text", ""))
if re.search(pattern, content, re.IGNORECASE):
content = c.get("content_with_weight", c.get("text", ""))
if re.search(re.escape(pattern), content, re.IGNORECASE):
🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 38-38: Regex pattern passed to re is built from a non-literal (variable, call, concatenation, or f-string) value. If that value is attacker-controlled it can introduce a malicious pattern with catastrophic backtracking (ReDoS). Use a hardcoded literal pattern, or validate/escape untrusted input with re.escape() and bound the regex complexity before compiling.
Context: re.search(pattern, content, re.IGNORECASE)
Note: [CWE-1333] Inefficient Regular Expression Complexity.

(redos-non-literal-regex-python)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/inspector.py` around lines 38 - 39, Update
grep_within’s re.search call to escape the untrusted pattern before matching,
preserving case-insensitive literal keyword search and preventing regex
interpretation or catastrophic backtracking.

Source: Linters/SAST tools

Comment on lines +30 to +35
async def mindmap_navigate(tools, concept: str, kb_ids: list[str] | None = None) -> dict:
"""按概念脑图定位。"""
_LOG.info("mindmap_navigate called for concept=%s", concept)
from rag.advanced_rag.harness.tools.search import hybrid_search

return await hybrid_search(tools, query=concept, kb_ids=kb_ids)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

mindmap_navigate parameter concept doesn't match schema parameter topic — will cause TypeError at runtime.

_navigate_schema generates a schema with parameter name topic, but the function signature uses concept. The tool executor calls fn(tools, **kwargs) with the LLM-provided arguments, so it will call mindmap_navigate(tools, topic="...") — which raises TypeError: mindmap_navigate() got an unexpected keyword argument 'topic'. The other two navigation tools correctly use topic.

🐛 Proposed fix — rename `concept` to `topic`
-async def mindmap_navigate(tools, concept: str, kb_ids: list[str] | None = None) -> dict:
-    """按概念脑图定位。"""
-    _LOG.info("mindmap_navigate called for concept=%s", concept)
+async def mindmap_navigate(tools, topic: str, kb_ids: list[str] | None = None) -> dict:
+    """按概念脑图定位。"""
+    _LOG.info("mindmap_navigate called for topic=%s", topic)
     from rag.advanced_rag.harness.tools.search import hybrid_search
 
-    return await hybrid_search(tools, query=concept, kb_ids=kb_ids)
+    return await hybrid_search(tools, query=topic, kb_ids=kb_ids)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async def mindmap_navigate(tools, concept: str, kb_ids: list[str] | None = None) -> dict:
"""按概念脑图定位。"""
_LOG.info("mindmap_navigate called for concept=%s", concept)
from rag.advanced_rag.harness.tools.search import hybrid_search
return await hybrid_search(tools, query=concept, kb_ids=kb_ids)
async def mindmap_navigate(tools, topic: str, kb_ids: list[str] | None = None) -> dict:
"""按概念脑图定位。"""
_LOG.info("mindmap_navigate called for topic=%s", topic)
from rag.advanced_rag.harness.tools.search import hybrid_search
return await hybrid_search(tools, query=topic, kb_ids=kb_ids)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/navigation.py` around lines 30 - 35, Rename
the mindmap_navigate parameter from concept to topic and update its logging and
hybrid_search query usage accordingly, matching the topic field produced by
_navigate_schema so executor calls with topic succeed.

}


def _inspector_schema(name: str, desc: str, props: dict = None) -> dict:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

props: dict = None should be props: dict | None = None (PEP 484).

Ruff RUF013 flags this: implicit Optional is prohibited. The project targets Python 3.13+, so use the T | None syntax.

♻️ Proposed fix
-def _inspector_schema(name: str, desc: str, props: dict = None) -> dict:
+def _inspector_schema(name: str, desc: str, props: dict | None = None) -> dict:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _inspector_schema(name: str, desc: str, props: dict = None) -> dict:
def _inspector_schema(name: str, desc: str, props: dict | None = None) -> dict:
🧰 Tools
🪛 Ruff (0.15.20)

[warning] 71-71: PEP 484 prohibits implicit Optional

Convert to T | None

(RUF013)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/registry.py` at line 71, Update the
_inspector_schema parameter annotation from an implicitly optional dict to the
explicit Python 3.13 union type dict | None, while keeping its default value and
function behavior unchanged.

Source: Linters/SAST tools

Comment on lines +71 to +87
def _inspector_schema(name: str, desc: str, props: dict = None) -> dict:
schema = {
"type": "function",
"function": {
"name": name,
"description": desc,
"parameters": {
"type": "object",
"properties": props
or {
"chunk_id": {"type": "string", "description": "chunk ID"},
},
"required": list((props or {"chunk_id": {}}).keys()),
},
},
}
return schema

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

_inspector_schema marks all properties as required, mismatching functions with optional parameters.

required is set to list(props.keys()), making every parameter required. But open_context has width: int = 500 and request_adjacent has direction: str = "next" and count: int = 3 — all optional. The LLM is forced to guess values for parameters that have sensible defaults, and any schema validation layer would reject calls that omit them.

🐛 Proposed fix — add explicit `required` parameter
-def _inspector_schema(name: str, desc: str, props: dict = None) -> dict:
+def _inspector_schema(name: str, desc: str, props: dict | None = None, required: list[str] | None = None) -> dict:
+    props = props or {"chunk_id": {"type": "string", "description": "chunk ID"}}
+    required = required if required is not None else list(props.keys())
     schema = {
         "type": "function",
         "function": {
             "name": name,
             "description": desc,
             "parameters": {
                 "type": "object",
-                "properties": props
-                or {
-                    "chunk_id": {"type": "string", "description": "chunk ID"},
-                },
-                "required": list((props or {"chunk_id": {}}).keys()),
+                "properties": props,
+                "required": required,
             },
         },
     }
     return schema

Then update registrations in __init__.py to pass required=["chunk_id"] for open_context and request_adjacent:

 register_tool(
     "inspector_open_context",
-    _inspector_schema("open_context", "展开一条 chunk 周围的原文上下文", {"chunk_id": {"type": "string"}, "width": {"type": "integer", "description": "扩展字符数"}}),
+    _inspector_schema("open_context", "展开一条 chunk 周围的原文上下文", {"chunk_id": {"type": "string"}, "width": {"type": "integer", "description": "扩展字符数"}}, required=["chunk_id"]),
     open_context,
 )
 register_tool(
     "inspector_request_adjacent",
-    _inspector_schema("request_adjacent", "获取 chunk 前后的相邻条目", {"chunk_id": {"type": "string"}, "direction": {"type": "string", "enum": ["prev", "next"]}, "count": {"type": "integer"}}),
+    _inspector_schema("request_adjacent", "获取 chunk 前后的相邻条目", {"chunk_id": {"type": "string"}, "direction": {"type": "string", "enum": ["prev", "next"]}, "count": {"type": "integer"}}, required=["chunk_id"]),
     request_adjacent,
 )
🧰 Tools
🪛 Ruff (0.15.20)

[warning] 71-71: PEP 484 prohibits implicit Optional

Convert to T | None

(RUF013)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/registry.py` around lines 71 - 87, Update
_inspector_schema to accept an explicit required parameter and use it for the
schema’s required fields instead of treating every property as required. Update
the open_context and request_adjacent registrations in __init__.py to pass only
["chunk_id"], while preserving the existing default behavior for callers that do
not provide required.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
rag/llm/chat_model.py (2)

678-682: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Syntax error: extra ) in f-string breaks module import.

Line 682 has {tc.function.arguments)} — the ) after tc.function.arguments is a typo that makes the f-string a syntax error. The file will fail to import, breaking all tool-streaming functionality. Additionally, args at lines 678–681 is now dead code: it was used by the previous _verbose_tool_use yield but the new yield uses tc.function.arguments (raw string) directly, and _exec_tool re-parses arguments independently.

🐛 Proposed fix: remove extra `)` and dead `args` parsing
                     for tc in tcs:
-                        try:
-                            args = json_repair.loads(tc.function.arguments)
-                        except Exception:
-                            args = {}
                         yield f"imd Executing {tc.function.name} with args: {tc.function.arguments}\n"
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/llm/chat_model.py` around lines 678 - 682, In the tool-call handling
block, fix the f-string in the yield using tc.function.arguments by removing the
extra closing parenthesis, and remove the now-unused args parsing and exception
handling around json_repair.loads. Preserve the existing raw-argument output and
downstream _exec_tool behavior.

Source: Linters/SAST tools


2121-2125: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Same syntax error and dead code as lines 678–682.

Line 2125 has the identical {tc.function.arguments)} typo, and lines 2121–2124 contain the same now-dead args parsing. See the comment on lines 678–682 for root cause.

🐛 Proposed fix: remove extra `)` and dead `args` parsing
                     for tc in tcs:
-                        try:
-                            args = json_repair.loads(tc.function.arguments)
-                        except Exception:
-                            args = {}
                         yield f"imid Executing {tc.function.name} with args: {tc.function.arguments}\n"
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/llm/chat_model.py` around lines 2121 - 2125, Update the tool-call
handling around tc.function.name by removing the unused json_repair.loads
parsing and its exception handling, then correct the execution message to
interpolate tc.function.arguments with matching delimiters and no extra closing
parenthesis.

Source: Linters/SAST tools

rag/advanced_rag/agentic_rag.py (1)

112-117: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove the duplicate self.kbinfos initialization.

self.kbinfos is assigned at line 112 and immediately overwritten at line 117 with a typed annotation and explanatory comment. The first assignment is dead code.

As per coding guidelines, remove dead code and duplicate assignments; converge on the single typed initialization at line 117.

🧹 Proposed fix
-        self.kbinfos = {"chunks": [], "doc_aggs": []}
         self.do_refer = do_refer
         # Citation pool shared with the final-answer node: the graph publishes
         # the chunks it actually used here (in the SAME order the answer's
         # ``[ID:n]`` markers index), so the caller can resolve references.
         self.kbinfos: dict[str, list] = {"chunks": [], "doc_aggs": []}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 112 - 117, Remove the earlier
untyped self.kbinfos assignment in the initializer, keeping the later typed
initialization and its explanatory comment as the single source of
initialization.

Source: Coding guidelines

♻️ Duplicate comments (4)
rag/advanced_rag/agentic_rag.py (4)

542-542: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

summarize_document still lacks an explicit timeout.

Bare @tool inherits the session default (10s), but this flow may issue many sequential chunk-list queries before returning. This was flagged in a prior review and remains unresolved.

Proposed fix
-    `@tool`
+    `@tool`(timeout=180)
     async def summarize_document(self, doc_id: str) -> list[str]:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` at line 542, Update the decorator on
summarize_document to configure an explicit timeout suitable for its sequential
chunk-list queries instead of relying on the 10-second session default. Keep the
tool’s existing behavior unchanged aside from applying this timeout.

241-259: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

pick_documents still unconditionally returns None.

Line 249 returns None before any scoping logic executes, making metadata filtering and title selection unreachable. This was flagged in a prior review and remains unresolved.

As per coding guidelines, remove dead branches and converge on the current implementation path.

Proposed fix
-        return None
         if not self.kb_ids:
             return None
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 241 - 259, Remove the
unconditional early return from pick_documents so its existing scoping logic
executes. Preserve the current behavior for empty kb_ids, cached metadata
filtering via _filter_by_metadata, and title selection via _select_by_titles,
including returning None when no IDs are found.

Source: Coding guidelines


580-587: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

_collect_doc_titles still returns None at the cap.

When max_docs is reached, line 586 returns None instead of result, causing _select_by_titles to skip title selection for large catalogues. This was flagged in a prior review and remains unresolved.

Proposed fix
                 if len(result) >= max_docs:
-                    return None
+                    return result
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 580 - 587, Update
_collect_doc_titles so reaching max_docs returns the accumulated result rather
than None, allowing _select_by_titles to process capped catalogues. Preserve the
existing collection and early-return behavior.

489-508: 🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Pagination still fetches beyond the token budget.

The inner break at line 506 only exits the per-chunk loop; the outer for offset loop continues fetching pages whose content cannot fit. This was flagged in a prior review and remains unresolved.

Proposed fix
         cks = []
         tokens = 0
+        budget_exhausted = False
         for offset in range(0, 10000, 128):
             chunks = await thread_pool_exec(
                 ...
             )
             if not chunks:
                 break
             for ck in chunks:
                 num = num_tokens_from_string(str(ck["content_with_weight"]))
                 if tokens + num > self.chat_mdl.max_length:
+                    budget_exhausted = True
                     break
                 tokens += num
                 cks.append(ck)
+            if budget_exhausted:
+                break
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 489 - 508, Update the
pagination logic around the outer offset loop and inner chunk iteration so
reaching the token budget stops fetching additional pages. Preserve the existing
chunk accumulation, but propagate the “no more chunks fit” condition from the
inner loop to terminate the outer for loop as well, while still allowing
pagination to continue when an entire page fits within the remaining budget.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@rag/advanced_rag/agentic_rag.py`:
- Around line 112-117: Remove the earlier untyped self.kbinfos assignment in the
initializer, keeping the later typed initialization and its explanatory comment
as the single source of initialization.

In `@rag/llm/chat_model.py`:
- Around line 678-682: In the tool-call handling block, fix the f-string in the
yield using tc.function.arguments by removing the extra closing parenthesis, and
remove the now-unused args parsing and exception handling around
json_repair.loads. Preserve the existing raw-argument output and downstream
_exec_tool behavior.
- Around line 2121-2125: Update the tool-call handling around tc.function.name
by removing the unused json_repair.loads parsing and its exception handling,
then correct the execution message to interpolate tc.function.arguments with
matching delimiters and no extra closing parenthesis.

---

Duplicate comments:
In `@rag/advanced_rag/agentic_rag.py`:
- Line 542: Update the decorator on summarize_document to configure an explicit
timeout suitable for its sequential chunk-list queries instead of relying on the
10-second session default. Keep the tool’s existing behavior unchanged aside
from applying this timeout.
- Around line 241-259: Remove the unconditional early return from pick_documents
so its existing scoping logic executes. Preserve the current behavior for empty
kb_ids, cached metadata filtering via _filter_by_metadata, and title selection
via _select_by_titles, including returning None when no IDs are found.
- Around line 580-587: Update _collect_doc_titles so reaching max_docs returns
the accumulated result rather than None, allowing _select_by_titles to process
capped catalogues. Preserve the existing collection and early-return behavior.
- Around line 489-508: Update the pagination logic around the outer offset loop
and inner chunk iteration so reaching the token budget stops fetching additional
pages. Preserve the existing chunk accumulation, but propagate the “no more
chunks fit” condition from the inner loop to terminate the outer for loop as
well, while still allowing pagination to continue when an entire page fits
within the remaining budget.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2276f167-a7de-4535-a7b6-80725e7cea72

📥 Commits

Reviewing files that changed from the base of the PR and between 0aeb88a and 6040f68.

📒 Files selected for processing (15)
  • rag/advanced_rag/agentic_rag.py
  • rag/advanced_rag/agentic_rag_graph.py
  • rag/advanced_rag/harness/agent.py
  • rag/advanced_rag/harness/orchestrator/decompose.py
  • rag/advanced_rag/harness/orchestrator/direct.py
  • rag/advanced_rag/harness/planner.py
  • rag/advanced_rag/harness/prompts/decompose_prompts.py
  • rag/advanced_rag/harness/prompts/report_prompt.py
  • rag/advanced_rag/harness/prompts/research_agent_prompt.py
  • rag/advanced_rag/harness/prompts/route_prompt.py
  • rag/advanced_rag/harness/prompts/sufficiency_prompt.py
  • rag/advanced_rag/harness/route.py
  • rag/advanced_rag/harness/tools/search.py
  • rag/llm/chat_model.py
  • rag/llm/tool_decorator.py
🚧 Files skipped from review as they are similar to previous changes (12)
  • rag/advanced_rag/harness/prompts/route_prompt.py
  • rag/advanced_rag/harness/prompts/sufficiency_prompt.py
  • rag/advanced_rag/harness/prompts/report_prompt.py
  • rag/advanced_rag/harness/prompts/research_agent_prompt.py
  • rag/advanced_rag/harness/orchestrator/direct.py
  • rag/advanced_rag/harness/prompts/decompose_prompts.py
  • rag/advanced_rag/harness/planner.py
  • rag/advanced_rag/harness/route.py
  • rag/advanced_rag/agentic_rag_graph.py
  • rag/advanced_rag/harness/agent.py
  • rag/advanced_rag/harness/orchestrator/decompose.py
  • rag/llm/tool_decorator.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
rag/advanced_rag/harness/tools/gating.py (1)

119-125: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

cross_domain looks unused. determine_current_phase() only returns locate, verify, or explore, and no other code path references phase="cross_domain". Remove the phase or wire it into phase selection.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/gating.py` around lines 119 - 125, The
determine_current_phase function must account for the cross_domain phase or
remove that phase from the surrounding phase model. Trace the phase definitions
and consumers, then either add the required cross_domain selection condition to
determine_current_phase or delete the unused cross_domain references so all
supported phases are consistent.
rag/advanced_rag/harness/planner.py (1)

123-125: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Narrow the formatting fallback exception.

Catching Exception converts configuration and programming defects into an apparently empty retrieval context, allowing the planner to continue without grounding. Catch only expected formatting/input failures and preserve the existing logging.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/planner.py` around lines 123 - 125, In the
seed-chunk formatting fallback around the planner formatting logic, replace the
broad Exception handler with only the expected formatting/input exception types.
Preserve _LOG.exception and the "(no preliminary results)" return for those
expected failures, while allowing configuration and programming errors to
propagate.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rag/advanced_rag/harness/agent.py`:
- Around line 96-140: Update _research_native to invoke the tool-aware
async_chat_streamly_with_tools loop instead of agent_mdl.async_chat, passing the
bound session and existing history/system inputs so tool_call_async executes and
max_rounds is enforced. Preserve the current final-text extraction, exception
handling, and session.report return behavior.

---

Nitpick comments:
In `@rag/advanced_rag/harness/planner.py`:
- Around line 123-125: In the seed-chunk formatting fallback around the planner
formatting logic, replace the broad Exception handler with only the expected
formatting/input exception types. Preserve _LOG.exception and the "(no
preliminary results)" return for those expected failures, while allowing
configuration and programming errors to propagate.

In `@rag/advanced_rag/harness/tools/gating.py`:
- Around line 119-125: The determine_current_phase function must account for the
cross_domain phase or remove that phase from the surrounding phase model. Trace
the phase definitions and consumers, then either add the required cross_domain
selection condition to determine_current_phase or delete the unused cross_domain
references so all supported phases are consistent.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 493c57bd-d313-4eb4-bf31-a71b65380e9b

📥 Commits

Reviewing files that changed from the base of the PR and between 6040f68 and 1f07a2a.

📒 Files selected for processing (14)
  • api/db/services/dialog_service.py
  • rag/advanced_rag/agentic_rag_graph.py
  • rag/advanced_rag/harness/agent.py
  • rag/advanced_rag/harness/planner.py
  • rag/advanced_rag/harness/prompts/decompose_prompts.py
  • rag/advanced_rag/harness/prompts/research_agent_prompt.py
  • rag/advanced_rag/harness/tools/__init__.py
  • rag/advanced_rag/harness/tools/exploration.py
  • rag/advanced_rag/harness/tools/gating.py
  • rag/advanced_rag/harness/tools/inspector.py
  • rag/advanced_rag/harness/tools/navigation.py
  • rag/advanced_rag/harness/tools/registry.py
  • rag/advanced_rag/harness/tools/search.py
  • rag/llm/chat_model.py
🚧 Files skipped from review as they are similar to previous changes (7)
  • rag/advanced_rag/harness/prompts/decompose_prompts.py
  • rag/advanced_rag/harness/tools/navigation.py
  • rag/advanced_rag/harness/tools/registry.py
  • rag/advanced_rag/harness/tools/init.py
  • rag/advanced_rag/harness/tools/exploration.py
  • rag/llm/chat_model.py
  • api/db/services/dialog_service.py

Comment on lines +96 to +140
# Deep-copy so binding tools never leaks onto the shared chat model.
agent_mdl = deepcopy(tools.chat_mdl)
if getattr(agent_mdl, "is_tools", False):
return await _research_native(claim, agent_mdl, pipeline, phase, phase_config, gated_defs, mode)

_LOG.info("research_agent: model lacks native tool support; falling back to text-based tool selection")
return await _research_text(claim, tools, pipeline, phase, phase_config, gated_defs, mode)


async def _research_native(
claim: ClaimTarget,
agent_mdl,
pipeline: Pipeline,
phase: str,
phase_config: dict,
gated_defs: list[dict],
mode: ExecutionStrategy,
) -> dict:
"""Bind tools onto ``agent_mdl`` and let its native tool loop drive research."""
schemas = _build_tool_schemas(gated_defs)
session = ResearchToolSession(pipeline, phase)
agent_mdl.bind_tools(session, schemas)
# Bound the model's internal tool loop to the mode's agent-cycle budget.
if hasattr(agent_mdl, "mdl") and hasattr(agent_mdl.mdl, "max_rounds"):
agent_mdl.mdl.max_rounds = max(1, mode.max_agent_cycles)

system = RESEARCH_AGENT_PROMPT.format(
claim_description=claim.description,
phase=phase,
phase_hint=phase_config.get("tool_hint", ""),
max_cycles=mode.max_agent_cycles,
)
history = [{"role": "user", "content": f"Research task: {claim.description}\nBegin."}]

final_text = ""
try:
final_text = await agent_mdl.async_chat(system, history, {"temperature": 0.3})
if isinstance(final_text, tuple):
final_text = final_text[0]
except Exception:
_LOG.exception("research_agent(native): tool loop failed")

if session.report is not None:
return session.report

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🔴 Critical | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n -B2 -A25 'async def async_chat\b' rag/llm/chat_model.py
rg -n 'is_tools' rag/llm/chat_model.py

Repository: infiniflow/ragflow

Length of output: 2761


🏁 Script executed:

#!/bin/bash
sed -n '520,730p' rag/llm/chat_model.py

Repository: infiniflow/ragflow

Length of output: 10912


🏁 Script executed:

#!/bin/bash
rg -n -A40 -B10 'def _async_chat\b|async def async_chat_streamly_with_tools\b|tool_call_async|max_rounds' rag/llm/chat_model.py

Repository: infiniflow/ragflow

Length of output: 33578


Use the tool-aware chat loop here. agent_mdl.async_chat(...) never dispatches bound tools; the actual tool execution lives in async_chat_streamly_with_tools, which is the only path that calls tool_call_async and consumes max_rounds. As written, generate_report and the other bound tools won’t run, so native-capable models still return a plain text answer.

🧰 Tools
🪛 Ruff (0.15.21)

[warning] 135-135: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/agent.py` around lines 96 - 140, Update
_research_native to invoke the tool-aware async_chat_streamly_with_tools loop
instead of agent_mdl.async_chat, passing the bound session and existing
history/system inputs so tool_call_async executes and max_rounds is enforced.
Preserve the current final-text extraction, exception handling, and
session.report return behavior.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
rag/advanced_rag/harness/orchestrator/agentic.py (1)

128-129: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Normalize replanned claims back into ClaimTarget objects.

Line 129 bypasses the conversion performed on line 40. If planner_node returns serialized claim dictionaries, the next cycle crashes when accessing c.is_verified.

Proposed fix
             new_plan = await planner_node(state, tools)
-            ctx.claims = new_plan.get("claims", ctx.claims)
+            replanned = new_plan.get("claims", ctx.claims)
+            ctx.claims = [
+                ClaimTarget(**claim) if isinstance(claim, dict) else claim
+                for claim in replanned
+            ]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/orchestrator/agentic.py` around lines 128 - 129,
Update the replanning flow after planner_node in the orchestrator to normalize
serialized claim dictionaries into ClaimTarget objects before assigning
ctx.claims. Reuse the existing conversion logic from the earlier initialization
path rather than storing new_plan’s raw claims, ensuring subsequent
c.is_verified access remains valid.
🧹 Nitpick comments (3)
rag/advanced_rag/agentic_rag.py (2)

112-117: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the duplicate self.kbinfos initialization.

The first assignment is immediately overwritten by the second, making it dead code and creating unnecessary ambiguity about the citation-pool type.

Proposed fix
-        self.kbinfos = {"chunks": [], "doc_aggs": []}
         self.do_refer = do_refer
         self.kbinfos: dict[str, list] = {"chunks": [], "doc_aggs": []}

As per coding guidelines, prefer deletion over duplicate code and converge on one implementation path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 112 - 117, Remove the earlier
untyped self.kbinfos initialization in the constructor, keeping the later typed
assignment dict[str, list] as the sole citation-pool initialization.

Source: Coding guidelines


529-551: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add boundary logging for the new rag tool flow.

Log tool start/completion (without recording the full user question) so failures and latency are observable at the tool boundary.

As per coding guidelines, **/*.py must add logging for new flows.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 529 - 551, Add boundary logging
to the async rag tool, recording start and successful completion with elapsed
time while identifying the request without logging the full question. Wrap the
run_agentic_rag streaming flow so failures are logged with exception details and
latency before propagating the error, using the module’s existing logging
conventions.

Source: Coding guidelines

rag/advanced_rag/harness/pipeline.py (1)

37-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log successful tool execution without logging arguments.

Add a structured debug/info event containing the tool name, elapsed time, result status, and chunk count. Avoid kwargs, which may contain user queries.

As per coding guidelines: “Add logging for new flows.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/pipeline.py` around lines 37 - 47, Add a structured
debug/info log in the successful tool-execution path after _normalize(raw),
including tool_name, elapsed time, successful result status, and the normalized
chunk count; do not include kwargs or user query data. Keep the existing trace
append and _merge_into_kbinfos behavior unchanged.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rag/advanced_rag/agentic_rag.py`:
- Around line 549-550: Update the citation-normalization regex in the final
response processing loop to match one or more digits in the ID, so multi-digit
citations such as (ID:10) are converted to [ID:10] while preserving the existing
single-digit behavior.

In `@rag/advanced_rag/harness/orchestrator/agentic.py`:
- Around line 145-169: Remove raw user-derived text from all specified lifecycle
logs: in rag/advanced_rag/harness/orchestrator/agentic.py lines 145-169, update
the claim start, timeout, and failure logs around research_agent_loop to remove
_snip(claim.description) while retaining claim identifiers and lifecycle events;
in rag/advanced_rag/harness/tools/search.py lines 168-172, 202-207, and 229-230,
remove query and keywords from the hybrid-search, vector-search, and BM25-search
logs, respectively, optionally retaining only non-sensitive identifiers,
lengths, counts, or redacted hashes.

In `@rag/advanced_rag/harness/pipeline.py`:
- Around line 80-81: Update the result handling around the chunks guard so
aggregation-only results still reach the metadata merge logic. Do not return
solely because result.chunks is empty; preserve the early exit only when the
result itself is absent, and ensure metadata["aggs"] is merged for results
containing document aggregates without chunks.

In `@rag/advanced_rag/harness/tools/search.py`:
- Around line 222-226: Normalize retrieval results immediately after both
vector-search output and BM25 output are obtained, before accessing chunks or
applying keyword narrowing. Update the vector-search flow around
_narrow_by_keywords and the corresponding BM25 flow so _normalize handles None
and empty mappings first, then preserve the existing narrowing and logging
behavior; both affected sites in rag/advanced_rag/harness/tools/search.py (lines
222-226 and 245-249) require this ordering change.
- Around line 126-134: Update the keyword fallback in the search filtering logic
to preserve the normalized unigram terms and append adjacent bigrams derived
from comma-cleaned keywords. Ensure a single keyword remains searchable and
inputs such as “foo, bar” produce separate terms plus the intended “foo bar”
bigram, without replacing the original terms.

---

Outside diff comments:
In `@rag/advanced_rag/harness/orchestrator/agentic.py`:
- Around line 128-129: Update the replanning flow after planner_node in the
orchestrator to normalize serialized claim dictionaries into ClaimTarget objects
before assigning ctx.claims. Reuse the existing conversion logic from the
earlier initialization path rather than storing new_plan’s raw claims, ensuring
subsequent c.is_verified access remains valid.

---

Nitpick comments:
In `@rag/advanced_rag/agentic_rag.py`:
- Around line 112-117: Remove the earlier untyped self.kbinfos initialization in
the constructor, keeping the later typed assignment dict[str, list] as the sole
citation-pool initialization.
- Around line 529-551: Add boundary logging to the async rag tool, recording
start and successful completion with elapsed time while identifying the request
without logging the full question. Wrap the run_agentic_rag streaming flow so
failures are logged with exception details and latency before propagating the
error, using the module’s existing logging conventions.

In `@rag/advanced_rag/harness/pipeline.py`:
- Around line 37-47: Add a structured debug/info log in the successful
tool-execution path after _normalize(raw), including tool_name, elapsed time,
successful result status, and the normalized chunk count; do not include kwargs
or user query data. Keep the existing trace append and _merge_into_kbinfos
behavior unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e782b207-818a-463f-bc3b-12edaf4e8b63

📥 Commits

Reviewing files that changed from the base of the PR and between 1f07a2a and 8230b27.

📒 Files selected for processing (8)
  • rag/advanced_rag/agentic_rag.py
  • rag/advanced_rag/agentic_rag_graph.py
  • rag/advanced_rag/harness/agent.py
  • rag/advanced_rag/harness/config.py
  • rag/advanced_rag/harness/orchestrator/agentic.py
  • rag/advanced_rag/harness/pipeline.py
  • rag/advanced_rag/harness/tools/inspector.py
  • rag/advanced_rag/harness/tools/search.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • rag/advanced_rag/harness/config.py
  • rag/advanced_rag/harness/agent.py
  • rag/advanced_rag/harness/tools/inspector.py
  • rag/advanced_rag/agentic_rag_graph.py

Comment on lines +549 to +550
for p, r in [(r"\(\**(ID:\d)\**\)", "[\1]")]:
final = re.sub(p, r, final)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Match multi-digit citation IDs.

\d only matches one digit, so citations such as (ID:10) are not normalized to [ID:10].

Proposed fix
-        for p, r in [(r"\(\**(ID:\d)\**\)", "[\1]")]:
+        for p, r in [(r"\(\**(ID:\d+)\**\)", r"[\1]")]:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for p, r in [(r"\(\**(ID:\d)\**\)", "[\1]")]:
final = re.sub(p, r, final)
for p, r in [(r"\(\**(ID:\d+)\**\)", r"[\1]")]:
final = re.sub(p, r, final)
🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 549-549: Regex pattern passed to re is built from a non-literal (variable, call, concatenation, or f-string) value. If that value is attacker-controlled it can introduce a malicious pattern with catastrophic backtracking (ReDoS). Use a hardcoded literal pattern, or validate/escape untrusted input with re.escape() and bound the regex complexity before compiling.
Context: re.sub(p, r, final)
Note: [CWE-1333] Inefficient Regular Expression Complexity.

(redos-non-literal-regex-python)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/agentic_rag.py` around lines 549 - 550, Update the
citation-normalization regex in the final response processing loop to match one
or more digits in the ID, so multi-digit citations such as (ID:10) are converted
to [ID:10] while preserving the existing single-digit behavior.

Comment on lines +145 to +169
_LOG.info("[agentic] claim start id=%s desc=%s", claim.claim_id, _snip(claim.description))
try:
result = await asyncio.wait_for(
research_agent_loop(claim, tools, pipeline, ctx, mode, compilation_map),
timeout=CLAIM_RESEARCH_TIMEOUT_SECONDS,
)
except asyncio.CancelledError:
raise
except asyncio.TimeoutError:
_LOG.warning(
"[agentic] claim timeout id=%s timeout=%ss desc=%s",
claim.claim_id,
CLAIM_RESEARCH_TIMEOUT_SECONDS,
_snip(claim.description),
)
return {
"report": "",
"is_verified": False,
"confidence": 0.0,
"evidence_ids": [],
"gaps": [f"claim research timeout after {CLAIM_RESEARCH_TIMEOUT_SECONDS}s"],
"discovered_claims": [],
}
except Exception:
_LOG.exception("[agentic] claim failed id=%s desc=%s", claim.claim_id, _snip(claim.description))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not persist raw user-derived content in application logs.

These info/error logs expose potentially sensitive prompts and claims. Retain lifecycle logging, but record identifiers, lengths, counts, or redacted hashes instead.

  • rag/advanced_rag/harness/orchestrator/agentic.py#L145-L169: remove _snip(claim.description) from claim lifecycle logs.
  • rag/advanced_rag/harness/tools/search.py#L168-L172: omit query and keywords from the hybrid-search log.
  • rag/advanced_rag/harness/tools/search.py#L202-L207: omit query and keywords from the vector-search log.
  • rag/advanced_rag/harness/tools/search.py#L229-L230: omit query and keywords from the BM25-search log.
🧰 Tools
🪛 Ruff (0.15.21)

[warning] 168-168: Do not catch blind exception: Exception

(BLE001)

📍 Affects 2 files
  • rag/advanced_rag/harness/orchestrator/agentic.py#L145-L169 (this comment)
  • rag/advanced_rag/harness/tools/search.py#L168-L172
  • rag/advanced_rag/harness/tools/search.py#L202-L207
  • rag/advanced_rag/harness/tools/search.py#L229-L230
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/orchestrator/agentic.py` around lines 145 - 169,
Remove raw user-derived text from all specified lifecycle logs: in
rag/advanced_rag/harness/orchestrator/agentic.py lines 145-169, update the claim
start, timeout, and failure logs around research_agent_loop to remove
_snip(claim.description) while retaining claim identifiers and lifecycle events;
in rag/advanced_rag/harness/tools/search.py lines 168-172, 202-207, and 229-230,
remove query and keywords from the hybrid-search, vector-search, and BM25-search
logs, respectively, optionally retaining only non-sensitive identifiers,
lengths, counts, or redacted hashes.

Comment on lines +80 to +81
if not result or not result.chunks:
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Do not discard aggregation-only results.

This return prevents metadata["aggs"] from being merged whenever a tool returns document aggregates without chunks, despite the helper’s stated contract.

Proposed fix
-        if not result or not result.chunks:
+        if not result:
             return
         kb = self.tools.kbinfos
         seen = {c.get("chunk_id") or c.get("id") or id(c) for c in kb.get("chunks", [])}
-        for c in result.chunks:
+        for c in result.chunks or []:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if not result or not result.chunks:
return
if not result:
return
kb = self.tools.kbinfos
seen = {c.get("chunk_id") or c.get("id") or id(c) for c in kb.get("chunks", [])}
for c in result.chunks or []:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/pipeline.py` around lines 80 - 81, Update the result
handling around the chunks guard so aggregation-only results still reach the
metadata merge logic. Do not return solely because result.chunks is empty;
preserve the early exit only when the result itself is absent, and ensure
metadata["aggs"] is merged for results containing document aggregates without
chunks.

Comment on lines +126 to +134
kwds = [k.strip().lower() for k in (keywords or "").split(",") if k.strip()]
if not kwds or not chunks:
return chunks
if len(kwds) < 3:
kwds = [k.strip().lower() for k in (keywords or "").split(" ") if k.strip()]
_kwds = []
for i in range(len(kwds)-1):
_kwds.append(kwds[i] + " "+ kwds[i+1])
kwds = _kwds

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve individual terms when generating bigrams.

A single keyword makes _kwds empty, while "foo, bar" becomes the unlikely literal bigram "foo, bar". Both paths can drop every retrieved chunk. Keep the normalized unigrams and add comma-cleaned bigrams instead of replacing them.

Proposed fix
     kwds = [k.strip().lower() for k in (keywords or "").split(",") if k.strip()]
     if not kwds or not chunks:
         return chunks
     if len(kwds) < 3:
-        kwds = [k.strip().lower() for k in (keywords or "").split(" ") if k.strip()]
-        _kwds = []
-        for i in range(len(kwds)-1):
-            _kwds.append(kwds[i] + " "+ kwds[i+1])
-        kwds = _kwds
+        words = keywords.replace(",", " ").lower().split()
+        bigrams = [f"{left} {right}" for left, right in zip(words, words[1:])]
+        kwds = list(dict.fromkeys([*kwds, *words, *bigrams]))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
kwds = [k.strip().lower() for k in (keywords or "").split(",") if k.strip()]
if not kwds or not chunks:
return chunks
if len(kwds) < 3:
kwds = [k.strip().lower() for k in (keywords or "").split(" ") if k.strip()]
_kwds = []
for i in range(len(kwds)-1):
_kwds.append(kwds[i] + " "+ kwds[i+1])
kwds = _kwds
kwds = [k.strip().lower() for k in (keywords or "").split(",") if k.strip()]
if not kwds or not chunks:
return chunks
if len(kwds) < 3:
words = keywords.replace(",", " ").lower().split()
bigrams = [f"{left} {right}" for left, right in zip(words, words[1:])]
kwds = list(dict.fromkeys([*kwds, *words, *bigrams]))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/search.py` around lines 126 - 134, Update the
keyword fallback in the search filtering logic to preserve the normalized
unigram terms and append adjacent bigrams derived from comma-cleaned keywords.
Ensure a single keyword remains searchable and inputs such as “foo, bar” produce
separate terms plus the intended “foo bar” bigram, without replacing the
original terms.

Comment on lines +222 to +226
if keywords:
l = len(kbinfos["chunks"])
kbinfos["chunks"] = _narrow_by_keywords(kbinfos.get("chunks", []), keywords)
_LOG.info(f"[Vector search]({keywords}): snippet {l} -> {len(kbinfos['chunks'])}")
return _normalize(kbinfos, tools.tenant_ids)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Normalize retrieval output before keyword narrowing.

_normalize explicitly supports falsy retrieval responses, but these paths index kbinfos["chunks"] first and therefore crash when retrieval returns None or an empty mapping.

  • rag/advanced_rag/harness/tools/search.py#L222-L226: normalize vector-search output immediately after retrieval, then narrow it.
  • rag/advanced_rag/harness/tools/search.py#L245-L249: normalize BM25 output immediately after retrieval, then narrow it.
🧰 Tools
🪛 Ruff (0.15.21)

[error] 223-223: Ambiguous variable name: l

(E741)

📍 Affects 1 file
  • rag/advanced_rag/harness/tools/search.py#L222-L226 (this comment)
  • rag/advanced_rag/harness/tools/search.py#L245-L249
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/advanced_rag/harness/tools/search.py` around lines 222 - 226, Normalize
retrieval results immediately after both vector-search output and BM25 output
are obtained, before accessing chunks or applying keyword narrowing. Update the
vector-search flow around _narrow_by_keywords and the corresponding BM25 flow so
_normalize handles None and empty mappings first, then preserve the existing
narrowing and logging behavior; both affected sites in
rag/advanced_rag/harness/tools/search.py (lines 222-226 and 245-249) require
this ordering change.

@KevinHuSh KevinHuSh added the ci Continue Integration label Jul 15, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft July 15, 2026 10:20
@KevinHuSh
KevinHuSh marked this pull request as ready for review July 15, 2026 10:20
@yingfeng
yingfeng force-pushed the feat/agentic_search1 branch 5 times, most recently from befed4b to 81dfff6 Compare July 15, 2026 13:51
@yingfeng yingfeng changed the title Feat: agentic search Feat: agentic search framework Jul 15, 2026
@codecov

codecov Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (5cf95d2) to head (59466fb).
⚠️ Report is 26 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16859      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yingfeng
yingfeng force-pushed the feat/agentic_search1 branch from 81dfff6 to 1f5cd62 Compare July 15, 2026 14:40
@yingfeng
yingfeng force-pushed the feat/agentic_search1 branch from 1f5cd62 to 59466fb Compare July 15, 2026 15:14
@yingfeng
yingfeng merged commit 454dea6 into infiniflow:main Jul 15, 2026
9 of 10 checks passed
@KevinHuSh
KevinHuSh deleted the feat/agentic_search1 branch July 20, 2026 10:43
martincivan added a commit to martincivan/ragflow that referenced this pull request Aug 27, 2026
LLMBundle.async_chat routed into async_chat_with_tools whenever the model
was declared tool-capable in the tenant config, without checking whether
tools were actually bound. The request then carried `tools: []`, which
providers that validate their request body reject with a 400.

The two streaming entry points already have the mdl.is_tools guard;
async_chat lost it in infiniflow#16859, so only the non-streaming path broke -
question rewriting, keyword extraction and non-streaming chat.

Restore the guard, and omit tools/tool_choice entirely when nothing is
bound, as the LiteLLM path already does.
martincivan added a commit to martincivan/ragflow that referenced this pull request Aug 30, 2026
LLMBundle.async_chat routed into async_chat_with_tools whenever the model
was declared tool-capable in the tenant config, without checking whether
tools were actually bound. The request then carried `tools: []`, which
providers that validate their request body reject with a 400.

The two streaming entry points already have the mdl.is_tools guard;
async_chat lost it in infiniflow#16859, so only the non-streaming path broke -
question rewriting, keyword extraction and non-streaming chat.

Restore the guard, and omit tools/tool_choice entirely when nothing is
bound, as the LiteLLM path already does.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants