Skip to content

Hide Chainlit Sources when no evidence is available - #807

Merged
hedhoud merged 14 commits into
developfrom
agent/hide-empty-chainlit-sources
Jul 30, 2026
Merged

Hide Chainlit Sources when no evidence is available#807
hedhoud merged 14 commits into
developfrom
agent/hide-empty-chainlit-sources

Conversation

@hedhoud

@hedhoud hedhoud commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

Closes #778

Context

A source should appear only when it actually supports the answer. Conversational replies were showing unrelated documents and presenting OpenRAG as a generic assistant, which made the product behavior unclear.

Fix

Chainlit now ignores sources it cannot safely render, and RAG responses keep only sources the model actually cited. Conversational requests receive an OpenRAG-specific answer without document sources, while factual and explicit search requests keep normal retrieval. Web results are validated before citation numbering so valid evidence remains aligned.

Validation

The full unit suite passes (2,263 tests), along with repository lint, formatting, and package build checks. Live Chainlit checks confirmed that identity and capability questions describe OpenRAG as LINAGORA’s document-grounded RAG system without sources, while document-backed answers keep valid citations.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

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

Changes

The PR hardens source validation and rendering, protects authoritative document-link fields, adds conversational retrieval classification, and filters unattributed sources while allowing structured responses to retain uncited sources. Tests cover source safety, retrieval decisions, and citation behavior.

Source handling

Layer / File(s) Summary
Enforce authoritative document links
openrag/api/routers/user/source_links.py, tests/unit/api/routers/user/test_source_links.py
Document links override conflicting metadata fields and omit file_url when no encoded source is available.
Validate and normalize source metadata
openrag/app_front.py, tests/unit/test_app_front_secret.py
Web and file metadata is validated, normalized, escaped, and assigned unique safe names.
Build and render supported source elements
openrag/app_front.py, tests/unit/test_app_front_secret.py
File types select Chainlit elements, text content is fetched when required, unavailable sources are skipped, and source streaming requires elements and names.

Retrieval and citation behavior

Layer / File(s) Summary
Define retrieval requirements
openrag/core/models/query.py, openrag/prompts/templates/query_contextualizer_tmpl.txt, openrag/services/orchestrators/query_service.py
Query output now declares whether retrieval is required, with prompt rules and examples for conversational and factual requests.
Gate and force retrieval
openrag/services/orchestrators/query_service.py, tests/unit/services/orchestrators/test_query_service.py
Conversational requests skip retrieval, while factual requests and forced websearch or map-reduce paths still retrieve sources.
Filter attributed sources
openrag/core/utils/source_filtering.py, openrag/services/orchestrators/query_service.py, tests/unit/core/utils/test_source_filtering.py, tests/unit/services/orchestrators/test_query_service.py
Sources without valid terminal citations are removed by default, with opt-in retention for structured outputs.
Handle conversational responses
openrag/prompts/templates/spoken_style_answer_tmpl.txt, openrag/prompts/templates/sys_prompt_tmpl.txt
Prompt instructions keep casual responses brief, omit retrieved context, and emit no sources unless a factual question is present.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant QueryContextualizer
  participant QueryService
  participant Retriever
  participant SourceFilter
  User->>QueryContextualizer: submit conversational or factual request
  QueryContextualizer->>QueryService: return requires_retrieval and query_list
  QueryService->>Retriever: retrieve when required or forced
  Retriever-->>QueryService: return answer context and sources
  QueryService->>SourceFilter: filter sources by terminal citations
  SourceFilter-->>User: return answer with attributed sources
Loading

Possibly related PRs

Suggested labels: fix, bug

Suggested reviewers: enjoybacon7, ahmath-gadji

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes align with #778 by suppressing sources when empty, invalid, unavailable, or irrelevant, while preserving supported citations.
Out of Scope Changes check ✅ Passed The added prompt, filtering, and source-formatting updates all support the same goal and do not appear unrelated to the issue scope.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: hiding Chainlit Sources when no valid evidence is available.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/hide-empty-chainlit-sources

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.

@hedhoud
hedhoud marked this pull request as ready for review July 27, 2026 07:43
@coderabbitai coderabbitai Bot added the fix Fix issue label Jul 27, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
tests/unit/test_app_front_secret.py (2)

434-453: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding a case with markdown-special characters in title/snippet.

Once escaping is added for source_label/snippet (see the companion comment on openrag/app_front.py lines 478-497), a regression test with characters like ], (, ) in the title would guard against link-spoofing regressions.

🤖 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 `@tests/unit/test_app_front_secret.py` around lines 434 - 453, Extend
test_chainlit_keeps_valid_web_sources to use a web source title and snippet
containing Markdown-special characters such as ], (, and ). Update the expected
source name and rendered element content to verify _format_sources escapes these
values while preserving the intended link URL and preventing link-spoofing.

456-480: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider adding a case where the chunk endpoint returns a non-dict JSON body.

This would cover the AttributeError gap raised on openrag/app_front.py lines 528-562 (data.get(...) failing when response.json() isn't a dict), ensuring that path is also gracefully skipped rather than propagating.

🤖 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 `@tests/unit/test_app_front_secret.py` around lines 456 - 480, Extend
test_chainlit_skips_unavailable_text_sources with a case where the mocked chunk
endpoint returns valid JSON that is not a dictionary, such as a list or scalar.
Assert that _format_sources gracefully skips the source and returns empty
elements and source_names, covering the data.get handling in the source-fetching
path.
🤖 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 `@openrag/app_front.py`:
- Around line 528-562: Update the source-processing try/except around
__fetch_page_content to catch AttributeError as well as the existing
httpx.HTTPError, TypeError, and ValueError exceptions, so malformed non-dict
JSON responses skip only the affected source via the existing warning and
continue behavior.
- Around line 478-497: Update the web-source rendering block around
source_label, content, and cl.Text to escape title-derived link-label text and
snippet text for Markdown before interpolating them. Preserve the URL as the
validated link target and keep the displayed source and snippet content
otherwise unchanged.

---

Nitpick comments:
In `@tests/unit/test_app_front_secret.py`:
- Around line 434-453: Extend test_chainlit_keeps_valid_web_sources to use a web
source title and snippet containing Markdown-special characters such as ], (,
and ). Update the expected source name and rendered element content to verify
_format_sources escapes these values while preserving the intended link URL and
preventing link-spoofing.
- Around line 456-480: Extend test_chainlit_skips_unavailable_text_sources with
a case where the mocked chunk endpoint returns valid JSON that is not a
dictionary, such as a list or scalar. Assert that _format_sources gracefully
skips the source and returns empty elements and source_names, covering the
data.get handling in the source-fetching path.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c993b759-9a76-466c-8cdb-11b7c3069ac7

📥 Commits

Reviewing files that changed from the base of the PR and between b2ab6b1 and 645b87f.

📒 Files selected for processing (2)
  • openrag/app_front.py
  • tests/unit/test_app_front_secret.py

Comment thread openrag/app_front.py
Comment thread openrag/app_front.py

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ec3e036978

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread openrag/app_front.py Outdated
@andyne13

Copy link
Copy Markdown
Contributor

Review — verified against f8ce6abb

Reviewed the diff against the merge-base b2ab6b11. ruff check / ruff format --check are clean on the touched files, and tests/unit/test_app_front_secret.py + tests/unit/api/routers/user/test_source_links.py pass (44 tests).

To separate what this PR changes from what was already broken, I ran the base and PR versions of _format_sources side by side on identical inputs. Summary: one blocking regression on the happy path; everything else is a real improvement that should land.


What this PR genuinely fixes

1. It removes three hard crashes. Base _format_sources used unchecked subscripts (s["filename"], s["file_url"], s["page"]) with no try/except, so one malformed source propagated out into on_message's except Exception and destroyed the entire sources block for that message. Same inputs, both versions:

pdf with page=None    base: RAISES TypeError    PR: that source skipped, rest render
missing 'filename'    base: RAISES KeyError     PR: that source skipped, rest render
missing 'page'        base: RAISES KeyError     PR: that source skipped, rest render

page=None is reachable, not theoretical: Chunk.page_number is typed int | None (core/models/chunk.py:50) and _dict_to_chunk reads it straight off the store row (services/storage/vector_store_searcher.py:36).

2. The source_links.py change closes a real hole. The chain is user-controlled end to end:

  • enable_dynamic_field=True (services/storage/milvus_store.py:223,275) and _entity_from_chunk starting from dict(chunk.metadata) (:680) mean arbitrary metadata keys persist to Milvus and come back on search.
  • IndexingService._build_metadata (services/orchestrators/indexing_service.py:103) force-sets source, filename, original_filename and a few file-identity fields — every other key from the caller's file_metadata survives untouched.
  • _dict_to_chunk's skip set (vector_store_searcher.py:29) filters _id/page/chunk_type/etc. but not source_type, file_url, chunk_url, url, title, snippet.

Before this PR the **doc_metadata spread came last, so a partition editor could flip a document source to source_type: "web" and supply their own url/title/snippet — landing an arbitrary link in another user's chat. Assigning the authoritative fields after the copy fixes it, and both new tests target it precisely.

3. Moving get_external_url() below the early return is a good catch — the empty-sources path no longer needs a live Chainlit context.


🔴 Blocking: escaping source_names makes document sources unclickable

app_front.py:578

source_names = [_escape_markdown_text(name) for name in d]

Chainlit links a side element by finding the element's raw name as a literal substring of the message body. From the shipped frontend of the pinned chainlit==2.11.1 (frontend/dist/assets/index-LFVFt-Wr.js), de-minified:

const names = elements.map(e => escapeRegExp(e.name));   // ZYn = /[.*+?^${}()|[\]\\]/g -> "\\$&"
const re = new RegExp(`(${names.join("|")})`, "g");
content = content.replaceAll(re, m => {
  const el = elements.find(f => f.name === m && sameId(msgId, f.forId));   // exact string equality
  if (!el) return m;                                                       // <- no link
  return el.display === "inline" ? m : (refElements.push(el), `[${m}](${nameToHref(m)})`);
});

The element keeps its unescaped name (d[source_name] = cl.Text(name=source_name, …) at :508, d[source_name] = elem at :576), while on_message (:636-638) streams the escaped name into the body. escapeRegExp("diagram.png") yields the pattern diagram\.png, which matches the literal text diagram.png — but the body now contains diagram\.png. No match → return m → no link is emitted, and the element is never pushed into refElements.

Because markdown swallows the backslash, the name still looks correct — it is just inert text, and the side panel becomes unreachable.

This is not an edge case. Base vs PR on ordinary, fully-populated sources (link_ok = element.name == displayed_name):

pdf, page=3         base: ['r.pdf (page: 3)']                   link_ok=True
                    PR  : ['r\.pdf \(page\: 3\)']               link_ok=False
notes.txt           base: ['n.txt']                             link_ok=True
                    PR  : ['n\.txt']                            link_ok=False
web title "Ref"     base: ['Ref']                               link_ok=True
                    PR  : ['Ref']                               link_ok=True

"Ref" survives only because it contains no ASCII punctuation. Since every filename contains a ., every document source loses its link; web sources break whenever the title contains punctuation.

The PR's own test encodes the mismatch as expected behaviour:

assert source_names == [r"diagram\.png", …]                  # message body
assert [element.name for element in elements] == ["diagram.png", …]   # element

Suggested fix

The name has to be markdown-inert at creation, so the element name and the rendered name are the same string — escaping only the rendered copy cannot work here.

# Chainlit's front-end matches an element's name literally inside the message
# body to build the side-panel link, so the name itself must be inert:
# escaping only the rendered copy silently breaks the match.
_MARKDOWN_UNSAFE_NAME_CHARS = str.maketrans(dict.fromkeys("[]()*_`~#>|\\", " "))


def _safe_source_name(value: str) -> str:
    return " ".join(value.translate(_MARKDOWN_UNSAFE_NAME_CHARS).split()) or "source"

Use it for source_name in both branches, then source_names = list(d). Keep _escape_markdown_text for content / snippet — that copy is only ever rendered, so escaping is correct there, and the injection defence it adds is worth keeping.

Regression guard, since this is the actual contract:

assert source_names == [element.name for element in elements]

Non-blocking suggestions

Fall back instead of dropping a page-less PDF. :535 computes page_label precisely because the page may be missing, then :555 hard-requires it via int(page); TypeError is swallowed at :572 and the source disappears. Since the code already anticipates the case, finishing the job keeps the citation:

case ".pdf":
    try:
        pdf_page = int(page)
    except (TypeError, ValueError):
        pdf_page = 1
    elem = cl.Pdf(name=source_name, url=file_url, page=pdf_page, display="side")

Related: the new parametrised test asserts {"filename": "document.pdf", "file_url": …} (no page) yields no elements, which locks the drop in — and there is currently no test that a valid .pdf produces a cl.Pdf at all.

Add httpx.InvalidURL to the except tuple at :572. It derives from Exception directly — neither HTTPError nor ValueError — so it escapes:

>>> await client.get("http://[::1")     -> InvalidURL   # not caught
>>> await client.get("https://….example") -> InvalidURL # not caught (IDNA failure)

The web branch at :498 already catches it, so this looks like an oversight rather than a decision. Narrow in practice (most malformed URLs raise UnsupportedProtocol/ConnectError, both caught, and chunk_url is server-authoritative after your source_links.py fix), but cheap to close and it keeps the two branches consistent.

Log every drop, not one of them. logger.warning at :573 covers the fetch failure; the validation continues at :484, :496, :499, :520, :544, :547, :567 and :570 are all silent. A source vanishing without a trace is hard to support in the field.


Nits

  • _MARKDOWN_ESCAPE_TABLE covering all of string.punctuation is CommonMark-correct (that set is CommonMark's ASCII punctuation), but it is what produces https\:\/\/spoof\.test in the test expectations. Fine for content; wrong tool for names, per the blocker.
  • case suffix if suffix in [...] (:558) is an irrefutable capture pattern shadowing the subject with itself. Carried over from base and it works, but case ".png" | ".jpg" | ".jpeg": reads better while you're in here.
  • Two chunks from the same file and page still collapse — d[source_name] = elem overwrites, so the user sees fewer sources than were retrieved. Pre-existing (base behaves identically), just noting it since this PR is about source-list fidelity.

Happy to re-review as soon as the naming fix is in — the rest of this is a clear improvement over what's on develop today.

@andyne13
andyne13 self-requested a review July 28, 2026 19:55
@hedhoud hedhoud added this to the v2.0.2 milestone Jul 29, 2026

@andyne13 andyne13 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.

Follow-up on 43060c69 — the clickability fix is correct, the strip set is too wide

Re-verified the fix against the new head. The blocker is genuinely resolved: _safe_source_name() makes the name Markdown-inert at creation and it's used for both element.name and the rendered list, so Chainlit's matcher finds it again. I re-ran the same before/after harness — every case is clickable now, including the ordinary .pdf and .txt sources that were broken:

pdf, page=3     was link_ok=False  ->  link_ok=True
notes.txt       was link_ok=False  ->  link_ok=True
pdf, page=None  was dropped        ->  renders

Nice extras I didn't ask for: page=int(page) if page_label else None (valid — cl.Pdf.page is Optional[int] = None), httpx.InvalidURL in the except tuple, and duplicate document sources no longer collapsing.

One refinement worth doing in this PR, since it's the same constant.

The problem

_MARKDOWN_UNSAFE_SOURCE_NAME_CHARS = str.maketrans(dict.fromkeys("[]()*_`~#>|\\", " "))

Twelve characters become spaces, but only some of them can actually alter rendering where a source name ends up. Chainlit substitutes a matched name into `[name](href)`, so the name lands inside a link label — which rules out every block-level construct. I checked each character against a CommonMark renderer in that exact position:

Char In a link label Verdict
[ ] closes the label early → breakout keep stripping
* foo*bar*bazfoo<em>bar</em>baz keep stripping
` opens a code span keep stripping
\ a trailing one escapes the closing ] keep stripping
> harmless in a label, but opens a blockquote on the degraded path where no element matched keep, cheap insurance
_ rapport_annuel_2026.pdf renders literally (intraword _ is never emphasis) over-aggressive
( ) [report.pdf (page: 3)](/el/x) → valid link, label intact over-aggressive
~ | # render literally over-aggressive

The cost lands on ordinary filenames — underscores are in most of them:

rapport_annuel_2026.pdf     ->  rapport annuel 2026.pdf
ISO_9001_procedure_v2.docx  ->  ISO 9001 procedure v2.docx
C++_style_guide.pdf         ->  C++ style guide.pdf
report.pdf (page: 3)        ->  report.pdf page: 3

There's also a knock-on: distinct files collapse onto the same base and get counter-suffixed, so a user sees a b.pdf and a b.pdf 2 for two unrelated documents (a_b.pdf and a b.pdf).

Patch

I applied and tested this locally against 43060c69 — 46 tests pass, ruff check and ruff format --check clean, and the before/after harness still shows link_ok=True everywhere.

--- a/openrag/app_front.py
+++ b/openrag/app_front.py
@@
-_MARKDOWN_UNSAFE_SOURCE_NAME_CHARS = str.maketrans(dict.fromkeys("[]()*_`~#>|\\", " "))
+# Only the characters that can actually alter rendering where a source name
+# ends up: Chainlit substitutes the name into `[name](url)`, so brackets and a
+# trailing backslash can break out of the link label, `*` and a backtick pair
+# still emphasise/codify inside it, and a leading `>` opens a blockquote on the
+# degraded path where no element matched. Everything else — `_ ( ) ~ # |` —
+# renders literally there, so stripping it only mangles ordinary filenames.
+_MARKDOWN_UNSAFE_SOURCE_NAME_CHARS = str.maketrans(dict.fromkeys("[]*`\\>", " "))

Three existing tests pin the stripped output and need updating with it:

--- a/tests/unit/test_app_front_secret.py
+++ b/tests/unit/test_app_front_secret.py
@@ test_chainlit_keeps_page_less_pdf_sources
-    assert source_names == ["report draft .pdf"]
+    assert source_names == ["report_ draft .pdf"]

@@ test_chainlit_escapes_untrusted_web_source_markdown
-    assert source_names == ["Reference https://spoof.test trusted"]
+    assert source_names == ["Reference (https://spoof.test) trusted"]

@@ test_chainlit_keeps_source_names_unique_after_sanitizing
             {"source_type": "web", "title": "Reference [draft]", "url": "https://example.test/one"},
-            {"source_type": "web", "title": "Reference (draft)", "url": "https://example.test/two"},
+            {"source_type": "web", "title": "Reference *draft*", "url": "https://example.test/two"},

That last one matters: under the narrower set those two titles no longer collide, so the test would stop exercising the de-duplication path — swapping the second to Reference *draft* keeps it meaningful.

And one new test, so the constant can't quietly drift again. It asserts the security invariant directly and needs no Markdown renderer:

@pytest.mark.parametrize(
    "hostile_name",
    [
        "x](https://evil.test)",
        "a]bc",
        "](javascript:alert(1))",
        "nested[a](b)c",
        "trailing\\",
        "**bold**",
        "back`tick`",
        ">quote",
    ],
)
def test_source_name_cannot_break_out_of_the_markdown_link(monkeypatch, hostile_name):
    """Chainlit rewrites a matched name into ``[name](url)``.

    Whatever the metadata contains, the sanitised name must not carry a
    character that can close that label early or start an inline construct
    inside it — otherwise a crafted filename or web-result title escapes into
    the surrounding Markdown.
    """
    module = _load_app_front(monkeypatch, auth_mode="token", module_name="app_front_source_name_safety_test")

    safe_name = module._safe_source_name(hostile_name, {})

    assert not set(safe_name) & set("[]*`\\>")
    assert safe_name.strip() == safe_name

Every hostile input above still yields exactly one anchor with the correct href under the narrowed set — the security properties are unchanged, only the mangling of legitimate names goes away.

Deliberately not chased

_draft_.pdf still renders as draft.pdf, because boundary underscores do emphasise inside a label. Neutralising only those needs a positional rule (_ is emphasis only when not between alphanumerics), and that immediately mis-handles C++_style_guide.pdf since + isn't alphanumeric. It's cosmetic rather than a breakout, so it isn't worth the complexity — a comment is the right amount of attention.

Minor, non-blocking

Six reachable paths still drop a source with no log line — :496 (entry not a dict), :508/:511 (bad web URL), :530 (no usable filename/file_url), :578 (no chunk_url), :581 (empty chunk content). Only the exception path at :584 logs. Since the whole point of this PR is to hide the block when there's no evidence, a support request of "it cited documents but showed nothing" currently can't distinguish nothing was cited from six sources were discarded. :581 is the one most likely to fire quietly, on image-only or whitespace chunks. One logger.debug per drop with the index and reason would close it.

(:519 isn't a drop — it's the success-path loop advance — and :555/:558 sit in the only_txt=True branch, which on_message never reaches.)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bae5a27f0f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread openrag/app_front.py

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3d89102f57

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread openrag/app_front.py Outdated
@coderabbitai coderabbitai Bot added the bug Something isn't working label Jul 30, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 37e4b46099

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread openrag/core/utils/source_filtering.py
Comment thread openrag/services/orchestrators/query_service.py Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@openrag/services/orchestrators/query_service.py`:
- Around line 92-93: Update the JSON example in the query contextualizer
instruction so requires_retrieval uses a neutral boolean placeholder instead of
being hard-coded to true. Preserve the existing query_list and temporal_filters
structure while ensuring the final hint does not force retrieval for greetings
or casual requests.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c127fa77-4844-4136-8cb3-a2f1b6dfec8a

📥 Commits

Reviewing files that changed from the base of the PR and between 3d89102 and 37e4b46.

📒 Files selected for processing (10)
  • openrag/app_front.py
  • openrag/core/models/query.py
  • openrag/core/utils/source_filtering.py
  • openrag/prompts/templates/query_contextualizer_tmpl.txt
  • openrag/prompts/templates/spoken_style_answer_tmpl.txt
  • openrag/prompts/templates/sys_prompt_tmpl.txt
  • openrag/services/orchestrators/query_service.py
  • tests/unit/core/utils/test_source_filtering.py
  • tests/unit/services/orchestrators/test_query_service.py
  • tests/unit/test_app_front_secret.py

Comment thread openrag/services/orchestrators/query_service.py Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 726a38761b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread openrag/core/utils/source_filtering.py
Comment thread openrag/services/orchestrators/query_service.py Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c4ee108183

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread openrag/services/orchestrators/query_service.py Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1616658861

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread openrag/app_front.py Outdated
@andyne13

Copy link
Copy Markdown
Contributor

@hedhoud heads-up on a merge interaction — nothing wrong on your side, just so it isn't a surprise.

I reviewed today's four commits. The requires_retrieval design reads well: SearchQueries.requires_retrieval defaults to True, so a model that omits the field still retrieves, and force_retrieval covers websearch/map-reduce — it fails safe. b141f46f also fixes a real gap in its own predecessor, where the no-retrieval path sent no system prompt at all. c4ee1081 moves normalize_web_url into core/ cleanly, and the layer guard passes at this head. I also ran the whole unit suite against the branch merged with develop: 2268 passed.

The interaction is with #835 (DB-backed prompt library). That PR replaces the __init__-time prompt snapshots with per-request resolution, so these two attributes no longer exist on it:

# your new no-retrieval path (copied from the existing line in _prepare_chat)
tmpl = self._spoken_style_answer_prompt if spoken_style else self._sys_prompt_tmplt

Whichever of us merges second has to reconcile that. My suggestion: land this PR first and I'll absorb it in #835 — it's a three-line substitution in a file I'm already working in, and it means you don't have to learn an architecture you haven't touched just to ship a Chainlit fix. If #835 happens to land first instead, the replacement is:

prompt_type = "spoken_style_answer" if spoken_style else "sys_prompt"
tmpl = await self._prompt_service.resolve_prompt(
    prompt_type, names=[self._generation_prompt_name(prompt_type, partition)]
)

which is what _prepare_chat already does there — your path would gain per-partition prompt selection for free.

Worth flagging because git may not force the issue: the visible conflict is elsewhere in query_service.py (we both edited _prepare_completions), while the two attribute references sit in a hunk that can auto-merge cleanly and then AttributeError at runtime. Neither side's tests would catch it, since each comes from its own branch.

One substantive review point, separate from the above — 726a3876, inline citation stripping. The streaming path is solid; I fed it a marker split across SSE chunks ('[Source' + ' 1]') and it stripped correctly. But the pattern can't tell an LLM citation from quoted document text, and it removes mid-sentence:

'See [Sources 1](http://x) for details.'             -> 'See(http://x) for details.'
'The contract says: "see [Sources 1, 2] of annex A"' -> 'The contract says: "see of annex A"'   (+ records citations 1,2)
'Refer to [Source 3] in the appendix.'               -> 'Refer to in the appendix.'

The markdown-link case looks like a straight bug. The other two are a trade-off you may well accept — previously those markers stayed visible — but a quoted reference in a document now gets mangled and mis-attributed. Worth a guard, or a note that it's deliberate.

@andyne13 andyne13 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.

Approving — the Chainlit source handling is in good shape and the strip-set refinement from my earlier review landed exactly as suggested.

What I verified on this branch (merged with develop): full unit suite 2268 passed, layer guard OK, and the requires_retrieval design fails safe — SearchQueries.requires_retrieval defaults to True, so a model that omits the field still retrieves, and force_retrieval covers websearch/map-reduce. b141f46f also closes a real gap its own predecessor opened, where the no-retrieval path sent no system prompt at all. I also checked the streaming path with a citation marker split across SSE chunks ('[Source' + ' 1]') — stripped correctly.

Two things left as follow-ups rather than blockers:

  1. Inline citation stripping still mangles text at this head — include_inline_markers defaults to True, so the default path is unchanged:

    'See [Sources 1](http://x) for details.'             -> 'See(http://x) for details.'
    'The contract says: "see [Sources 1, 2] of annex A"' -> 'The contract says: "see of annex A"'   (+ records citations 1,2)
    

    The markdown-link case looks like a straight bug; the quoted-document case mangles text and mis-attributes sources. Worth a guard in a follow-up.

  2. The #835 interaction described in my earlier comment — self._spoken_style_answer_prompt / self._sys_prompt_tmplt are replaced there by per-request resolution. Nothing for you to do: land this first and I'll absorb it on my side.

@hedhoud
hedhoud merged commit 012ba1d into develop Jul 30, 2026
6 checks passed
@hedhoud
hedhoud deleted the agent/hide-empty-chainlit-sources branch July 30, 2026 12:12
andyne13 added a commit that referenced this pull request Jul 30, 2026
The no-retrieval reply came from #807 and read an __init__-time snapshot this
branch removes. Git auto-merged that reference without raising a conflict, so
the resolution I wrote during the merge had nothing asserting it — the same
shape of gap that let two stale attribute references through in the first
place.
@andyne13 andyne13 mentioned this pull request Jul 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working fix Fix issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Chainlit should hide Sources when no relevant evidence supports the answer

2 participants