Repository navigation
Add Anthropic Go model provider - #14940
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds Anthropic provider config and a Go AnthropicModel driver with ChatWithMessages (text/image/data-URL mapping), ListModels/CheckConnection, factory registration for "anthropic", unsupported-method stubs, and httptest-backed tests covering request/response shapes and validations. ChangesAnthropic Model Provider Integration
Sequence Diagram(s)sequenceDiagram
participant Client
participant AnthropicModel
participant AnthropicAPI
Client->>AnthropicModel: ChatWithMessages(messages, config)
AnthropicModel->>AnthropicModel: Validate API key and message list
AnthropicModel->>AnthropicModel: Convert Message objects to Anthropic format
AnthropicModel->>AnthropicModel: Extract system prompts and normalize content blocks
AnthropicModel->>AnthropicAPI: POST /v1/messages (x-api-key, anthropic-version)
AnthropicAPI-->>AnthropicModel: JSON response with content blocks
AnthropicModel->>AnthropicModel: Parse text content as answer and thinking as reasoning
AnthropicModel-->>Client: ChatResponse(Answer, Reasoning)
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)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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 |
9b7136c to
03acf70
Compare
03acf70 to
f2cbd01
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/anthropic.json`:
- Line 14: The JSON entries for Claude models currently set "max_tokens": 200000
for every model; update each model-specific object so that variants of
"claude-opus-4" use "max_tokens": 128000 and variants of "claude-sonnet-4" and
"claude-haiku-4" use "max_tokens": 64000 (replace the uniform 200000 value
accordingly for each model entry named "claude-opus-4", "claude-opus-4-*"
variants, "claude-sonnet-4", "claude-sonnet-4-*", "claude-haiku-4", and
"claude-haiku-4-*"); keep all other fields unchanged so the config accurately
reflects Anthropic's Messages API output limits.
In `@internal/entity/models/anthropic_test.go`:
- Around line 72-76: Replace t.Fatalf calls inside the httptest handler
goroutine with t.Errorf and return early to avoid terminating only the handler
goroutine; specifically, in the handler where you check body["messages"] and
later assert msg/role/content (the code that assigns msgs, msg and ok), change
both t.Fatalf("messages=...") and t.Fatalf("message=...") to t.Errorf(...) and
then return from the handler after each error so the test records failures
reliably.
🪄 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
Run ID: e00df6ab-fb86-4e6a-96e7-35f049bfc860
📒 Files selected for processing (4)
conf/models/anthropic.jsoninternal/entity/models/anthropic.gointernal/entity/models/anthropic_test.gointernal/entity/models/factory.go
|
@carlos4s Would you please fix the compilation error? |
Update the Anthropic driver for the current ModelDriver interface, adjust Claude 4 output limits, and avoid Fatalf inside httptest handlers.
9ada64b to
7047dd8
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
conf/models/anthropic.json (1)
60-91:⚠️ Potential issue | 🟠 Major | ⚡ Quick winCorrect max_tokens values for Claude 3.x models to match Anthropic API limits.
The configuration sets
max_tokens: 200000for all Claude 3.x models, but Anthropic's Messages API enforces significantly lower output limits:
- claude-3-haiku-20240307 (line 86): Should be 4,096 tokens
- claude-3-5-sonnet-20241022 (line 70): Should be 8,192 tokens
- claude-3-5-haiku-20241022 (line 78): Should be 8,192 tokens
- claude-3-7-sonnet-20250219 (line 62): Should be 64,000 tokens
The current 200,000 values are 20-50× higher than the actual API limits and could cause validation errors or mislead users about model capabilities.
📝 Proposed fix to correct max_tokens for Claude 3.x models
{ "name": "claude-3-7-sonnet-20250219", - "max_tokens": 200000, + "max_tokens": 64000, "model_types": [ "chat", "vision" ] }, { "name": "claude-3-5-sonnet-20241022", - "max_tokens": 200000, + "max_tokens": 8192, "model_types": [ "chat", "vision" ] }, { "name": "claude-3-5-haiku-20241022", - "max_tokens": 200000, + "max_tokens": 8192, "model_types": [ "chat", "vision" ] }, { "name": "claude-3-haiku-20240307", - "max_tokens": 200000, + "max_tokens": 4096, "model_types": [ "chat", "vision" ] }🤖 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/anthropic.json` around lines 60 - 91, Update the incorrect max_tokens values for the listed Claude 3.x model entries so they match Anthropic API limits: set claude-3-7-sonnet-20250219 max_tokens to 64000, set claude-3-5-sonnet-20241022 and claude-3-5-haiku-20241022 max_tokens to 8192, and set claude-3-haiku-20240307 max_tokens to 4096; locate the objects by their "name" fields in conf/models/anthropic.json (e.g., "claude-3-7-sonnet-20250219", "claude-3-5-sonnet-20241022", "claude-3-5-haiku-20241022", "claude-3-haiku-20240307") and replace the current 200000 values with the correct token limits.
🧹 Nitpick comments (2)
internal/entity/models/anthropic.go (2)
264-266: ⚡ Quick winSilent type assertion could drop text content.
Line 265 uses
text, _ := block["text"].(string)which silently returns an empty string if thetextfield is not a string. If the input contains malformed text blocks (e.g.,textis an int or object), the content will be dropped without error.Consider adding validation:
🛡️ Proposed validation for text blocks
case "text": - text, _ := block["text"].(string) + text, ok := block["text"].(string) + if !ok { + return nil, fmt.Errorf("anthropic: text block missing or invalid text field") + } return map[string]interface{}{"type": "text", "text": text}, nil🤖 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 264 - 266, The "text" branch currently does a silent type assertion (text, _ := block["text"].(string)) which drops non-string content; update the "case \"text\"" handling for the block variable to perform an explicit type check (e.g., text, ok := block["text"].(string)) and return a descriptive error when ok is false (including the actual type with %T), or otherwise coerce/format the value safely before returning the map so malformed text blocks are not silently lost.
267-268: ⚡ Quick winAdd validation to the "image" case or document the assumption that blocks are pre-converted to Anthropic format.
The code returns
imageblocks without validation, assuming they're already in Anthropic's format{type: "image", source: {...}}. Unlike thetextandimage_urlcases—which construct or transform blocks to the required schema—theimagecase silently passes through any structure. No test coverage exists for this case, and no code in the codebase appears to create blocks withtype: "image", suggesting this is either dead code or an undocumented feature. If blocks can reach this code path, they should be validated to match Anthropic's expected schema before being sent to the API.🤖 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 267 - 268, The "image" switch branch currently returns block as-is (case "image") without validating its shape; update the handler that contains the case "image" (look for the switch handling block types in anthropic.go and the variable named block) to either validate that block matches Anthropic's expected image schema (e.g., block.Type == "image" and block.Source contains required fields like url/source and mime/type) and return a clear error if invalid, or add a conversion step that maps known internal shapes to the Anthropic format before returning; alternatively, if the codebase guarantees pre-converted blocks, add an explicit comment/docstring above the case "image" documenting that assumption and add tests covering a valid and an invalid image block to prevent silent pass-through.
🤖 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.
Duplicate comments:
In `@conf/models/anthropic.json`:
- Around line 60-91: Update the incorrect max_tokens values for the listed
Claude 3.x model entries so they match Anthropic API limits: set
claude-3-7-sonnet-20250219 max_tokens to 64000, set claude-3-5-sonnet-20241022
and claude-3-5-haiku-20241022 max_tokens to 8192, and set
claude-3-haiku-20240307 max_tokens to 4096; locate the objects by their "name"
fields in conf/models/anthropic.json (e.g., "claude-3-7-sonnet-20250219",
"claude-3-5-sonnet-20241022", "claude-3-5-haiku-20241022",
"claude-3-haiku-20240307") and replace the current 200000 values with the
correct token limits.
---
Nitpick comments:
In `@internal/entity/models/anthropic.go`:
- Around line 264-266: The "text" branch currently does a silent type assertion
(text, _ := block["text"].(string)) which drops non-string content; update the
"case \"text\"" handling for the block variable to perform an explicit type
check (e.g., text, ok := block["text"].(string)) and return a descriptive error
when ok is false (including the actual type with %T), or otherwise coerce/format
the value safely before returning the map so malformed text blocks are not
silently lost.
- Around line 267-268: The "image" switch branch currently returns block as-is
(case "image") without validating its shape; update the handler that contains
the case "image" (look for the switch handling block types in anthropic.go and
the variable named block) to either validate that block matches Anthropic's
expected image schema (e.g., block.Type == "image" and block.Source contains
required fields like url/source and mime/type) and return a clear error if
invalid, or add a conversion step that maps known internal shapes to the
Anthropic format before returning; alternatively, if the codebase guarantees
pre-converted blocks, add an explicit comment/docstring above the case "image"
documenting that assumption and add tests covering a valid and an invalid image
block to prevent silent pass-through.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 54cc3870-6eda-418a-a9e4-ec899f862e2b
📒 Files selected for processing (3)
conf/models/anthropic.jsoninternal/entity/models/anthropic.gointernal/entity/models/anthropic_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/entity/models/anthropic_test.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14940 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
internal/entity/models/anthropic_test.go (1)
162-165:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAvoid panic-prone assertions in data-URL mapping test.
This handler path also uses unchecked nested assertions. Add
okchecks andt.Errorf+returnso payload-shape regressions fail cleanly instead of panicking.Suggested patch
- msgs := body["messages"].([]interface{}) - content := msgs[0].(map[string]interface{})["content"].([]interface{}) - source := content[0].(map[string]interface{})["source"].(map[string]interface{}) + msgs, ok := body["messages"].([]interface{}) + if !ok || len(msgs) == 0 { + t.Errorf("messages=%v, want non-empty array", body["messages"]) + return + } + first, ok := msgs[0].(map[string]interface{}) + if !ok { + t.Errorf("first message=%v, want object", msgs[0]) + return + } + content, ok := first["content"].([]interface{}) + if !ok || len(content) == 0 { + t.Errorf("content=%v, want non-empty array", first["content"]) + return + } + block, ok := content[0].(map[string]interface{}) + if !ok { + t.Errorf("content[0]=%v, want object", content[0]) + return + } + source, ok := block["source"].(map[string]interface{}) + if !ok { + t.Errorf("source=%v, want object", block["source"]) + return + }🤖 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_test.go` around lines 162 - 165, The test currently does unchecked type assertions on body["messages"], msgs[0]["content"], and the nested source map (variables msgs, content, source) which can panic on payload-shape regressions; update the test in anthropic_test.go to perform safe type assertions (use the "ok" idiom) for each step and, if any assertion fails, call t.Errorf with a descriptive message and return so the test fails cleanly instead of panicking.
🧹 Nitpick comments (1)
internal/entity/models/anthropic.go (1)
103-103: 💤 Low valueConsider documenting why default max_tokens is 1024.
The default
max_tokensis set to 1024, which is significantly lower than the model limits (64k-200k in the config). While this value is overridden bychatModelConfigif provided, a brief comment explaining this conservative default would help future maintainers understand the choice.🤖 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` at line 103, Add a short inline comment next to the default "max_tokens": 1024 in internal/entity/models/anthropic.go explaining this is a conservative fallback chosen to limit token usage and costs despite model limits (64k–200k) and noting that chatModelConfig overrides it when provided; reference the "max_tokens" default and the chatModelConfig override so future maintainers understand why the low default was chosen.
🤖 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/anthropic.json`:
- Line 62: The current max_tokens value is wrong for Claude 3.x models and the
retired model entry must be removed: update the "max_tokens" fields for each
model entry so that claude-3-7-sonnet-20250219 uses 8192 (or 64000/128000
variants only if you maintain separate profile entries for extended/beta),
claude-3-5-sonnet-20241022 and claude-3-5-haiku-20241022 use 8192, and
claude-3-haiku-20240307 should be removed entirely from the config; ensure each
model object in anthopic.json references the correct model name string (e.g.,
"claude-3-7-sonnet-20250219", "claude-3-5-sonnet-20241022",
"claude-3-5-haiku-20241022") and adjust their "max_tokens" values accordingly.
In `@internal/entity/models/anthropic_test.go`:
- Around line 125-129: The test currently uses chained type assertions on msgs,
content, image and source which can panic; update the body parsing in the test
to use checked assertions (e.g., v, ok := body["messages"].([]interface{}) and
similarly for content, image and source) and for each failed assertion call
t.Errorf with a descriptive message and return immediately to avoid panics in
handler goroutines; reference the variables msgs, content, image, source and the
t.Errorf return pattern when making the change.
In `@internal/entity/models/anthropic.go`:
- Around line 347-349: In parseAnthropicChatResponse, the branch that checks if
answer.Len() == 0 currently returns ("", reasoning.String(), fmt.Errorf(...))
which leaks computed reasoning; change that return to ("", "", fmt.Errorf("no
text content in Anthropic response")) so the function consistently returns empty
answer and empty reasoning on error (match the JSON parsing error pattern).
---
Duplicate comments:
In `@internal/entity/models/anthropic_test.go`:
- Around line 162-165: The test currently does unchecked type assertions on
body["messages"], msgs[0]["content"], and the nested source map (variables msgs,
content, source) which can panic on payload-shape regressions; update the test
in anthropic_test.go to perform safe type assertions (use the "ok" idiom) for
each step and, if any assertion fails, call t.Errorf with a descriptive message
and return so the test fails cleanly instead of panicking.
---
Nitpick comments:
In `@internal/entity/models/anthropic.go`:
- Line 103: Add a short inline comment next to the default "max_tokens": 1024 in
internal/entity/models/anthropic.go explaining this is a conservative fallback
chosen to limit token usage and costs despite model limits (64k–200k) and noting
that chatModelConfig overrides it when provided; reference the "max_tokens"
default and the chatModelConfig override so future maintainers understand why
the low default was chosen.
🪄 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
Run ID: 153d0b66-90ac-40de-9acd-b7e2fd761ee6
📒 Files selected for processing (4)
conf/models/anthropic.jsoninternal/entity/models/anthropic.gointernal/entity/models/anthropic_test.gointernal/entity/models/factory.go
Correct Anthropic model output limits, validate multimodal content blocks, and harden provider tests.
|
@JinHai-CN Thanks for merging this PR. |
What problem does this PR solve?
Adds the missing Anthropic provider implementation for the Go model provider layer.
Closes #14939
What changed
conf/models/anthropic.jsonwith Anthropic Claude chat/vision models and API endpoints.internal/entity/models/anthropic.goimplementing non-streaming Messages API chat, model listing, and connection checking.anthropicin the Go model factory.Notes
Streaming chat is left as an explicit
no such methodfollow-up because this initial provider focuses on non-streaming chat and connection checking.Tests
docker run --rm -v /home/ubuntu/Documents/gitTensor_repos/carlos/ragflow:/work -v /tmp/ragflow-go-cache:/go/pkg/mod -v /tmp/ragflow-go-build:/root/.cache/go-build -w /work golang:1.25 go test -vet=off ./internal/entity/models -run Anthropic -count=1 -vdocker run --rm -v /home/ubuntu/Documents/gitTensor_repos/carlos/ragflow:/work -v /tmp/ragflow-go-cache:/go/pkg/mod -v /tmp/ragflow-go-build:/root/.cache/go-build -w /work golang:1.25 go test -vet=off ./internal/entity -count=1git diff --checkjq . conf/models/anthropic.json >/dev/nullPlain
go test ./internal/entity/modelscurrently hits pre-existing unrelated vet findings in other provider files (baidu.go,cohere.go,fishaudio.go,openrouter.go).