Skip to content

fix(agent): prevent empty LLM user message after prompt fitting - #16413

Merged
yuzhichang merged 5 commits into
infiniflow:mainfrom
Taranum01:fix/agent-empty-llm-user-16411
Jul 1, 2026
Merged

yuzhichang merged 5 commits into
infiniflow:mainfrom
Taranum01:fix/agent-empty-llm-user-16411

Conversation

@Taranum01

Copy link
Copy Markdown
Contributor

Summary

  • Treat max_tokens=0 as unset (or 8192) when building model context budgets, fixing agents that silently zeroed prompts when a vLLM model had max_tokens: 0 in tenant config
  • Replace trailing same-role canvas history in LLM._sys_prompt_and_msg instead of skipping the current user prompt
  • Add LLM.fit_messages() validation after message_fit_in on agent paths so empty user content fails fast with a clear error instead of reaching vLLM

Fixes #16411

Root cause

Agent canvas workflow called message_fit_in with int(max_length * 0.97). When max_length was 0, 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 a user role message.

Test plan

  • Added test/unit_test/agent/component/test_llm_prompt.py for role-replace, validation, and zero-budget fitting
  • Added test_message_fit_in_zero_budget_preserves_non_empty_messages in test_generator_message_fit_in.py
  • CI unit tests
  • Manual: agent canvas begin → Retrieval → Agent → Message with vLLM Qwen3; confirm user message reaches LLM

Made with Cursor

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 27, 2026
@coderabbitai

coderabbitai Bot commented Jun 27, 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

Refactors shared LLM message fitting, updates streaming and invoke paths to use fitted messages and handle fit failures, hardens several max_tokens fallbacks to 8192, and adds unit coverage for prompt assembly and zero-budget behavior.

Changes

LLM Message Fitting and max_tokens Hardening

Layer / File(s) Summary
max_tokens fallback and fit guard
api/db/joint_services/tenant_model_service.py, api/db/services/dialog_service.py, api/db/services/tenant_llm_service.py, rag/prompts/generator.py
max_tokens and max_length now fall back to 8192 when falsy or non-positive in model config and prompt-fitting paths.
LLM fit helpers and prompt assembly
agent/component/llm.py
Adds effective_context_length, context_fit_budget, validate_fitted_messages, and fit_messages, and updates prompt assembly to replace or append formatted prompt messages.
LLM async paths use fit results
agent/component/llm.py
_stream_output_async and both branches of _invoke_async now use fit_messages and short-circuit on fit failures.
Agent tool callers consume fit results
agent/component/agent_with_tools.py
_fit_messages now returns a fitted-message/error pair, and agent tool formatting uses LLM.context_fit_budget.
Unit coverage for fitting edge cases
test/unit_test/agent/component/test_llm_prompt.py, test/unit_test/rag/prompts/test_generator_message_fit_in.py
Covers prompt rendering order, fit validation errors, zero-length fit_messages, and zero-budget message_fit_in behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • #16411: Agent-side fit handling and early-failure paths touch the empty-message flow described in the bug report.

Possibly related PRs

  • infiniflow/ragflow#15945: Both PRs modify get_model_config_from_provider_instance in tenant_model_service.py to change how max_tokens is propagated into downstream context sizing.

Poem

🐇 I hopped through tokens, snug and light,
No empty message sneaks by tonight.
With 8192 as the floor,
The rabbit keeps the prompt full to the core.
Fit, validate, and stream with cheer —
The LLM hears each word loud and clear!

🚥 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 is concise and accurately captures the main fix: preventing empty LLM user messages after prompt fitting.
Description check ✅ Passed The description matches the required template and includes summary, root cause, test plan, and linked issue reference.
Linked Issues check ✅ Passed The changes address the linked bug by preserving the user prompt, validating fitted messages, and preventing empty content from reaching vLLM.
Out of Scope Changes check ✅ Passed The touched files and tests align with the stated fix, with no clear unrelated code changes beyond the prompt-fitting and max_tokens behavior.

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

Guard 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 a text.strip() check here, or validate fmt_msgs before 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

📥 Commits

Reviewing files that changed from the base of the PR and between f90be41 and 75efeaa.

📒 Files selected for processing (8)
  • agent/component/agent_with_tools.py
  • agent/component/llm.py
  • api/db/joint_services/tenant_model_service.py
  • api/db/services/dialog_service.py
  • api/db/services/tenant_llm_service.py
  • rag/prompts/generator.py
  • test/unit_test/agent/component/test_llm_prompt.py
  • test/unit_test/rag/prompts/test_generator_message_fit_in.py

Comment thread agent/component/agent_with_tools.py Resolved
Comment thread agent/component/llm.py Resolved
Comment thread agent/component/llm.py Resolved
Comment thread agent/component/llm.py Resolved
Comment thread rag/prompts/generator.py Resolved
@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 27, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

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

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

Validate the schema-repair prompt before _generate_async().

Line 186 still calls message_fit_in() directly, so this retry path bypasses LLM.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 reuse LLM.fit_messages() here (or validate the fitted result before sending) and surface the fit_error instead 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

📥 Commits

Reviewing files that changed from the base of the PR and between 75efeaa and 47ff815.

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

@yuzhichang
yuzhichang self-requested a review June 28, 2026 00:44
@yuzhichang
yuzhichang force-pushed the main branch 2 times, most recently from 78db4e9 to f86a0e7 Compare June 29, 2026 01:47
@Taranum01
Taranum01 force-pushed the fix/agent-empty-llm-user-16411 branch from 47ff815 to dce0273 Compare June 29, 2026 05:09

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

📥 Commits

Reviewing files that changed from the base of the PR and between 47ff815 and dce0273.

📒 Files selected for processing (8)
  • agent/component/agent_with_tools.py
  • agent/component/llm.py
  • api/db/joint_services/tenant_model_service.py
  • api/db/services/dialog_service.py
  • api/db/services/tenant_llm_service.py
  • 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 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

📥 Commits

Reviewing files that changed from the base of the PR and between 47ff815 and dce0273.

📒 Files selected for processing (8)
  • agent/component/agent_with_tools.py
  • agent/component/llm.py
  • api/db/joint_services/tenant_model_service.py
  • api/db/services/dialog_service.py
  • api/db/services/tenant_llm_service.py
  • 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 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_prompt from 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

@yuzhichang yuzhichang added the ci Continue Integration label Jun 29, 2026

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jun 30, 2026
@Taranum01

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main and resolved the conflict in agent/component/llm.py — kept upstream's sys.files handling while preserving fit_messages() validation and async_chat_streamly_delta streaming.

@yuzhichang could you re-approve when you have a moment? The rebase will have dismissed the prior approval. Thanks!

@Taranum01
Taranum01 force-pushed the fix/agent-empty-llm-user-16411 branch from 7a2ca85 to d84b40f Compare June 30, 2026 08:42

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

123-131: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Limit same-role replacement to one history-boundary prompt.

After Line 128 replaces the trailing history message, len(msg) still equals history_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

📥 Commits

Reviewing files that changed from the base of the PR and between 7a2ca85 and d84b40f.

📒 Files selected for processing (8)
  • agent/component/agent_with_tools.py
  • agent/component/llm.py
  • api/db/joint_services/tenant_model_service.py
  • api/db/services/dialog_service.py
  • api/db/services/tenant_llm_service.py
  • 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 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

@Taranum01

Copy link
Copy Markdown
Contributor Author

CI failures (ragflow_tests_elasticsearch / ragflow_tests_infinity) are not from this PR's agent changes — Docker build fails on upstream main with:

```
Identifier 'React' has already been declared — web/src/components/ui/modal/modal.tsx:6
```

Same failure reproduces on main CI. Pushed a one-line fix (remove duplicate import React on line 2) to unblock the test jobs.

@Taranum01

Copy link
Copy Markdown
Contributor Author

Update on CI:

  1. Reverted the modal.tsx one-liner — it fixed the Docker build error but triggered preflight web-prettier / web-eslint failures (hooks only run when web files change). PR is back to agent-only scope.

  2. ragflow_tests_elasticsearch / ragflow_tests_infinity still fail on upstream main due to duplicate React import in web/src/components/ui/modal/modal.tsx — not caused by this PR's Python changes. Same failure on main CI.

  3. ragflow_preflight should pass again on the latest push (Python-only diff).

@yuzhichang — agent fix is approved; infra CI on main may need a separate web fix before full test jobs go green. Happy to drop the modal fix as a separate PR if useful.

Taranum01 and others added 4 commits June 30, 2026 14:45
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]>
@Taranum01
Taranum01 force-pushed the fix/agent-empty-llm-user-16411 branch from 3eb6a83 to 498564f Compare June 30, 2026 09:15
@codecov

codecov Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (540acb4) to head (5831996).
⚠️ Report is 16 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

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

@Taranum01

Copy link
Copy Markdown
Contributor Author

@yuzhichang — quick note on the remaining red check (ragflow_tests_elasticsearch).

Not related to this PR's agent changes. The only failure is a network timeout in a document REST API test:

test_documents_parse_chunks_and_scaled_bulk_contract
→ _seed_documents(..., count=20) uploading via POST /datasets/{id}/documents
ReadTimeout: host.docker.internal:11544 (read timeout=30)

Same test passed on ragflow_tests_infinity in the same workflow run (same PR merge ref). Overall: 512 passed, 1 failed — looks like ES runner load flakiness, not a regression from the agent/max_tokens diff (8 Python files only; no document upload/parse code touched).

ragflow_preflight ✅ · infinity ✅ · Codecov ✅ · LGTM ✅

Could you re-run ragflow_tests_elasticsearch when convenient, or merge if that’s acceptable on your side? Thanks!

@Taranum01

Copy link
Copy Markdown
Contributor Author

@yuzhichang — ES re-run also failed for infra reasons, not this PR:

  • Attempt 1: 512 passed, 1 ReadTimeout on document upload (test_documents_parse_chunks_and_scaled_bulk_contract)
  • Attempt 2 (re-run): SIGTERM (exit 143) killed pytest mid-run — not a test assertion failure

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]>
@Taranum01

Copy link
Copy Markdown
Contributor Author

@yuzhichang — all checks green on latest push (5831996c3). Ready to merge when you have a moment — thanks for the review!

@yuzhichang
yuzhichang merged commit e23f63b into infiniflow:main Jul 1, 2026
3 checks passed
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
@dosubot dosubot Bot mentioned this pull request Jul 8, 2026
4 tasks done
@dosubot dosubot Bot mentioned this pull request Jul 22, 2026
4 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Agent returns empty LLM response despite correct retrieval context

2 participants