Skip to content

Go: refactor models - #17784

Closed
JinHai-CN wants to merge 3 commits into
infiniflow:mainfrom
JinHai-CN:fix611
Closed

JinHai-CN wants to merge 3 commits into
infiniflow:mainfrom
JinHai-CN:fix611

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member
  1. Add max_input_tokens and max_output_tokens
  2. Remove warnings

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN JinHai-CN added the ci Continue Integration label Aug 4, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review August 4, 2026 06:31
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Aug 4, 2026
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR replaces the shared MaxTokens field with ContentLength and MaxOutput. It updates model contracts, provider catalogs, request mappings, service propagation, response fields, and tests.

Changes

Model token limit migration

Layer / File(s) Summary
Model contracts and metadata
internal/entity/models/model.go, internal/entity/models/types.go, internal/entity/models/base_model.go
Public model and chat structures expose ContentLength and MaxOutput. Model listing and search responses replace max_tokens with content_length and max_output.
Provider model catalog updates
conf/models/anthropic.json, conf/models/astraflow.json, conf/models/moonshot.json, conf/models/zhipu-ai.json
Catalog entries use separate content and output limits. Three Moonshot models are added. Zhipu-AI models are added or updated.
Provider request field mapping
internal/entity/models/*.go, internal/agent/component/llm.go, internal/ingestion/task/knowledge_compiler_wiring.go
Adapters and configuration builders map ContentLength or MaxOutput to provider-specific token fields.
Service propagation and validation
internal/handler/providers.go, internal/ingestion/component/*.go, internal/service/*.go, internal/entity/models/*_test.go
Handlers, ingestion, pipelines, and model services propagate the renamed fields. Tests update configuration and model metadata assertions.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Possibly related PRs

Suggested labels: ☯️ refactor, size:XXL

Suggested reviewers: xugangqiang, jay77721, haruko386

Poem

A rabbit maps each token field,
Content length is now revealed.
Output limits stand apart,
Provider paths receive their part.
Hop, the model names align!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description lists intended changes but omits the required Summary heading and background context. Add the required Summary section and explain the purpose, field changes, and warning-related fixes for reviewers.
Docstring Coverage ⚠️ Warning Docstring coverage is 19.05% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title identifies a model refactor and matches the primary changes to model fields, configurations, and provider handling.
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.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

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

🧹 Nitpick comments (1)
internal/entity/models/model.go (1)

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

Rewrite the exported method comments as complete Go doc sentences.

The comments start with the method names, but they remain fragments. ListProviders also retains the meaningless 1. prefix. Use complete descriptions for all eight methods.

Proposed documentation cleanup
-// ListProviders 1. List all providers
+// ListProviders lists all providers.
-// GetProviderByName get specific provider information (including base_url)
+// GetProviderByName gets provider information, including base_url.
-// ListModels list models under a specific provider
+// ListModels lists models under a provider.
-// SearchModelInfo search specific model information with filtering by max_tokens or type
+// SearchModelInfo searches model information with filters for max_tokens and type.
-// SearchByFeature search models with specific features
+// SearchByFeature searches models by feature.
-// SearchByType search models with specific type
+// SearchByType searches models by type.
-// FindProvider find provider by name
+// FindProvider finds a provider by name.
-// FindModel find model by provider and model name
+// FindModel finds a model by provider and model name.

As per coding guidelines: remove stale superseded comments and keep Go documentation aligned with the current runtime path.

Also applies to: 451-451, 468-468, 559-559, 626-626, 657-657, 789-789, 799-799

🤖 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` at line 355, Rewrite the exported method
comments for ListProviders and the seven other affected methods as complete Go
doc sentences that begin with each method’s name. Remove the stale “1.” prefix
from ListProviders and replace all fragmentary or superseded wording while
keeping the documentation aligned with each method’s current behavior.

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/entity/models/model.go`:
- Around line 163-175: Add JSON coverage for the Model fields MaxInputTokens and
MaxOutputTokens, verifying configured integer values, omitted fields, and
explicit null values. Confirm the tests capture the intended nil-to-null
marshaling behavior alongside the existing MaxTokens coverage before treating
this contract as stable.

---

Nitpick comments:
In `@internal/entity/models/model.go`:
- Line 355: Rewrite the exported method comments for ListProviders and the seven
other affected methods as complete Go doc sentences that begin with each
method’s name. Remove the stale “1.” prefix from ListProviders and replace all
fragmentary or superseded wording while keeping the documentation aligned with
each method’s current behavior.
🪄 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 Plus

Run ID: f4f45aca-d505-4e31-9b6e-89c246400ca3

📥 Commits

Reviewing files that changed from the base of the PR and between bf1e98e and 88e2c89.

📒 Files selected for processing (1)
  • internal/entity/models/model.go

Comment thread internal/entity/models/model.go Outdated
Comment on lines +163 to +175
Name string `json:"name"`
MaxTokens *int `json:"max_tokens"`
MaxInputTokens *int `json:"max_input_tokens"`
MaxOutputTokens *int `json:"max_output_tokens"`
ModelTypes []string `json:"model_types"`
Thinking *ModelThinking `json:"thinking"`
Tools *ModelTools `json:"tools"`
Class *string `json:"class"`
MaxDimension *int `json:"max_dimension"` // used by embedding models
Dimensions []int `json:"dimensions"`
Alias []string `json:"alias"`
Rank *int `json:"rank"`
ModelTypeMap map[string]bool

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

rg -n -C 4 \
  -e '\b(MaxInputTokens|MaxOutputTokens)\b' \
  -e '"max_(input|output)_tokens"' \
  -e 'json\.(Marshal|Unmarshal)' \
  --glob '*.go' --glob '*.json' .

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== model.go relevant excerpt =="
sed -n '1,230p' internal/entity/models/model.go

echo
echo "== focused searches, limited matches =="
rg -n -C 2 \
  '(MaxInputTokens|MaxOutputTokens|max_input_tokens|max_output_tokens|MaxTokens|max_tokens|ModelConfig|all_models\.json|provider_manager|InitProviderManager)' \
  --glob '*.go' --glob '*.json' internal common conf python test 2>/dev/null | sed -n '1,260p'

echo
echo "== Go tests mentioning Model fields =="
rg -n -C 2 '\b(MaxInputTokens|MaxOutputTokens|MaxTokens|max_tokens|max_input_tokens|max_output_tokens)\b' --glob '*_test.go' internal 2>/dev/null | sed -n '1,260p'

echo
echo "== JSON fixture/model config snippets =="
for f in $(git ls-files '*.json' | rg '(^|/)all_models\.json$|models?|provider|model' | head -50); do
  echo "--- $f"
  rg -n -C 2 '(max_input_tokens|max_output_tokens|max_tokens)' "$f" -q && rg -n -C 3 '(max_input_tokens|max_output_tokens|max_tokens)' "$f" | sed -n '1,120p'
done

Repository: infiniflow/ragflow

Length of output: 17639


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== ModelResponse and provider/model API paths =="
rg -n -C 4 'ModelResponse|AllModels|Model|provider.*json|model_providers|all_models|Get.*Provider|List.*Model|New.*ProviderManager' \
  --glob '*.go' internal common agent 2>/dev/null | sed -n '1,260p'

echo
echo "== focused go tests for entity/models/model =="
git ls-files 'internal/entity/models/*_test.go' 'internal/**/*_test.go' 'api/**/*_test.go' 2>/dev/null | sed -n '1,120p'

echo
echo "== precise field references in Go tests excluding unrelated max_tokens text if possible =="
rg -n -C 3 '(MaxInputTokens|MaxOutputTokens|model_types|max_output_tokens|max_input_tokens)' --glob '*_test.go' internal api 2>/dev/null | sed -n '1,220p'

echo
echo "== deterministic Go JSON null/omit behavior probe =="
python3 - <<'PY'
import subprocess, json, tempfile, os
code = '''
package main
import (
  "encoding/json"
  "fmt"
)
type M struct {
  MaxTokens      *int `json:"max_tokens"`
  MaxInputTokens *int `json:"max_input_tokens"`
  MaxOutputTokens *int `json:"max_output_tokens,omitempty"`
}
func main() {
  v := M{}
  b, _ := json.Marshal(v)
  fmt.Println(string(b))
}
'''
with tempfile.TemporaryDirectory() as d:
  p = os.path.join(d, 'probe.go')
  open(p,'w').write(code)
  r = subprocess.run(['go','run',p], cwd=d, text=True, capture_output=True)
  print('stdout:', r.stdout.strip())
  print('stderr:', r.stderr.strip())
PY

Repository: infiniflow/ragflow

Length of output: 34019


Verify the intended null behavior for omitted token limits.

max_input_tokens and max_output_tokens are exported *int fields without omitempty, so nil values marshal as JSON null; current config coverage covers max_tokens but not these fields. Add coverage for configured values, omitted values, and explicit null values before relying on this public JSON contract.

🤖 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 163 - 175, Add JSON coverage
for the Model fields MaxInputTokens and MaxOutputTokens, verifying configured
integer values, omitted fields, and explicit null values. Confirm the tests
capture the intended nil-to-null marshaling behavior alongside the existing
MaxTokens coverage before treating this contract as stable.

@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 Aug 4, 2026
Signed-off-by: Jin Hai <[email protected]>

@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: 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 `@internal/entity/models/anthropic.go`:
- Around line 95-96: Update the Anthropic request construction used by
ChatWithMessages and ChatStreamlyWithSender to always include max_tokens before
any nil ChatConfig return path. Use the supported default when chatModelConfig
is nil, or enforce non-nil configuration consistently and add coverage; ensure
neither request omits the required field.

In `@internal/entity/models/base_model.go`:
- Around line 517-518: Update the guard in the request-body construction to
check cfg.MaxOutput != nil before dereferencing it, and assign max_tokens
whenever MaxOutput is provided. Do not use cfg.ContentLength for this condition,
since the two optional fields are independent.

In `@internal/entity/models/google.go`:
- Around line 328-332: Use consistent max-output terminology in the validation
and test diagnostics: update the error message in the MaxOutput validation
within Google model configuration to say max_output_tokens, and update the
t.Fatalf messages in internal/entity/models/google_test.go at lines 538-543 to
reference max_output_tokens and cfg.MaxOutputTokens instead of max_tokens and
cfg.MaxOutput.

In `@internal/service/model_service_test.go`:
- Around line 285-286: Update the reconciliation test fixture and assertions
around the model mapping to verify separate persisted limits: assert MaxOutput
is stored as extra["max_output"] and that the content-length limit is stored in
extra["content_length"], rather than checking only extra["max_tokens"]. Ensure
the assertions cover the production mapping’s distinct fields for the
nvidia/new-embed model.

In `@internal/service/model_service.go`:
- Around line 454-455: Separate ContentLength and MaxOutput at the persistence
boundary: in internal/service/model_service.go:454-455 persist ContentLength
under its legacy key or add a distinct max_output field; at 2541-2543 read the
corresponding key into the matching model field. Update the resolution paths in
internal/service/model_service.go:3485-3492, 3881-3889, 3943-3952, 4001-4005,
and 4066-4074 so defaults and tenant overrides consistently use either MaxOutput
or ContentLength without combining them. Apply the same matching-field mapping
in internal/ingestion/component/dispatch_model.go:162-167, 220-225, and 262-263,
and update internal/service/model_service_test.go:285-286 to assert separate
persisted output and content limits.
🪄 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 Plus

Run ID: b2b84d7d-da18-4665-8b1c-6bdfc1600004

📥 Commits

Reviewing files that changed from the base of the PR and between 88e2c89 and fc0cfdf.

📒 Files selected for processing (50)
  • conf/models/anthropic.json
  • conf/models/astraflow.json
  • conf/models/moonshot.json
  • conf/models/zhipu-ai.json
  • internal/agent/component/llm.go
  • internal/entity/models/anthropic.go
  • internal/entity/models/anthropic_test.go
  • internal/entity/models/astraflow_test.go
  • internal/entity/models/avian_test.go
  • internal/entity/models/azure_openai.go
  • internal/entity/models/base_model.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/bedrock_test.go
  • internal/entity/models/cometapi_test.go
  • internal/entity/models/gitee_test.go
  • internal/entity/models/google.go
  • internal/entity/models/google_test.go
  • internal/entity/models/gpustack_test.go
  • internal/entity/models/groq_test.go
  • internal/entity/models/huaweicloud.go
  • internal/entity/models/hunyuan_test.go
  • internal/entity/models/jina_test.go
  • internal/entity/models/longcat_test.go
  • internal/entity/models/mistral_test.go
  • internal/entity/models/model.go
  • internal/entity/models/model_test.go
  • internal/entity/models/modelscope_test.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/nvidia_test.go
  • internal/entity/models/perplexity_test.go
  • internal/entity/models/ppio_test.go
  • internal/entity/models/replicate.go
  • internal/entity/models/replicate_test.go
  • internal/entity/models/togetherai_test.go
  • internal/entity/models/tokenpony_test.go
  • internal/entity/models/types.go
  • internal/entity/models/upstage_test.go
  • internal/entity/models/xiaomi.go
  • internal/entity/models/xiaomi_test.go
  • internal/entity/models/xinference_test.go
  • internal/entity/models/xunfei.go
  • internal/handler/providers.go
  • internal/ingestion/component/dispatch_model.go
  • internal/ingestion/component/tokenizer.go
  • internal/ingestion/task/knowledge_compiler_wiring.go
  • internal/service/chat_pipeline.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • internal/service/openai_chat_test.go
  • internal/service/related_question.go
🚧 Files skipped from review as they are similar to previous changes (15)
  • internal/entity/models/huaweicloud.go
  • internal/entity/models/replicate.go
  • internal/agent/component/llm.go
  • internal/entity/models/xunfei.go
  • internal/service/related_question.go
  • internal/entity/models/types.go
  • internal/entity/models/xiaomi.go
  • internal/entity/models/bedrock.go
  • internal/handler/providers.go
  • internal/ingestion/task/knowledge_compiler_wiring.go
  • internal/entity/models/azure_openai.go
  • internal/service/chat_pipeline.go
  • conf/models/moonshot.json
  • internal/entity/models/nvidia.go
  • internal/entity/models/model.go

Comment on lines +95 to +96
"model": modelName,
"messages": apiMessages,

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Files:"
git ls-files | rg '(^|/)anthropic\.go$|internal/entity/models/anthropic\.go' || true

echo
echo "anthropic.go outline:"
ast-grep outline internal/entity/models/anthropic.go --view expanded || true

echo
echo "Relevant sections:"
sed -n '1,170p' internal/entity/models/anthropic.go
echo
sed -n '450,510p' internal/entity/models/anthropic.go

echo
echo "ChatConfig definitions/usages:"
rg -n "type ChatConfig|MaxOutput|applyAnthropicChatConfig|max_tokens|anthropic.*chat" internal/entity/models internal .github go.mod 2>/dev/null | head -200

Repository: infiniflow/ragflow

Length of output: 30639


🌐 Web query:

Anthropic API Messages create max_tokens required optional max_output_tokens current documentation

💡 Result:

In the Anthropic Messages API, max_tokens is a required parameter [1][2]. You must explicitly specify it in every call to the create endpoint [3][2]. There is no default value [2]. Regarding the specific terms requested: 1. max_tokens: This is the correct, required parameter for the Messages API [3][1]. It defines the absolute maximum number of tokens to generate in the model response [3][4]. The model may stop before reaching this limit if it completes its response naturally [3][4]. 2. max_output_tokens: This is not a parameter in the Anthropic Messages API. It is sometimes used in client-side abstractions or model profile documentation to refer to the maximum allowed output for a specific model [5], but it is not a field you pass to the Anthropic API directly [3][4]. 3. max_tokens_to_sample: This was the parameter name used in the legacy Text Completions API [6][7]. It is not used in the current Messages API [3][8]. If you are seeing references to "max_output_tokens" or "max_tokens_to_sample," they are either referring to model-specific limits found in documentation or are remnants of legacy API usage [6][5][7]. Always use max_tokens for current Messages API implementations [3][8].

Citations:


🌐 Web query:

Anthropic Messages API max_tokens required parameter create endpoint examples current documentation

💡 Result:

In the Anthropic Messages API, max_tokens is a mandatory, required parameter for the messages.create endpoint [1][2]. You must specify this value explicitly in every API call, as there is no default setting [2]. The max_tokens parameter defines the absolute maximum number of tokens the model is permitted to generate in a single response [3][2]. It functions as a hard ceiling; if the model reaches this limit, generation will stop immediately, potentially mid-sentence [3][2]. It is important to note that models may stop naturally before reaching this specified limit [3][4]. Below are examples of how to include max_tokens in the messages.create endpoint across different languages [5][6]. Python anthropic = Anthropic message = anthropic.messages.create( model="claude-3-5-sonnet-20240620", max_tokens=1024, messages=[{"role": "user", "content": "Hello, Claude"}]) TypeScript const anthropic = new Anthropic; const message = await anthropic.messages.create({ model: "claude-3-5-sonnet-20240620", max_tokens: 1024, messages: [{ role: "user", content: "Hello, Claude" }] }); cURL curl https://api.anthropic.com/v1/messages \ -H "x-api-key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "content-type: application/json" \ -d '{ "model": "claude-3-5-sonnet-20240620", "max_tokens": 1024, "messages": [ {"role": "user", "content": "Hello, Claude"} ] }' If you omit the max_tokens parameter, the API request will fail with an error indicating that the required argument is missing [2]. You can set max_tokens to 0 in specific scenarios, such as when using prompt caching to pre-warm the cache without generating a response [3][1].

Citations:


Set Anthropic max_tokens before the nil ChatConfig return path.

Anthropic Messages requires max_tokens; omit it from both ChatWithMessages and ChatStreamlyWithSender requests when chatModelConfig is nil. Use a default here if nil is supported, or enforce non-nil inputs and add coverage instead of relying on removed legacy behavior.

🤖 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 95 - 96, Update the
Anthropic request construction used by ChatWithMessages and
ChatStreamlyWithSender to always include max_tokens before any nil ChatConfig
return path. Use the supported default when chatModelConfig is nil, or enforce
non-nil configuration consistently and add coverage; ensure neither request
omits the required field.

Comment on lines +517 to +518
if cfg.ContentLength != nil {
reqBody["max_tokens"] = *cfg.MaxOutput

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.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Use cfg.MaxOutput as the guard.

ContentLength and MaxOutput are independent optional fields. If cfg.ContentLength is non-nil and cfg.MaxOutput is nil, Line 518 dereferences a nil pointer and panics. If only cfg.MaxOutput is non-nil, the request omits max_tokens. The provided internal/agent/component/llm.go, Lines 186-244, and internal/entity/models/astraflow_test.go, Lines 94-141, show both configurations. Change the condition to cfg.MaxOutput != nil.

Proposed fix
-		if cfg.ContentLength != nil {
+		if cfg.MaxOutput != nil {
			reqBody["max_tokens"] = *cfg.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.

Suggested change
if cfg.ContentLength != nil {
reqBody["max_tokens"] = *cfg.MaxOutput
if cfg.MaxOutput != nil {
reqBody["max_tokens"] = *cfg.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/entity/models/base_model.go` around lines 517 - 518, Update the
guard in the request-body construction to check cfg.MaxOutput != nil before
dereferencing it, and assign max_tokens whenever MaxOutput is provided. Do not
use cfg.ContentLength for this condition, since the two optional fields are
independent.

Comment on lines +328 to +332
if chatModelConfig.MaxOutput != nil {
if *chatModelConfig.MaxOutput < 0 || *chatModelConfig.MaxOutput > math.MaxInt32 {
return nil, fmt.Errorf("gemini: max_tokens %d is out of range for int32", *chatModelConfig.MaxOutput)
}
cfg.MaxOutputTokens = int32(*chatModelConfig.MaxTokens)
cfg.MaxOutputTokens = int32(*chatModelConfig.MaxOutput)

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locate relevant files"
git ls-files | rg '(^|/)internal/entity/models/google(_test)?\.go$' || true

echo
echo "Relevant snippets"
for f in internal/entity/models/google.go internal/entity/models/google_test.go; do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    cat -n "$f" | sed -n '318,338p' 2>/dev/null || true
    echo "--- test around 530-550 ---"
    cat -n "$f" | sed -n '530,550p' 2>/dev/null || true
  fi
done

echo
echo "Search MaxTokens/MaxOutput max_tokens constants"
rg -n "MaxOutput|MaxTokens|max_tokens|max_output_tokens|MaxOutputTokens" internal/entity/models/google.go internal/entity/models/google_test.go || true

Repository: infiniflow/ragflow

Length of output: 5262


Use consistent max-output terminology in the validation messages.

The implementation accepts MaxOutput and assigns MaxOutputTokens, but the error/diagnostic messages still say max_tokens, and the success-case failure message still prints cfg.MaxOutput. Update the error message to max_output_tokens, then update the test’s t.Fatalf strings at lines 529 and 543 to use max_output_tokens/cfg.MaxOutputTokens instead.

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] 331-331: Narrowing a non-constant integer to a smaller fixed-width type (int8/int16/int32, uint8/uint16/uint32) can silently overflow or wrap, yielding negative or truncated values that are dangerous in size, length, or index logic. Validate the source value is within the target type's range before converting (e.g. bounds-check, or use a checked helper), and avoid narrowing untrusted or len()/parsed values.
Context: int32(*chatModelConfig.MaxOutput)
Note: [CWE-190] Integer Overflow or Wraparound.

(integer-overflow-narrowing-conversion-go)

📍 Affects 2 files
  • internal/entity/models/google.go#L328-L332 (this comment)
  • internal/entity/models/google_test.go#L538-L543
🤖 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/google.go` around lines 328 - 332, Use consistent
max-output terminology in the validation and test diagnostics: update the error
message in the MaxOutput validation within Google model configuration to say
max_output_tokens, and update the t.Fatalf messages in
internal/entity/models/google_test.go at lines 538-543 to reference
max_output_tokens and cfg.MaxOutputTokens instead of max_tokens and
cfg.MaxOutput.

Source: Coding guidelines

Comment on lines +285 to +286
{Name: "nvidia/keep", MaxOutput: &maxTokens, ModelTypes: []string{"chat", "vision"}},
{Name: "nvidia/new-embed", MaxOutput: ptrService(8192), MaxDimension: &maxDimension, Dimensions: []int{1024, 2048}, ModelTypes: []string{"embedding"}},

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Make the reconciliation test verify separate limits.

The fixture now sets MaxOutput, but the assertion at Lines [311]-[313] still checks only extra["max_tokens"]. That allows the field collision to pass without checking the new max_output and content_length contract. Assert the distinct persisted fields after the production mapping is corrected.

🤖 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/service/model_service_test.go` around lines 285 - 286, Update the
reconciliation test fixture and assertions around the model mapping to verify
separate persisted limits: assert MaxOutput is stored as extra["max_output"] and
that the content-length limit is stored in extra["content_length"], rather than
checking only extra["max_tokens"]. Ensure the assertions cover the production
mapping’s distinct fields for the nvidia/new-embed model.

Comment on lines +454 to +455
if remote.MaxOutput != nil && *remote.MaxOutput > 0 {
maxTokens = *remote.MaxOutput

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Separate ContentLength and MaxOutput at the persistence boundary.

The changed paths use one max_tokens value for both fields. NVIDIA discovery writes MaxOutput, model metadata reads the value as ContentLength, and model resolution uses MaxOutput as the default before applying the same legacy override. This can lose output limits, misreport content limits, and return zero for models without MaxOutput.

  • internal/service/model_service.go#L454-L455: Persist ContentLength under the legacy key, or add a separate max_output metadata field.
  • internal/service/model_service.go#L2541-L2543: Read the matching metadata key into the matching model field.
  • internal/service/model_service.go#L3485-L3492: Do not combine a MaxOutput default with a ContentLength-based tenant override.
  • internal/service/model_service.go#L3881-L3889: Resolve Builtin embedding limits from the content-limit field.
  • internal/service/model_service.go#L3943-L3952: Keep provider-instance defaults and tenant overrides on the same field.
  • internal/service/model_service.go#L4001-L4005: Apply the same field mapping in factory fallback resolution.
  • internal/service/model_service.go#L4066-L4074: Apply the same field mapping in the legacy resolver.
  • internal/ingestion/component/dispatch_model.go#L162-L167: Use a matching field for provider metadata and tenant overrides.
  • internal/ingestion/component/dispatch_model.go#L220-L225: Use a matching field for provider-instance resolution.
  • internal/ingestion/component/dispatch_model.go#L262-L263: Use a matching field for catalog fallback resolution.
  • internal/service/model_service_test.go#L285-L286: Assert separate persisted output and content limits instead of only max_tokens.
📍 Affects 3 files
  • internal/service/model_service.go#L454-L455 (this comment)
  • internal/service/model_service.go#L2541-L2543
  • internal/service/model_service.go#L3485-L3492
  • internal/service/model_service.go#L3881-L3889
  • internal/service/model_service.go#L3943-L3952
  • internal/service/model_service.go#L4001-L4005
  • internal/service/model_service.go#L4066-L4074
  • internal/ingestion/component/dispatch_model.go#L162-L167
  • internal/ingestion/component/dispatch_model.go#L220-L225
  • internal/ingestion/component/dispatch_model.go#L262-L263
  • internal/service/model_service_test.go#L285-L286
🤖 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/service/model_service.go` around lines 454 - 455, Separate
ContentLength and MaxOutput at the persistence boundary: in
internal/service/model_service.go:454-455 persist ContentLength under its legacy
key or add a distinct max_output field; at 2541-2543 read the corresponding key
into the matching model field. Update the resolution paths in
internal/service/model_service.go:3485-3492, 3881-3889, 3943-3952, 4001-4005,
and 4066-4074 so defaults and tenant overrides consistently use either MaxOutput
or ContentLength without combining them. Apply the same matching-field mapping
in internal/ingestion/component/dispatch_model.go:162-167, 220-225, and 262-263,
and update internal/service/model_service_test.go:285-286 to assert separate
persisted output and content limits.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant