Skip to content

Go: implement provider: Avian - #15045

Merged
JinHai-CN merged 7 commits into
infiniflow:mainfrom
dripsmvcp:fix/15044-go-avian-driver
May 21, 2026
Merged

JinHai-CN merged 7 commits into
infiniflow:mainfrom
dripsmvcp:fix/15044-go-avian-driver

Conversation

@dripsmvcp

Copy link
Copy Markdown
Contributor

Closes #15044.

Avian was listed unchecked in the Go-rewrite tracker #14736 and already had an llm_factories.json entry with 4 preconfigured chat models (deepseek-v3.2, kimi-k2.5, glm-5, minimax-m2.5), but the Go API server had no driver to route them. The Python side has supported Avian at rag/llm/chat_model.py:1220 (AvianChat) via the LiteLLM openai/ provider with default base https://api.avian.io/v1.

This adds:

  • internal/entity/models/avian.go: SaaS OpenAI-compatible driver with chat (sync + SSE stream with avianStreamTimeout=10m), list_models, and check_connection. Always-on Bearer auth (validated up front). Reasoning extraction prefers reasoning_content and falls back to reasoning. Mirrors the TogetherAI pattern (Add TogetherAI chat provider #14957).
  • internal/entity/models/avian_test.go: 13 tests covering name, factory routing, chat happy path / reasoning fallback / API-key required / messages required / upstream-error status propagation, stream happy path / stream=false rejection / sender required, list_models + check_connection, missing-base-URL clear error, and the no-such-method sentinels.
  • conf/models/avian.json: shipped config (class: "avian", default URL https://api.avian.io, suffixes v1/chat/completions and v1/models, and the 4 chat models from llm_factories.json:6733).
  • internal/entity/models/factory.go: case "avian" -> AvianModel.

No change to selfDeployed map: Avian is SaaS, not self-hosted, so availability gates on the user supplying an API key (matches Novita, TogetherAI, Replicate, etc.).

Follow-on issues will add Embed and Rerank, in line with how Novita, NVIDIA, TogetherAI, and other providers landed method-by-method.

What problem does this PR solve?

Briefly describe what this PR aims to solve. Include background context that will help reviewers understand the purpose of the PR.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

Closes infiniflow#15044.

Avian was listed unchecked in the Go-rewrite tracker infiniflow#14736 and already
had an llm_factories.json entry with 4 preconfigured chat models
(deepseek-v3.2, kimi-k2.5, glm-5, minimax-m2.5), but the Go API server
had no driver to route them. The Python side has supported Avian at
rag/llm/chat_model.py:1220 (AvianChat) via the LiteLLM openai/ provider
with default base https://api.avian.io/v1.

This adds:
- internal/entity/models/avian.go: SaaS OpenAI-compatible driver with
  chat (sync + SSE stream with avianStreamTimeout=10m), list_models,
  and check_connection. Always-on Bearer auth (validated up front).
  Reasoning extraction prefers reasoning_content and falls back to
  reasoning. Mirrors the TogetherAI pattern (infiniflow#14957).
- internal/entity/models/avian_test.go: 13 tests covering name, factory
  routing, chat happy path / reasoning fallback / API-key required /
  messages required / upstream-error status propagation, stream happy
  path / stream=false rejection / sender required, list_models +
  check_connection, missing-base-URL clear error, and the no-such-method
  sentinels.
- conf/models/avian.json: shipped config (class: "avian", default URL
  https://api.avian.io, suffixes v1/chat/completions and v1/models,
  and the 4 chat models from llm_factories.json:6733).
- internal/entity/models/factory.go: case "avian" -> AvianModel.

No change to selfDeployed map: Avian is SaaS, not self-hosted, so
availability gates on the user supplying an API key (matches Novita,
TogetherAI, Replicate, etc.).

Follow-on issues will add Embed and Rerank, in line with how Novita,
NVIDIA, TogetherAI, and other providers landed method-by-method.
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 20, 2026
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: e3d77632-4631-41d4-9cdc-c1a6bc7635e0

📥 Commits

Reviewing files that changed from the base of the PR and between eee49e5 and 213f8d2.

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

📝 Walkthrough

Walkthrough

Adds Avian provider JSON config and a new Go AvianModel driver implementing synchronous chat, SSE streaming, ListModels/CheckConnection, factory registration, and comprehensive unit tests.

Changes

Avian Chat Provider Integration

Layer / File(s) Summary
Provider configuration
conf/models/avian.json
Adds Avian provider JSON config with base URLs, URL suffixes, and six chat-only models.
Driver foundation
internal/entity/models/avian.go
Defines AvianModel, imports, and constructor that clones/tunes http.DefaultTransport for SSE usage.
Factory registration
internal/entity/models/factory.go
Registers "avian" in CreateModelDriver to instantiate NewAvianModel.
Core helpers, URL/payload builders, and types
internal/entity/models/avian.go
Implements NewInstance, Name, region-aware base URL normalization, chatPayload builder, chatURL resolver, and response/message structs (including reasoning fields).
Chat sync implementation
internal/entity/models/avian.go
Implements ChatWithMessages with input validation, request marshaling, non-stream request execution, JSON decoding, and reasoning/content mapping.
SSE streaming implementation
internal/entity/models/avian.go
Implements ChatStreamlyWithSender: SSE POST, data: event scanning, delta routing to sender callbacks, upstream error event handling, and terminal detection ([DONE]/finish).
Model discovery and connection check
internal/entity/models/avian.go
Implements ListModels (GET /v1/models, parse/filter IDs) and CheckConnection delegating to ListModels.
Interface stubs
internal/entity/models/avian.go
Stubs other ModelDriver methods to return \"avian, no such method\" errors.
Test infrastructure and basic tests
internal/entity/models/avian_test.go
Adds test imports, an HTTP test-server helper validating headers and parsing JSON, a test AvianModel factory, and Name/factory tests.
Chat and streaming tests
internal/entity/models/avian_test.go
Adds ChatWithMessages happy-path, reasoning-content fallback, validation tests (API key/messages), upstream error propagation, SSE streaming happy-path with [DONE], and streaming validation tests.
Model listing and edge-case tests
internal/entity/models/avian_test.go
Adds ListModels/CheckConnection tests, missing base-URL failure test, and unsupported-methods assertions.

Sequence Diagram

sequenceDiagram
  participant Client
  participant AvianModel
  participant AvianAPI
  Client->>AvianModel: ChatWithMessages / ChatStreamlyWithSender (model, messages, stream)
  AvianModel->>AvianAPI: HTTP POST /v1/chat/completions (Authorization: Bearer key)
  AvianAPI-->>AvianModel: JSON response (choices) OR text/event-stream (data: JSON chunks, [DONE])
  AvianModel-->>Client: ChatResponse (sync) OR sender callbacks with content/reasoning deltas (stream)
  Client->>AvianModel: ListModels / CheckConnection (GET /v1/models)
  AvianModel->>AvianAPI: HTTP GET /v1/models (Authorization)
  AvianAPI-->>AvianModel: JSON model list
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#14850: Adds Novita provider driver with similar config, factory, chat, and SSE streaming patterns.
  • infiniflow/ragflow#14938: Adds another OpenAI-compatible provider driver implementing chat, SSE parsing, and model listing.
  • infiniflow/ragflow#14809: Related factory routing change for a different provider; similar CreateModelDriver update pattern.

Suggested reviewers

  • Haruko386

Poem

🐰 I nudged Avian into the stack,
streams trickled in, no packets slack,
tests chirped loud, endpoints aligned,
configs set and drivers signed.
Hooray — a provider joins the track!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: implement provider: Avian' clearly and concisely summarizes the main change—adding a Go driver for the Avian provider.
Description check ✅ Passed The PR description thoroughly explains the feature addition, context, implementation details, files changed, and testing, but incompletely fills the template by not explicitly selecting a 'Type of change' checkbox.
Linked Issues check ✅ Passed The PR fully implements all core objectives from issue #15044: AvianModel driver with chat/sync/SSE streaming, list_models, check_connection, Bearer auth, config file with 4 models, factory registration, and comprehensive tests.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the Avian provider implementation. No out-of-scope modifications to selfDeployed map or other unrelated areas are included.

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

@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

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

78-126: ⚡ Quick win

Consider validating all request parameters in test handler.

The test passes topP: 0.9 and stop: []string{"END"} (lines 109-110) but the handler only validates max_tokens and temperature (lines 89-94). For more comprehensive validation, consider checking that top_p and stop are correctly included in the request body.

Suggested enhancement
 		if body["temperature"] != 0.3 {
 			t.Errorf("temperature=%v, want 0.3", body["temperature"])
 		}
+		if body["top_p"] != 0.9 {
+			t.Errorf("top_p=%v, want 0.9", body["top_p"])
+		}
+		if stopSlice, ok := body["stop"].([]interface{}); !ok || len(stopSlice) != 1 || stopSlice[0] != "END" {
+			t.Errorf("stop=%v, want [END]", body["stop"])
+		}
 		_ = json.NewEncoder(w).Encode(map[string]interface{}{
🤖 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/avian_test.go` around lines 78 - 126, The test handler
inside newAvianServer (the anonymous func used in TestAvianChatHappyPath)
currently verifies model, stream, max_tokens and temperature but not top_p or
stop; update that handler to also assert body["top_p"] == 0.9 (float64) and that
body["stop"] is a slice containing the string "END" (body["stop"] will be a
[]interface{} so check its length and element string value) so the request built
by ChatWithMessages (called below with TopP and Stop) is fully validated.
🤖 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/avian_test.go`:
- Around line 35-38: Add a brief inline comment above the Content-Type check
(the r.Header.Get("Content-Type") validation in the test helper) explaining that
the Avian API intentionally sets "Content-Type: application/json" on GET
requests (see avian.go line 363) so this non-standard requirement applies even
for requests without a body; update the test helper comment near the
Content-Type assertion to state this intent so future maintainers understand why
the GET is validated for a JSON Content-Type.

In `@internal/entity/models/avian.go`:
- Around line 305-314: The streaming branch currently forwards both
choice.Delta.ReasoningContent and choice.Delta.Reasoning which duplicates
chunks; change the logic to mirror ChatWithMessages by preferring
reasoning_content and only falling back to reasoning when reasoning_content is
empty—i.e., inside the streaming handler where sender is called, send
choice.Delta.ReasoningContent if non-empty, else send choice.Delta.Reasoning,
and remove the second unconditional send; reference the symbols
choice.Delta.ReasoningContent, choice.Delta.Reasoning, sender and the
ChatWithMessages fallback behavior when making the change.
- Around line 81-90: The baseURLForRegion method should also normalize and
remove a trailing "/v1" (and any trailing slash) from tenant-supplied BaseURL
entries to avoid duplicating the API version in constructed paths; update
AvianModel.baseURLForRegion to trim an optional "/v1" suffix (e.g., remove "/v1"
or "/v1/") and then trim any remaining trailing "/" before returning the base so
callers that append "v1/..." won't produce "/v1/v1/...".

---

Nitpick comments:
In `@internal/entity/models/avian_test.go`:
- Around line 78-126: The test handler inside newAvianServer (the anonymous func
used in TestAvianChatHappyPath) currently verifies model, stream, max_tokens and
temperature but not top_p or stop; update that handler to also assert
body["top_p"] == 0.9 (float64) and that body["stop"] is a slice containing the
string "END" (body["stop"] will be a []interface{} so check its length and
element string value) so the request built by ChatWithMessages (called below
with TopP and Stop) is fully validated.
🪄 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: 6c55e1da-5791-4d40-82aa-f8d15a39b016

📥 Commits

Reviewing files that changed from the base of the PR and between 6499bce and 9e42d99.

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

Comment thread internal/entity/models/avian_test.go Resolved
Comment thread internal/entity/models/avian.go Resolved
Comment thread internal/entity/models/avian.go Resolved

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/entity/models/avian.go (1)

380-383: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Fix ListModels response parsing to handle OpenAI-compatible wrapper format.

The code unmarshals directly to []avianModelInfo, but Avian's /v1/models endpoint returns {"object": "list", "data": [...]} (matching OpenAI's format). This causes json.Unmarshal to fail at runtime because the response is an object, not an array.

Add a wrapper struct and update the unmarshaling target:

Fix
+type avianModelsResponse struct {
+	Data []avianModelInfo `json:"data"`
+}
+
 func (a *AvianModel) ListModels(apiConfig *APIConfig) ([]string, error) {
 	// ... existing code ...
 
-	var result []avianModelInfo
+	var result avianModelsResponse
 	if err = json.Unmarshal(body, &result); err != nil {
 		return nil, fmt.Errorf("failed to parse response: %w", err)
 	}
 
-	models := make([]string, 0, len(result))
-	for _, model := range result {
+	models := make([]string, 0, len(result.Data))
+	for _, model := range result.Data {
 		if model.ID != "" {
 			models = append(models, model.ID)
 		}
 	}
🤖 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/avian.go` around lines 380 - 383, The code currently
unmarshals the /v1/models response directly into []avianModelInfo (variable
result) but the API returns an OpenAI-style wrapper object
{"object":"list","data":[...]} causing json.Unmarshal to fail; add a small
wrapper type (e.g., type avianModelsList struct { Object string `json:"object"`;
Data []avianModelInfo `json:"data"` }) and unmarshal into that in the ListModels
flow, then set result = wrapper.Data (or return wrapper.Data) instead of
unmarshaling directly into []avianModelInfo.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@internal/entity/models/avian.go`:
- Around line 380-383: The code currently unmarshals the /v1/models response
directly into []avianModelInfo (variable result) but the API returns an
OpenAI-style wrapper object {"object":"list","data":[...]} causing
json.Unmarshal to fail; add a small wrapper type (e.g., type avianModelsList
struct { Object string `json:"object"`; Data []avianModelInfo `json:"data"` })
and unmarshal into that in the ListModels flow, then set result = wrapper.Data
(or return wrapper.Data) instead of unmarshaling directly into []avianModelInfo.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c6bbbbc4-2775-4263-b5a6-1ec0f3262a6e

📥 Commits

Reviewing files that changed from the base of the PR and between 9e42d99 and 5d4ad42.

📒 Files selected for processing (2)
  • internal/entity/models/avian.go
  • internal/entity/models/avian_test.go

@dripsmvcp

Copy link
Copy Markdown
Contributor Author

@dosu review this PR

@dosubot

dosubot Bot commented May 20, 2026

Copy link
Copy Markdown

Hi @dripsmvcp! I'm Dosu and I’m helping the ragflow team.

I appreciate the mention, but I don't perform traditional code reviews (assessing PRs for bugs, design, style, performance, or security).

However, I can help in other ways:

  • Research how other providers (like TogetherAI, Novita) were implemented in the Go rewrite, so you can compare patterns
  • Answer questions about the codebase relevant to this PR
  • Suggest documentation updates if this new provider needs docs

Let me know if any of those would be useful!

To reply, just mention @dosu.


Share context across your team and agents. Try Dosu.

Leave Feedback Learn about ragflow with Dosu Add Dosu to your team

@dripsmvcp

Copy link
Copy Markdown
Contributor Author

@dosu check #15045

@dosubot

dosubot Bot commented May 20, 2026

Copy link
Copy Markdown

PR #15045 adds the Avian LLM provider to RAGFlow's Go API server [1]. It's currently open and addresses issue #15044 (an item from the Go-rewrite tracker #14736).

What it does: Implements an OpenAI-compatible SaaS driver for Avian (base URL https://api.avian.io) with chat completions (sync + SSE streaming, 10-min timeout), model listing, and connection checking. Reasoning extraction prefers reasoning_content with fallback to reasoning.

Files added/modified:

  • conf/models/avian.json — config with 4 chat models (deepseek-v3.2, kimi-k2.5, glm-5, minimax-m2.5)
  • internal/entity/models/avian.go — the driver implementation
  • internal/entity/models/avian_test.go — 13 test cases covering happy paths, error handling, streaming, and factory routing
  • internal/entity/models/factory.go — adds "avian" case to the factory switch

Pattern: Mirrors the TogetherAI provider structure. Avian is SaaS (not self-deployed), so access is gated by the user supplying an API key [1].

As noted in my earlier comment, I don't perform traditional code reviews (assessing for bugs, design, style, or security). But I can research how other providers were implemented for comparison, answer specific questions about the codebase, or help with documentation if needed.

To reply, just mention @dosu.


Share context across your team and agents. Try Dosu.

Leave Feedback Learn about ragflow with Dosu Add Dosu to your team

@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 @dripsmvcp, thank you for your contribution.
Two small changes will be ok.

Comment thread internal/entity/models/avian.go Outdated
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
req.Header.Set("Accept", "text/event-stream")

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.

no req.Header.Set("Accept", "text/event-stream")
delete it plz

Comment thread conf/models/avian.json
@@ -0,0 +1,41 @@
{

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.

would you mind add deekseek-v4-flash/pro ?

@Haruko386 Haruko386 added the ci Continue Integration label May 21, 2026
@codecov

codecov Bot commented May 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (fec0b96) to head (213f8d2).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15045   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  Misses         29       29           
  Partials       20       20           

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

@JinHai-CN
JinHai-CN merged commit 78f2356 into infiniflow:main May 21, 2026
1 check passed
JinHai-CN added a commit that referenced this pull request May 21, 2026
Closes #15044.

Avian was listed unchecked in the Go-rewrite tracker #14736 and already
had an llm_factories.json entry with 4 preconfigured chat models
(deepseek-v3.2, kimi-k2.5, glm-5, minimax-m2.5), but the Go API server
had no driver to route them. The Python side has supported Avian at
rag/llm/chat_model.py:1220 (AvianChat) via the LiteLLM openai/ provider
with default base https://api.avian.io/v1.

Co-authored-by: Jin Hai <[email protected]>
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]: Implement provider: Avian in Go driver

3 participants