Skip to content

Go: implement provider: LongCat - #14809

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
tmimmanuel:go/localai-driver
May 13, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
tmimmanuel:go/localai-driver

Conversation

@tmimmanuel

@tmimmanuel tmimmanuel commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

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/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 #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

  • New Feature (non-breaking change which adds functionality)

Tracking: #14736

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

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

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

Changes

LongCat Model Provider Integration

Layer / File(s) Summary
Factory Registration
internal/entity/models/factory.go
Registers provider name longcat in ModelFactory.CreateModelDriver to return NewLongCatModel.
Provider Manifest
conf/models/longcat.json
Adds LongCat provider manifest with default base URL, chat url suffix, class: "longcat", and five chat model entries (each max_tokens: 131072).
LongCatModel Type & Constructor
internal/entity/models/longcat.go (lines 1–113)
Defines LongCatModel, static catalog and ping model constants, and constructor that clones/tunes HTTP transport; implements NewInstance, Name, and region-to-base-URL resolution that errors when misconfigured.
Chat Completion (non-streaming)
internal/entity/models/longcat.go (lines 115–240)
ChatWithMessages validates API key/messages, sends OpenAI-shaped JSON with stream=false, forwards only documented fields, enforces timeout and HTTP 200, parses response and maps reasoning_content into ChatResponse.ReasonContent.
Chat Completion (SSE streaming)
internal/entity/models/longcat.go (lines 242–410)
ChatStreamlyWithSender validates inputs and API key, requires stream=true, scans data: SSE events with increased buffer, unmarshals events, emits reasoning_content before content via sender callback, and requires [DONE] or finish_reason to terminate.
ListModels, CheckConnection & Unsupported Stubs
internal/entity/models/longcat.go (lines 412–480)
ListModels returns a static model list (API key required); CheckConnection sends a 1-token chat ping; unsupported endpoints return consistent “no such method” errors.
Tests: helpers & non-streaming
internal/entity/models/longcat_test.go (lines 1–168)
Adds httptest server helper, constructor helper, Name() test, non-streaming chat tests (happy path, reasoning extraction, undocumented-field omission, API key/messages validation, HTTP error propagation).
Tests: streaming & guards
internal/entity/models/longcat_test.go (lines 170–333)
Adds streaming SSE tests (happy path, reasoning extraction, stream=false rejection, sender requirement, terminal-signal enforcement).
Tests: models/check & unsupported
internal/entity/models/longcat_test.go (lines 334–458)
Tests ListModels returns pinned catalog and requires API key; CheckConnection pings chat endpoint and surfaces auth errors; unsupported-method tests assert “no such method” errors.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

💞 feature

Suggested reviewers

  • Haruko386

Poem

🐰 I nibble bytes where long cats stream,

reasoning whispers, chunks that gleam.
I stitch the answers, soft and spry,
SSE tails that flutter by.
Hooray — new models scamper nigh!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.86% 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 PR title clearly and concisely summarizes the main change: implementing a Go provider driver for LongCat.
Description check ✅ Passed The PR description fully addresses the template, clearly explaining the problem (adding a LongCat driver for an unchecked provider), the type of change (New Feature), and implementation details including comprehensive testing evidence.
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.

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.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8738cfe8-5f82-4dd5-84d6-be9900536917

📥 Commits

Reviewing files that changed from the base of the PR and between 7920a50 and 467f62b.

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

Comment thread internal/entity/models/localai.go Resolved
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 12, 2026

@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 @tmimmanuel, ReasonContent should not be empty.
plz fix this.

Comment thread internal/entity/models/localai.go Resolved
Comment thread internal/entity/models/localai.go Resolved
@JinHai-CN

Copy link
Copy Markdown
Member

Duplicated with #14811. I will close it. Please feel free to re-open it, if i am wrong.

@JinHai-CN JinHai-CN closed this May 12, 2026
@JinHai-CN JinHai-CN reopened this May 12, 2026
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
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
@tmimmanuel

tmimmanuel commented May 12, 2026 •

Copy link
Copy Markdown
Contributor Author

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

@tmimmanuel tmimmanuel closed this May 12, 2026
@tmimmanuel
tmimmanuel force-pushed the go/localai-driver branch from d656064 to 5e46457 Compare May 12, 2026 16:38
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels May 12, 2026
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.
@tmimmanuel tmimmanuel changed the title Go: implement provider: LocalAI Go: implement provider: LongCat May 12, 2026
@tmimmanuel tmimmanuel reopened this May 12, 2026
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels May 12, 2026

@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 @tmimmanuel, thank you for your contribution
I hope you would read API reference more carefully before you test or submit your code

Comment thread conf/models/longcat.json Resolved
Comment thread conf/models/longcat.json Resolved
Comment thread conf/models/longcat.json Resolved
Comment thread conf/models/longcat.json Resolved
Comment thread internal/entity/models/longcat.go Resolved
@tmimmanuel

Copy link
Copy Markdown
Contributor Author

Thanks @Haruko386
I will look at the api docs more carefully and fix the issues.

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.
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels May 13, 2026
@tmimmanuel

Copy link
Copy Markdown
Contributor Author

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

Surface Docs Previous code Now
Base URL https://api.longcat.chat/openai …/openai/v1 …/openai
Chat endpoint POST /v1/chat/completions /chat/completions (relative to wrong base, but resolved to the same URL by luck) v1/chat/completions suffix
Documented body fields model, messages, stream, max_tokens, temperature, top_p also sent stop, reasoning_effort only the documented six
/models not listed GET /models (worked, but undocumented) hardcoded shipped catalog
Model catalog LongCat-Flash-Chat, -Lite, -Thinking-2601, -Omni-2603, 2.0-Preview unversioned LongCat-Flash-Thinking, no Omni / 2.0 aligned with platform/docs/Models.html

Why hardcode ListModels instead of calling /models?
I did verify live that GET /openai/v1/models returns the same five model ids — but since it isn't in the docs, the maintainer (you) can pull it at any time. Shipping the catalog is the safer contract.

CheckConnection now does a chat ping. A 1-token LongCat-Flash-Lite completion is the cheapest documented call that actually validates the key against the documented surface; /models couldn't.

On the previous "live test passed" report — I was hitting the undocumented /models endpoint and the undocumented stop/reasoning_effort fields. Both returned 200, so the green check was real, but it was green for the wrong reasons (LongCat silently accepts unknown body fields without rejecting them). That's exactly the failure mode you flagged. Apologies for that.

Live re-test against api.longcat.chat on 02923da:

  • Non-stream chat (LongCat-Flash-Chat) → pong ✓
  • 1-token ping (LongCat-Flash-Lite) → finish_reason: length, valid response ✓
  • Thinking (LongCat-Flash-Thinking-2601) → content + reasoning_content both present ✓
  • Stream → data: SSE chunks with finish_reason + [DONE] ✓
  • POST /v1/embeddings → 404 (driver already returns "no such method") ✓

A new test (TestLongCatChatDropsUndocumentedFields) pins this so anyone re-adding stop/reasoning_effort/tools/etc. has to delete the guard first.

For ReasonContent not being empty on the prior review — the new commit also keeps the message.reasoning_content + delta.reasoning_content extraction (verified live above), and a fixture in TestLongCatChatExtractsReasoningContent / TestLongCatStreamExtractsReasoningContent covers it.

@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

🧹 Nitpick comments (3)
internal/entity/models/longcat_test.go (3)

82-87: ⚡ Quick win

Guard response pointers before dereferencing in assertions.

Direct dereference of resp.Answer/resp.ReasonContent can panic and hide the real failure cause. A nil check with t.Fatalf first 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 win

Add request-shape assertions to streaming test servers.

These stream tests don’t currently assert endpoint path or Authorization header, so a regression in stream request wiring could pass unnoticed. Reusing/extending newLongCatServer for 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 win

Relax exact Content-Type assertion in the test helper.

application/json; charset=utf-8 is 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

📥 Commits

Reviewing files that changed from the base of the PR and between c93424a and 02923da.

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

Comment thread internal/entity/models/longcat.go Resolved
Comment thread internal/entity/models/longcat.go Resolved
JinHai-CN added a commit that referenced this pull request May 13, 2026
### 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]>
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
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).
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
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.
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
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.
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 14, 2026
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.
sxxtony added a commit to sxxtony/ragflow that referenced this pull request May 20, 2026
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.
sxxtony added a commit to sxxtony/ragflow that referenced this pull request May 20, 2026
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.
@coderabbitai coderabbitai Bot mentioned this pull request May 21, 2026
6 tasks
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### 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]>
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants