Repository navigation
Go: introduce content_length and max_output - #17807
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThe change separates provider content length from maximum output length. It adds Moonshot and Zhipu AI models, updates provider configurations, changes model metadata structures and listings, centralizes Anthropic token configuration, and updates service and dispatch paths. ChangesModel output limit migration
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 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: 5
🤖 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 `@conf/models/moonshot.json`:
- Around line 14-61: Migrate every remaining max_tokens-only model entry to the
max_output schema, using the correct existing output-limit value and removing
stale duplicate entries where appropriate. Apply this across
conf/models/moonshot.json (including the models around kimi-k3 and
kimi-k2.7-code), conf/models/anthropic.json lines 71-72, and
conf/models/astraflow.json lines 58-59; ensure all built-in limits load through
Model.MaxOutput.
In `@internal/entity/models/model.go`:
- Around line 415-416: Propagate ContentLength alongside MaxOutput through all
model metadata paths: add content_length in ListAllModels, ListModels,
SearchModelInfo, and SearchByType in internal/entity/models/model.go; assign
modelEntity.ContentLength in ParseListModel in
internal/entity/models/base_model.go; and assign preset.ContentLength in
parseNvidiaModelList in internal/entity/models/nvidia.go. Update all listed
sites: internal/entity/models/model.go lines 415-416, 492, 607, and 670;
internal/entity/models/base_model.go line 413; and
internal/entity/models/nvidia.go lines 733-740.
- Around line 584-590: Update the max_output branch in the model filter logic to
handle a nil model.MaxOutput without dereferencing it, treating an unset limit
as not meeting a requested maximum-output filter. For non-nil values, compare
using *model.MaxOutput and format the dereferenced value in the response message
rather than the pointer.
In `@internal/handler/providers.go`:
- Line 184: Update the live model map in the provider listing flow to include
m.ContentLength alongside max_output, preserving the content_length field when
live entries replace static entries on name conflicts. Keep the existing model
response structure and naming contract consistent with model_service.go.
In `@internal/ingestion/component/dispatch_model.go`:
- Around line 162-163: Update the tenant model extra handling used by the
dispatch branches around tenantModelExtra and the GetModelByName lookup so the
persisted max_tokens override from ModelProviderService.create_instance_model is
honored for max_output. Either persist new overrides under max_output
consistently, or add backward-compatible unmarshalling/support for the legacy
max_tokens key while preserving provider model MaxOutput behavior.
🪄 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: d6e03800-a422-4fb2-87de-a53aa95be029
📒 Files selected for processing (13)
conf/models/anthropic.jsonconf/models/astraflow.jsonconf/models/moonshot.jsonconf/models/zhipu-ai.jsoninternal/entity/models/base_model.gointernal/entity/models/gitee_test.gointernal/entity/models/model.gointernal/entity/models/nvidia.gointernal/entity/models/types.gointernal/handler/providers.gointernal/ingestion/component/dispatch_model.gointernal/service/model_service.gointernal/service/model_service_test.go
| { | ||
| "name": "kimi-k3", | ||
| "content_length": 1048576, | ||
| "max_output": 131072, | ||
| "model_types": [ | ||
| "chat", | ||
| "vision" | ||
| ], | ||
| "thinking": { | ||
| "default_value": true, | ||
| "clear_thinking": true | ||
| }, | ||
| "tools": { | ||
| "support": true | ||
| } | ||
| }, | ||
| { | ||
| "name": "kimi-k2.7-code", | ||
| "content_length": 262144, | ||
| "max_output": 131072, | ||
| "model_types": [ | ||
| "chat", | ||
| "vision" | ||
| ], | ||
| "thinking": { | ||
| "default_value": true, | ||
| "clear_thinking": true | ||
| }, | ||
| "tools": { | ||
| "support": true | ||
| } | ||
| }, | ||
| { | ||
| "name": "kimi-k2.7-code-highspeed", | ||
| "content_length": 262144, | ||
| "max_output": 131072, | ||
| "model_types": [ | ||
| "chat", | ||
| "vision" | ||
| ], | ||
| "thinking": { | ||
| "default_value": true, | ||
| "clear_thinking": true | ||
| }, | ||
| "tools": { | ||
| "support": true | ||
| } | ||
| }, |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
for file in conf/models/anthropic.json conf/models/astraflow.json conf/models/moonshot.json; do
rg -n '"(max_tokens|max_output|content_length)"' "$file"
done
rg -n 'MaxTokens|MaxOutput|ContentLength|UnmarshalJSON|json:"(max_tokens|max_output|content_length)"' internal/entity/models internal/serviceRepository: infiniflow/ragflow
Length of output: 17593
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== candidate model config files =="
git ls-files 'conf/models/*.json' | sed -n '1,120p'
echo
echo "== model.go outline =="
ast-grep outline internal/entity/models/model.go --view expanded | sed -n '1,220p'
echo
echo "== relevant model.go sections =="
cat -n internal/entity/models/model.go | sed -n '1,230p;400,440p;480,510p;580,595p;630,665p'
echo
echo "== model_service max output/default token sections =="
cat -n internal/service/model_service.go | sed -n '2500,2590p;3745,3755p;3880,3892p;3940,3952p;4065,4076p'
echo
echo "== all provider JSON models with content_length/max_output/max_tokens =="
python3 - <<'PY'
import json, pathlib
for p in sorted(pathlib.Path('conf/models').glob('*.json')):
try:
data=json.loads(p.read_text())
except Exception as e:
print(f"{p}: parse error: {e}")
continue
entries=data.get("models")
if not entries:
continue
for i,e in enumerate(entries):
k=max_tokens=max_output=content_length=None
if isinstance(e, dict):
k=e.get("name")
max_tokens=e.get("max_tokens")
max_output=e.get("max_output")
content_length=e.get("content_length")
if max_output is not None or content_length is not None or max_tokens is not None:
print(f"{p}:{i+1}: name={k!r} max_tokens={max_tokens} max_output={max_output} content_length={content_length}")
PYRepository: infiniflow/ragflow
Length of output: 50374
Migrate remaining max_tokens entries to max_output.
Model.MaxOutput is the source of truth for built-in model token limits, and Model.max_tokens is no longer mapped. Entries that still use only max_tokens in conf/models/moonshot.json, other provider JSON files, and the duplicated provider configs won’t be loaded as MaxOutput; update or remove them so the split schema does not introduce stale models with the wrong default output limit.
📍 Affects 3 files
conf/models/moonshot.json#L14-L61(this comment)conf/models/anthropic.json#L71-L72conf/models/astraflow.json#L58-L59
🤖 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 `@conf/models/moonshot.json` around lines 14 - 61, Migrate every remaining
max_tokens-only model entry to the max_output schema, using the correct existing
output-limit value and removing stale duplicate entries where appropriate. Apply
this across conf/models/moonshot.json (including the models around kimi-k3 and
kimi-k2.7-code), conf/models/anthropic.json lines 71-72, and
conf/models/astraflow.json lines 58-59; ensure all built-in limits load through
Model.MaxOutput.
Source: Coding guidelines
| if model.MaxOutput != nil { | ||
| modelData["max_output"] = *model.MaxOutput |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Propagate ContentLength through all model metadata paths.
The migration adds ContentLength, but the changed listing, parser, and NVIDIA mapping code copies only MaxOutput. This drops the provider input limit before it reaches API consumers.
internal/entity/models/model.go#L415-L416: addcontent_lengthtoListAllModels.internal/entity/models/model.go#L492-L492: addcontent_lengthtoListModels.internal/entity/models/model.go#L607-L607: addcontent_lengthtoSearchModelInfo.internal/entity/models/model.go#L670-L670: addcontent_lengthtoSearchByType.internal/entity/models/base_model.go#L413-L413: assignmodelEntity.ContentLengthinParseListModel.internal/entity/models/nvidia.go#L733-L740: assignpreset.ContentLengthinparseNvidiaModelList.
📍 Affects 3 files
internal/entity/models/model.go#L415-L416(this comment)internal/entity/models/model.go#L492-L492internal/entity/models/model.go#L607-L607internal/entity/models/model.go#L670-L670internal/entity/models/base_model.go#L413-L413internal/entity/models/nvidia.go#L733-L740
🤖 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/entity/models/model.go` around lines 415 - 416, Propagate
ContentLength alongside MaxOutput through all model metadata paths: add
content_length in ListAllModels, ListModels, SearchModelInfo, and SearchByType
in internal/entity/models/model.go; assign modelEntity.ContentLength in
ParseListModel in internal/entity/models/base_model.go; and assign
preset.ContentLength in parseNvidiaModelList in
internal/entity/models/nvidia.go. Update all listed sites:
internal/entity/models/model.go lines 415-416, 492, 607, and 670;
internal/entity/models/base_model.go line 413; and
internal/entity/models/nvidia.go lines 733-740.
| case "max_output": | ||
| if maxVal, ok := filterValue.(int); ok { | ||
| if *model.MaxTokens < maxVal { | ||
| if *model.MaxOutput < maxVal { | ||
| matchFilter = false | ||
| resp.Code = 400 | ||
| resp.Message = fmt.Sprintf("Model does not meet filter criteria: max_tokens (%d) < %d", | ||
| model.MaxTokens, maxVal) | ||
| resp.Message = fmt.Sprintf("Model does not meet filter criteria: max_output (%d) < %d", | ||
| model.MaxOutput, maxVal) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== file size =="
wc -l internal/entity/models/model.go
echo "== relevant model definition/import formatting references =="
python3 - <<'PY'
from pathlib import Path
p = Path('internal/entity/models/model.go')
lines = p.read_text().splitlines()
for i,l in enumerate(lines,1):
if 'type Model' in l or 'MaxOutput' in l or 'func (m *Model) Filter' in l or 'fmt.Sprintf' in l and 580 <= i <= 600:
start=max(1,i-8); end=min(len(lines),i+12)
print(f"\n--- lines {start}-{end} ---")
for n in range(start,end+1):
print(f"{n:5d}: {lines[n-1]}")
PY
echo "== broader MaxOutput filter and Model struct =="
rg -n "MaxOutput|filterValue|matchFilter" internal/entity/models/model.goRepository: infiniflow/ragflow
Length of output: 12203
🌐 Web query:
Go fmt %d verb prints pointer as non-nil pointer address
💡 Result:
In Go, the %d format verb does not print a pointer as a non-nil address; instead, it formats the pointer's underlying memory address as a decimal integer [1][2][3]. According to the official Go documentation, the %d verb (as well as %b, %o, %x, and %X) is explicitly supported for pointers [1][2]. When used with a pointer, these verbs format the pointer's address—the numeric value representing the location in memory—exactly as if it were an integer [1][2][3]. Because this behavior treats the pointer's address as a standard integer, it can often result in misleading or unexpected output, such as a large decimal number that does not resemble a typical hexadecimal pointer representation (which is obtained using the %p verb) [4][5]. Due to the potential for confusion, it is widely considered a best practice to avoid using integer verbs like %d with pointers [5]. The Go static analysis tool (go vet) includes a check specifically designed to flag this pattern, as it is frequently the result of a programmer's mistake, such as failing to dereference a pointer to an integer [5].
Citations:
- 1: https://pkg.go.dev/fmt
- 2: https://go.dev/src/fmt/doc.go
- 3: https://pkg.go.dev/[email protected]
- 4: fmt: behavior of pointer-like format arguments is undocumented golang/go#28865
- 5: go/analysis/passes/printf: disallow %d formatting of pointers golang/go#62595
Guard nullable MaxOutput before applying the filter.
MaxOutput is a *int, and filter requests can match models with no output limit. The dereference at line 586 can panic when model.MaxOutput is nil, and the %d placeholder at line 590 formats the pointer address instead of the configured limit. Handle nil explicitly and format *model.MaxOutput for matching non-nil values.
🤖 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/entity/models/model.go` around lines 584 - 590, Update the
max_output branch in the model filter logic to handle a nil model.MaxOutput
without dereferencing it, treating an unset limit as not meeting a requested
maximum-output filter. For non-nil values, compare using *model.MaxOutput and
format the dereferenced value in the response message rather than the pointer.
| "name": m.Name, | ||
| "model_types": m.ModelTypes, | ||
| "max_tokens": m.MaxTokens, | ||
| "max_output": m.MaxOutput, |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Preserve content_length in live model responses.
The live-model map includes max_output but omits m.ContentLength. Because the remote map replaces the static entry on name conflicts at Line 207, live discovery can remove content_length from the response. The same listing contract exposes both fields in internal/service/model_service.go Line 398-405.
Proposed fix
remoteModels = append(remoteModels, map[string]interface{}{
"name": m.Name,
"model_types": m.ModelTypes,
+ "content_length": m.ContentLength,
"max_output": m.MaxOutput,
})📝 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.
| "max_output": m.MaxOutput, | |
| remoteModels = append(remoteModels, map[string]interface{}{ | |
| "name": m.Name, | |
| "model_types": m.ModelTypes, | |
| "content_length": m.ContentLength, | |
| "max_output": m.MaxOutput, | |
| }) |
🤖 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/handler/providers.go` at line 184, Update the live model map in the
provider listing flow to include m.ContentLength alongside max_output,
preserving the content_length field when live entries replace static entries on
name conflicts. Keep the existing model response structure and naming contract
consistent with model_service.go.
| if mi, _ := dao.GetModelProviderManager().GetModelByName(provider.ProviderName, modelObj.ModelName); mi != nil && mi.MaxOutput != nil { | ||
| maxTokens = *mi.MaxOutput |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 5 'type tenantModelExtra|MaxTokens|MaxOutput|max_tokens|max_output' --glob '*.go' .Repository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '--- dispatch_model relevant slices ---\n'
sed -n '130,245p' internal/ingestion/component/dispatch_model.go
printf '\n--- exact field/function usages in Go files only ---\n'
rg -n -C 3 'tenantModelExtra|MaxTokens|MaxOutput|max_tokens|max_output|tenantExtra' internal --glob '*.go'
printf '\n--- model definitions mentioning MaxTokens/MaxOutput ---\n'
rg -n -C 4 'type .*Model .*struct|MaxTokens|MaxOutput' internal/models --glob '*.go'Repository: infiniflow/ragflow
Length of output: 247
🏁 Script executed:
#!/bin/bash
set -euo pipefail
cat -n internal/ingestion/component/dispatch_model.go | sed -n '130,245p'
cat > /tmp/rg-grep.sh <<'POSIX'
#!/bin/bash
set -euo pipefail
rg -n -C 3 'tenantModelExtra|MaxTokens|MaxOutput|max_tokens|max_output|tenantExtra' internal --glob '*.go'
EOF
printf '\n--- exact field/function usages in Go files only ---\n'
rg -n -C 3 'tenantModelExtra|MaxTokens|MaxOutput|max_tokens|max_output|tenantExtra' internal --glob '*.go'
printf '\n--- model definitions mentioning MaxTokens/MaxOutput ---\n'
rg -n -C 4 'type .*Model .*struct|MaxTokens|MaxOutput' internal/models --glob '*.go'Repository: infiniflow/ragflow
Length of output: 5733
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- dispatch_model tenantModelExtra definition/usages ---'
rg -n -C 4 'type tenantModelExtra|tenantModelExtra|UnmarshalJSON|MarshalJSON|maxTokensFromTenantModelExtra' internal/ingestion/component/dispatch_model.go internal --glob '*.go' || true
printf '%s\n' '--- tenant model Extra writers ---'
rg -n -C 4 'TenantModel|tenantModel|modelObj.Extra|Extra.*MaxTokens|MaxTokens.*Extra|max_tokens|max_output|max_output' internal --glob '*.go' || true
printf '%s\n' '--- model definitions near MaxTokens/MaxOutput ---'
rg -n -C 4 'type .*Model .*struct|MaxTokens|MaxOutput' internal/models internal/ingestion --glob '*.go' || trueRepository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
cat -n internal/ingestion/component/dispatch_model.go | sed -n '1,125p'
printf '%s\n' '--- tenantModelExtra definitions/usages (focused file list) ---'
python3 - <<'PY'
from pathlib import Path
for p in Path('internal').rglob('*.go'):
text = p.read_text(errors='ignore')
if any(s in text for s in ['type tenantModelExtra', 'tenantModelExtra', 'MaxTokens', 'UnmarshalJSON', 'MarshalJSON', 'max_tokens', 'max_output']):
print(f'-- {p}')
for i, line in enumerate(text.splitlines(), 1):
if any(s in line for s in ['type tenantModelExtra', 'tenantModelExtra', 'MaxTokens', 'UnmarshalJSON', 'MarshalJSON', 'max_tokens', 'max_output']) and 'internal/models' not in str(p):
print(f'{i}: {line}')
PY
printf '%s\n' '--- direct writes into TenantModelExtra in Go ---'
rg -n -C 3 'TenantModel.*Extra|tenantModelExtra\{\s*$|MaxTokens\s*:|extraFields\["max_tokens"|extra\["max_tokens"|mergedExtra\["max_tokens"|unmarshal.*tenantModelExtra|marshal.*tenantModelExtra' internal --glob '*.go' \
| rg -C 3 'TenantModel.*Extra|tenantModelExtra|M\.Extra|modelObj\.Extra|extraFields|max_tokens|max_output|Unmarshal\(|UnmarshalJSON\(|MarshalJSON\(' || trueRepository: infiniflow/ragflow
Length of output: 49824
Persist tenant max token overrides as max_output.
TenantModel.Extra already uses {"max_tokens": ...} via ModelProviderService.create_instance_model, while these dispatch branches unmarshal with tenantModelExtra.MaxTokens and ignore it for max_output. Either write this migration as max_output or support the legacy max_tokens key in tenantModelExtra so saved tenant limits are respected.
🤖 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/dispatch_model.go` around lines 162 - 163,
Update the tenant model extra handling used by the dispatch branches around
tenantModelExtra and the GetModelByName lookup so the persisted max_tokens
override from ModelProviderService.create_instance_model is honored for
max_output. Either persist new overrides under max_output consistently, or add
backward-compatible unmarshalling/support for the legacy max_tokens key while
preserving provider model MaxOutput behavior.
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/entity/models/anthropic.go (1)
130-138: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winAlign the Anthropic max_tokens fallback with model capacity.
applyAnthropicChatConfigdefaults onlychatModelConfig’s missingMaxTokensto 1024, but callers such as the extractor can pass aChatConfig{}with noMaxTokens, sending Anthropic requests below models that expose much largerMaxOutput. Use the resolved service limit, or fail clearly when no Anthropic-compatible limit is available.🤖 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/entity/models/anthropic.go` around lines 130 - 138, Update applyAnthropicChatConfig so a nil ChatConfig.MaxTokens uses the resolved Anthropic service/model output limit instead of the hardcoded 1024 default. Reuse the existing max-output resolution symbol and ensure the function fails clearly when no Anthropic-compatible limit is available, while preserving explicitly configured MaxTokens.
🤖 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 `@internal/entity/models/anthropic.go`:
- Around line 130-138: Update applyAnthropicChatConfig so a nil
ChatConfig.MaxTokens uses the resolved Anthropic service/model output limit
instead of the hardcoded 1024 default. Reuse the existing max-output resolution
symbol and ensure the function fails clearly when no Anthropic-compatible limit
is available, while preserving explicitly configured MaxTokens.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ea0759b3-f615-424d-83a8-b02a2173816c
📒 Files selected for processing (9)
conf/models/gitee.jsonconf/models/ppio.jsonconf/models/siliconflow.jsoninternal/entity/models/anthropic.gointernal/entity/models/gitee_test.gointernal/entity/models/model_test.gointernal/entity/models/nvidia.gointernal/entity/models/nvidia_test.gointernal/service/model_service_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/entity/models/gitee_test.go
- internal/entity/models/nvidia.go
- internal/service/model_service_test.go
No description provided.