Repository navigation
Go: refactor models - #17784
Go: refactor models#17784JinHai-CN wants to merge 3 commits into
Conversation
JinHai-CN
commented
Aug 4, 2026
- Add max_input_tokens and max_output_tokens
- Remove warnings
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThe PR replaces the shared ChangesModel token limit migration
Estimated code review effort: 3 (Moderate) | ~30 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
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: 1
🧹 Nitpick comments (1)
internal/entity/models/model.go (1)
355-355: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRewrite the exported method comments as complete Go doc sentences.
The comments start with the method names, but they remain fragments.
ListProvidersalso retains the meaningless1.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
📒 Files selected for processing (1)
internal/entity/models/model.go
| 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 |
There was a problem hiding this comment.
🗄️ 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'
doneRepository: 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())
PYRepository: 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.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
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 `@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
📒 Files selected for processing (50)
conf/models/anthropic.jsonconf/models/astraflow.jsonconf/models/moonshot.jsonconf/models/zhipu-ai.jsoninternal/agent/component/llm.gointernal/entity/models/anthropic.gointernal/entity/models/anthropic_test.gointernal/entity/models/astraflow_test.gointernal/entity/models/avian_test.gointernal/entity/models/azure_openai.gointernal/entity/models/base_model.gointernal/entity/models/bedrock.gointernal/entity/models/bedrock_test.gointernal/entity/models/cometapi_test.gointernal/entity/models/gitee_test.gointernal/entity/models/google.gointernal/entity/models/google_test.gointernal/entity/models/gpustack_test.gointernal/entity/models/groq_test.gointernal/entity/models/huaweicloud.gointernal/entity/models/hunyuan_test.gointernal/entity/models/jina_test.gointernal/entity/models/longcat_test.gointernal/entity/models/mistral_test.gointernal/entity/models/model.gointernal/entity/models/model_test.gointernal/entity/models/modelscope_test.gointernal/entity/models/nvidia.gointernal/entity/models/nvidia_test.gointernal/entity/models/perplexity_test.gointernal/entity/models/ppio_test.gointernal/entity/models/replicate.gointernal/entity/models/replicate_test.gointernal/entity/models/togetherai_test.gointernal/entity/models/tokenpony_test.gointernal/entity/models/types.gointernal/entity/models/upstage_test.gointernal/entity/models/xiaomi.gointernal/entity/models/xiaomi_test.gointernal/entity/models/xinference_test.gointernal/entity/models/xunfei.gointernal/handler/providers.gointernal/ingestion/component/dispatch_model.gointernal/ingestion/component/tokenizer.gointernal/ingestion/task/knowledge_compiler_wiring.gointernal/service/chat_pipeline.gointernal/service/model_service.gointernal/service/model_service_test.gointernal/service/openai_chat_test.gointernal/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
| "model": modelName, | ||
| "messages": apiMessages, |
There was a problem hiding this comment.
🎯 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 -200Repository: 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:
- 1: https://github.com/anthropics/anthropic-sdk-python/blob/main/src/anthropic/types/message_create_params.py
- 2: https://theneuralbase.com/anthropic-api/learn/beginner/max-tokens-required-parameter-and-why/
- 3: https://platform.claude.com/docs/en/api/python/messages/create
- 4: https://platform.claude.com/docs/en/api/messages
- 5: https://reference.langchain.com/python/langchain-anthropic/chat_models/ChatAnthropic/max_tokens
- 6: https://github.com/anthropics/anthropic-sdk-python/blob/49d639a6/src/anthropic/resources/completions.py
- 7: https://github.com/anthropics/anthropic-sdk-typescript/blob/0f8153b3/src/resources/completions.ts
- 8: https://platform.claude.com/docs/en/build-with-claude/working-with-messages
🌐 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:
- 1: https://github.com/anthropics/anthropic-sdk-python/blob/main/src/anthropic/types/message_create_params.py
- 2: https://theneuralbase.com/anthropic-api/learn/beginner/max-tokens-required-parameter-and-why/
- 3: https://platform.claude.com/docs/en/api/messages
- 4: https://github.com/anthropics/anthropic-sdk-python/blob/49d639a6/src/anthropic/resources/messages/messages.py
- 5: https://platform.claude.com/docs/en/build-with-claude/working-with-messages
- 6: https://platform.claude.com/docs/en/build-with-claude/working-with-messages?fcdaa149_sort_date=desc
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.
| if cfg.ContentLength != nil { | ||
| reqBody["max_tokens"] = *cfg.MaxOutput |
There was a problem hiding this comment.
🩺 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.
| 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.
| 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) |
There was a problem hiding this comment.
📐 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 || trueRepository: 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
| {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"}}, |
There was a problem hiding this comment.
🗄️ 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.
| if remote.MaxOutput != nil && *remote.MaxOutput > 0 { | ||
| maxTokens = *remote.MaxOutput |
There was a problem hiding this comment.
🗄️ 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: PersistContentLengthunder the legacy key, or add a separatemax_outputmetadata 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 onlymax_tokens.
📍 Affects 3 files
internal/service/model_service.go#L454-L455(this comment)internal/service/model_service.go#L2541-L2543internal/service/model_service.go#L3485-L3492internal/service/model_service.go#L3881-L3889internal/service/model_service.go#L3943-L3952internal/service/model_service.go#L4001-L4005internal/service/model_service.go#L4066-L4074internal/ingestion/component/dispatch_model.go#L162-L167internal/ingestion/component/dispatch_model.go#L220-L225internal/ingestion/component/dispatch_model.go#L262-L263internal/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.