Skip to content

fix(agent): inject uploaded attachments into LLM context (#15215) - #15220

Merged
yuzhichang merged 6 commits into
infiniflow:mainfrom
Rene0422:fix/agent-attachment-not-reaching-llm
Jun 30, 2026
Merged

yuzhichang merged 6 commits into
infiniflow:mainfrom
Rene0422:fix/agent-attachment-not-reaching-llm

Conversation

@Rene0422

Copy link
Copy Markdown
Contributor

Summary

Fixes #15215 — attachments uploaded to an agent were not reaching the LLM.

When a user uploads a file in an agent chat, canvas.run parses it into
the sys.files global (text content for documents, data:image/... URIs
for images — see agent/canvas.py:752-768). But the LLM/Agent component's
_prepare_prompt_variables only substitutes variables the user's prompt
template explicitly references via {var} placeholders. The default
prompt is [{"role": "user", "content": "{sys.query}"}] with no
{sys.files}, so the parsed attachment content never reaches the model.

In the reporter's logs, this is why the agent saw only the bare query
附件 摘要 attachment summary and went searching the dataset instead of
reading the uploaded PDF.

Fix

agent/component/llm.py — added _collect_sys_files() and an
auto-injection step in _prepare_prompt_variables:

  • If sys.files is non-empty and neither sys_prompt nor any entry
    in prompts already contains {sys.files} (no double-injection),
    split the entries into text vs. data:image/... URIs.
  • Image URIs are merged into self.imgs, which the existing logic uses
    to switch the chat model to IMAGE2TEXT and pass images=... to
    async_chat.
  • Text content is appended to the last user role message in msg,
    mirroring how dialog_service.async_chat_solo handles attachments for
    the non-agent chat path (api/db/services/dialog_service.py:318-321).

Both LLM._invoke_async and Agent._invoke_async (tool-using) go
through _prepare_prompt_variables, so plain LLM nodes and Agent nodes
are fixed in both streaming and non-streaming paths.

Test plan

  • Upload a PDF attachment to an agent with the default {sys.query}
    prompt and ask "summarize the attachment" — the model should answer
    from the file content rather than searching the knowledge base.
  • Upload an image attachment to an agent and ask about its contents —
    the model should switch to the vision-capable LLM and answer from
    the image.
  • Verify that an agent whose prompt does include {sys.files}
    still works and does not include the file content twice.
  • Verify that an agent run with no attachments behaves unchanged.
  • Run uv run pytest to make sure no existing tests regress.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 25, 2026
@coderabbitai

coderabbitai Bot commented May 25, 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

agent/component/llm.py collects sys.files from canvas globals, separates text and data:image URIs (unless {sys.files} is referenced), merges images into self.imgs with deduplication, rebinds the chat model to IMAGE2TEXT when images exist, and injects joined system-file text into the latest user message (or adds one).

Changes

System Files Integration into LLM Prompts

Layer / File(s) Summary
System file collection helper
agent/component/llm.py, test/unit_test/agent/component/test_llm_sys_files.py
_collect_sys_files() extracts text entries and data:image/... URIs from self._canvas.globals['sys.files'], skips injection when {sys.files} is present in system or user prompt templates, and is covered by tests and test scaffolding.
Prompt preparation integration
agent/component/llm.py, test/unit_test/agent/component/test_llm_sys_files.py
_prepare_prompt_variables() merges deduplicated system-file images into self.imgs, rebinds chat_mdl to IMAGE2TEXT when images exist and LLM type is CHAT, and concatenates system-file text into the latest user-role message or creates one; tests verify skipping behavior when {sys.files} is explicit.

Sequence Diagram(s)

sequenceDiagram
  participant CanvasGlobals
  participant LLMComponent
  participant ChatModel
  CanvasGlobals->>LLMComponent: provide sys.files entries (text + data:image URIs)
  LLMComponent->>LLMComponent: _collect_sys_files() -> split text vs image URIs
  LLMComponent->>LLMComponent: merge/deduplicate images into self.imgs
  LLMComponent->>ChatModel: if imgs && LLM type == CHAT => rebind chat_mdl to IMAGE2TEXT
  LLMComponent->>LLMComponent: append joined text into latest user message (or create one)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I found the files tucked in a stack,
Text and pixels joining the chat,
I hop, dedupe, then bind the right pack,
User words hold the system stack,
Hooray—attachments now answer back!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Title check ✅ Passed The title concisely summarizes the main fix: injecting uploaded attachments into LLM context, directly addressing the bug described in issue #15215.
Description check ✅ Passed The PR description includes all template sections: problem statement (attachment not reaching LLM), type of change (Bug Fix selected), and comprehensive context including root cause, fix details, and test plan.
Linked Issues check ✅ Passed The PR implements all coding requirements from #15215: auto-injecting non-empty sys.files into prompts, splitting text vs image URIs, merging images into self.imgs for vision model switching, and appending text to user messages.
Out of Scope Changes check ✅ Passed All changes are within scope: agent/component/llm.py adds the sys.files injection logic, and test/unit_test/agent/component/test_llm_sys_files.py provides comprehensive unit tests for the new functionality.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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: 2

Caution

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

⚠️ Outside diff range comments (1)
agent/component/llm.py (1)

227-291: 🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

Add automated test coverage for system file injection flow.

The new _collect_sys_files() and integration logic introduces several branches that should be tested:

  • Empty sys.files (no injection)
  • Explicit {sys.files} placeholder present (skip auto-injection)
  • Text-only files
  • Image-only files
  • Mixed text and images
  • No existing user messages in history

Without automated tests, regressions and edge cases may go undetected.

Consider adding unit tests for _collect_sys_files() and integration tests for the full prompt preparation flow with various sys.files configurations.

🤖 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 `@agent/component/llm.py` around lines 227 - 291, Add automated tests covering
the new system-file injection logic: write unit tests for _collect_sys_files on
the Agent/LLM component to assert behavior for empty sys.files, explicit
"{sys.files}" in _param.sys_prompt or in entries of _param.prompts, text-only
files, image-only data URIs, and mixed lists; then add integration tests
exercising _prepare_prompt_variables to verify that sys file texts are injected
into the user message (or appended as a new user message when history has no
user messages), that image data URIs are routed into imgs and trigger chat image
model creation when llm type is CHAT (use TenantLLMService.llm_id2llm_type and
LLMBundle mocks), and that inputs get their data images removed via
_extract_data_images/_remove_data_images and set via set_input_value; use
mocks/stubs for _canvas.get_variable_value, _canvas.globals["sys.files"],
_canvas.get_history, and LLMBundle to assert side-effects.
🤖 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 `@agent/component/llm.py`:
- Around line 227-250: In _collect_sys_files, add logging to make the flow
observable: when files is empty log and return, when files is present log the
total count, when the explicit placeholder check detects "{sys.files}" (variable
explicit) log that injection is being skipped, log whenever a non-str entry is
skipped, and before returning log counts of text_parts and image_data_uris; use
the class logger (e.g. self._logger) and appropriate levels (debug/info) and
include the relevant variables (files, explicit, text_parts length,
image_data_uris length) so callers can trace why attachments were ignored.
- Around line 274-291: The code injects system file texts and images into the
prompt without any logging; add logging calls around the two flows: after
self.imgs is updated (the line using self._uniq_images and imgs + extracted_imgs
+ sys_file_imgs) log a concise summary (counts of new images, maybe their
filenames or ids) and the LLM type check result, and after injecting
sys_file_texts into msg (the block that builds joined and appends/merges into
msg) log that system text was merged into the user message including a short
preview or length and which message index was modified (use symbols
_collect_sys_files, imgs, _uniq_images, chat_mdl/LLMBundle, _sys_prompt_and_msg,
msg, sys_file_texts to locate the spots). Use the existing logger (e.g.
self._logger) at info/debug level and avoid logging full sensitive content.

---

Outside diff comments:
In `@agent/component/llm.py`:
- Around line 227-291: Add automated tests covering the new system-file
injection logic: write unit tests for _collect_sys_files on the Agent/LLM
component to assert behavior for empty sys.files, explicit "{sys.files}" in
_param.sys_prompt or in entries of _param.prompts, text-only files, image-only
data URIs, and mixed lists; then add integration tests exercising
_prepare_prompt_variables to verify that sys file texts are injected into the
user message (or appended as a new user message when history has no user
messages), that image data URIs are routed into imgs and trigger chat image
model creation when llm type is CHAT (use TenantLLMService.llm_id2llm_type and
LLMBundle mocks), and that inputs get their data images removed via
_extract_data_images/_remove_data_images and set via set_input_value; use
mocks/stubs for _canvas.get_variable_value, _canvas.globals["sys.files"],
_canvas.get_history, and LLMBundle to assert side-effects.
🪄 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: 426c9565-7c44-49b8-82e0-fea7d5d36343

📥 Commits

Reviewing files that changed from the base of the PR and between 4b36801 and 72203d5.

📒 Files selected for processing (1)
  • agent/component/llm.py

Comment thread agent/component/llm.py Resolved
Comment thread agent/component/llm.py Resolved

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

♻️ Duplicate comments (1)
agent/component/llm.py (1)

283-300: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add logging to track system file injection into prompt.

The integration of system files into the prompt still lacks logging. When images are merged, when the model switches to IMAGE2TEXT, and when text is appended to messages, there's no visibility. This makes debugging attachment issues (like #15215) difficult.

As per coding guidelines, "Add logging for new flows" for **/*.py.

📝 Proposed logging additions
     sys_file_texts, sys_file_imgs = self._collect_sys_files()
     self.imgs = self._uniq_images(self.imgs + extracted_imgs + sys_file_imgs)
+    if sys_file_imgs:
+        logging.info("[LLM] merged %d system file image(s) into context", len(sys_file_imgs))
     if self.imgs and TenantLLMService.llm_id2llm_type(self._param.llm_id) == LLMType.CHAT.value:
         self.chat_mdl = LLMBundle(self._canvas.get_tenant_id(), LLMType.IMAGE2TEXT.value,
                                   self._param.llm_id, max_retries=self._param.max_retries,
                                   retry_interval=self._param.delay_after_error
                                   )
+        logging.info("[LLM] switched to IMAGE2TEXT model for %d total image(s)", len(self.imgs))

     msg, sys_prompt = self._sys_prompt_and_msg(self._canvas.get_history(self._param.message_history_window_size)[:-1], args)

     if sys_file_texts:
         joined = "\n\n".join(sys_file_texts)
+        logging.info("[LLM] injecting %d system file text item(s) into user message (total_len=%d)", len(sys_file_texts), len(joined))
         for i in range(len(msg) - 1, -1, -1):
             if msg[i].get("role") == "user":
                 msg[i]["content"] = (msg[i].get("content") or "") + "\n\n" + joined
+                logging.debug("[LLM] appended system text to user message at index %d", i)
                 break
         else:
+            logging.info("[LLM] no user message found; creating new user message for system file text")
             msg.append({"role": "user", "content": joined})
🤖 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 `@agent/component/llm.py` around lines 283 - 300, The code injects system files
and images into prompts but lacks logging; add debug/info logs in the block
around _collect_sys_files/_uniq_images and the IMAGE2TEXT chat model switch: log
counts and identifiers after calling self._collect_sys_files(), log before/after
calling self._uniq_images(self.imgs + extracted_imgs + sys_file_imgs) (e.g.,
previous count, added count), log when
TenantLLMService.llm_id2llm_type(self._param.llm_id) triggers creating
self.chat_mdl = LLMBundle(..., LLMType.IMAGE2TEXT.value) (include llm_id and
chosen type), and log when sys_file_texts are joined and appended into msg
inside the for/else that mutates msg returned by
_sys_prompt_and_msg/self._canvas.get_history (include length of joined text and
index where it was inserted or that a new user message was appended). Use the
existing component logger (e.g., self.logger or module logger) at debug/info
level and keep messages concise and structured for traceability.
🤖 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.

Duplicate comments:
In `@agent/component/llm.py`:
- Around line 283-300: The code injects system files and images into prompts but
lacks logging; add debug/info logs in the block around
_collect_sys_files/_uniq_images and the IMAGE2TEXT chat model switch: log counts
and identifiers after calling self._collect_sys_files(), log before/after
calling self._uniq_images(self.imgs + extracted_imgs + sys_file_imgs) (e.g.,
previous count, added count), log when
TenantLLMService.llm_id2llm_type(self._param.llm_id) triggers creating
self.chat_mdl = LLMBundle(..., LLMType.IMAGE2TEXT.value) (include llm_id and
chosen type), and log when sys_file_texts are joined and appended into msg
inside the for/else that mutates msg returned by
_sys_prompt_and_msg/self._canvas.get_history (include length of joined text and
index where it was inserted or that a new user message was appended). Use the
existing component logger (e.g., self.logger or module logger) at debug/info
level and keep messages concise and structured for traceability.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9424ec36-bc34-47ad-8183-c170eb6c5af2

📥 Commits

Reviewing files that changed from the base of the PR and between 72203d5 and b8c2a2a.

📒 Files selected for processing (1)
  • agent/component/llm.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

🤖 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 `@test/unit_test/agent/component/test_llm_sys_files.py`:
- Around line 17-109: The new tests in test_llm_sys_files.py lack the repo's
pytest priority markers; import pytest and add the appropriate priority (e.g.,
p1) so they follow the p1/p2/p3 convention — the easiest fix is to add a
module-level marker like pytestmark = [pytest.mark.p1] at top of the file (or
add `@pytest.mark.p1` to each test function such as
test_collect_sys_files_empty_returns_empty, test_collect_sys_files_text_only,
etc.) ensuring all test functions in this file are marked.
🪄 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: 9834adde-5ffe-4cc6-a435-75e2261e3770

📥 Commits

Reviewing files that changed from the base of the PR and between 7fc5334 and 97d4e09.

📒 Files selected for processing (1)
  • test/unit_test/agent/component/test_llm_sys_files.py

@wangq8
wangq8 requested a review from buua436 May 26, 2026 01:57
@Rene0422

Copy link
Copy Markdown
Contributor Author

@buua436 please review this PR and let me know the result.

@Rene0422
Rene0422 force-pushed the fix/agent-attachment-not-reaching-llm branch from 0a388d3 to 7066901 Compare June 4, 2026 13:15
@yuzhichang
yuzhichang self-requested a review June 28, 2026 00:49
@yuzhichang

yuzhichang commented Jun 28, 2026 •

Copy link
Copy Markdown
Member

This PR currently has merge conflicts with main and cannot be auto-synced.

Please run locally:

git fetch origin main
git rebase origin/main
# or
git merge origin/main

After resolving the conflicts, push to the current head branch and CI will re-run the review checks.

Triggered by reviewer yuzhichang (request-for-action)

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jun 30, 2026
@yuzhichang
yuzhichang merged commit dc8b6d7 into infiniflow:main Jun 30, 2026
6 checks passed
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 1, 2026
…15215) (infiniflow#15220)

## Summary

Fixes infiniflow#15215 — attachments uploaded to an agent were not reaching the
LLM.

When a user uploads a file in an agent chat, `canvas.run` parses it into
the `sys.files` global (text content for documents, `data:image/...`
URIs
for images — see `agent/canvas.py:752-768`). But the LLM/Agent
component's
`_prepare_prompt_variables` only substitutes variables the user's prompt
template explicitly references via `{var}` placeholders. The default
prompt is `[{"role": "user", "content": "{sys.query}"}]` with no
`{sys.files}`, so the parsed attachment content never reaches the model.

In the reporter's logs, this is why the agent saw only the bare query
`附件 摘要 attachment summary` and went searching the dataset instead of
reading the uploaded PDF.

## Fix

`agent/component/llm.py` — added `_collect_sys_files()` and an
auto-injection step in `_prepare_prompt_variables`:

- If `sys.files` is non-empty **and** neither `sys_prompt` nor any entry
  in `prompts` already contains `{sys.files}` (no double-injection),
  split the entries into text vs. `data:image/...` URIs.
- Image URIs are merged into `self.imgs`, which the existing logic uses
  to switch the chat model to `IMAGE2TEXT` and pass `images=...` to
  `async_chat`.
- Text content is appended to the last `user` role message in `msg`,
  mirroring how `dialog_service.async_chat_solo` handles attachments for
  the non-agent chat path (`api/db/services/dialog_service.py:318-321`).

Both `LLM._invoke_async` and `Agent._invoke_async` (tool-using) go
through `_prepare_prompt_variables`, so plain LLM nodes and Agent nodes
are fixed in both streaming and non-streaming paths.

## Test plan

- [ ] Upload a PDF attachment to an agent with the default `{sys.query}`
prompt and ask "summarize the attachment" — the model should answer
      from the file content rather than searching the knowledge base.
- [ ] Upload an image attachment to an agent and ask about its contents
—
      the model should switch to the vision-capable LLM and answer from
      the image.
- [ ] Verify that an agent whose prompt **does** include `{sys.files}`
      still works and does **not** include the file content twice.
- [ ] Verify that an agent run with no attachments behaves unchanged.
- [ ] Run `uv run pytest` to make sure no existing tests regress.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):

---------

Co-authored-by: yzc <[email protected]>
yuzhichang pushed a commit that referenced this pull request Jul 2, 2026
### Summary

Port the following PRs to GO in this PR

#14210
#14641
#15220
#15228
#15384
#15754
#16413
#16483
#16419
#16361   
#16050
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Question]: The Attachment of Agent not works

2 participants