Skip to content

Add Anthropic Go model provider - #14940

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
carlos4s:feature/anthropic-go-provider-14939
May 18, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
carlos4s:feature/anthropic-go-provider-14939

Conversation

@carlos4s

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Adds the missing Anthropic provider implementation for the Go model provider layer.

Closes #14939

What changed

  • Add conf/models/anthropic.json with Anthropic Claude chat/vision models and API endpoints.
  • Add internal/entity/models/anthropic.go implementing non-streaming Messages API chat, model listing, and connection checking.
  • Register anthropic in the Go model factory.
  • Add httptest coverage for headers, payload mapping, response parsing, validation errors, provider errors, model listing, connection checking, factory registration, and unsupported methods.

Notes

Streaming chat is left as an explicit no such method follow-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 -v
  • 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 -count=1
  • git diff --check
  • jq . conf/models/anthropic.json >/dev/null

Plain go test ./internal/entity/models currently hits pre-existing unrelated vet findings in other provider files (baidu.go, cohere.go, fishaudio.go, openrouter.go).

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 14, 2026
@coderabbitai

coderabbitai Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 08eac378-f050-44a4-a790-1eceb80ad412

📥 Commits

Reviewing files that changed from the base of the PR and between fd0a194 and 96a68a0.

📒 Files selected for processing (1)
  • internal/entity/models/factory.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/entity/models/factory.go

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Anthropic Model Provider Integration

Layer / File(s) Summary
Configuration and Driver Initialization
conf/models/anthropic.json, internal/entity/models/anthropic.go
Provider JSON with base URL and model registry; AnthropicModel struct, HTTP client/transport setup, region/base URL helpers, and constructor.
Chat Request/Response Processing
internal/entity/models/anthropic.go
ChatWithMessages validates API key/messages, maps RAGFlow Message to Anthropic payload (roles, system prompt, content blocks, images, data-URL base64), applies chat config (max_tokens, temperature, top_p, stop_sequences), sends POST /v1/messages with required headers, and parses text/thinking content into ChatResponse.
Model Listing and Connection Verification
internal/entity/models/anthropic.go
ListModels GETs /v1/models, parses data into model IDs; CheckConnection delegates to ListModels.
Unsupported Capability Stubs
internal/entity/models/anthropic.go
Streaming, embedding, rerank, ASR/TTS/OCR, ParseFile, Balance, ListTasks, ShowTask return explicit “no such method” errors.
Factory Registration
internal/entity/models/factory.go
CreateModelDriver recognizes "anthropic" and returns NewAnthropicModel(...).
Test Suite
internal/entity/models/anthropic_test.go
httptest helpers and tests covering naming, chat happy path, system prompt and image mapping, data-URL handling, validation errors, HTTP provider error propagation, malformed response handling, ListModels/CheckConnection, factory registration, and unsupported-method checks.

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)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

💞 feature, size:XL

Suggested reviewers

  • Haruko386

Poem

🐇 I stitched messages into Claude’s gate,
Images tucked and data URLs sate,
Tests hop in, assert and then cheer,
Anthropic in Go now lives here,
A rabbit’s small patch — provider is clear.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR implements all core requirements from issue #14939: configuration file, AnthropicModel driver with ChatWithMessages/ListModels/CheckConnection, factory registration, and httptest coverage. However, the implementation has unresolved build errors (missing ListTasks method and OCRResponse type) that prevent successful compilation. Add the missing ListTasks method stub to AnthropicModel and fix the OCRResponse reference to match the actual type name in the codebase.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 'Add Anthropic Go model provider' clearly summarizes the main change: adding a new Anthropic model provider for the Go layer.
Description check ✅ Passed The description includes a problem statement, lists what changed, provides notes on deferred functionality, and documents test commands. It covers the required template sections adequately.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing the Anthropic provider: configuration, driver implementation, tests, and factory registration. No unrelated modifications are present.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@carlos4s
carlos4s force-pushed the feature/anthropic-go-provider-14939 branch from 9b7136c to 03acf70 Compare May 14, 2026 21:48
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 14, 2026
@carlos4s
carlos4s force-pushed the feature/anthropic-go-provider-14939 branch from 03acf70 to f2cbd01 Compare May 14, 2026 21:49
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels May 14, 2026

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5a5bbee and f2cbd01.

📒 Files selected for processing (4)
  • conf/models/anthropic.json
  • internal/entity/models/anthropic.go
  • internal/entity/models/anthropic_test.go
  • internal/entity/models/factory.go

Comment thread conf/models/anthropic.json Resolved
@JinHai-CN
JinHai-CN requested a review from Haruko386 May 15, 2026 01:34

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @carlos4s, LGTM
Thank you for your contribution

@Haruko386 Haruko386 added the ci Continue Integration label May 15, 2026
@JinHai-CN

Copy link
Copy Markdown
Member

@carlos4s Would you please fix the compilation error?

Building RAGFlow binary: /home/infiniflow/runners_work/inf26-b251184c627b/ragflow/ragflow/bin/server_main, /home/infiniflow/runners_work/inf26-b251184c627b/ragflow/ragflow/bin/admin_server, and /home/infiniflow/runners_work/inf26-b251184c627b/ragflow/ragflow/bin/ragflow_cli
# ragflow/internal/entity/models
internal/entity/models/anthropic.go:63:9: cannot use NewAnthropicModel(baseURL, a.URLSuffix) (value of type *AnthropicModel) as ModelDriver value in return statement: *AnthropicModel does not implement ModelDriver (missing method ListTasks)
internal/entity/models/anthropic.go:443:128: undefined: OCRResponse
internal/entity/models/factory.go:37:10: cannot use NewAnthropicModel(baseURL, urlSuffix) (value of type *AnthropicModel) as ModelDriver value in return statement: *AnthropicModel does not implement ModelDriver (missing method ListTasks)

Update the Anthropic driver for the current ModelDriver interface, adjust Claude 4 output limits, and avoid Fatalf inside httptest handlers.
@carlos4s
carlos4s force-pushed the feature/anthropic-go-provider-14939 branch from 9ada64b to 7047dd8 Compare May 15, 2026 11:30

@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.

♻️ Duplicate comments (1)
conf/models/anthropic.json (1)

60-91: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Correct max_tokens values for Claude 3.x models to match Anthropic API limits.

The configuration sets max_tokens: 200000 for 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 win

Silent type assertion could drop text content.

Line 265 uses text, _ := block["text"].(string) which silently returns an empty string if the text field is not a string. If the input contains malformed text blocks (e.g., text is 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 win

Add validation to the "image" case or document the assumption that blocks are pre-converted to Anthropic format.

The code returns image blocks without validation, assuming they're already in Anthropic's format {type: "image", source: {...}}. Unlike the text and image_url cases—which construct or transform blocks to the required schema—the image case silently passes through any structure. No test coverage exists for this case, and no code in the codebase appears to create blocks with type: "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

📥 Commits

Reviewing files that changed from the base of the PR and between f2cbd01 and 9ada64b.

📒 Files selected for processing (3)
  • conf/models/anthropic.json
  • internal/entity/models/anthropic.go
  • internal/entity/models/anthropic_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/entity/models/anthropic_test.go

@codecov

codecov Bot commented May 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (e194027) to head (96a68a0).
⚠️ Report is 2 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@carlos4s

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@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: 3

♻️ Duplicate comments (1)
internal/entity/models/anthropic_test.go (1)

162-165: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Avoid panic-prone assertions in data-URL mapping test.

This handler path also uses unchecked nested assertions. Add ok checks and t.Errorf+return so 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 value

Consider documenting why default max_tokens is 1024.

The default max_tokens is set to 1024, which is significantly lower than the model limits (64k-200k in the config). While this value is overridden by chatModelConfig if 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

📥 Commits

Reviewing files that changed from the base of the PR and between bf41d35 and 7047dd8.

📒 Files selected for processing (4)
  • conf/models/anthropic.json
  • internal/entity/models/anthropic.go
  • internal/entity/models/anthropic_test.go
  • internal/entity/models/factory.go

Comment thread conf/models/anthropic.json Resolved
Comment thread internal/entity/models/anthropic.go Resolved
carlos4s and others added 2 commits May 15, 2026 14:31
Correct Anthropic model output limits, validate multimodal content blocks, and harden provider tests.
@JinHai-CN
JinHai-CN merged commit 2eba2c4 into infiniflow:main May 18, 2026
1 check passed
@carlos4s
carlos4s deleted the feature/anthropic-go-provider-14939 branch May 18, 2026 12:08
@carlos4s

Copy link
Copy Markdown
Contributor Author

@JinHai-CN Thanks for merging this PR.

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.

[Feature Request]: Add Go driver for Anthropic model provider

3 participants