Skip to content

fix(agent): fit LLM prompts to model content_length - #18093

Merged
yuzhichang merged 7 commits into
infiniflow:mainfrom
jay77721:pr/3-agent-content-length
Aug 12, 2026
Merged

yuzhichang merged 7 commits into
infiniflow:mainfrom
jay77721:pr/3-agent-content-length

Conversation

@jay77721

@jay77721 jay77721 commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Use the chat model's context window (content_length) as the message-fitting budget instead of the canvas max_tokens parameter.

Why

max_tokens caps generation length only. Using it as the input-trimming budget collapsed the usable context for models whose context window is much larger than max_output — exactly the failure the fitting logic was added to avoid.

Changes

  • internal/agent/component/llm.go: fitting budget is now the resolved content_length (0 → 8192 fallback). Resolution goes through the shared dao.ResolveModelContentLength (feat(dao): add shared ResolveModelContentLength helper #18106), and a resolution-failure debug log is emitted from LLMComponent.Invoke so an unexpected 8192 fallback is diagnosable.
  • The canvas max_tokens is left untouched as the generation cap — it still reaches the invoker as ChatInvokeRequest.MaxTokens (output limit); it just no longer drives input trimming.
  • internal/agent/component/llm.go: validation errors now point at the model content_length setting instead of max_tokens.
  • No field renames: MaxTokens keeps its existing name; only the fitting-budget source changes.

Testing

Known limitations (follow-up)

dao.ResolveModelContentLength (from #18106) currently reads content_length from the provider catalog only; per-model max_tokens overrides in tenant_model.extra are not honored yet (Python resolves them via model_extra.get("max_tokens") or 8192). Models absent from the catalog therefore fall back to the 8192 fitting budget. A follow-up PR will honor the extra["max_tokens"] override — tracked alongside #18106.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code labels Aug 11, 2026
@coderabbitai

coderabbitai Bot commented Aug 11, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e40bb479-2994-4ef6-a9cf-7078fe40cc61

📥 Commits

Reviewing files that changed from the base of the PR and between b73aac3 and adf1a81.

📒 Files selected for processing (8)
  • internal/agent/chat/chat.go
  • internal/agent/component/fixture_stubs.go
  • internal/agent/component/llm.go
  • internal/agent/component/llm_test.go
  • internal/component/messagefit/messagefit.go
  • internal/component/messagefit/messagefit_test.go
  • internal/dao/model_context.go
  • internal/dao/model_context_test.go
🚧 Files skipped from review as they are similar to previous changes (7)
  • internal/agent/chat/chat.go
  • internal/component/messagefit/messagefit_test.go
  • internal/agent/component/fixture_stubs.go
  • internal/component/messagefit/messagefit.go
  • internal/dao/model_context.go
  • internal/agent/component/llm_test.go
  • internal/agent/component/llm.go

📝 Walkthrough

Walkthrough

The change renames output-token fields to MaxOutput, adds model context-length resolution, centralizes message fitting in messagefit, and updates multimodal fitting and validation.

Changes

LLM token budgeting

Layer / File(s) Summary
Output limit contract
internal/agent/chat/chat.go, internal/agent/component/fixture_stubs.go, internal/agent/component/llm.go
Renames MaxTokens to MaxOutput across request, parameter, conversion, invocation, retry, metadata, and registration paths.
Model context resolution
internal/dao/model_context.go, internal/dao/model_context_test.go, internal/agent/component/llm.go
Resolves model content length from tenant records, composite references, and driver/model fallbacks. Tests cover active, inactive, unknown, and empty references.
Shared message fitting
internal/component/messagefit/*
Adds messagefit.Message and messagefit.Fit for budgeted trimming, message retention, proportional system trimming, and token counting.
Context-aware LLM fitting
internal/agent/component/llm.go, internal/agent/component/llm_test.go
Uses the resolved context window and shared fitter. Preserves image-only and multimodal content, restores trimmed text, removes dropped parts, and validates the final user turn. Tests cover these fitting cases.

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

Possibly related PRs

Suggested labels: 🐞 bug, 🧪 test

Suggested reviewers: xugangqiang

Sequence Diagram(s)

sequenceDiagram
  participant LLMComponent
  participant ModelContextDAO
  participant messagefit
  LLMComponent->>ModelContextDAO: Resolve model content length
  ModelContextDAO-->>LLMComponent: Return context window
  LLMComponent->>messagefit: Fit messages to context budget
  messagefit-->>LLMComponent: Return fitted messages
  LLMComponent->>LLMComponent: Restore multimodal content and validate final user turn
Loading

Poem

A rabbit trims the tokens light,
Keeps system words and user’s bite.
Images hop, text folds with care,
MaxOutput guides the answer there.
Context windows bloom just right.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: fitting LLM prompts using the model content_length budget.
Description check ✅ Passed The description includes the required summary, background, implementation details, testing, dependencies, and known limitations.

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.

@jay77721 jay77721 added the ci Continue Integration label Aug 11, 2026
@jay77721
jay77721 requested a review from xugangqiang August 11, 2026 07:43

@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

🧹 Nitpick comments (5)
internal/agent/component/llm.go (2)

1030-1114: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider splitting fitMessages into conversion helpers.

The function now performs four phases in ~85 lines: deep copy, conversion to messagefit.Message with source tracking, fitting, and conversion back. Extracting toFitMessages(systemPrompt, copied) ([]messagefit.Message, []fitSource) and fromFitMessages(all, sources, copied) []schema.Message would make each phase testable on its own and would let fitSource move to file scope. This is a readability change only; behavior stays the same.

🤖 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 `@internal/agent/component/llm.go` around lines 1030 - 1114, Split fitMessages
into focused conversion helpers: move fitSource to file scope, extract
toFitMessages for building messagefit.Message values and source metadata, and
extract fromFitMessages for reconstructing []schema.Message. Keep deep-copying
and contextFitBudget/messagefit.Fit orchestration in fitMessages, preserving the
existing behavior and ordering.

1052-1113: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add over-budget coverage for multimodal messages.

The new conversion tracks whether text lives in Content or in a UserInputMultiContent text part. Both new multimodal tests (TestFitMessages_PreservesImageOnlyTurn and TestFitMessages_EverythingFits) use maxLength = 100000, so they only exercise the everything-fits path in messagefit.Fit.

Two branches stay untested:

  • A message whose text lives in UserInputMultiContent[multiIdx] and is trimmed by step 3. Line 1107 must write the trimmed text back into the part and keep the image parts.
  • An image-only turn that becomes lastNonSystem in messagefit.Fit. Its Content is "", so step 3 assigns the whole budget to the system message and drops the preceding text-bearing turn.

Add a test with a small maxLength and a user message that carries both a text part and an image part.

🤖 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 `@internal/agent/component/llm.go` around lines 1052 - 1113, Add over-budget
coverage for multimodal fitting using a small maxLength: create a user message
containing both a text part and an image part, and assert the fitted text is
written back to the original UserInputMultiContent part while the image part
remains. Also cover an image-only turn becoming lastNonSystem, verifying the
preceding text-bearing turn is dropped while the image-only turn is preserved.
internal/component/messagefit/messagefit_test.go (1)

33-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the dead scaffolding in the new test file. The new test file carries leftover helpers and computations that no assertion uses. The shared root cause is exploratory scaffolding kept after the tests were finalized.

  • internal/component/messagefit/messagefit_test.go#L33-L61: delete the budget computation and the _ = budget discard on lines 43-45, and replace the "at least one non-empty message" loop with an assertion that the middle message is empty and the last message is not.
  • internal/component/messagefit/messagefit_test.go#L8-L16: delete the unused countMessages helper.

As per coding guidelines: "Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them."

🤖 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 `@internal/component/messagefit/messagefit_test.go` around lines 33 - 61,
Remove the unused countMessages helper in
internal/component/messagefit/messagefit_test.go#L8-L16. In
TestFit_Step2_DropsMiddle at
internal/component/messagefit/messagefit_test.go#L33-L61, delete the budget
calculation and discard, then assert directly that the middle message is empty
and the last message remains non-empty.

Source: Coding guidelines

internal/component/messagefit/messagefit.go (1)

9-14: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the unsupported Extractor claim. messagefit has only an agent consumer. Remove the ingestion Extractor reference from the package comment.

🤖 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 `@internal/component/messagefit/messagefit.go` around lines 9 - 14, Update the
package comment for messagefit to remove the unsupported ingestion Extractor
reference, while retaining the agent canvas LLM consumer description and
existing Fit usage guidance.

Source: Coding guidelines

internal/agent/component/llm_credentials.go (1)

74-80: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Extract the shared context-length lookup.

The service and agent paths duplicate tenant-model and provider-catalog lookups, although their error and fallback behavior differs. Move the common catalog lookup into a lower-level package, keep caller-specific behavior at each boundary, and remove the duplicate implementation.

🤖 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 `@internal/agent/component/llm_credentials.go` around lines 74 - 80, Extract
the shared tenant-model and provider-catalog lookup logic used by
resolveModelContentLength and service.ResolveModelContextLength into a
lower-level package that avoids the canvas import cycle. Keep service- and
agent-specific error handling and fallback behavior at their respective
boundaries, then replace both duplicate implementations with the shared lookup.

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.

Inline comments:
In `@internal/agent/component/llm_credentials.go`:
- Around line 90-107: Update the zero-return path of the content-length
resolution logic to emit a debug or warning log containing modelRef, driver, and
modelName before returning 0. Preserve the existing resolution behavior and
ensure the log includes no credential values.
- Around line 82-89: Remove the early return in the nil-DB handling of the model
lookup function, while preserving the fallback from db to dao.DB. When no
database is available, skip only the tenant-model lookup and continue to the
catalog lookup via GetModelProviderManager().GetModelByName(driver, modelName),
allowing its content_length to be returned.

---

Nitpick comments:
In `@internal/agent/component/llm_credentials.go`:
- Around line 74-80: Extract the shared tenant-model and provider-catalog lookup
logic used by resolveModelContentLength and service.ResolveModelContextLength
into a lower-level package that avoids the canvas import cycle. Keep service-
and agent-specific error handling and fallback behavior at their respective
boundaries, then replace both duplicate implementations with the shared lookup.

In `@internal/agent/component/llm.go`:
- Around line 1030-1114: Split fitMessages into focused conversion helpers: move
fitSource to file scope, extract toFitMessages for building messagefit.Message
values and source metadata, and extract fromFitMessages for reconstructing
[]schema.Message. Keep deep-copying and contextFitBudget/messagefit.Fit
orchestration in fitMessages, preserving the existing behavior and ordering.
- Around line 1052-1113: Add over-budget coverage for multimodal fitting using a
small maxLength: create a user message containing both a text part and an image
part, and assert the fitted text is written back to the original
UserInputMultiContent part while the image part remains. Also cover an
image-only turn becoming lastNonSystem, verifying the preceding text-bearing
turn is dropped while the image-only turn is preserved.

In `@internal/component/messagefit/messagefit_test.go`:
- Around line 33-61: Remove the unused countMessages helper in
internal/component/messagefit/messagefit_test.go#L8-L16. In
TestFit_Step2_DropsMiddle at
internal/component/messagefit/messagefit_test.go#L33-L61, delete the budget
calculation and discard, then assert directly that the middle message is empty
and the last message remains non-empty.

In `@internal/component/messagefit/messagefit.go`:
- Around line 9-14: Update the package comment for messagefit to remove the
unsupported ingestion Extractor reference, while retaining the agent canvas LLM
consumer description and existing Fit usage guidance.
🪄 Autofix

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 Plus

Run ID: d8e70dbc-bd5b-481a-9782-e783825bf0b4

📥 Commits

Reviewing files that changed from the base of the PR and between dd52dee and 937d10d.

📒 Files selected for processing (7)
  • internal/agent/chat/chat.go
  • internal/agent/component/fixture_stubs.go
  • internal/agent/component/llm.go
  • internal/agent/component/llm_credentials.go
  • internal/agent/component/llm_test.go
  • internal/component/messagefit/messagefit.go
  • internal/component/messagefit/messagefit_test.go

@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 `@internal/component/messagefit/messagefit.go`:
- Around line 96-99: The message-fitting logic around lastNonSystem in
internal/component/messagefit/messagefit.go:96-99 must handle system-only inputs
before treating the final retained entry as a non-system message: when
lastNonSystem < 0, call trimSystems(msgs, kept, maxTokens) and return
countTokensMulti(msgs, kept). Add a system-only test in
internal/component/messagefit/messagefit_test.go:76-105 verifying all retained
system messages share the fitting budget and the total stays within maxTokens.
🪄 Autofix

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 Plus

Run ID: 5e0bedf2-635a-4b29-a015-0f1d3afcd7bf

📥 Commits

Reviewing files that changed from the base of the PR and between 937d10d and 0df36a2.

📒 Files selected for processing (2)
  • internal/component/messagefit/messagefit.go
  • internal/component/messagefit/messagefit_test.go

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Aug 11, 2026
@jay77721

Copy link
Copy Markdown
Member Author

Addressed the CodeRabbit comments (pushed to this branch):

  1. llm_credentials.go:89 — nil-DB early return skipped the catalog lookup (Major): resolveModelContentLength no longer returns 0 when both the passed db and dao.DB are nil — only the tenant-model lookup is skipped and the provider-catalog lookup (step 2) still runs, since it needs no database. (b0e76a6)

  2. llm_credentials.go:107 — log resolution failures (Major): the zero-return path now emits a debug log with model_ref/driver/model_name (no credentials), so silent degradation to the 8192 budget is diagnosable in production. (b0e76a6)

  3. messagefit.go:99 — system-only message lists (Minor): when only system messages are retained (no non-system message), the whole budget is now spread across every retained system message via trimSystems (in PR feat(component): add shared message-fit package #18091, 94baa61, synced here); TestFit_SystemOnlyMessages added.

All bash build.sh --test ./internal/agent/component/... ./internal/component/messagefit/... pass.

@jay77721

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor
⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@jay77721

Copy link
Copy Markdown
Member Author

Updated to use the shared helper: resolveModelContentLength (private copy) is removed and the call site now uses dao.ResolveModelContentLength from #18106; the resolution-failure debug log moved to LLMComponent.Invoke. Depends on #18106.

@jay77721
jay77721 force-pushed the pr/3-agent-content-length branch 2 times, most recently from 33b3298 to adf1a81 Compare August 12, 2026 03:23
@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@jay77721
jay77721 force-pushed the pr/3-agent-content-length branch from 67ff383 to 74509c3 Compare August 12, 2026 05:22
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Aug 12, 2026
@jay77721
jay77721 force-pushed the pr/3-agent-content-length branch 2 times, most recently from 06bb255 to f7dfcbb Compare August 12, 2026 06:12
@jay77721 jay77721 changed the title fix(agent): fit LLM prompts to model content_length, not max_tokens fix(agent): fit LLM prompts to model content_length Aug 12, 2026
@jay77721
jay77721 requested a review from yuzhichang August 12, 2026 07:56
The canvas max_tokens param caps generation length only; using it
as the message-fitting budget collapsed the input context for
models whose context window is much larger than max_output.

Resolve the chat model's content_length from the tenant model row
or the provider catalog (resolveModelContentLength) and fit
messages against that instead.
…failures

- resolveModelContentLength no longer returns 0 up front when both
  the passed db and dao.DB are nil: the provider-catalog lookup
  (step 2) needs no database, so it still runs. Only the
  tenant-model lookup is skipped without a DB.
- Log a debug line with model_ref/driver/model_name when
  content_length cannot be resolved, so silent degradation to the
  8192 budget is diagnosable in production.
Drop the private resolveModelContentLength copy and use the shared
dao.ResolveModelContentLength helper introduced in the new dao PR.
The content_length resolution-failure debug log moves to the call
site in LLMComponent.Invoke.
Invoke with gpt-4o@openai (content_length 128000) and a user prompt far
larger than the 8192 fallback: the prompt must be passed through to the
invoker untrimmed, proving the budget comes from dao.ResolveModelContentLength
rather than the canvas max_tokens / default.
The content_length change replaced the fitting budget, so two properties
need locking: the canvas max_tokens must still reach the invoker as the
generation cap (but must NOT be the fitting budget), and an unresolvable
content_length must fall back to the 8192 budget. Both tests fail on the
old budget-from-max_tokens behavior.
@jay77721
jay77721 force-pushed the pr/3-agent-content-length branch from 509fc78 to 65cbde3 Compare August 12, 2026 08:28
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Aug 12, 2026
- TestFitMessages_FoldsMultipleTextParts now asserts the image part survives
  the step-3 write-back, not just the folded text count.
- New TestFitMessages_ImageOnlyLastTurnOverBudget: an image-only turn as the
  last non-system message with a tiny budget (ll2 = 0) must survive while the
  system share is trimmed to the budget.
- New TestLLM_Invoke_UUIDModel_ResolvesContentLength: tenant-model UUID path
  of content_length resolution through the real Invoke + in-memory DB
  (gpt-4o@OpenAI), proving the budget comes from content_length (128k), not
  the 8192 fallback.
- Note the catalog coupling in TestLLM_Invoke_UsesModelContentLengthBudget.
Comment thread internal/agent/component/llm.go Resolved
@yuzhichang
yuzhichang merged commit d7682b5 into infiniflow:main Aug 12, 2026
3 checks passed
@jay77721
jay77721 deleted the pr/3-agent-content-length branch August 13, 2026 08:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants