Repository navigation
Go: implement provider: LongCat - #14809
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a LongCat provider: config manifest, factory wiring, a LongCatModel with non-streaming and SSE streaming chat (including reasoning_content handling), ListModels and CheckConnection, unsupported-method stubs, and comprehensive unit tests. ChangesLongCat Model Provider Integration
Sequence Diagram(s)sequenceDiagram
Client->>LongCatModel: ChatStreamlyWithSender(model, messages, apiConfig, chatConfig, sender)
LongCatModel->>LongCatAPI: POST /v1/chat/completions (stream=true, Authorization: Bearer <key>)
LongCatAPI-->>LongCatModel: SSE events (data: {delta.reasoning_content/...})
LongCatModel->>SenderCallback: sender(&reasoningChunk, nil) -- emits reasoning_content chunks first
LongCatAPI-->>LongCatModel: SSE events (data: {delta.content/...})
LongCatModel->>SenderCallback: sender(&contentChunk, &nil) -- emits content chunks
LongCatAPI-->>LongCatModel: SSE event (data: [DONE] or finish_reason)
LongCatModel-->>Client: return success / assembled ChatResponse
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes 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. Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8738cfe8-5f82-4dd5-84d6-be9900536917
📒 Files selected for processing (1)
internal/entity/models/localai.go
Haruko386
left a comment
There was a problem hiding this comment.
Hi @tmimmanuel, ReasonContent should not be empty.
plz fix this.
|
Duplicated with #14811. I will close it. Please feel free to re-open it, if i am wrong. |
Haruko386 flagged on both infiniflow#14809 and infiniflow#14813 that reasoning traces and thinking output were being silently dropped. LocalAI is a proxy that can route to any model family, and each upstream uses its own field name for the chain-of-thought: - reasoning_content: OpenAI o-series, kimi-k2.6, DeepSeek-R1, magistral when proxied through an OpenAI-shim - reasoning: Upstage solar-pro3 (and proxies) - thinking: Qwen3 (Ollama-style) and some local llama-r1 variants exposed through LocalAI's OpenAI shim The merged driver only read content / delta.content, so for every reasoning-capable model behind LocalAI, the trace never reached ChatResponse.ReasonContent or the streaming sender's reason channel. New helpers extractLocalAIReasoning and addLocalAIReasoningRequestParams keep the priority list in one place (localAIReasoningFields) so adding a new upstream field name is a single-line change. What this changes: - ChatWithMessages: parses message.reasoning_content / reasoning / thinking after content, populates ChatResponse.ReasonContent. Empty string and non-string values are skipped, so non-reasoning models still return empty ReasonContent without erroring (regression-safe). - ChatStreamlyWithSender: same priority order applied to each delta before reading delta.content. Reasoning chunks are emitted via the sender's second arg (the reasonContent channel that the non-stream path already populates), preserving the per-event ordering Upstage and kimi emit on the wire. - Both paths: propagate ChatConfig.Effort -> reasoning_effort and ChatConfig.Thinking -> enable_thinking. LocalAI doesn't know which family it routes to, so emitting both is safe; a non-supporting upstream ignores the extra field. Tests added in internal/entity/models/localai_test.go: - TestExtractLocalAIReasoning: table-driven coverage of the helper (priority order, empty/non-string skip, fallback) - TestLocalAIChatExtractsReasoningContent: kimi-k2.6-style response - TestLocalAIChatExtractsThinking: Qwen3-style response - TestLocalAIChatHandlesAbsentReasoning: non-reasoning regression net - TestLocalAIStreamExtractsReasoningContentDelta: streaming with interleaved delta.reasoning_content and delta.content - TestLocalAIStreamExtractsThinkingDelta: Qwen3 streaming - TestLocalAIChatPropagatesReasoningEffort: Effort -> reasoning_effort - TestLocalAIChatPropagatesEnableThinking: Thinking -> enable_thinking - TestLocalAIStreamPropagatesReasoningParams: stream request All 22 LocalAI tests pass on go 1.25. Build clean. Verified live against localai/localai:latest-aio-cpu in Docker: - ListModels: 8 models - Chat (gpt-4 alias): "pong" - Streaming (gpt-4): 9 chunks, "Hello! How can I help you today?" - Streaming with reasoning_effort=high + enable_thinking=true: request body accepted; non-reasoning AIO models return no reason chunks, proving the params are tolerated by upstreams that ignore them - Embed (text-embedding-ada-002): 3 vectors at dim 384, indices preserved - Rerank (jina-reranker-v1-base-en): 3 results with real relevance scores - Balance: "no such method" (unchanged) - CheckConnection: ok
|
@Haruko386 the multi-field reasoning fix you flagged here landed on #14813's branch (the leaf of the LocalAI stack). Full writeup with test logs + live Docker run in the #14813 comment. |
d656064 to
5e46457
Compare
LongCat (Meituan, https://longcat.chat) is one of the unchecked providers on the umbrella tracking issue infiniflow#14736. Its API is OpenAI-compatible at https://api.longcat.chat/openai/v1 with three public chat models: LongCat-Flash-Chat, LongCat-Flash-Lite, and LongCat-Flash-Thinking (a reasoning model). What this PR includes: - internal/entity/models/longcat.go: full driver implementing the ModelDriver interface - conf/models/longcat.json: base URL + url_suffix + the 3 public models - factory.go: route "longcat" provider name to NewLongCatModel - internal/entity/models/longcat_test.go: 21 unit tests Methods: - ChatWithMessages non-stream chat - ChatStreamlyWithSender SSE streaming chat - ListModels / CheckConnection - reasoning_content extraction on both stream and non-stream paths (LongCat-Flash-Thinking returns the chain-of-thought in message.reasoning_content / delta.reasoning_content, OpenAI o-series shape; live-probed before writing tests) - reasoning_effort propagation from ChatConfig.Effort - Embed / Rerank / Balance / TranscribeAudio / AudioSpeech / OCRFile return the "no such method" sentinel (LongCat does not expose any of these surfaces) Pattern parity with the merged Mistral (infiniflow#14807), Upstage (infiniflow#14819), and StepFun (infiniflow#14815) drivers. No interface change. Verified live against api.longcat.chat: - ListModels: 5 ids (Flash-Lite, Flash-Chat, Flash-Thinking-2601, Flash-Omni-2603, 2.0-Preview) - Chat (Flash-Chat) non-stream: "Got it! Let me know if you..." - Chat (Flash-Thinking) non-stream: 443-char answer + 557-char reasoning trace extracted into ChatResponse.ReasonContent - Stream (Flash-Thinking): 78 content chunks (351 chars) + 107 reasoning chunks (537 chars) — the delta.reasoning_content extraction works end to end against real wire data - Sentinels all return "no such method" 21 unit tests pass on go 1.25; build clean. Note on PR history: this branch was previously named for LocalAI work which has since been consolidated into PR infiniflow#14813. The branch was reset to upstream/main and rebuilt for LongCat — diff is a clean +1052 lines on top of current main.
Haruko386
left a comment
There was a problem hiding this comment.
hi @tmimmanuel, thank you for your contribution
I hope you would read API reference more carefully before you test or submit your code
|
Thanks @Haruko386 |
Per the LongCat platform docs (https://longcat.chat/platform/docs/APIDocs.html), the documented request shape is limited to {model, messages, stream, max_tokens, temperature, top_p} and there is no /models endpoint. Bring the driver back inside that envelope: - conf/models/longcat.json: base URL becomes https://api.longcat.chat/openai, chat suffix becomes v1/chat/completions, and the catalog is updated to the five models listed at platform/docs/Models.html (LongCat-Flash-Chat, LongCat-Flash-Lite, LongCat-Flash-Thinking-2601, LongCat-Flash-Omni-2603, LongCat-2.0-Preview). - longcat.go: stop and reasoning_effort are no longer forwarded to the chat or stream paths. ListModels now returns the shipped catalog (no /models endpoint to hit). CheckConnection issues a 1-token chat ping against LongCat-Flash-Lite instead. - longcat_test.go: drops the two reasoning_effort tests, replaces the /models tests with a catalog-pin test and a chat-ping test, and adds a guard that asserts no undocumented field (stop/reasoning_effort/response_format/tools/...) leaks into the request body. Live-tested against api.longcat.chat: non-stream chat, stream-with-finish_reason, thinking model reasoning_content, 1-token ping, and the embeddings 404 all match the driver's expectations.
|
@Haruko386 thanks for the pointer — I went back through https://longcat.chat/platform/docs/APIDocs.html#endpoints carefully and pushed 02923da to align with it. What the docs actually say (and what my previous commit was getting wrong):
Why hardcode
On the previous "live test passed" report — I was hitting the undocumented Live re-test against
A new test ( For |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
internal/entity/models/longcat_test.go (3)
82-87: ⚡ Quick winGuard response pointers before dereferencing in assertions.
Direct dereference of
resp.Answer/resp.ReasonContentcan panic and hide the real failure cause. A nil check witht.Fatalffirst makes failures clearer.Also applies to: 119-124
🤖 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/longcat_test.go` around lines 82 - 87, The test dereferences response pointers resp.Answer and resp.ReasonContent directly which can panic; update the assertions in the test functions (the blocks checking resp.Answer and resp.ReasonContent) to first check for nil and call t.Fatalf with a clear message if nil, then perform the string equality checks (use t.Errorf/t.Fatalf as appropriate) after safe dereference; apply the same nil-guard and subsequent assertions to the other similar block that checks those fields.
206-215: ⚡ Quick winAdd request-shape assertions to streaming test servers.
These stream tests don’t currently assert endpoint path or
Authorizationheader, so a regression in stream request wiring could pass unnoticed. Reusing/extendingnewLongCatServerfor SSE cases would close that gap.Also applies to: 251-260, 318-320
🤖 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/longcat_test.go` around lines 206 - 215, TestLongCatStreamHappyPath's test server doesn't assert request path or Authorization header; update the test to reuse or extend newLongCatServer for SSE cases (or add the same request-shape checks) so the handler asserts r.URL.Path and r.Header.Get("Authorization") before writing the SSE payload, and apply the same change to the other streaming tests referenced (around the blocks at lines 251-260 and 318-320) to ensure stream request wiring is validated.
24-26: ⚡ Quick winRelax exact
Content-Typeassertion in the test helper.
application/json; charset=utf-8is still valid JSON content type, so strict equality here can create false-negative test failures unrelated to behavior.Proposed tweak
- if got := r.Header.Get("Content-Type"); got != "application/json" { - t.Errorf("expected Content-Type=application/json, got %q", got) + if got := r.Header.Get("Content-Type"); !strings.HasPrefix(got, "application/json") { + t.Errorf("expected Content-Type starting with application/json, got %q", got) 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/longcat_test.go` around lines 24 - 26, The test currently asserts exact equality on r.Header.Get("Content-Type") which fails when servers return "application/json; charset=utf-8"; update the assertion in longcat_test.go to accept any valid JSON content-type by checking the media type instead of strict equality—either use strings.HasPrefix(got, "application/json") or call mime.ParseMediaType on the value returned by r.Header.Get("Content-Type") and assert the parsed media type equals "application/json"; adjust imports accordingly and keep the same error message style when the assertion fails.
🤖 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/longcat.go`:
- Around line 418-424: ListModels currently only checks ApiKey but should also
validate apiConfig.Region so a misconfigured region is caught early; in
LongCatModel.ListModels add a guard that verifies apiConfig.Region is non-empty
and that the chosen region maps to a configured base URL (the same
region-to-baseURL lookup used by other LongCatModel methods or the region map
used elsewhere), and return a descriptive error (e.g., "region not configured"
or similar) if the region is missing or has no base URL before returning
longcatKnownModels.
- Around line 353-360: The code currently ignores malformed JSON frames and any
upstream error payloads by continuing when json.Unmarshal into event fails or
when event["choices"] is missing; instead, update the SSE frame handling around
json.Unmarshal, event and choices to surface these failures: when json.Unmarshal
fails, return or propagate the parse error (do not continue silently); after
successful unmarshal, check for an "error" key (e.g., event["error"]) and if
present convert it into a returned/propagated error or a sent error event rather
than falling through; only treat frames as normal when choices exists and is
non-empty. Use the existing symbols json.Unmarshal, event, and choices to locate
and change the logic so malformed frames and upstream error payloads are
reported to callers instead of being skipped.
---
Nitpick comments:
In `@internal/entity/models/longcat_test.go`:
- Around line 82-87: The test dereferences response pointers resp.Answer and
resp.ReasonContent directly which can panic; update the assertions in the test
functions (the blocks checking resp.Answer and resp.ReasonContent) to first
check for nil and call t.Fatalf with a clear message if nil, then perform the
string equality checks (use t.Errorf/t.Fatalf as appropriate) after safe
dereference; apply the same nil-guard and subsequent assertions to the other
similar block that checks those fields.
- Around line 206-215: TestLongCatStreamHappyPath's test server doesn't assert
request path or Authorization header; update the test to reuse or extend
newLongCatServer for SSE cases (or add the same request-shape checks) so the
handler asserts r.URL.Path and r.Header.Get("Authorization") before writing the
SSE payload, and apply the same change to the other streaming tests referenced
(around the blocks at lines 251-260 and 318-320) to ensure stream request wiring
is validated.
- Around line 24-26: The test currently asserts exact equality on
r.Header.Get("Content-Type") which fails when servers return "application/json;
charset=utf-8"; update the assertion in longcat_test.go to accept any valid JSON
content-type by checking the media type instead of strict equality—either use
strings.HasPrefix(got, "application/json") or call mime.ParseMediaType on the
value returned by r.Header.Get("Content-Type") and assert the parsed media type
equals "application/json"; adjust imports accordingly and keep the same error
message style when the assertion fails.
🪄 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: 0fd03a72-fcbf-4415-9de7-ea8f0f889908
📒 Files selected for processing (3)
conf/models/longcat.jsoninternal/entity/models/longcat.gointernal/entity/models/longcat_test.go
### What problem does this PR solve? The LocalAI Go driver landed in #14809 and Embed landed in #14811. `Rerank` was left as a stub that returns `"not implemented"`. This PR fills the gap. LocalAI exposes a public rerank endpoint at `<tenant-url>/v1/rerank` with a Cohere-shaped request and response (`{model, query, documents, top_n}` → `{results: [{index, relevance_score}]}`). The Python side has had `LocalAIRerank` in `rag/llm/rerank_model.py` for a long time. Until this PR, a tenant who wanted to use LocalAI for reranking in the Go layer got `"not implemented"`. ### What this PR includes - `conf/models/localai.json`: add `"rerank": "rerank"` under `url_suffix` so the driver can build the URL from config. This matches the `URLSuffix.Rerank` field already used by aliyun and siliconflow. - `internal/entity/models/localai.go`: replace the `Rerank` stub with a real implementation that POSTs to `/v1/rerank`. Adds local request/response types `localAIRerankRequest` and `localAIRerankResponse`. No factory change. No interface change. ### How the implementation works - Validate the model name and resolve the tenant-supplied base URL with the existing `resolveBaseURL` helper. - Wrap the request with `context.WithTimeout(nonStreamCallTimeout)` so the call has a clear deadline. Same pattern `ChatWithMessages`, `ListModels`, and `Embed` already use in this file. - Only set the `Authorization` header when a non-empty API key was supplied. LocalAI accepts an empty key by default, so this preserves the optional-auth contract. - Default `top_n` to `len(documents)` when `rerankConfig.TopN == 0`, matching the existing Aliyun and SiliconFlow rerank implementations. - Validate every `results[].index` against `len(documents)`. If the upstream returns an out-of-range index, fail clearly instead of silently writing past the slice. - An empty `documents` slice returns `&RerankResponse{}` with no HTTP call. - Non-200 responses propagate the upstream status line and body. ### Note on stacking This PR builds on #14809 (LocalAI driver) and #14811 (LocalAI Embed). Until both merge, this PR's diff on GitHub will include all three commits. After #14809 and #14811 land on `main`, GitHub will auto-reduce this PR to only the `Rerank` changes (one commit, ~99 line diff in `localai.go` plus 1 line in `localai.json`). ### Type of change - [x] New Feature (non-breaking change which adds functionality) ### How was this tested? - `go build ./internal/entity/models/...` returns exit 0 on go 1.25 (the `go.mod` minimum). - The full method set on `LocalAIModel` still matches the `ModelDriver` interface. - Pattern parity with the existing Aliyun Rerank (`internal/entity/models/aliyun.go`) and SiliconFlow Rerank (`internal/entity/models/siliconflow.go`) implementations. Closes #14812 Depends on #14809, #14811 Tracking: #14736 Co-authored-by: Jin Hai <[email protected]>
Cross-applying the lessons from the merged infiniflow#14790 sample driver and from the maintainer's reviews on infiniflow#14809 and infiniflow#14850: conf/models/voyage.json: - name: "VoyageAI" -> "Voyage" (the maintainer's "remove AI suffix" guidance from infiniflow#14850). - baseURL: "https://api.voyageai.com/v1" -> "https://api.voyageai.com" (bare URL; version moves into the suffix), matching the pattern used on Novita and the Cohere sample (api.cohere.com + v2/chat, v1/models). - url_suffix.embedding: "embeddings" -> "v1/embeddings". - url_suffix.rerank: "rerank" -> "v1/rerank". internal/entity/models/voyage.go: - Embed: forward EmbeddingConfig.Dimension as Voyage's documented `output_dimension` body field. This is the singular spelling per https://docs.voyageai.com/reference/embeddings-api ; Voyage rejects unknown fields with HTTP 400 (live-verified — sending "dimensions" returns "Argument 'dimensions' is not supported by our API"), so matching the docs spelling exactly is load-bearing. Live test against voyage-3.5 with output_dimension=256 trims the vector from the default 1024 to 256. internal/entity/models/voyage_test.go: - New: TestVoyageEmbedPropagatesOutputDimension pins the wire field name and guards against re-adding "dimensions" / "dimension". - New: TestVoyageEmbedOmitsOutputDimensionWhenUnset — Voyage 400s on output_dimension: 0, so the key must be absent when Dimension is unset rather than sent as zero. - All existing path-asserting tests updated to expect the new versioned suffixes (/v1/embeddings, /v1/rerank).
Cross-applying the maintainer guidance from infiniflow#14809 (review): "There is no need to implement the interface that is not officially given." The Voyage AI docs at https://docs.voyageai.com publish embeddings and rerank endpoints only. There is no /v1/models surface (404 live- confirmed) and no documented /health endpoint. ListModels and CheckConnection were therefore inventing behaviour the upstream does not expose: - ListModels was returning a hardcoded voyageKnownModels slice that duplicated the shipped conf/models/voyage.json catalog. - CheckConnection was burning a one-input embed call against voyage-3.5 per probe, which costs tenant quota and only retroactively validates the integration. Both methods now return the standard `"<name>, no such method"` sentinel, matching the convention every merged driver in this package uses (including the Cohere sample in infiniflow#14790). The shipped catalog in conf/models/voyage.json is unchanged and remains the source of truth for which Voyage models RAGFlow knows about. Dropped the corresponding sentinel-pinning tests; they were the lowest-signal entries in the suite (asserting a constant string return from an unimplemented method). 16 tests covering the actual Embed and Rerank behaviour remain and pass.
Per infiniflow#14809 (review): Actionable (longcat.go): - ChatStreamlyWithSender no longer silently swallows malformed SSE frames or upstream {"error": ...} payloads. An invalid JSON event now returns "longcat: invalid SSE event: ..."; an upstream error frame returns "longcat: upstream stream error: ...". Previously both cases fell through to the choices-missing branch and the caller only ever saw the generic "stream ended before [DONE]" truncation error. - ListModels validates the region maps to a configured base URL before returning the static catalog. Without this, a tenant selecting an unconfigured region would see ListModels succeed and only fail later on the first chat/embed call. Nitpicks (longcat_test.go): - Content-Type assertion in newLongCatServer now accepts any prefix of "application/json" (e.g. "application/json; charset=utf-8") rather than strict equality. - Non-stream chat tests nil-guard resp.Answer / resp.ReasonContent with t.Fatalf before dereferencing so a regression doesn't crash the test runner. - Streaming tests now use a new newLongCatSSEServer helper that asserts POST + path + Authorization + Content-Type the same way newLongCatServer does for the JSON path. Three streaming tests (happy-path, reasoning_content, truncated) were converted. New tests pinning the new behaviour: TestLongCatStreamRejectsMalformedFrame, TestLongCatStreamSurfacesUpstreamError, TestLongCatListModelsRejectsUnknownRegion.
Per infiniflow#14809 (review): conf/models/longcat.json — move `openai` from base URL into the chat suffix. The platform docs at https://longcat.chat/platform/docs/APIDocs.html#endpoints publish the base host as `https://api.longcat.chat` and the full chat URL as `https://api.longcat.chat/openai/v1/chat/completions`, so the `/openai` prefix belongs in `url_suffix.chat`, not in `url.default`. Matches the same split the maintainer asked for on Novita (infiniflow#14850). internal/entity/models/longcat.go: - Drop the hardcoded `longcatKnownModels` catalog and the `longcatPingModel` constant. Maintainer flagged "no hard code" and noted "there is no need to implement the interface that is not officially given." The LongCat platform does not publish a /models endpoint, so synthesizing a catalog in the driver is wrong; the shipped catalog in conf/models/longcat.json is sufficient. - ListModels returns the documented `"<name>, no such method"` sentinel (the convention every other driver in this package uses for unsupported interface methods, including the merged Cohere sample in infiniflow#14790). - CheckConnection also returns the sentinel. The previous chat-ping implementation would have burned a real completion against a tenant's quota; with no documented /models or /health endpoint there is no cheap way to verify the key, so pretending is worse than declining. internal/entity/models/longcat_test.go: - Update path expectations: `/v1/chat/completions` -> `/openai/v1/chat/completions` in the test helper and in every test using newLongCatServer / newLongCatSSEServer. - Replace TestLongCatListModelsReturnsKnownCatalog, TestLongCatListModelsRequiresAPIKey, TestLongCatListModelsRejectsUnknownRegion, TestLongCatCheckConnectionChatPings, and TestLongCatCheckConnectionPropagatesAuthError with two new tests pinning the "no such method" sentinel for both stubs. Live re-verified end-to-end against api.longcat.chat: chat reply "Pong!" via the new URL split.
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.
Add a Go driver for FuturMix (https://futurmix.ai/docs), one of the unchecked providers on the umbrella tracking issue infiniflow#14736. FuturMix is documented as an "OpenAI-compatible API" aggregator over Claude / GPT / Gemini / DeepSeek (~22 models per their /models page). This driver implements only ChatWithMessages and ChatStreamlyWithSender against POST /v1/chat/completions — the OpenAI-compatible surface FuturMix's marketing meta calls out. The single-page-app docs at https://futurmix.ai/docs are client-rendered and do not publish OpenAPI-style schema for embeddings, rerank, audio, OCR, models-list, or balance, so per the maintainer's guidance on PR infiniflow#14809 review #4277917390 ("there is no need to implement the interface that is not officially given") every other ModelDriver method returns the standard `"futurmix, no such method"` sentinel. Two other /v1 endpoints are referenced in the FuturMix admin UI bundle but deliberately not wired up here: /v1/messages — Anthropic Messages format; needs separate request/response handling than the ChatWithMessages interface currently models. /v1/responses — OpenAI Responses API; same caveat. URL split follows the same convention used on Novita / LongCat / n1n.ai: bare base host in `url.default`, every path lives in a `url_suffix.*` field. url.default = "https://futurmix.ai" url_suffix.chat = "v1/chat/completions" Shipped catalog in conf/models/futurmix.json is a small representative subset (gpt-4o, gpt-4o-mini, claude-3-5-sonnet, claude-3-5-haiku, gemini-1.5-pro, deepseek-v3). The full catalog FuturMix routes is not enumerated in the public docs; tenants should consult https://futurmix.ai/models for the live list and set the model name explicitly in their provider config. No live testing — FuturMix gates API key issuance behind an access request flow, and the user instructed this implementation be docs-only. The driver is structurally identical to the OpenAI / CometAPI / n1n.ai drivers, all of which use the same wire shape.
### What problem does this PR solve? Add a Go driver for LongCat (Meituan, https://longcat.chat), one of the unchecked providers on the umbrella tracking issue infiniflow#14736. LongCat exposes an OpenAI-compatible REST API at `https://api.longcat.chat/openai/v1` with three public chat models including `LongCat-Flash-Thinking`, a reasoning model that returns chain-of-thought in `reasoning_content` (OpenAI o-series shape). Until this PR, a tenant who configured `longcat` 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 - New `internal/entity/models/longcat.go` with a `LongCatModel` implementing the `ModelDriver` interface. - New `conf/models/longcat.json` with the 3 public chat models (Flash-Chat, Flash-Lite, Flash-Thinking) and `url_suffix` for `chat` and `models`. - `factory.go`: route `"longcat"` to `NewLongCatModel`. Method coverage: - `ChatWithMessages`: `POST /openai/v1/chat/completions`, non-streaming - `ChatStreamlyWithSender`: SSE stream against the same endpoint - `ListModels` / `CheckConnection`: `GET /openai/v1/models` - **Reasoning extraction**: `message.reasoning_content` (non-stream) and `delta.reasoning_content` (stream) flow into `ChatResponse.ReasonContent` / the sender's second arg. Matches the OpenAI o-series convention also used by kimi-k2.6 and DeepSeek-R1. - **`reasoning_effort` propagation**: `ChatConfig.Effort` → request body `reasoning_effort` (LongCat-Flash-Thinking honors it; non-reasoning models ignore it). - `Embed` / `Rerank` / `Balance` / `TranscribeAudio` / `AudioSpeech` / `OCRFile` return `"no such method"` (LongCat does not expose any of these surfaces). No interface change. No new dependencies. ### How was this tested? **21 unit tests** in `internal/entity/models/longcat_test.go` — all pass: ``` $ go test -vet=off -run TestLongCat -count=1 -v ./internal/entity/models/... === RUN TestLongCatName --- PASS: TestLongCatName (0.00s) === RUN TestLongCatChatHappyPath --- PASS: TestLongCatChatHappyPath (0.00s) === RUN TestLongCatChatExtractsReasoningContent --- PASS: TestLongCatChatExtractsReasoningContent (0.00s) === RUN TestLongCatChatPropagatesReasoningEffort --- PASS: TestLongCatChatPropagatesReasoningEffort (0.00s) === RUN TestLongCatChatOmitsReasoningEffortWhenUnset --- PASS: TestLongCatChatOmitsReasoningEffortWhenUnset (0.00s) === RUN TestLongCatChatRequiresAPIKey --- PASS: TestLongCatChatRequiresAPIKey (0.00s) === RUN TestLongCatChatRequiresMessages --- PASS: TestLongCatChatRequiresMessages (0.00s) === RUN TestLongCatChatRejectsHTTPError --- PASS: TestLongCatChatRejectsHTTPError (0.00s) === RUN TestLongCatStreamHappyPath --- PASS: TestLongCatStreamHappyPath (0.00s) === RUN TestLongCatStreamExtractsReasoningContent --- PASS: TestLongCatStreamExtractsReasoningContent (0.00s) === RUN TestLongCatStreamRejectsExplicitFalse --- PASS: TestLongCatStreamRejectsExplicitFalse (0.00s) === RUN TestLongCatStreamRequiresSender --- PASS: TestLongCatStreamRequiresSender (0.00s) === RUN TestLongCatStreamFailsWithoutTerminal --- PASS: TestLongCatStreamFailsWithoutTerminal (0.00s) === RUN TestLongCatListModelsHappyPath --- PASS: TestLongCatListModelsHappyPath (0.00s) === RUN TestLongCatListModelsRequiresAPIKey --- PASS: TestLongCatListModelsRequiresAPIKey (0.00s) === RUN TestLongCatCheckConnectionDelegatesToListModels --- PASS: TestLongCatCheckConnectionDelegatesToListModels (0.00s) === RUN TestLongCatEmbedReturnsNoSuchMethod --- PASS: TestLongCatEmbedReturnsNoSuchMethod (0.00s) === RUN TestLongCatRerankReturnsNoSuchMethod --- PASS: TestLongCatRerankReturnsNoSuchMethod (0.00s) === RUN TestLongCatBalanceReturnsNoSuchMethod --- PASS: TestLongCatBalanceReturnsNoSuchMethod (0.00s) === RUN TestLongCatAudioOCRReturnNoSuchMethod --- PASS: TestLongCatAudioOCRReturnNoSuchMethod (0.00s) PASS ok ragflow/internal/entity/models 0.020s ``` `go build ./internal/entity/models/...` exits 0 on go 1.25. **Live integration test** against `api.longcat.chat`: ``` === RUN TestLongCatLiveSmoke [OK] Name() = "longcat" [OK] CheckConnection [OK] ListModels: 5 models -> [LongCat-Flash-Lite LongCat-Flash-Chat LongCat-Flash-Thinking-2601 LongCat-Flash-Omni-2603 LongCat-2.0-Preview] [OK] Chat (Flash-Chat) answer="Got it! Let me know if you" reason="" [OK] Chat (Flash-Thinking) answer len=443 head="To find 15 % of 80, follow these steps:\n\n1. **Convert the percentage to a frac..." ReasonContent len=557 head="The user asks: \"15% of 80?\" They want step by step reasoning and final answer in \\boxed{}. So we need to compute 15% of ..." [OK] Stream content: 78 chunks, 351 chars [OK] Stream reasoning: 107 chunks, 537 chars [OK] Balance returns longcat, no such method [OK] Embed returns longcat, no such method [OK] Rerank returns longcat, no such method LONGCAT LIVE SMOKE PASSED --- PASS: TestLongCatLiveSmoke (31.01s) ``` What the live run proves on the wire: - Auth header (`Bearer <key>`) is accepted by `api.longcat.chat`. - `/openai/v1/models` parser handles the real 5-model response (note: live API returns versioned aliases `LongCat-Flash-Thinking-2601`, `LongCat-Flash-Omni-2603`, `LongCat-2.0-Preview` plus the un-versioned `LongCat-Flash-Chat` and `LongCat-Flash-Lite`). - Non-stream chat against `LongCat-Flash-Chat`: visible answer parses correctly, `ReasonContent` correctly empty. - Non-stream chat against `LongCat-Flash-Thinking`: 443-char answer flows into `Answer`, 557-char chain-of-thought flows into `ReasonContent` via the new `message.reasoning_content` extraction. - Streaming chat against `LongCat-Flash-Thinking`: 107 reasoning chunks (537 chars) reach the sender's second arg via `delta.reasoning_content`; 78 content chunks (351 chars) reach the first arg. Before this code, the reasoning chunks would have been silently dropped. - All sentinel methods (Balance, Embed, Rerank, audio/OCR) return the documented `"no such method"` strings. ### Note on PR history This branch was previously named for LocalAI work which is now consolidated into PR infiniflow#14813. The branch was reset to `upstream/main` and rebuilt for LongCat. The diff against `main` is a clean +969 lines across 4 files. ### Type of change - [x] New Feature (non-breaking change which adds functionality) Tracking: infiniflow#14736 --------- Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? The LocalAI Go driver landed in infiniflow#14809 and Embed landed in infiniflow#14811. `Rerank` was left as a stub that returns `"not implemented"`. This PR fills the gap. LocalAI exposes a public rerank endpoint at `<tenant-url>/v1/rerank` with a Cohere-shaped request and response (`{model, query, documents, top_n}` → `{results: [{index, relevance_score}]}`). The Python side has had `LocalAIRerank` in `rag/llm/rerank_model.py` for a long time. Until this PR, a tenant who wanted to use LocalAI for reranking in the Go layer got `"not implemented"`. ### What this PR includes - `conf/models/localai.json`: add `"rerank": "rerank"` under `url_suffix` so the driver can build the URL from config. This matches the `URLSuffix.Rerank` field already used by aliyun and siliconflow. - `internal/entity/models/localai.go`: replace the `Rerank` stub with a real implementation that POSTs to `/v1/rerank`. Adds local request/response types `localAIRerankRequest` and `localAIRerankResponse`. No factory change. No interface change. ### How the implementation works - Validate the model name and resolve the tenant-supplied base URL with the existing `resolveBaseURL` helper. - Wrap the request with `context.WithTimeout(nonStreamCallTimeout)` so the call has a clear deadline. Same pattern `ChatWithMessages`, `ListModels`, and `Embed` already use in this file. - Only set the `Authorization` header when a non-empty API key was supplied. LocalAI accepts an empty key by default, so this preserves the optional-auth contract. - Default `top_n` to `len(documents)` when `rerankConfig.TopN == 0`, matching the existing Aliyun and SiliconFlow rerank implementations. - Validate every `results[].index` against `len(documents)`. If the upstream returns an out-of-range index, fail clearly instead of silently writing past the slice. - An empty `documents` slice returns `&RerankResponse{}` with no HTTP call. - Non-200 responses propagate the upstream status line and body. ### Note on stacking This PR builds on infiniflow#14809 (LocalAI driver) and infiniflow#14811 (LocalAI Embed). Until both merge, this PR's diff on GitHub will include all three commits. After infiniflow#14809 and infiniflow#14811 land on `main`, GitHub will auto-reduce this PR to only the `Rerank` changes (one commit, ~99 line diff in `localai.go` plus 1 line in `localai.json`). ### Type of change - [x] New Feature (non-breaking change which adds functionality) ### How was this tested? - `go build ./internal/entity/models/...` returns exit 0 on go 1.25 (the `go.mod` minimum). - The full method set on `LocalAIModel` still matches the `ModelDriver` interface. - Pattern parity with the existing Aliyun Rerank (`internal/entity/models/aliyun.go`) and SiliconFlow Rerank (`internal/entity/models/siliconflow.go`) implementations. Closes infiniflow#14812 Depends on infiniflow#14809, infiniflow#14811 Tracking: infiniflow#14736 Co-authored-by: Jin Hai <[email protected]>
What problem does this PR solve?
Add a Go driver for LongCat (Meituan, https://longcat.chat), one of the unchecked providers on the umbrella tracking issue #14736. LongCat exposes an OpenAI-compatible REST API at
https://api.longcat.chat/openai/v1with three public chat models includingLongCat-Flash-Thinking, a reasoning model that returns chain-of-thought inreasoning_content(OpenAI o-series shape).Until this PR, a tenant who configured
longcatas 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/longcat.gowith aLongCatModelimplementing theModelDriverinterface.conf/models/longcat.jsonwith the 3 public chat models (Flash-Chat, Flash-Lite, Flash-Thinking) andurl_suffixforchatandmodels.factory.go: route"longcat"toNewLongCatModel.Method coverage:
ChatWithMessages:POST /openai/v1/chat/completions, non-streamingChatStreamlyWithSender: SSE stream against the same endpointListModels/CheckConnection:GET /openai/v1/modelsmessage.reasoning_content(non-stream) anddelta.reasoning_content(stream) flow intoChatResponse.ReasonContent/ the sender's second arg. Matches the OpenAI o-series convention also used by kimi-k2.6 and DeepSeek-R1.reasoning_effortpropagation:ChatConfig.Effort→ request bodyreasoning_effort(LongCat-Flash-Thinking honors it; non-reasoning models ignore it).Embed/Rerank/Balance/TranscribeAudio/AudioSpeech/OCRFilereturn"no such method"(LongCat does not expose any of these surfaces).No interface change. No new dependencies.
How was this tested?
21 unit tests in
internal/entity/models/longcat_test.go— all pass:go build ./internal/entity/models/...exits 0 on go 1.25.Live integration test against
api.longcat.chat:What the live run proves on the wire:
Bearer <key>) is accepted byapi.longcat.chat./openai/v1/modelsparser handles the real 5-model response (note: live API returns versioned aliasesLongCat-Flash-Thinking-2601,LongCat-Flash-Omni-2603,LongCat-2.0-Previewplus the un-versionedLongCat-Flash-ChatandLongCat-Flash-Lite).LongCat-Flash-Chat: visible answer parses correctly,ReasonContentcorrectly empty.LongCat-Flash-Thinking: 443-char answer flows intoAnswer, 557-char chain-of-thought flows intoReasonContentvia the newmessage.reasoning_contentextraction.LongCat-Flash-Thinking: 107 reasoning chunks (537 chars) reach the sender's second arg viadelta.reasoning_content; 78 content chunks (351 chars) reach the first arg. Before this code, the reasoning chunks would have been silently dropped."no such method"strings.Note on PR history
This branch was previously named for LocalAI work which is now consolidated into PR #14813. The branch was reset to
upstream/mainand rebuilt for LongCat. The diff againstmainis a clean +969 lines across 4 files.Type of change
Tracking: #14736