Repository navigation
fix(ingestion): fit extractor and tagger prompts to model content_length - #18095
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:
📝 WalkthroughWalkthroughThe PR adds token-budget fitting for message lists. Extractor and tag-generation requests resolve model context lengths, trim messages before LLM calls, and validate that retained messages include a non-empty final user turn. ChangesMessage fitting and extractor integration
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Extractor
participant ModelResolver
participant messagefit
participant ChatProvider
Extractor->>ModelResolver: resolve effective model context length
ModelResolver-->>Extractor: return context length
Extractor->>messagefit: fit assembled messages within budget
messagefit-->>Extractor: return fitted messages or error
Extractor->>ChatProvider: send fitted chat request
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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: 3
🧹 Nitpick comments (1)
internal/ingestion/component/extractor_test.go (1)
1796-1800: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the review-history phrase.
review feedbackdoes not describe test behavior. Keep the explanation of the empty-user-turn condition.As per coding guidelines, keep documentation aligned with current runtime behavior rather than migration history.
🤖 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/ingestion/component/extractor_test.go` around lines 1796 - 1800, Update the comment for TestFitExtractorMessages_RejectsEmptyUserTurn to remove the “review feedback” phrase while preserving the explanation that messagefit’s proportional trim can empty the final user turn and the extractor should return a clear error instead of sending an empty user message.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/component/messagefit/messagefit_test.go`:
- Around line 33-61: Update TestFit_Step2_DropsMiddle to use a fixture matching
its description: retain the system and final user messages while making the
middle turn droppable. Pass the calculated budget to Fit instead of the
hard-coded value, assert the middle message is empty, and assert both required
retained messages are nonempty. Remove the unused budget assignment and stale
comments describing the old fixture or Step 3 behavior.
In `@internal/component/messagefit/messagefit.go`:
- Around line 93-113: Update the message-fitting logic around kept, ll, and ll2
to trim every retained system-message index rather than only msgs[sysIdx].
Allocate the available system-token budget across all retained system messages
while preserving the final non-system message allocation, then ensure
countTokensMulti never exceeds maxTokens. Add coverage for two retained system
messages plus one user message asserting the returned token count stays within
the budget.
- Around line 55-83: Update both token-budget checks in the message-fitting flow
around countTokens and keptMsgs to use <= maxTokens instead of < maxTokens,
preserving all messages when the total exactly matches the budget and accepting
retained messages that exactly fit.
---
Nitpick comments:
In `@internal/ingestion/component/extractor_test.go`:
- Around line 1796-1800: Update the comment for
TestFitExtractorMessages_RejectsEmptyUserTurn to remove the “review feedback”
phrase while preserving the explanation that messagefit’s proportional trim can
empty the final user turn and the extractor should return a clear error instead
of sending an empty user message.
🪄 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: e3ad9cd5-62ee-4575-828b-e0652e874de2
📒 Files selected for processing (6)
internal/component/messagefit/messagefit.gointernal/component/messagefit/messagefit_test.gointernal/ingestion/component/extractor.gointernal/ingestion/component/extractor_tag.gointernal/ingestion/component/extractor_tag_test.gointernal/ingestion/component/extractor_test.go
|
Two items addressed on this branch:
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/dao/model_context_test.go (1)
28-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the three-part composite reference.
splitCompositeModelRefsupportsmodel@instance@provider, but this test only coversmodel@provider. Add a case such asgpt-4o@instance-1@openai. The two-part case can pass while the three-part branch regresses.As per coding guidelines, “Preserve still-valid behavior with focused tests.”
Proposed test update
func TestResolveModelContentLength_CompositeReference(t *testing.T) { - if got := ResolveModelContentLength(t.Context(), nil, "gpt-4o@openai", "", ""); got != 128000 { - t.Fatalf("ResolveModelContentLength(gpt-4o@openai) = %d, want 128000", got) + for _, ref := range []string{"gpt-4o@openai", "gpt-4o@instance-1@openai"} { + if got := ResolveModelContentLength(t.Context(), nil, ref, "", ""); got != 128000 { + t.Fatalf("ResolveModelContentLength(%s) = %d, want 128000", ref, got) + } } }🤖 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/dao/model_context_test.go` around lines 28 - 34, Add a focused assertion to TestResolveModelContentLength_CompositeReference covering the three-part model@instance@provider form, using a reference such as gpt-4o@instance-1@openai and the expected content length of 128000. Keep the existing two-part case unchanged.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.
Nitpick comments:
In `@internal/dao/model_context_test.go`:
- Around line 28-34: Add a focused assertion to
TestResolveModelContentLength_CompositeReference covering the three-part
model@instance@provider form, using a reference such as gpt-4o@instance-1@openai
and the expected content length of 128000. Keep the existing two-part case
unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1ce0f7de-da8b-46f0-b1c0-427c7fd900c9
📒 Files selected for processing (5)
internal/component/messagefit/messagefit.gointernal/component/messagefit/messagefit_test.gointernal/dao/model_context.gointernal/dao/model_context_test.gointernal/ingestion/component/extractor.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/component/messagefit/messagefit.go
- internal/ingestion/component/extractor.go
d3b1d5b to
0f44156
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/ingestion/component/extractor_test.go (2)
1852-1854: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winRemove the unused global DAO database replacement.
Every test passes
dbtoextractorContextLength. That function passes the same handle todefaultChatModelRefanddao.ResolveModelContentLength. Thedao.DBreplacement does not affect these assertions. Remove it to avoid shared test-state interference.Proposed change
- "ragflow/internal/dao" @@ - prev := dao.DB - dao.DB = db - t.Cleanup(func() { dao.DB = prev })🤖 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/ingestion/component/extractor_test.go` around lines 1852 - 1854, Remove the dao.DB replacement and its t.Cleanup restoration from the test setup around extractorContextLength. Keep passing db directly to extractorContextLength, defaultChatModelRef, and dao.ResolveModelContentLength as currently implemented, without introducing shared DAO state changes.
1799-1803: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove review-history text from the test comment.
Remove the phrase “review feedback”. Describe the fitting condition and expected error only.
As per coding guidelines, keep Go doc comments aligned with the current runtime path rather than migration history.
Proposed change
-// review feedback: when messagefit's proportional trim would empty the final +// when messagefit's proportional trim would empty the final🤖 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/ingestion/component/extractor_test.go` around lines 1799 - 1803, Update the comment for TestFitExtractorMessages_RejectsEmptyUserTurn to remove the phrase “review feedback” and describe only the proportional-trim condition and the expected clear error when the system prompt exceeds the context budget.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.
Nitpick comments:
In `@internal/ingestion/component/extractor_test.go`:
- Around line 1852-1854: Remove the dao.DB replacement and its t.Cleanup
restoration from the test setup around extractorContextLength. Keep passing db
directly to extractorContextLength, defaultChatModelRef, and
dao.ResolveModelContentLength as currently implemented, without introducing
shared DAO state changes.
- Around line 1799-1803: Update the comment for
TestFitExtractorMessages_RejectsEmptyUserTurn to remove the phrase “review
feedback” and describe only the proportional-trim condition and the expected
clear error when the system prompt exceeds the context budget.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 35959521-473b-4b56-93b4-3606aece0817
📒 Files selected for processing (1)
internal/ingestion/component/extractor_test.go
6fd2af1 to
e6c292e
Compare
The agent LLM component and the ingestion Extractor component both need to trim prompts to the model's context window before calling the provider. Each previously did (or would do) this with its own copy of the logic. This PR adds the shared primitive; follow-up PRs wire it into the agent LLM component (#18092) and the ingestion Extractor/tagger (#18095).
Trim Extractor call prompts and the automatic tagger prompt to the chat model's context window (content_length) before sending, so oversized chunks or tag files are trimmed instead of rejected by the provider with a context-length error. - fitExtractorMessages: shared helper wrapping messagefit.Fit; drops entries the fitter removed and returns a clear error instead of sending a conversation whose final user turn was trimmed to empty. - extractorContextLength: resolves content_length for the effective model; when llm_id is empty it resolves the tenant default chat model (mirroring resolveExtractorChatTarget), so the default-model path gets fitting too. - llmTagChunk: skips tagging (with a warning) when fitting fails.
extractor.go called service.ModelProviderService.ResolveModelContextLength, but the service package's tests import internal/ingestion/component to register components, creating an import cycle in test builds (component -> service -> (test) component). Resolve content_length through the DAO and the provider catalog directly (mirroring service.ResolveModelContextLength) and drop the service import.
Drop the private resolveExtractorModelContextLength copy and use the shared dao.ResolveModelContentLength helper introduced in the new dao PR. Behavior is unchanged.
Add unit tests for extractorContextLength against an in-memory DB with a tenant, provider and active gpt-4o tenant model row: - tenant_model UUID resolves content_length via the provider catalog - llm_id empty falls back to the tenant default chat model (pinned UUID and composite llm_id forms) - unknown model references return 0 (skip fitting)
messagefit.Fit was called with the full content_length as the budget. The cl100k tokenizer used for counting differs from each model's own tokenizer and the per-message formatting overhead is uncounted, so a prompt trimmed to exactly the context window could still be rejected by the provider with a context-length error. Budget at 97% of content_length, mirroring the agent component's contextFitBudget; clamp tiny contexts to 1 token so Fit never falls back to its <=0 → 8192 default. Tests assert the margin and the tagger path now trims within the margin-adjusted budget.
…ookup Two robustness fixes in the extractor message-fitting path: - fitExtractorMessages now requires at least one retained system message. The proportional trim can empty every system message when the final user turn alone fills the budget; sending only the user turn loses the extraction contract (output format, field definitions) and would silently produce garbage. Fail with a clear error instead. - defaultChatModelRef returns "" when db is nil (and extractorContextLength falls back to the global dao.DB handle), so resolving the tenant default chat model without a database degrades to 0 / skip-fitting instead of panicking in TenantDAO.GetByID. Tests cover both: the system-prompt-loss scenario errors, and a nil-db default-model lookup returns 0 without panicking.
…esent The system-prompt guard in fitExtractorMessages fired even for user-only requests (systemPrompt is optional and defaults to empty), so any extractor without a system prompt failed once the model's content_length was resolvable. Track whether the input actually had a system message and only enforce the guard then. Also drop the unused dao.DB swap in openExtractorContextTestDB and remove review-history phrasing from a test comment.
…essagefit API messagefit.Fit now returns (kept, keptIdx, count) instead of clearing dropped entries in place; rebuild fitted from keptIdx and write kept[j]. Content back to the original messages. Because a system message kept but trimmed to empty is still reported as kept, the system-prompt guard now requires a retained system message with non-empty content — an emptied system prompt carries no extraction contract and would silently produce garbage.
0efd738 to
1408be4
Compare
The fitExtractorMessages unit tests and the tagger test cover the fitter, but nothing exercised the production wiring (callRaw resolves the context length, fits, then hands the fitted messages to the invoker). Add an end-to-end test asserting the system prompt survives, the sent total stays within the margin-adjusted budget, and the chunk text is retained.
Summary
Trim Extractor call prompts and the automatic tagger prompt to the chat model's context window (
content_length) before sending, so oversized chunks or tag files are trimmed instead of rejected by the provider with a context-length error. Uses the sharedmessagefitpackage (#18091) anddao.ResolveModelContentLength(#18106).Changes
internal/ingestion/component/extractor.go:fitExtractorMessages: shared helper wrappingmessagefit.Fit(feat(component): add shared message-fit package #18091), adapted to the non-mutating API (kept+keptIdx); drops entries the fitter removed and returns a clear error instead of sending a conversation whose final user turn was trimmed to empty.extractorContextLength: resolvescontent_lengthfor the effective model through the shareddao.ResolveModelContentLength(feat(dao): add shared ResolveModelContentLength helper #18106); the privateresolveExtractorModelContextLengthcopy is removed. Whenllm_idis empty it resolves the tenant default chat model (mirroringresolveExtractorChatTarget), so the default-model path gets fitting too.extractorContextFitBudget: 97% of the resolved context window (clamped to >= 1 somessagefitnever falls into its 8192 default).callRawreturns the fitting error directly instead of retrying an empty-user request.internal/ingestion/component/extractor_tag.go:llmTagChunkuses the shared helper; skips tagging (with a warning) when fitting fails.dao.ResolveModelContentLength(feat(dao): add shared ResolveModelContentLength helper #18106, merged) resolvescontent_length; no copies are carried on this branch.callRawtest asserting the invoker receives fitted messages within the budget (TestExtractorComponent_CallRaw_FitsBeforeInvoke).Testing
bash build.sh --test ./internal/ingestion/component/... ./internal/dao/...passes (full ingestion/component suite).main(7b2d052f8) with feat(component): add shared message-fit package #18091 and feat(dao): add shared ResolveModelContentLength helper #18106 merged; the carriedmessagefitanddao.ResolveModelContentLengthcopies are gone.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 get no fitting here (extractor passes prompts through untrimmed). A follow-up PR will honor theextra["max_tokens"]override — tracked alongside #18106.