Repository navigation
fix(agent): fit LLM prompts to model content_length - #18093
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:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (8)
🚧 Files skipped from review as they are similar to previous changes (7)
📝 WalkthroughWalkthroughThe change renames output-token fields to ChangesLLM token budgeting
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Suggested labels: Suggested reviewers: 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
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: 2
🧹 Nitpick comments (5)
internal/agent/component/llm.go (2)
1030-1114: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider splitting
fitMessagesinto conversion helpers.The function now performs four phases in ~85 lines: deep copy, conversion to
messagefit.Messagewith source tracking, fitting, and conversion back. ExtractingtoFitMessages(systemPrompt, copied) ([]messagefit.Message, []fitSource)andfromFitMessages(all, sources, copied) []schema.Messagewould make each phase testable on its own and would letfitSourcemove 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 winAdd over-budget coverage for multimodal messages.
The new conversion tracks whether text lives in
Contentor in aUserInputMultiContenttext part. Both new multimodal tests (TestFitMessages_PreservesImageOnlyTurnandTestFitMessages_EverythingFits) usemaxLength = 100000, so they only exercise the everything-fits path inmessagefit.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
lastNonSysteminmessagefit.Fit. ItsContentis"", so step 3 assigns the whole budget to the system message and drops the preceding text-bearing turn.Add a test with a small
maxLengthand 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 winRemove 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 thebudgetcomputation and the_ = budgetdiscard 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 unusedcountMessageshelper.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 valueRemove the unsupported Extractor claim.
messagefithas 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 liftExtract 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
📒 Files selected for processing (7)
internal/agent/chat/chat.gointernal/agent/component/fixture_stubs.gointernal/agent/component/llm.gointernal/agent/component/llm_credentials.gointernal/agent/component/llm_test.gointernal/component/messagefit/messagefit.gointernal/component/messagefit/messagefit_test.go
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 `@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
📒 Files selected for processing (2)
internal/component/messagefit/messagefit.gointernal/component/messagefit/messagefit_test.go
|
Addressed the CodeRabbit comments (pushed to this branch):
All |
|
@coderabbitai review |
|
33b3298 to
adf1a81
Compare
|
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. |
67ff383 to
74509c3
Compare
06bb255 to
f7dfcbb
Compare
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.
509fc78 to
65cbde3
Compare
- 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.
Summary
Use the chat model's context window (
content_length) as the message-fitting budget instead of the canvasmax_tokensparameter.Why
max_tokenscaps generation length only. Using it as the input-trimming budget collapsed the usable context for models whose context window is much larger thanmax_output— exactly the failure the fitting logic was added to avoid.Changes
internal/agent/component/llm.go: fitting budget is now the resolvedcontent_length(0 → 8192 fallback). Resolution goes through the shareddao.ResolveModelContentLength(feat(dao): add shared ResolveModelContentLength helper #18106), and a resolution-failure debug log is emitted fromLLMComponent.Invokeso an unexpected 8192 fallback is diagnosable.max_tokensis left untouched as the generation cap — it still reaches the invoker asChatInvokeRequest.MaxTokens(output limit); it just no longer drives input trimming.internal/agent/component/llm.go: validation errors now point at the modelcontent_lengthsetting instead ofmax_tokens.MaxTokenskeeps its existing name; only the fitting-budget source changes.Testing
bash build.sh --test ./internal/agent/component/... ./internal/dao/...passes.TestLLM_Invoke_UsesModelContentLengthBudget: a 40k-token prompt undergpt-4o@openai(128k context) is preserved instead of trimmed to the old 8192 default.TestLLM_Invoke_MaxTokensStillOutputCapAndNotBudget: a smallmax_tokensstill reaches the invoker as the generation cap but is NOT the fitting budget (the 40k prompt survives).TestLLM_Invoke_UnresolvableModelFallsBackTo8192: an unknown model falls back to the 8192 budget and still trims.main(eada2f6b6). feat(component): add shared message-fit package #18091, feat(dao): add shared ResolveModelContentLength helper #18106, refactor(agent): use shared message-fit in LLM component #18092, and fix(ingestion): fit extractor and tagger prompts to model content_length #18095 are all merged; this branch no longer carriesmessagefit,dao.ResolveModelContentLength, or refactor(agent): use shared message-fit in LLM component #18092's agent changes.fitMessagesuses the non-mutatingmessagefit.FitAPI already onmain.Known limitations (follow-up)
dao.ResolveModelContentLength(from #18106) currently readscontent_lengthfrom the provider catalog only; per-modelmax_tokensoverrides intenant_model.extraare not honored yet (Python resolves them viamodel_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 theextra["max_tokens"]override — tracked alongside #18106.