Repository navigation
fix(agent): prevent empty LLM user message after prompt fitting - #16413
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:
📝 WalkthroughWalkthroughRefactors shared LLM message fitting, updates streaming and invoke paths to use fitted messages and handle fit failures, hardens several ChangesLLM Message Fitting and max_tokens Hardening
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
agent/component/agent_with_tools.py (1)
181-186: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winGuard the schema-reformat retry against empty
text.If the first model call comes back empty, Line 183 builds
{"role":"user","content": ""}and Line 186 immediately resubmits it because this path reuses the shared budget calculation but skips the new empty-user validation. That leaves structured-output agents with the same bad request shape on the retry path. Add atext.strip()check here, or validatefmt_msgsbefore calling_generate_async().🤖 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/agent_with_tools.py` around lines 181 - 186, The schema-reformat retry path in `AgentWithTools._generate_async` can resend an empty user message when the first model response is blank. Add an explicit `text.strip()` guard before building `fmt_msgs`, or validate the assembled messages before calling `_generate_async()`, so the retry path does not submit the same empty request shape.
🤖 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/agent_with_tools.py`:
- Around line 117-120: The prompt-fit validation in _fit_messages() is being
turned into an uncaught ValueError, which can bypass the agent’s normal
_ERROR/default-output handling. Keep the same recoverable contract used by
LLM._invoke_async() and _stream_output_async() by handling the fit_error in
Agent._fit_messages(), or immediately in Agent._invoke_async() and
stream_output_with_tools_async(), and convert it into agent error state/output
instead of throwing. Also add logging for this new validation failure path so
the clear agent error is surfaced consistently.
In `@agent/component/llm.py`:
- Around line 323-330: The streaming fit-failure path in the async generator
currently returns after setting content, so the downstream consumer never
receives the configured exception default. Update the fit_error branch in the
generator that calls fit_messages to mirror the later model-error handling: when
get_exception_default_value() is present, set the output content and yield that
fallback before returning, and keep the existing _ERROR behavior when no default
is configured.
- Around line 141-149: The validation in validate_fitted_messages is too
permissive because it accepts any earlier non-empty user message instead of
requiring the final fitted message to be the user prompt. Update
validate_fitted_messages to check msg_fit[-1] directly (after the length guard)
and return success only when that last message has role user and non-empty
content; otherwise return the existing error. Keep the check localized to
validate_fitted_messages so the fitted message list always ends with a valid
user message.
- Around line 124-129: The prompt assembly logic in the message-building loop is
collapsing consecutive same-role configured prompts by overwriting the last
entry in msg. Update the replacement behavior in the code that formats
self._param.prompts so it only applies to the initial history boundary, and
allow later configured prompts in the sequence to append normally even when
roles match. Use the msg list handling around formatted, self.string_format, and
the msg[-1]["role"] check to preserve the intended prompt ordering.
In `@rag/prompts/generator.py`:
- Around line 70-72: The new fallback in generator.py normalizes non-positive
max_length values without any trace, so add a low-noise debug log in the
max_length guard before assigning the 8192 fallback. Use the existing context in
the prompt generation flow around the max_length check in the generator
function, and log only that the fit budget was normalized without including
message content or tenant data.
In `@test/unit_test/rag/prompts/test_generator_message_fit_in.py`:
- Around line 154-168: The zero-budget test for message_fit_in is too small to
reliably validate the intended fallback behavior. In
test_message_fit_in_zero_budget_preserves_non_empty_messages, strengthen the
assertion by either pushing the message sizes near the 8192 fallback boundary or
asserting the fallback boundary directly, so a regression in message_fit_in’s
max_length=0 handling cannot still pass with a much smaller non-zero reset
value. Use the existing message_fit_in, used_tokens, and trimmed checks to keep
the test focused on the zero-budget path.
---
Outside diff comments:
In `@agent/component/agent_with_tools.py`:
- Around line 181-186: The schema-reformat retry path in
`AgentWithTools._generate_async` can resend an empty user message when the first
model response is blank. Add an explicit `text.strip()` guard before building
`fmt_msgs`, or validate the assembled messages before calling
`_generate_async()`, so the retry path does not submit the same empty request
shape.
🪄 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: eb1d6942-ce91-4f76-9b6b-8b79473785ec
📒 Files selected for processing (8)
agent/component/agent_with_tools.pyagent/component/llm.pyapi/db/joint_services/tenant_model_service.pyapi/db/services/dialog_service.pyapi/db/services/tenant_llm_service.pyrag/prompts/generator.pytest/unit_test/agent/component/test_llm_prompt.pytest/unit_test/rag/prompts/test_generator_message_fit_in.py
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
agent/component/agent_with_tools.py (1)
181-187: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winValidate the schema-repair prompt before
_generate_async().Line 186 still calls
message_fit_in()directly, so this retry path bypassesLLM.validate_fitted_messages(). If the schema prompt consumes the whole budget,fmt_msgs[-1]["content"]can be trimmed to"", and_generate_async()will send the same empty user turn this PR is trying to block. Please reuseLLM.fit_messages()here (or validate the fitted result before sending) and surface thefit_errorinstead of invoking the model unconditionally. 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 `@agent/component/agent_with_tools.py` around lines 181 - 187, The schema-repair retry in _force_format_to_schema_async currently uses message_fit_in() and then calls _generate_async() without validating the fitted messages, so an empty or invalid user turn can still be sent. Update this path to use LLM.fit_messages() or otherwise run LLM.validate_fitted_messages() before generation, and stop early by surfacing the fit_error when the prompt cannot fit safely. Keep the existing schema_prompt/ fmt_msgs flow, but ensure the retry only reaches _generate_async() with a valid, non-empty user message and add logging for this new failure path.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.
Outside diff comments:
In `@agent/component/agent_with_tools.py`:
- Around line 181-187: The schema-repair retry in _force_format_to_schema_async
currently uses message_fit_in() and then calls _generate_async() without
validating the fitted messages, so an empty or invalid user turn can still be
sent. Update this path to use LLM.fit_messages() or otherwise run
LLM.validate_fitted_messages() before generation, and stop early by surfacing
the fit_error when the prompt cannot fit safely. Keep the existing
schema_prompt/ fmt_msgs flow, but ensure the retry only reaches
_generate_async() with a valid, non-empty user message and add logging for this
new failure path.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 008e1816-87a2-47b2-9c56-136d4a38a36c
📒 Files selected for processing (5)
agent/component/agent_with_tools.pyagent/component/llm.pyrag/prompts/generator.pytest/unit_test/agent/component/test_llm_prompt.pytest/unit_test/rag/prompts/test_generator_message_fit_in.py
🚧 Files skipped from review as they are similar to previous changes (4)
- test/unit_test/rag/prompts/test_generator_message_fit_in.py
- test/unit_test/agent/component/test_llm_prompt.py
- rag/prompts/generator.py
- agent/component/llm.py
78db4e9 to
f86a0e7
Compare
47ff815 to
dce0273
Compare
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 `@agent/component/agent_with_tools.py`:
- Around line 199-205: The new debug log in _invoke_async is exposing raw
user_prompt content, so update it to log metadata only while keeping the flow
trace. In agent_with_tools.py, adjust the _logger.debug call in
Agent._invoke_async to remove the json.dumps(kwargs.get("user_prompt", ...))
value and replace it with non-sensitive indicators such as presence/length or a
redacted placeholder. Keep the other context fields like self._id, kwargs keys,
and tools count so the log remains useful without leaking prompt text.
🪄 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: 510329e3-166c-40c3-8a4c-7ba6df926efb
📒 Files selected for processing (8)
agent/component/agent_with_tools.pyagent/component/llm.pyapi/db/joint_services/tenant_model_service.pyapi/db/services/dialog_service.pyapi/db/services/tenant_llm_service.pyrag/prompts/generator.pytest/unit_test/agent/component/test_llm_prompt.pytest/unit_test/rag/prompts/test_generator_message_fit_in.py
💤 Files with no reviewable changes (1)
- test/unit_test/rag/prompts/test_generator_message_fit_in.py
✅ Files skipped from review due to trivial changes (1)
- api/db/services/tenant_llm_service.py
🚧 Files skipped from review as they are similar to previous changes (5)
- rag/prompts/generator.py
- test/unit_test/agent/component/test_llm_prompt.py
- api/db/joint_services/tenant_model_service.py
- api/db/services/dialog_service.py
- agent/component/llm.py
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
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 `@agent/component/agent_with_tools.py`:
- Around line 199-205: The new debug log in _invoke_async is exposing raw
user_prompt content, so update it to log metadata only while keeping the flow
trace. In agent_with_tools.py, adjust the _logger.debug call in
Agent._invoke_async to remove the json.dumps(kwargs.get("user_prompt", ...))
value and replace it with non-sensitive indicators such as presence/length or a
redacted placeholder. Keep the other context fields like self._id, kwargs keys,
and tools count so the log remains useful without leaking prompt text.
🪄 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: 510329e3-166c-40c3-8a4c-7ba6df926efb
📒 Files selected for processing (8)
agent/component/agent_with_tools.pyagent/component/llm.pyapi/db/joint_services/tenant_model_service.pyapi/db/services/dialog_service.pyapi/db/services/tenant_llm_service.pyrag/prompts/generator.pytest/unit_test/agent/component/test_llm_prompt.pytest/unit_test/rag/prompts/test_generator_message_fit_in.py
💤 Files with no reviewable changes (1)
- test/unit_test/rag/prompts/test_generator_message_fit_in.py
✅ Files skipped from review due to trivial changes (1)
- api/db/services/tenant_llm_service.py
🚧 Files skipped from review as they are similar to previous changes (5)
- rag/prompts/generator.py
- test/unit_test/agent/component/test_llm_prompt.py
- api/db/joint_services/tenant_model_service.py
- api/db/services/dialog_service.py
- agent/component/llm.py
🛑 Comments failed to post (1)
agent/component/agent_with_tools.py (1)
199-205: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Redact
user_promptfrom the new debug log.Line 203 writes raw end-user prompt text into application logs. Agent prompts can carry tenant data, retrieved context, or secrets, so this creates a new log-based data exposure path. Keep the flow log, but record metadata only. As per coding guidelines,
**/*.py: Add logging for new flows.Suggested fix
_logger.debug( - "[Agent] _invoke_async called. Component: %s, Keys in kwargs: %s, user_prompt: %s, tools count: %d", + "[Agent] _invoke_async called. Component: %s, Keys in kwargs: %s, user_prompt_len: %d, tools count: %d", self._id, list(kwargs.keys()), - json.dumps(kwargs.get("user_prompt", ""), ensure_ascii=False, default=str)[:300], + 0 if kwargs.get("user_prompt") is None else len(str(kwargs["user_prompt"])), len(self.tools) if self.tools else 0, )📝 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._logger.debug( "[Agent] _invoke_async called. Component: %s, Keys in kwargs: %s, user_prompt_len: %d, tools count: %d", self._id, list(kwargs.keys()), 0 if kwargs.get("user_prompt") is None else len(str(kwargs["user_prompt"])), len(self.tools) if self.tools else 0, )🧰 Tools
🪛 ast-grep (0.44.0)
[info] 202-202: use jsonify instead of json.dumps for JSON output
Context: json.dumps(kwargs.get("user_prompt", ""), ensure_ascii=False, default=str)
Note: [CWE-116] Improper Encoding or Escaping of Output.(use-jsonify)
🤖 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/agent_with_tools.py` around lines 199 - 205, The new debug log in _invoke_async is exposing raw user_prompt content, so update it to log metadata only while keeping the flow trace. In agent_with_tools.py, adjust the _logger.debug call in Agent._invoke_async to remove the json.dumps(kwargs.get("user_prompt", ...)) value and replace it with non-sensitive indicators such as presence/length or a redacted placeholder. Keep the other context fields like self._id, kwargs keys, and tools count so the log remains useful without leaking prompt text.Source: Coding guidelines
|
Rebased onto latest @yuzhichang could you re-approve when you have a moment? The rebase will have dismissed the prior approval. Thanks! |
7a2ca85 to
d84b40f
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
agent/component/llm.py (1)
123-131: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winLimit same-role replacement to one history-boundary prompt.
After Line 128 replaces the trailing history message,
len(msg)still equalshistory_size, so a second configured prompt with the same role can replace the first configured prompt instead of appending. Use a one-shot flag and clear it after the first prompt is processed.Proposed fix
history_size = len(msg) + replace_trailing_history = bool(msg) for p in self._param.prompts: formatted = deepcopy(p) formatted["content"] = self.string_format(formatted["content"], args) - if len(msg) == history_size and msg and msg[-1]["role"] == formatted["role"]: + if replace_trailing_history and len(msg) == history_size and msg[-1]["role"] == formatted["role"]: msg[-1] = formatted else: msg.append(formatted) + replace_trailing_history = False return msg, self.string_format(self._param.sys_prompt, args)🤖 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 123 - 131, The prompt merge logic in string_format() currently allows multiple configured prompts with the same role to keep replacing the same trailing history message because len(msg) never changes after the first swap. Add a one-shot boundary flag in the loop over self._param.prompts so only the first same-role prompt can replace msg[-1], then clear the flag immediately after that replacement and append all subsequent prompts normally.
🤖 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 123-131: The prompt merge logic in string_format() currently
allows multiple configured prompts with the same role to keep replacing the same
trailing history message because len(msg) never changes after the first swap.
Add a one-shot boundary flag in the loop over self._param.prompts so only the
first same-role prompt can replace msg[-1], then clear the flag immediately
after that replacement and append all subsequent prompts normally.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 6dbab534-c4fd-4a51-99a7-8c6db20eb55f
📒 Files selected for processing (8)
agent/component/agent_with_tools.pyagent/component/llm.pyapi/db/joint_services/tenant_model_service.pyapi/db/services/dialog_service.pyapi/db/services/tenant_llm_service.pyrag/prompts/generator.pytest/unit_test/agent/component/test_llm_prompt.pytest/unit_test/rag/prompts/test_generator_message_fit_in.py
💤 Files with no reviewable changes (3)
- rag/prompts/generator.py
- test/unit_test/agent/component/test_llm_prompt.py
- test/unit_test/rag/prompts/test_generator_message_fit_in.py
🚧 Files skipped from review as they are similar to previous changes (4)
- api/db/services/tenant_llm_service.py
- api/db/services/dialog_service.py
- api/db/joint_services/tenant_model_service.py
- agent/component/agent_with_tools.py
|
CI failures ( ``` Same failure reproduces on main CI. Pushed a one-line fix (remove duplicate |
|
Update on CI:
@yuzhichang — agent fix is approved; infra CI on |
Treat max_tokens=0 as unset, replace trailing same-role prompts instead of skipping them, and validate agent messages after message_fit_in so canvas agents no longer send empty user content to vLLM. Fixes infiniflow#16411
Handle fit errors via agent output state instead of ValueError, only replace trailing history on the first configured prompt, require the final fitted message to be a non-empty user turn, yield streaming fallbacks, and tighten zero-budget tests.
Log presence and length only instead of serializing prompt content.
Align modal.tsx with upstream fix (revert had reintroduced duplicate React import). Run ruff format on changed Python files for preflight. Co-authored-by: Cursor <[email protected]>
3eb6a83 to
498564f
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16413 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
@yuzhichang — quick note on the remaining red check ( Not related to this PR's agent changes. The only failure is a network timeout in a document REST API test: Same test passed on
Could you re-run |
|
@yuzhichang — ES re-run also failed for infra reasons, not this PR:
Infinity is green on the same SHA; ES was fully green on Jun 29 for this PR. Changes are agent/LLM prompt fitting only — no overlap with document upload or dataset search tests. No code changes planned. Would appreciate merge when convenient. Thanks! |
Co-authored-by: Cursor <[email protected]>
|
@yuzhichang — all checks green on latest push ( |
Summary
max_tokens=0as unset (or 8192) when building model context budgets, fixing agents that silently zeroed prompts when a vLLM model hadmax_tokens: 0in tenant configLLM._sys_prompt_and_msginstead of skipping the current user promptLLM.fit_messages()validation aftermessage_fit_inon agent paths so empty user content fails fast with a clear error instead of reaching vLLMFixes #16411
Root cause
Agent canvas workflow called
message_fit_inwithint(max_length * 0.97). Whenmax_lengthwas0, both system and user content were trimmed to empty strings. The[HISTORY STREAMLY]log showing only{"role":"user","content":""}matches this. A secondary bug skipped appending the formatted user prompt when history ended with auserrole message.Test plan
test/unit_test/agent/component/test_llm_prompt.pyfor role-replace, validation, and zero-budget fittingtest_message_fit_in_zero_budget_preserves_non_empty_messagesintest_generator_message_fit_in.pybegin → Retrieval → Agent → Messagewith vLLM Qwen3; confirm user message reaches LLMMade with Cursor