Skip to content

Go: implement provider: xAI - #14550

Merged
JinHai-CN merged 6 commits into
infiniflow:mainfrom
davidv399:feat/go-xai-provider
May 6, 2026
Merged

JinHai-CN merged 6 commits into
infiniflow:mainfrom
davidv399:feat/go-xai-provider

Conversation

@davidv399

@davidv399 davidv399 commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Closes #14552

What problem does this PR solve?

Add a Go driver for xAI (Grok models).

The config file conf/models/xai.json has been in the repo since the early Go provider work, but internal/entity/models/factory.go had no case for "xai". So any xAI request fell through to the dummy driver
and never reached the API. This PR adds the missing driver and wires it up.

What this PR includes

  • New file internal/entity/models/xai.go with an XAIModel that implements the ModelDriver interface.
  • factory.go: route the "xai" provider name to NewXAIModel.

How the driver works

  • xAI exposes an OpenAI-compatible API at https://api.x.ai/v1.
  • ChatWithMessages and ChatStreamlyWithSender post to /chat/completions in the same shape the moonshot and deepseek drivers use.
  • ListModels and CheckConnection call /models to confirm the API key works and to list available model ids.
  • reasoning_content is passed through for grok-3-mini and other xAI reasoning models, both in the non-stream and stream paths.
  • Encode, Rerank, and Balance are not part of the public xAI API at the moment, so they return a clear "not implemented" or "no such method" error.

Type of change

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

How was this tested?

Add a Go driver for xAI (Grok models). The xai.json config has been
in conf/models since the early Go provider work, but factory.go had
no case for it, so xAI requests fell through to the dummy driver
and never reached the API.

The new driver follows the same pattern used by the moonshot and
deepseek drivers and talks to the OpenAI-compatible endpoint at
https://api.x.ai/v1. Key points:

- ChatWithMessages and ChatStreamlyWithSender hit /chat/completions.
- ListModels and CheckConnection use /models.
- reasoning_content is passed through for grok-3-mini and other xAI
  reasoning models, both in the non-stream and stream paths.
- Encode, Rerank, and Balance are not exposed by xAI yet, so they
  return a clear "not implemented" or "no such method" error.

factory.go now wires "xai" to NewXAIModel.
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 30, 2026
@coderabbitai

coderabbitai Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

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 an xAI provider to the model factory and introduces a new XAIModel driver implementing non-streaming and SSE-based streaming chat, model listing and connection checks, plus explicit unimplemented stubs for encode/balance/rerank.

Changes

Cohort / File(s) Summary
Factory Provider Routing
internal/entity/models/factory.go
Added "xai" branch in CreateModelDriver to return NewXAIModel instead of the dummy driver.
XAI Model Driver Implementation
internal/entity/models/xai.go
New exported XAIModel and constructor. Implements ChatWithMessages (JSON POST, 120s timeout, parse choices[0].message.content and reasoning_content), ChatStreamlyWithSender (SSE streaming POST, increased buffer, parse data: events, emit delta.content and delta.reasoning_content tokens via callback, handle [DONE] and finish_reason), ListModels, CheckConnection, and stubs for Encode, Balance, Rerank. Uses region-aware base URLs and a cloned HTTP transport.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant XAI as XAIModel
    participant API as xAI_API
    participant Parser as Parser

    Client->>XAI: ChatWithMessages(modelName, messages, apiConfig)
    XAI->>API: POST /chat/completions (JSON payload, stream=false)
    API->>XAI: HTTP 200 JSON response
    XAI->>Parser: extract choices[0].message.content + reasoning_content
    Parser-->>XAI: content, reasoning_content
    XAI->>Client: return ChatResponse (content + reasoning_content)
Loading
sequenceDiagram
    participant Client as Client
    participant XAI as XAIModel
    participant API as xAI_API
    participant SSE as SSE_Parser
    participant Sender as Sender_Callback

    Client->>XAI: ChatStreamlyWithSender(modelName, messages, apiConfig, sender)
    XAI->>API: POST /chat/completions (JSON payload, stream=true)
    API-->>SSE: SSE stream (lines `data: {...}` / `[DONE]`)
    loop per SSE event
        SSE->>XAI: event JSON
        XAI->>Sender: emit delta.reasoning_content tokens (if any)
        XAI->>Sender: emit delta.content token(s)
    end
    SSE->>XAI: [DONE] or finish_reason
    XAI->>Sender: send trailing `[DONE]` marker
    Sender-->>Client: streaming complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 minutes

Possibly related PRs

Suggested labels

ci

Poem

🐰 I hopped in with keys and code tonight,
xAI streams tokens, nibbling bytes so bright.
Reasoning crumbs and answers stitched anew,
SSE carrots fall — one token, then two.
A rabbit grins: newline and done — we’re through.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main change: implementing a provider driver for xAI in Go.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.
Description check ✅ Passed The pull request description comprehensively addresses the template requirements with clear problem statement, feature type, implementation details, testing approach, and pattern alignment.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/entity/models/xai.go`:
- Around line 191-199: ChatStreamlyWithSender and ListModels dereference
apiConfig and its fields (e.g., apiConfig.ApiKey, apiConfig.Region) without nil
checks which can panic; update both functions (ChatStreamlyWithSender,
ListModels) to guard against a nil apiConfig and nil pointer fields before
dereferencing by returning a clear error or using safe defaults, e.g., check if
apiConfig == nil then return fmt.Errorf(...) or set defaults, and check if
apiConfig.ApiKey == nil (and apiConfig.Region == nil) before using
*apiConfig.ApiKey / *apiConfig.Region so no direct dereference occurs when nil.
- Around line 55-57: NewInstance currently returns nil which will cause panics
when callers expect a valid ModelDriver; update XAIModel.NewInstance to
construct and return a concrete XAIModel instance (populating its fields with
the provided baseURL) rather than nil, ensuring the returned value implements
the ModelDriver interface; specifically locate the XAIModel.NewInstance function
and return a newly initialized XAIModel (with any required fields set from
baseURL) so subsequent method calls on the driver are safe.
- Line 269: Replace the raw Info-level logging of model stream chunks (the
logger.Info(line) call) with a non-sensitive, lower-volume approach: stop
logging the full chunk content and either log at Debug level or remove the call,
or log only metadata (e.g., chunk index, byte/char length, and a redacted or
truncated preview) so the stream data cannot leak; locate the logger.Info(line)
use in internal/entity/models/xai.go (the streaming handler that emits chunks)
and update it to log only sanitized metadata or downgrade to logger.Debug with
redaction/truncation.
- Around line 93-96: In ChatWithMessages, do not propagate
chatModelConfig.Stream into the request body because this method expects a
single JSON response; when building reqBody (where chatModelConfig and
chatModelConfig.Stream are currently used to set reqBody["stream"]), either omit
the "stream" field entirely or explicitly set reqBody["stream"] = false so
SSE/streaming is never enabled for ChatWithMessages and JSON unmarshalling won’t
break.
- Around line 266-267: The scanner loop using bufio.NewScanner(resp.Body) in the
SSE handling (scanner := bufio.NewScanner(resp.Body); for scanner.Scan() { … })
can silently fail on tokens >64KB; update the code to either configure
scanner.Buffer with a larger max token size before scanning or switch to using
bufio.NewReader/ReadString/ReadBytes to stream lines robustly, and after the
loop check scanner.Err() (or the reader error) and handle/log the error and
abort the stream processing; ensure you modify the code around scanner :=
bufio.NewScanner(resp.Body), the for scanner.Scan() loop, and the post-loop
error handling to prevent silent truncation of long SSE `data:` chunks.
🪄 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: 437d8ed6-3148-4384-b21d-1a804dd6ae04

📥 Commits

Reviewing files that changed from the base of the PR and between 24af087 and df67e82.

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

Comment thread internal/entity/models/xai.go Resolved
Comment thread internal/entity/models/xai.go Resolved
Comment thread internal/entity/models/xai.go Resolved
Comment thread internal/entity/models/xai.go Resolved
Comment thread internal/entity/models/xai.go Resolved
CodeRabbit flagged five issues on the new xAI driver. All five are
fixed in this commit.

- NewInstance now returns a real XAIModel built from the given
  base URL and the existing URL suffix, instead of nil. This matches
  what callers expect from the ModelDriver interface.
- ChatWithMessages no longer copies chatModelConfig.Stream into the
  request body. This method parses a single JSON response, so the
  stream flag must always be off here, otherwise the API would return
  SSE and the JSON unmarshal would fail.
- ChatStreamlyWithSender and ListModels now check that apiConfig and
  apiConfig.ApiKey are not nil before any dereference. Without this
  guard a missing key would panic the worker.
- The SSE scanner buffer is raised from the 64KB default to 1MB so
  long data: lines from reasoning models do not get silently cut.
- The function now checks scanner.Err() before sending the final
  [DONE] marker, so a read error is not reported as a clean stream.
- The raw logger.Info(line) call is removed from the stream loop.
  It was logging full chunk content at info level, which leaked the
  model output to logs and was very noisy under load.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/entity/models/xai.go`:
- Around line 63-71: In ChatWithMessages (method XAIModel.ChatWithMessages) add
an early API key validation like the other flows
(ChatStreamlyWithSender/ListModels): check that apiConfig is not nil and
contains a non-empty API key (e.g., apiConfig.APIKey or a HasAPIKey helper) and
return a local error immediately if missing instead of letting the call proceed
to a remote request; apply the same change pattern to the related block at lines
~124-126.
- Around line 221-224: In ChatStreamlyWithSender, don't override
reqBody["stream"] to false: change the logic around chatModelConfig.Stream so
you only set reqBody["stream"] when chatModelConfig.Stream != nil &&
*chatModelConfig.Stream is true (i.e., only set it to true); if the pointer is
nil or false, leave reqBody["stream"] unset so the SSE branch won't be forced to
parse non-SSE JSON. Update the code referencing chatModelConfig.Stream and
reqBody["stream"] accordingly.
🪄 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: 07392098-337a-453e-b857-19e9fc2c3cd0

📥 Commits

Reviewing files that changed from the base of the PR and between df67e82 and 7b8bd0a.

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

Comment thread internal/entity/models/xai.go Resolved
Comment thread internal/entity/models/xai.go Resolved
Address two more review notes from CodeRabbit.

- ChatWithMessages now validates apiConfig and the api key at the top
  of the function, the same way ChatStreamlyWithSender and ListModels
  already do. Without the key the call can never succeed, so we fail
  fast with a clear error before building the request. The redundant
  inline guard around the Authorization header is removed.

- ChatStreamlyWithSender now returns an error if the caller explicitly
  passes stream=false. The body of this method only knows how to read
  SSE, so a non-SSE JSON response would be parsed as a stream and yield
  no chunks. When Stream is nil or true, the request body keeps the
  default stream=true that was set in the initial map literal.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/entity/models/xai.go`:
- Around line 42-49: The shared httpClient currently sets a global Timeout and a
custom Transport that overrides http.DefaultTransport defaults, which breaks
long-lived streaming in ChatStreamlyWithSender and loses proxy/HTTP2/TLS
defaults; fix by cloning the default transport (t :=
http.DefaultTransport.(*http.Transport).Clone()), apply only the custom fields
on that clone, remove the global httpClient.Timeout (leave zero for no
client-wide deadline) so streams aren’t cut off, and implement request-scoped
deadlines using context.WithTimeout in non-streaming calls such as
ChatWithMessages when performing the request; ensure ChatStreamlyWithSender
continues to use the no-timeout httpClient while ChatWithMessages wraps its
request with the per-call context timeout.
🪄 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: 2ea648bf-5573-4395-b4b8-46e683919f9b

📥 Commits

Reviewing files that changed from the base of the PR and between 7b8bd0a and 857ee8f.

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

Comment thread internal/entity/models/xai.go Resolved
Address one more review note from CodeRabbit on the http.Client setup.

The shared httpClient had two related problems:

- Timeout was set to 120 seconds on the Client itself. http.Client.Timeout
  also caps the time spent reading the response body, so a long SSE
  stream from ChatStreamlyWithSender would be cut off after two minutes
  even when the API was still sending tokens.
- Transport was a fresh &http.Transport{} with only a few fields set.
  This drops Go's defaults: ProxyFromEnvironment, DialContext with
  KeepAlive, ForceAttemptHTTP2, TLSHandshakeTimeout, and
  ExpectContinueTimeout. Behind a corporate proxy or on HTTP/2 the
  client would not behave like the rest of the codebase expects.

The fix follows the standard Go pattern for clients that have to handle
both short and long-lived calls:

- The Transport is now built by cloning http.DefaultTransport and only
  overriding MaxIdleConns, MaxIdleConnsPerHost, IdleConnTimeout, and
  DisableCompression. All the other defaults are kept.
- The Client itself has no Timeout. ChatStreamlyWithSender can now keep
  the SSE connection open as long as the server keeps streaming.
- ChatWithMessages and ListModels each wrap their request with
  context.WithTimeout(nonStreamCallTimeout). The 120-second cap that
  used to live on the Client now lives on the call, where it actually
  belongs, and it does not leak into the streaming path.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/entity/models/xai.go`:
- Around line 89-95: The code accesses z.BaseURL[region] without validating the
key, causing silent/late failures for unknown regions; add a small helper method
(e.g., func (z *XAI) baseURLForRegion(region string) (string, error)) that
checks whether region exists in z.BaseURL and returns the base URL or an error
if missing, then replace direct lookups in the URL-building sites (the block
that sets region and calls fmt.Sprintf("%s/%s", z.BaseURL[region],
z.URLSuffix.Chat) and the other two occurrences) to call baseURLForRegion and
propagate/return the error so configuration failures fail fast and predictably.
- Around line 297-364: The code currently always sends a synthetic "[DONE]"
after scanning even when the upstream never sent "[DONE]" or a non-empty
finish_reason; add a boolean flag (e.g., sawEnd) that you set to true when you
encounter data == "[DONE]" or when you detect a non-empty
firstChoice["finish_reason"], and only call sender(&endOfStream, nil) if sawEnd
is true; also if scanner.Err() is nil but sawEnd is false, return an error
indicating the stream ended prematurely instead of emitting a synthetic
"[DONE]". Ensure you update the loop handling (around scanner, the JSON parsing,
delta handling and finishReason checks) to flip sawEnd and then perform the
conditional send using the existing sender and endOfStream variables.
🪄 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: f0e5050f-70b6-4c38-a62b-058bc9704bf9

📥 Commits

Reviewing files that changed from the base of the PR and between 857ee8f and a71794b.

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

Comment thread internal/entity/models/xai.go Resolved
Comment thread internal/entity/models/xai.go Resolved
…eams

Address two more review notes from CodeRabbit.

- Add a baseURLForRegion helper. The three URL build sites used to
  read z.BaseURL[region] without checking if the region key was
  actually configured. For an unknown region, the lookup returned an
  empty string and the call later failed with a confusing transport
  error. The helper now returns a clear "no base URL configured for
  region" error up front, and ChatWithMessages,
  ChatStreamlyWithSender, and ListModels all use it.
- Track a sawTerminal flag in ChatStreamlyWithSender. The previous
  code always sent a synthetic "[DONE]" at the end, even if the
  upstream closed the body before sending "[DONE]" or a non-empty
  finish_reason. That turned a truncated stream into a successful
  one. Now we only send "[DONE]" when the upstream actually told us
  the stream is over. If the body ends early without scanner.Err,
  we return a clear "stream ended before [DONE] or finish_reason"
  error so the caller sees the partial result.
@davidv399

Copy link
Copy Markdown
Contributor Author

Hi, @Magicbook1108
How are you? This is the first PR to contribute to this project. Could you take a look at my PR at your convenience please?
Appreciate.

@JinHai-CN
JinHai-CN requested a review from Haruko386 May 6, 2026 02:52
@Haruko386 Haruko386 added the ci Continue Integration label May 6, 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.

done

@JinHai-CN
JinHai-CN merged commit c2ad672 into infiniflow:main May 6, 2026
1 check passed
@codecov

codecov Bot commented May 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (cd54c08) to head (5aeb4df).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14550   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pandadev66 pandadev66 mentioned this pull request May 7, 2026
1 task done
JinHai-CN pushed a commit that referenced this pull request May 7, 2026
### What problem does this PR solve?

Add a Go driver for OpenAI (GPT models).

The config file conf/models/openai.json has been in the repo for a while
with the full GPT-5 model list, but
internal/entity/models/factory.go had no case for "openai". So any
tenant that configured OpenAI as a model provider in the Go layer fell
through to the default branch and got the dummy driver. Chat, list
models, and check connection all returned dummy responses instead of
reaching the API.

OpenAI is the most commonly requested provider and the JSON config
already ships with the repo, so this gap is high impact even though the
JSON has been there for some time.

### What this PR includes

- New file internal/entity/models/openai.go with an OpenAIModel that
implements the ModelDriver interface.
- factory.go: route the "openai" provider name to NewOpenAIModel.
- conf/models/openai.json: add "models": "models" under url_suffix so
ListModels can hit /v1/models with no hardcoded fallback.

### How the driver works

- OpenAI exposes the canonical OpenAI-compatible API at
https://api.openai.com/v1.
- ChatWithMessages and ChatStreamlyWithSender post to /chat/completions
in the same shape the moonshot, vllm, and xai drivers use.
- ListModels and CheckConnection call /models to list available ids and
confirm the API key works.
- reasoning_content is passed through for the o-series and other
reasoning models, in both the non-stream and stream paths.
- Encode (embeddings) is left as "not implemented" for now, the same way
the other recent provider drivers do it. Rerank and Balance are not part
of OpenAI's public API surface in this layer and return a clear "not
implemented" or "no such method" error.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- go build ./internal/entity/models/... in a clean go 1.25 image (the
go.mod minimum) returns exit 0 with no errors.
- Method set of OpenAIModel matches the ModelDriver interface:
NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode,
Rerank, ListModels, Balance, CheckConnection.
- Pattern parity with the merged moonshot (#14433), volcengine (#14460),
minimax (#14478), vllm (#14532), xai (#14550), and lm-studio (#14586)
PRs.

Closes #14604
@coderabbitai coderabbitai Bot mentioned this pull request May 9, 2026
1 task done
@tmimmanuel tmimmanuel mentioned this pull request May 12, 2026
1 task done
JinHai-CN pushed a commit that referenced this pull request May 12, 2026
### What problem does this PR solve?

Add a Go driver for StepFun (阶跃星辰), one of the unchecked providers on
the umbrella tracking issue #14736.

Until this PR, a tenant who configured `stepfun` 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. Chat, list
models, and check connection all returned `"not implemented"` instead of
reaching the StepFun API.

The Python side has had StepFun registered in `rag/llm/__init__.py` as a
`SupportedLiteLLMProvider` with base URL `https://api.stepfun.com/v1`,
plus `StepFunCV` for vision and `StepFunSeq2txt` for ASR, but no Go
path. StepFun's chat API is OpenAI-compatible, so the implementation
pattern is the same as the merged Moonshot driver (#14433) and OpenAI
driver (#14605).

### What this PR includes

- New file `internal/entity/models/stepfun.go` with a `StepFunModel`
that implements the `ModelDriver` interface.
- `factory.go`: route the `"stepfun"` provider name to
`NewStepFunModel`.
- New `conf/models/stepfun.json` with the public StepFun chat models
(step-2-16k, step-1 family in 8k/32k/128k/256k context lengths,
step-1-flash, and the step-1v / step-1o vision models) and `url_suffix`
entries for `chat` and `models`.

### How the driver works

- StepFun exposes the OpenAI-compatible API at
`https://api.stepfun.com/v1`.
- `ChatWithMessages` and `ChatStreamlyWithSender` post to
`/chat/completions` in the same shape as the merged moonshot,
openrouter, and openai drivers.
- `ListModels` and `CheckConnection` call `/models` to list available
ids and confirm the API key works.
- `Embed` is left as `"not implemented"`. StepFun has not advertised a
public embeddings endpoint in the API reference linked from the umbrella
issue
(`https://platform.stepfun.com/docs/en/api-reference/chat/chat-completion-create`
is the chat endpoint), so any real implementation belongs in a separate
follow-up only after the endpoint is verified.
- `Rerank` and `Balance` return `"no such method"` because StepFun does
not expose either.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- `go build ./internal/entity/models/...` returns exit 0 with no errors
on go 1.25 (the `go.mod` minimum).
- Method set of `StepFunModel` matches the `ModelDriver` interface:
`NewInstance`, `Name`, `ChatWithMessages`, `ChatStreamlyWithSender`,
`Embed`, `Rerank`, `ListModels`, `Balance`, `CheckConnection`.
- Pattern parity with the merged moonshot (#14433), openai (#14605),
openrouter (#14652), and xai (#14550) drivers.

Closes #14814
Tracking: #14736
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 OpenAI (GPT models).

The config file conf/models/openai.json has been in the repo for a while
with the full GPT-5 model list, but
internal/entity/models/factory.go had no case for "openai". So any
tenant that configured OpenAI as a model provider in the Go layer fell
through to the default branch and got the dummy driver. Chat, list
models, and check connection all returned dummy responses instead of
reaching the API.

OpenAI is the most commonly requested provider and the JSON config
already ships with the repo, so this gap is high impact even though the
JSON has been there for some time.

### What this PR includes

- New file internal/entity/models/openai.go with an OpenAIModel that
implements the ModelDriver interface.
- factory.go: route the "openai" provider name to NewOpenAIModel.
- conf/models/openai.json: add "models": "models" under url_suffix so
ListModels can hit /v1/models with no hardcoded fallback.

### How the driver works

- OpenAI exposes the canonical OpenAI-compatible API at
https://api.openai.com/v1.
- ChatWithMessages and ChatStreamlyWithSender post to /chat/completions
in the same shape the moonshot, vllm, and xai drivers use.
- ListModels and CheckConnection call /models to list available ids and
confirm the API key works.
- reasoning_content is passed through for the o-series and other
reasoning models, in both the non-stream and stream paths.
- Encode (embeddings) is left as "not implemented" for now, the same way
the other recent provider drivers do it. Rerank and Balance are not part
of OpenAI's public API surface in this layer and return a clear "not
implemented" or "no such method" error.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- go build ./internal/entity/models/... in a clean go 1.25 image (the
go.mod minimum) returns exit 0 with no errors.
- Method set of OpenAIModel matches the ModelDriver interface:
NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode,
Rerank, ListModels, Balance, CheckConnection.
- Pattern parity with the merged moonshot (infiniflow#14433), volcengine (infiniflow#14460),
minimax (infiniflow#14478), vllm (infiniflow#14532), xai (infiniflow#14550), and lm-studio (infiniflow#14586)
PRs.

Closes infiniflow#14604
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 StepFun (阶跃星辰), one of the unchecked providers on
the umbrella tracking issue infiniflow#14736.

Until this PR, a tenant who configured `stepfun` 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. Chat, list
models, and check connection all returned `"not implemented"` instead of
reaching the StepFun API.

The Python side has had StepFun registered in `rag/llm/__init__.py` as a
`SupportedLiteLLMProvider` with base URL `https://api.stepfun.com/v1`,
plus `StepFunCV` for vision and `StepFunSeq2txt` for ASR, but no Go
path. StepFun's chat API is OpenAI-compatible, so the implementation
pattern is the same as the merged Moonshot driver (infiniflow#14433) and OpenAI
driver (infiniflow#14605).

### What this PR includes

- New file `internal/entity/models/stepfun.go` with a `StepFunModel`
that implements the `ModelDriver` interface.
- `factory.go`: route the `"stepfun"` provider name to
`NewStepFunModel`.
- New `conf/models/stepfun.json` with the public StepFun chat models
(step-2-16k, step-1 family in 8k/32k/128k/256k context lengths,
step-1-flash, and the step-1v / step-1o vision models) and `url_suffix`
entries for `chat` and `models`.

### How the driver works

- StepFun exposes the OpenAI-compatible API at
`https://api.stepfun.com/v1`.
- `ChatWithMessages` and `ChatStreamlyWithSender` post to
`/chat/completions` in the same shape as the merged moonshot,
openrouter, and openai drivers.
- `ListModels` and `CheckConnection` call `/models` to list available
ids and confirm the API key works.
- `Embed` is left as `"not implemented"`. StepFun has not advertised a
public embeddings endpoint in the API reference linked from the umbrella
issue
(`https://platform.stepfun.com/docs/en/api-reference/chat/chat-completion-create`
is the chat endpoint), so any real implementation belongs in a separate
follow-up only after the endpoint is verified.
- `Rerank` and `Balance` return `"no such method"` because StepFun does
not expose either.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- `go build ./internal/entity/models/...` returns exit 0 with no errors
on go 1.25 (the `go.mod` minimum).
- Method set of `StepFunModel` matches the `ModelDriver` interface:
`NewInstance`, `Name`, `ChatWithMessages`, `ChatStreamlyWithSender`,
`Embed`, `Rerank`, `ListModels`, `Balance`, `CheckConnection`.
- Pattern parity with the merged moonshot (infiniflow#14433), openai (infiniflow#14605),
openrouter (infiniflow#14652), and xai (infiniflow#14550) drivers.

Closes infiniflow#14814
Tracking: infiniflow#14736
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Add Go driver for xAI (Grok) model provider

3 participants