Skip to content

Go: implement provider: n1n.ai - #15010

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
sxxtony:go/n1n-driver
May 21, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
sxxtony:go/n1n-driver

Conversation

@sxxtony

@sxxtony sxxtony commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Update (commit d3e01a7) — addresses maintainer review:

  • Added thinking: {type: "enabled" | "disabled"} body field via ChatConfig.Thinking (per @Haruko386's example curl against deepseek-v3-1-250821).
  • Added deepseek-v3-1-250821 and deepseek-v3-1-think-250821 to the shipped catalog.
  • ChatWithMessages now leaves ChatResponse.ReasonContent as nil when the upstream omits reasoning_content (CodeRabbit nit).
  • Live test transcripts confirming all of the above are at Go: implement provider: n1n.ai #15010 (comment)

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 n1n as a model provider in the Go layer fell through to the default branch of internal/entity/models/factory.go and got the dummy driver.

What this PR includes

  • internal/entity/models/n1n.go — N1NModel implementing ModelDriver.
  • 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" to NewN1NModel.

Method coverage (docs-driven)

ModelDriver method n1n.ai endpoint Status
ChatWithMessages POST /v1/chat/completions ✅ implemented
ChatStreamlyWithSender POST /v1/chat/completions (SSE, [DONE]) ✅ implemented
Embed POST /v1/embeddings ✅ implemented
Rerank POST /v1/rerank ✅ implemented
ListModels GET /v1/models ✅ implemented
CheckConnection delegates to ListModels ✅ implemented
Balance not documented "n1n, no such method"
TranscribeAudio, AudioSpeech /v1/audio/* documented but multipart/binary "n1n, no such method" (deferred)
OCRFile, ParseFile, ListTasks, ShowTask not documented "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-mini

POST /v1/chat/completions   {"model":"gpt-4o-mini","messages":[{"role":"user","content":"What is 15% of 80? answer in one short sentence."}],"max_tokens":64}
→ finish_reason: stop
→ content: "15% of 80 is 12."
→ usage.total_tokens: 32

2. Chat (streaming) — gpt-4o-mini

POST /v1/chat/completions   {"model":"gpt-4o-mini","messages":[...],"max_tokens":16,"stream":true}
→ 12 SSE lines total
→ delta keys observed: ['content', 'refusal', 'role']
→ reassembled content: "Hello world!"
→ finish_reason: "stop"
→ data: [DONE]   ✓ terminator present

3. Embeddings — text-embedding-3-small

POST /v1/embeddings   {"model":"text-embedding-3-small","input":["walkerwhat","jumperwho","what is rag"]}
→ count:    3
→ indices:  [0, 1, 2]   ✓ ordered
→ dims:     [1536, 1536, 1536]
→ first[:3]: [0.0076, -0.0252, -0.0319]

4. Embeddings with dimensions override

POST /v1/embeddings   {"model":"text-embedding-3-small","input":["hello"],"dimensions":512}
→ dim with dimensions=512 → 512   ✓ EmbeddingConfig.Dimension propagation works

5. Rerank — BAAI/bge-reranker-v2-m3

POST /v1/rerank   {"model":"BAAI/bge-reranker-v2-m3","query":"What is the capital of France?","documents":["Paris is the capital of France","Berlin is in Germany","Tokyo is in Japan"],"top_n":3}
→ index=0  relevance_score=0.999784   (Paris ✓)
→ index=1  relevance_score=0.000437
→ index=2  relevance_score=0.000057

6. ListModels + CheckConnection control

GET /v1/models
→ total: 453
→ every model shipped in conf/models/n1n.json is present in the live catalog (12/12)

GET /v1/models   (bad key)
→ HTTP 401   ✓ CheckConnection surfaces credential errors via ListModels

Design notes

  • URL split. url.default is bare https://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.
  • Embed reorder + dedup. The driver realigns data[*] by index so 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.
  • Rerank dedup. Mirrors the Embed validation: an upstream that repeats an index in results fails fast.
  • SSE. Standard OpenAI shape: data: lines, [DONE] terminator, finish_reason as the inner break signal. A malformed JSON frame returns "n1n: invalid SSE event" rather than silently skipping (caller can distinguish truncation from upstream malformation).
  • No client-level Timeout on the http.Client (would also cap SSE body reads); non-stream calls each wrap their context in nonStreamCallTimeout.

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.

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 19, 2026
@coderabbitai

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

N1N Model Provider Integration

Layer / File(s) Summary
Configuration and factory registration
conf/models/n1n.json, internal/entity/models/factory.go
Provider config defines regional base URLs, endpoint suffixes, and a model catalog; factory switch registers "n1n" to NewN1NModel.
Driver core and request helpers
internal/entity/models/n1n.go (lines 1–133)
N1NModel struct with tuned HTTP client; region selection, endpoint construction, API key validation, and JSON/Bearer request helper functions.
Chat schema and builder
internal/entity/models/n1n.go (lines 135–191)
n1n-specific chat request/message types and builder mapping internal chat settings to n1n schema.
Non-streaming chat completion
internal/entity/models/n1n.go (lines 193–284)
ChatWithMessages: validates inputs, forces stream=false, timeout-bounded full response read, validates choices and content, returns ChatResponse with answer and reasoning.
Streaming chat (SSE)
internal/entity/models/n1n.go (lines 286–398)
ChatStreamlyWithSender: SSE parsing of data: frames, emits reasoning/content deltas via callbacks, and requires terminal [DONE] or finish_reason for completion.
Embeddings
internal/entity/models/n1n.go (lines 400–498)
Embed: validates inputs, optional dimensions, parses /v1/embeddings, reorders vectors by index, rejects duplicates/out-of-range/missing indices.
Reranking
internal/entity/models/n1n.go (lines 500–587)
Rerank: validates documents, optional top_n, parses /v1/rerank into RerankResponse, rejects invalid indices.
Model listing, connection, unsupported methods
internal/entity/models/n1n.go (lines 589–702)
ListModels (GET /v1/models), CheckConnection delegates to ListModels, and remaining methods return explicit "no such method" errors for unsupported features.

Sequence Diagram

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

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Suggested labels

💞 feature

Suggested reviewers

  • Haruko386

Poem

🐰 I hopped to n1n's bright API gate,
Streams of thought arrived, nice and straight,
Embeddings hum and reranks align,
Factory wakes, the models sign,
A rabbit claps — the driver’s great!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% 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: n1n.ai" clearly and specifically describes the main change: adding a Go driver implementation for the n1n.ai provider.
Description check ✅ Passed The PR description comprehensively addresses all required template sections with detailed problem context, change type identification (New Feature), implementation details, design decisions, live test results, and explicit scope boundaries.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

📥 Commits

Reviewing files that changed from the base of the PR and between eacec86 and d1eccfa.

📒 Files selected for processing (3)
  • conf/models/n1n.json
  • internal/entity/models/factory.go
  • internal/entity/models/n1n.go

Comment thread internal/entity/models/n1n.go Resolved
Comment on lines +611 to +617
models := make([]string, 0, len(parsed.Data))
for _, item := range parsed.Data {
if item.ID != "" {
models = append(models, item.ID)
}
}
return models, nil

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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.

@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 @sxxtony. All tests are passed, just do a small change

reqBody.MaxTokens = chatModelConfig.MaxTokens
reqBody.Temperature = chatModelConfig.Temperature
reqBody.TopP = chatModelConfig.TopP
reqBody.Stop = chatModelConfig.Stop

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.

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"
     }
}'

sxxtony added a commit to sxxtony/ragflow that referenced this pull request May 20, 2026
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".
@sxxtony

sxxtony commented May 20, 2026

Copy link
Copy Markdown
Contributor Author

@Haruko386 thanks — pushed d3e01a7 addressing both your inline request and the CodeRabbit reasoning-pointer nit.

Changes

File Change
internal/entity/models/n1n.go New n1nThinking struct + Thinking *n1nThinking field on the chat request body; buildN1NChatRequest maps ChatConfig.Thinking *bool → thinking: {type: "enabled" | "disabled"} (your curl shape). Unset stays absent via *n1nThinking + omitempty.
internal/entity/models/n1n.go ChatWithMessages now leaves ChatResponse.ReasonContent as nil when the upstream omits message.reasoning_content, matching the streaming path's behavior (CodeRabbit nit).
conf/models/n1n.json Added deepseek-v3-1-250821 and deepseek-v3-1-think-250821 to the shipped catalog.

Live tests (api.n1n.ai)

1. thinking: {type: "enabled"} on a reasoning model — non-stream

POST /v1/chat/completions   model=deepseek-v3-1-think-250821, thinking.type=enabled
→ finish_reason: stop
→ message keys: ['role', 'content', 'reasoning_content']
→ content: "15% of 80 is 12.\n\n**Reasoning**: 15% is equivalent to 15/100 or 0.15…"
→ reasoning_content: 358 chars
→ reasoning[:120]: "We are asked: \"What is 15% of 80? Show your reasoning briefly.\"…"

2. thinking: {type: "disabled"} on the same model — non-stream

POST /v1/chat/completions   model=deepseek-v3-1-think-250821, thinking.type=disabled
→ finish_reason: stop
→ message keys: ['role', 'content']             ← reasoning_content absent ✓
→ content: "15% of 80 is 12."

3. Streaming with thinking: {type: "enabled"} — matches your curl shape

POST /v1/chat/completions   model=deepseek-v3-1-think-250821
                            temperature=1.0, stream=true, stream_options.include_usage=true
                            thinking.type=enabled
→ 208 SSE lines
→ distinct delta keys: ['content', 'reasoning_content', 'role']
→ delta.reasoning_content chunks: 101
→ delta.content chunks: 1   (final answer "12")
→ data: [DONE]   ✓ terminator present

The driver streams delta.reasoning_content chunks through the sender's second arg and delta.content through the first — same routing the maintainer's UI ("Thinking:" then "Answer:" in the CLI transcript on #14809) expects.

4. Non-reasoning model — confirms CodeRabbit nil-pointer fix

POST /v1/chat/completions   model=gpt-4o-mini
→ message keys: ['role', 'content', 'refusal', 'annotations']
→ content: "Pong!"
→ reasoning_content: absent
→ driver returns ChatResponse.ReasonContent == nil   ✓

What stays out

  • The CodeRabbit "empty model catalog → error" nit on ListModels:617 — skipped. An empty data: [] from a one-api gateway with no allocated quota is a valid response; failing on it would surface as a confusing connectivity error during onboarding. Empty id strings inside data[*] are already skipped.

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

@sxxtony LGTM, thx for your contribution

@Haruko386 Haruko386 added the ci Continue Integration label May 20, 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.

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

272-283: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use a pointer in the response schema to actually preserve nil-vs-empty.

This guard still collapses reasoning_content omitted and reasoning_content: "" into the same result, because n1nChatMessage.ReasoningContent is decoded as a plain string. If callers rely on the new contract, an explicitly empty upstream value will still come back as nil.

💡 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

📥 Commits

Reviewing files that changed from the base of the PR and between d1eccfa and d3e01a7.

📒 Files selected for processing (2)
  • conf/models/n1n.json
  • internal/entity/models/n1n.go

@codecov

codecov Bot commented May 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (dc01e0e) to head (cc4788b).

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

Copy link
Copy Markdown
Member

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

sxxtony added 2 commits May 20, 2026 18:30
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".
@sxxtony

sxxtony commented May 20, 2026

Copy link
Copy Markdown
Contributor Author

@JinHai-CN done — rebased onto current main (dc01e0e5) and force-pushed.

commit description
cc23db07 original n1n.ai driver (formerly d1eccfad)
cc4788b3 thinking-mode + nil-ReasonContent fix (formerly d3e01a7d)

GitHub shows mergeable: true after the rebase. One factory-route conflict against the new case "jiekouai" / "302.ai" / "mineru_local" entries that landed on main; resolved by keeping all of them and appending case "n1n" last.

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

📥 Commits

Reviewing files that changed from the base of the PR and between d3e01a7 and cc4788b.

📒 Files selected for processing (3)
  • conf/models/n1n.json
  • internal/entity/models/factory.go
  • internal/entity/models/n1n.go

Comment on lines +107 to +111
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

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants