Repository navigation
fix(agent): inject uploaded attachments into LLM context (#15215) - #15220
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughagent/component/llm.py collects ChangesSystem Files Integration into LLM Prompts
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)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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 liftAdd 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 varioussys.filesconfigurations.🤖 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
📒 Files selected for processing (1)
agent/component/llm.py
There was a problem hiding this comment.
♻️ Duplicate comments (1)
agent/component/llm.py (1)
283-300:⚠️ Potential issue | 🟠 Major | ⚡ Quick winAdd 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
📒 Files selected for processing (1)
agent/component/llm.py
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
test/unit_test/agent/component/test_llm_sys_files.py
|
@buua436 please review this PR and let me know the result. |
0a388d3 to
7066901
Compare
|
This PR currently has merge conflicts with Please run locally: git fetch origin main
git rebase origin/main
# or
git merge origin/mainAfter resolving the conflicts, push to the current head branch and CI will re-run the review checks.
|
…t-not-reaching-llm
…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]>
Summary
Fixes #15215 — attachments uploaded to an agent were not reaching the LLM.
When a user uploads a file in an agent chat,
canvas.runparses it intothe
sys.filesglobal (text content for documents,data:image/...URIsfor images — see
agent/canvas.py:752-768). But the LLM/Agent component's_prepare_prompt_variablesonly substitutes variables the user's prompttemplate explicitly references via
{var}placeholders. The defaultprompt 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 summaryand went searching the dataset instead ofreading the uploaded PDF.
Fix
agent/component/llm.py— added_collect_sys_files()and anauto-injection step in
_prepare_prompt_variables:sys.filesis non-empty and neithersys_promptnor any entryin
promptsalready contains{sys.files}(no double-injection),split the entries into text vs.
data:image/...URIs.self.imgs, which the existing logic usesto switch the chat model to
IMAGE2TEXTand passimages=...toasync_chat.userrole message inmsg,mirroring how
dialog_service.async_chat_solohandles attachments forthe non-agent chat path (
api/db/services/dialog_service.py:318-321).Both
LLM._invoke_asyncandAgent._invoke_async(tool-using) gothrough
_prepare_prompt_variables, so plain LLM nodes and Agent nodesare fixed in both streaming and non-streaming paths.
Test plan
{sys.query}prompt and ask "summarize the attachment" — the model should answer
from the file content rather than searching the knowledge base.
the model should switch to the vision-capable LLM and answer from
the image.
{sys.files}still works and does not include the file content twice.
uv run pytestto make sure no existing tests regress.Type of change