Repository navigation
Go: implement provider: n1n.ai - #15010
Conversation
📝 WalkthroughWalkthroughAdds n1n.ai provider support: provider config, factory registration, and a full N1NModel driver implementing chat (streaming + non-streaming), embeddings, reranking, model listing, connection checks, and explicit unsupported-method errors. ChangesN1N Model Provider Integration
Sequence DiagramsequenceDiagram
participant Client
participant N1NModel
participant n1n_API
Client->>N1NModel: Call ChatStreamlyWithSender(messages, config, sender)
N1NModel->>n1n_API: POST /v1/chat/completions (stream=true, Bearer token)
n1n_API-->>N1NModel: SSE data: events (delta JSON)
N1NModel->>Client: Invoke sender callbacks with deltas
n1n_API-->>N1NModel: SSE [DONE] or finish_reason
N1NModel->>Client: Emit final end-of-stream marker
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 |
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 `@internal/entity/models/n1n.go`:
- Around line 250-255: The code currently always returns ReasonContent as a
pointer to an empty string because it takes the address of a local string
(reasonContent); instead, preserve a nil when the provider omitted reasoning by
assigning ReasonContent directly from parsed.Choices[0].Message.ReasoningContent
only if it is non-nil. Concretely, replace the reasonContent := ... /
ReasonContent: &reasonContent pattern with logic that sets a local *string
(e.g., rc) to parsed.Choices[0].Message.ReasoningContent when that value is
non-nil, otherwise leave rc nil, and return ChatResponse{Answer: &content,
ReasonContent: rc}.
- Around line 611-617: ListModels currently collects item.ID into models and
returns success even if models is empty; update ListModels to treat an empty
usable model catalog as a failure by returning a non-nil error when len(models)
== 0 (after iterating parsed.Data), include a clear error message (e.g., "no
usable models found" or similar) so callers like CheckConnection receive a
failure instead of a false-positive; locate the ListModels function and the
models slice population that iterates parsed.Data and item.ID and add the
post-loop check to return an error when models is empty.
🪄 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: 123bc49a-44e0-4fed-9d00-ee7efac32ac1
📒 Files selected for processing (3)
conf/models/n1n.jsoninternal/entity/models/factory.gointernal/entity/models/n1n.go
| models := make([]string, 0, len(parsed.Data)) | ||
| for _, item := range parsed.Data { | ||
| if item.ID != "" { | ||
| models = append(models, item.ID) | ||
| } | ||
| } | ||
| return models, nil |
There was a problem hiding this comment.
Treat an empty usable model catalog as a failure.
ListModels currently returns success even when every decoded item has an empty id. Because CheckConnection delegates here, an upstream schema drift or stripped response becomes a false-positive connectivity check.
Suggested fix
models := make([]string, 0, len(parsed.Data))
for _, item := range parsed.Data {
- if item.ID != "" {
+ if strings.TrimSpace(item.ID) != "" {
models = append(models, item.ID)
}
}
+ if len(models) == 0 {
+ return nil, fmt.Errorf("n1n: models response contained no usable model ids")
+ }
return models, nil📝 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.
| models := make([]string, 0, len(parsed.Data)) | |
| for _, item := range parsed.Data { | |
| if item.ID != "" { | |
| models = append(models, item.ID) | |
| } | |
| } | |
| return models, nil | |
| models := make([]string, 0, len(parsed.Data)) | |
| for _, item := range parsed.Data { | |
| if strings.TrimSpace(item.ID) != "" { | |
| models = append(models, item.ID) | |
| } | |
| } | |
| if len(models) == 0 { | |
| return nil, fmt.Errorf("n1n: models response contained no usable model ids") | |
| } | |
| return models, 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/n1n.go` around lines 611 - 617, ListModels currently
collects item.ID into models and returns success even if models is empty; update
ListModels to treat an empty usable model catalog as a failure by returning a
non-nil error when len(models) == 0 (after iterating parsed.Data), include a
clear error message (e.g., "no usable models found" or similar) so callers like
CheckConnection receive a failure instead of a false-positive; locate the
ListModels function and the models slice population that iterates parsed.Data
and item.ID and add the post-loop check to return an error when models is empty.
| reqBody.MaxTokens = chatModelConfig.MaxTokens | ||
| reqBody.Temperature = chatModelConfig.Temperature | ||
| reqBody.TopP = chatModelConfig.TopP | ||
| reqBody.Stop = chatModelConfig.Stop |
There was a problem hiding this comment.
Refer this and add thinking mode for deepseek-v3-1-250821
curl --location 'https://api.n1n.ai/v1/chat/completions' \
--header 'Accept: application/json' \
--header 'X-Forwarded-Host: localhost:5173' \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '{
"model": "deepseek-v3-1-250821",
"max_tokens": 1000,
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你好"
}
],
"temperature": 1.0,
"stream": true,
"stream_options": {
"include_usage": true
},
"thinking":{
"type":"enabled"
}
}'Per maintainer review on PR infiniflow#15010: - buildN1NChatRequest now maps ChatConfig.Thinking *bool -> n1n.ai's documented `thinking: {type: "enabled"|"disabled"}` body field (Haruko386's example curl against deepseek-v3-1-250821). Unset Thinking leaves the field absent thanks to *n1nThinking + omitempty, so non-reasoning models see no change in wire shape. - conf/models/n1n.json gains deepseek-v3-1-250821 and deepseek-v3-1-think-250821 (the explicit reasoning variant) so the maintainer's example model is in the shipped catalog. Also addresses the CodeRabbit nit on the same review: - ChatWithMessages no longer takes the address of a local empty string for ReasonContent. When the upstream omits message.reasoning_content the driver now leaves ChatResponse.ReasonContent as nil, matching how the streaming path already suppresses empty reasoning chunks. Downstream callers can now distinguish "no reasoning emitted" from "reasoning present but empty".
|
@Haruko386 thanks — pushed d3e01a7 addressing both your inline request and the CodeRabbit reasoning-pointer nit. Changes
Live tests (api.n1n.ai)1. 2. 3. Streaming with The driver streams 4. Non-reasoning model — confirms CodeRabbit nil-pointer fix What stays out
|
There was a problem hiding this comment.
♻️ Duplicate comments (1)
internal/entity/models/n1n.go (1)
272-283:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUse a pointer in the response schema to actually preserve nil-vs-empty.
This guard still collapses
reasoning_contentomitted andreasoning_content: ""into the same result, becausen1nChatMessage.ReasoningContentis decoded as a plainstring. If callers rely on the new contract, an explicitly empty upstream value will still come back asnil.💡 Minimal fix
type n1nChatMessage struct { Content *string `json:"content"` - ReasoningContent string `json:"reasoning_content"` + ReasoningContent *string `json:"reasoning_content"` }content := *parsed.Choices[0].Message.Content chatResp := &ChatResponse{ Answer: &content, } - if parsed.Choices[0].Message.ReasoningContent != "" { - reasonContent := parsed.Choices[0].Message.ReasoningContent - chatResp.ReasonContent = &reasonContent - } + chatResp.ReasonContent = parsed.Choices[0].Message.ReasoningContent return chatResp, 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/n1n.go` around lines 272 - 283, The code collapses omitted vs explicitly empty reasoning because n1nChatMessage.ReasoningContent is a plain string; change the decoded field to a *string (pointer) so you can detect nil vs "" and then assign that pointer through to ChatResponse.ReasonContent (i.e., stop creating a new local reasonContent string and instead set chatResp.ReasonContent = parsed.Choices[0].Message.ReasoningContent after updating the type), ensuring JSON decoding preserves nil when the upstream omits the field.
🤖 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 `@internal/entity/models/n1n.go`:
- Around line 272-283: The code collapses omitted vs explicitly empty reasoning
because n1nChatMessage.ReasoningContent is a plain string; change the decoded
field to a *string (pointer) so you can detect nil vs "" and then assign that
pointer through to ChatResponse.ReasonContent (i.e., stop creating a new local
reasonContent string and instead set chatResp.ReasonContent =
parsed.Choices[0].Message.ReasoningContent after updating the type), ensuring
JSON decoding preserves nil when the upstream omits the field.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ae579466-9148-4157-9904-b411178b3a1a
📒 Files selected for processing (2)
conf/models/n1n.jsoninternal/entity/models/n1n.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15010 +/- ##
==========================================
- Coverage 94.53% 93.12% -1.41%
==========================================
Files 10 10
Lines 713 713
Branches 116 116
==========================================
- Hits 674 664 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
@sxxtony Since previous PR includes a binary file which is very big. So, I reset the head of main branch. Would you please re-submit the commit from current HEAD of main branch? Thank you very much. |
Add a Go driver for n1n.ai (https://docs.n1n.ai), one of the unchecked providers on the umbrella tracking issue infiniflow#14736. n1n.ai is an OpenAI-compatible aggregator that exposes a 450+ model catalog (GPT, Claude, Gemini, DeepSeek, Kimi, Qwen, embedding + reranker families) under https://api.n1n.ai/v1. ModelDriver coverage maps directly to documented endpoints: ChatWithMessages POST /v1/chat/completions ChatStreamlyWithSender POST /v1/chat/completions (SSE, [DONE]) Embed POST /v1/embeddings Rerank POST /v1/rerank ListModels GET /v1/models CheckConnection delegates to ListModels Everything else (Balance, TranscribeAudio, AudioSpeech, OCRFile, ParseFile, ListTasks, ShowTask) returns "n1n, no such method" — the n1n.ai docs list /v1/audio/* and /v1/contents/generations/tasks endpoints but they involve multipart upload / binary response / async job orchestration and are deferred to a follow-up. Per the maintainer's guidance on infiniflow#14809 review #4277917390, the driver only implements interface methods backed by JSON surfaces that the docs publish. URL split follows the same convention the maintainer asked for on Novita (infiniflow#14850) and LongCat (infiniflow#14809): url.default = "https://api.n1n.ai" url_suffix.chat = "v1/chat/completions" etc. Shipped catalog in conf/models/n1n.json is a representative 12-model subset (chat + embedding + rerank); the full live catalog is reachable via ListModels.
Per maintainer review on PR infiniflow#15010: - buildN1NChatRequest now maps ChatConfig.Thinking *bool -> n1n.ai's documented `thinking: {type: "enabled"|"disabled"}` body field (Haruko386's example curl against deepseek-v3-1-250821). Unset Thinking leaves the field absent thanks to *n1nThinking + omitempty, so non-reasoning models see no change in wire shape. - conf/models/n1n.json gains deepseek-v3-1-250821 and deepseek-v3-1-think-250821 (the explicit reasoning variant) so the maintainer's example model is in the shipped catalog. Also addresses the CodeRabbit nit on the same review: - ChatWithMessages no longer takes the address of a local empty string for ReasonContent. When the upstream omits message.reasoning_content the driver now leaves ChatResponse.ReasonContent as nil, matching how the streaming path already suppresses empty reasoning chunks. Downstream callers can now distinguish "no reasoning emitted" from "reasoning present but empty".
|
@JinHai-CN done — rebased onto current
GitHub shows |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/n1n.go`:
- Around line 107-111: n1nValidateAPIKey currently treats whitespace-only
strings as valid; update it to trim surrounding whitespace from
*apiConfig.ApiKey (use strings.TrimSpace) and then validate that the trimmed
value is non-empty, returning the trimmed string on success or an error like
"api key is required" if empty. Ensure you reference the APIConfig.ApiKey
pointer when trimming and return the trimmed key rather than the original.
🪄 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: b0cd6319-02d8-4245-b735-533a03103fee
📒 Files selected for processing (3)
conf/models/n1n.jsoninternal/entity/models/factory.gointernal/entity/models/n1n.go
| func n1nValidateAPIKey(apiConfig *APIConfig) (string, error) { | ||
| if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { | ||
| return "", fmt.Errorf("api key is required") | ||
| } | ||
| return *apiConfig.ApiKey, nil |
There was a problem hiding this comment.
Trim whitespace in API key validation.
n1nValidateAPIKey currently accepts whitespace-only keys (e.g. " "), which become invalid Bearer headers and fail later with less clear errors.
Suggested patch
func n1nValidateAPIKey(apiConfig *APIConfig) (string, error) {
- if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ if apiConfig == nil || apiConfig.ApiKey == nil || strings.TrimSpace(*apiConfig.ApiKey) == "" {
return "", fmt.Errorf("api key is required")
}
- return *apiConfig.ApiKey, nil
+ return strings.TrimSpace(*apiConfig.ApiKey), nil
}📝 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.
| func n1nValidateAPIKey(apiConfig *APIConfig) (string, error) { | |
| if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { | |
| return "", fmt.Errorf("api key is required") | |
| } | |
| return *apiConfig.ApiKey, nil | |
| func n1nValidateAPIKey(apiConfig *APIConfig) (string, error) { | |
| if apiConfig == nil || apiConfig.ApiKey == nil || strings.TrimSpace(*apiConfig.ApiKey) == "" { | |
| return "", fmt.Errorf("api key is required") | |
| } | |
| return strings.TrimSpace(*apiConfig.ApiKey), 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/n1n.go` around lines 107 - 111, n1nValidateAPIKey
currently treats whitespace-only strings as valid; update it to trim surrounding
whitespace from *apiConfig.ApiKey (use strings.TrimSpace) and then validate that
the trimmed value is non-empty, returning the trimmed string on success or an
error like "api key is required" if empty. Ensure you reference the
APIConfig.ApiKey pointer when trimming and return the trimmed key rather than
the original.
What problem does this PR solve?
Add a Go driver for n1n.ai (https://docs.n1n.ai), one of the unchecked providers on the umbrella tracking issue #14736. n1n.ai is an OpenAI-compatible aggregator hosting a 450+ model catalog (GPT, Claude, Gemini, DeepSeek, Kimi, Qwen, embedding + reranker families) under
https://api.n1n.ai/v1.Until this PR, a tenant who configured
n1nas a model provider in the Go layer fell through to the default branch ofinternal/entity/models/factory.goand got the dummy driver.What this PR includes
internal/entity/models/n1n.go—N1NModelimplementingModelDriver.conf/models/n1n.json— base URL + versioned suffixes (bare host +v1/...paths, matching the maintainer's split on Novita / LongCat) and a representative 12-model catalog (chat + embedding + rerank).factory.go— route"n1n"toNewN1NModel.Method coverage (docs-driven)
ChatWithMessagesPOST /v1/chat/completionsChatStreamlyWithSenderPOST /v1/chat/completions(SSE,[DONE])EmbedPOST /v1/embeddingsRerankPOST /v1/rerankListModelsGET /v1/modelsCheckConnectionListModelsBalance"n1n, no such method"TranscribeAudio,AudioSpeech/v1/audio/*documented but multipart/binary"n1n, no such method"(deferred)OCRFile,ParseFile,ListTasks,ShowTask"n1n, no such method"Per the maintainer's guidance on #14809 (review #4277917390), the driver only implements interface methods backed by documented JSON surfaces, and stubs the rest with the standard
"<name>, no such method"sentinel.Live test transcripts (api.n1n.ai)
All six tests run against the real API. Bodies elided to score & key facts.
1. Chat (non-stream) —
gpt-4o-mini2. Chat (streaming) —
gpt-4o-mini3. Embeddings —
text-embedding-3-small4. Embeddings with
dimensionsoverride5. Rerank —
BAAI/bge-reranker-v2-m36. ListModels + CheckConnection control
Design notes
url.defaultis barehttps://api.n1n.ai; the version lives in each suffix (v1/chat/completions,v1/embeddings, etc.). This matches the maintainer's preferred split on Go: implement provider: Novita.ai #14850 (Novita) and Go: implement provider: LongCat #14809 (LongCat) so the prefix isn't double-counted if a tenant overrides the base URL.data[*]byindexso output rows line up with input texts. Duplicate or out-of-range indices fail loudly rather than silently overwriting an earlier vector — same defensive posture as the Voyage and CometAPI drivers in this package.resultsfails fast.data:lines,[DONE]terminator,finish_reasonas the inner break signal. A malformed JSON frame returns"n1n: invalid SSE event"rather than silently skipping (caller can distinguish truncation from upstream malformation).Timeouton thehttp.Client(would also cap SSE body reads); non-stream calls each wrap their context innonStreamCallTimeout.Out of scope (follow-ups)
/v1/audio/speech(TTS) and/v1/audio/transcriptions(STT) are documented but need multipart upload and binary response handling — happy to do as a follow-up PR./v1/contents/generations/tasks(async image/video jobs) — model surface is non-trivial; defer.