Skip to content

Go: implement provider: OpenAI - #14605

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
pandadev66:feat/go-openai-provider
May 7, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
pandadev66:feat/go-openai-provider

Conversation

@pandadev66

@pandadev66 pandadev66 commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

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

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

How was this tested?

Closes #14604

Add a Go driver for OpenAI (GPT models). The conf/models/openai.json
config has been in the repo for a while with full GPT-5 model
definitions, but factory.go had no case for "openai". So any tenant
that configured OpenAI in the Go layer fell through to the dummy
driver and never reached the API.

OpenAI is the most commonly requested provider, and the JSON config
already ships with the repo, so this gap is high impact.

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 without a hardcoded fallback.

How the driver works:

- ChatWithMessages and ChatStreamlyWithSender post to
  /chat/completions in the standard OpenAI shape.
- ListModels and CheckConnection call /models to list available ids
  and confirm the API key.
- 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 unimplemented for now, the same way
  the other recent provider drivers do it.
- Rerank and Balance are not exposed by OpenAI, so they return a
  clear "not implemented" or "no such method" error.

Safety patterns reused from the recently merged xAI driver
(infiniflow#14550), so the review surface should look familiar:

- Early validation of apiConfig and the API key in every method.
- baseURLForRegion helper that fails fast on unknown regions.
- ChatWithMessages refuses stream=true, ChatStreamlyWithSender
  refuses stream=false, so each method only ever sees the body
  shape it knows how to parse.
- http.Client built by cloning http.DefaultTransport, no client
  Timeout (so SSE streams are not cut off), per-call
  context.WithTimeout for non-streaming calls.
- bufio.Scanner buffer raised to 1MB and scanner.Err() checked
  after the loop.
- sawTerminal flag in the SSE loop, so the synthetic "[DONE]"
  marker is only forwarded when the upstream actually finished.

Closes infiniflow#14604
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 7, 2026
@pandadev66

Copy link
Copy Markdown
Contributor Author

Hi @Magicbook1108, gentle ping for review when you have time. This follows the same pattern as the recently merged xAI (#14550) and lm-studio (#14586) drivers, and it closes #14604. Thanks!

@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 73d107c8-cce5-42bf-bbb3-06eb84780ca0

📥 Commits

Reviewing files that changed from the base of the PR and between 5a88240 and aadb2ac.

📒 Files selected for processing (1)
  • internal/entity/models/openai.go
✅ Files skipped from review due to trivial changes (1)
  • internal/entity/models/openai.go

📝 Walkthrough

Walkthrough

This PR adds a new OpenAI model driver implementation and wires the factory to return it for provider name "openai". It updates the OpenAI JSON config to include a models endpoint suffix and implements chat (streaming and non-streaming), ListModels, and connection checking in the Go driver.

Changes

OpenAI Driver Implementation

Layer / File(s) Summary
Configuration / Data Shape
conf/models/openai.json
url_suffix expanded to include "chat": "chat/completions" and "models": "models".
Core Driver Implementation
internal/entity/models/openai.go
Adds OpenAIModel and NewOpenAIModel; implements ChatWithMessages (non-streaming with timeout), ChatStreamlyWithSender (SSE streaming with 1MB scanner buffer), ListModels (GET /models), CheckConnection (delegates to ListModels), and explicit unimplemented Encode/Rerank/Balance behaviors. Includes http.Client transport tuning, region→baseURL resolution, reasoning_content passthrough, and error handling.
Factory Wiring / Integration
internal/entity/models/factory.go
CreateModelDriver now recognizes provider "openai" (case-insensitive) and returns NewOpenAIModel(baseURL, urlSuffix).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant OpenAIDriver as OpenAI Driver
    participant OpenAIAPI as OpenAI API

    Client->>OpenAIDriver: ChatWithMessages(messages, config)
    OpenAIDriver->>OpenAIDriver: Validate API key & messages
    OpenAIDriver->>OpenAIDriver: Build JSON (stream=false) + generation params
    OpenAIDriver->>OpenAIDriver: Create ctx with timeout
    OpenAIDriver->>OpenAIAPI: POST /v1/chat/completions
    OpenAIAPI-->>OpenAIDriver: 200 OK + JSON
    OpenAIDriver->>OpenAIDriver: Parse choices[0].message.content and reasoning_content
    OpenAIDriver-->>Client: ChatResponse (content + reasoning)
Loading
sequenceDiagram
    participant Client
    participant OpenAIDriver as OpenAI Driver
    participant OpenAIAPI as OpenAI API
    participant SSEReader as SSE Reader
    participant Sender as Sender Callback

    Client->>OpenAIDriver: ChatStreamlyWithSender(messages, sender)
    OpenAIDriver->>OpenAIDriver: Validate inputs & enforce stream=true
    OpenAIDriver->>OpenAIDriver: Build JSON (stream=true) + generation params
    OpenAIDriver->>OpenAIAPI: POST /v1/chat/completions
    OpenAIAPI-->>OpenAIDriver: 200 OK + SSE stream
    OpenAIDriver->>SSEReader: Read SSE `data:` lines (1MB buffer)
    loop until [DONE] or finish_reason
      SSEReader->>OpenAIDriver: Emit event JSON
      OpenAIDriver->>Sender: Send partial delta.reasoning_content / delta.content
    end
    OpenAIDriver->>Sender: Emit trailing [DONE]
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

Suggested labels

size:XL

Poem

🐰 I hopped through JSON, new endpoints in tow,
Wired the factory so OpenAI can flow,
Streams and timeouts, reasoning passed along,
Models now listed — the driver sings a song,
Rabbit-approved, the integration's strong!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: implement provider: OpenAI' clearly and specifically describes the main change—adding a Go driver for the OpenAI provider—which is exactly what the changeset does.
Description check ✅ Passed The description comprehensively covers the template requirements: it explains the problem (OpenAI JSON config exists but no factory case), includes detailed implementation details, explicitly marks it as a 'New Feature', and documents how it was tested.
Linked Issues check ✅ Passed The PR fully implements all coding objectives from #14604: adds OpenAIModel driver with chat/streaming support, wires 'openai' in factory.go, updates conf/models/openai.json with models endpoint, and passes through reasoning_content for o-series models.
Out of Scope Changes check ✅ Passed All three file changes (openai.go, factory.go, openai.json) are directly scoped to implementing the OpenAI driver feature requested in #14604 with no extraneous changes.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

🧹 Nitpick comments (1)
internal/entity/models/openai.go (1)

427-428: 💤 Low value

Content-Type header is unnecessary on a GET request.

A GET request carries no body; the header is ignored by the server and signals the wrong intent.

📝 Suggested fix
-	req.Header.Set("Content-Type", "application/json")
 	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
🤖 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/openai.go` around lines 427 - 428, Remove the
unnecessary Content-Type header being set on the GET request: locate the code
that calls req.Header.Set("Content-Type", "application/json") (the same function
that also sets Authorization with fmt.Sprintf("Bearer %s", *apiConfig.ApiKey"))
and delete that header set so only the Authorization header remains for the GET
path; leave Content-Type in any POST/PUT request handlers if present.
🤖 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/openai.go`:
- Around line 472-474: Comment headers for the Balance and Rerank methods
incorrectly mention "xAI" due to copy-paste; update the doc comments above the
OpenAIModel.Balance and OpenAIModel.Rerank methods to accurately reflect that
the OpenAI API (not xAI) does not expose these features (e.g., "Balance is not
exposed by the OpenAI API" and "Rerank is not exposed by the OpenAI API"),
keeping the existing behavior (returning an error) unchanged and ensuring the
method names Balance and Rerank are referenced in the comments for clarity.
- Around line 203-204: Update the stale comment that references xAI/grok models:
in internal/entity/models/openai.go where the code handles the reasoning_content
field, replace the grok-3-mini/xAI wording with OpenAI-specific wording
(referencing OpenAI's o-series, e.g., o3/o4 or "o-series") so the comment
correctly states that OpenAI's o-series models return reasoning in
reasoning_content.
- Around line 291-294: The streaming request is created with http.NewRequest
which uses context.Background(), risking a goroutine stuck on scanner.Scan;
change to create and use a per-request context (e.g., ctx, cancel :=
context.WithTimeout(parentCtxOrBackground, <reasonableDuration>); defer
cancel()) and call http.NewRequestWithContext(ctx, "POST", url,
bytes.NewBuffer(jsonData)); if possible prefer passing a ctx parameter through
ChatStreamlyWithSender to callers so callers can control deadlines — otherwise
at minimum add a per-request context here and ensure cancel is deferred to avoid
leaks; also consider setting ResponseHeaderTimeout on the transport as an
additional safeguard.
- Around line 396-400: The comment above OpenAIModel.Encode is stale and
factually wrong (it incorrectly references "xAI"); update the comment for the
Encode method on type OpenAIModel to state that OpenAI does provide embeddings
(e.g., text-embedding-ada-002 / text-embedding-3-*) but this driver
intentionally leaves embedding support unimplemented for now, and add a
TODO/NOTE pointing to the relevant PR or issue for future implementation; leave
the Encode signature and its current nil, fmt.Errorf("not implemented") return
as-is.

---

Nitpick comments:
In `@internal/entity/models/openai.go`:
- Around line 427-428: Remove the unnecessary Content-Type header being set on
the GET request: locate the code that calls req.Header.Set("Content-Type",
"application/json") (the same function that also sets Authorization with
fmt.Sprintf("Bearer %s", *apiConfig.ApiKey")) and delete that header set so only
the Authorization header remains for the GET path; leave Content-Type in any
POST/PUT request handlers if present.
🪄 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: 85ff948f-8388-44ab-8f63-1d405db97ea8

📥 Commits

Reviewing files that changed from the base of the PR and between 15dcdd7 and 5a88240.

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

Comment thread internal/entity/models/openai.go Resolved
Comment thread internal/entity/models/openai.go Resolved
Comment thread internal/entity/models/openai.go Resolved
Comment thread internal/entity/models/openai.go Resolved
CodeRabbit flagged five things on the new OpenAI driver. All five
are fixed in this commit.

- The reasoning_content comment in ChatWithMessages no longer
  references xAI grok-3-mini. It now mentions OpenAI's o-series.
- The Encode comment is rewritten. OpenAI does have embedding
  endpoints (text-embedding-ada-002 and text-embedding-3-*), so
  the comment now says the driver intentionally leaves embedding
  support unimplemented in this initial version, with a follow-up
  PR planned.
- The Balance and Rerank comments now correctly say "OpenAI",
  not "xAI".
- The streaming request in ChatStreamlyWithSender is now built
  with http.NewRequestWithContext(context.Background(), ...) so
  it is explicitly cancellable. Threading a real ctx through the
  ModelDriver interface is a wider change for a follow-up PR.
- The shared transport now also sets ResponseHeaderTimeout to
  60 seconds. This protects the streaming path against a server
  that opens the TCP connection and then never sends a response.
- The GET request in ListModels no longer sets Content-Type. A
  GET has no body, so the header was unnecessary.
@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 7, 2026
@Magicbook1108
Magicbook1108 requested a review from Haruko386 May 7, 2026 01:53

@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 added the ci Continue Integration label May 7, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft May 7, 2026 02:00
@JinHai-CN
JinHai-CN marked this pull request as ready for review May 7, 2026 02:00
@codecov

codecov Bot commented May 7, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14605      +/-   ##
==========================================
- Coverage   95.59%   94.16%   -1.43%     
==========================================
  Files          10       10              
  Lines         703      703              
  Branches      112      112              
==========================================
- Hits          672      662      -10     
- Misses         21       25       +4     
- Partials       10       16       +6     

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

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

@JinHai-CN
JinHai-CN merged commit b8b7415 into infiniflow:main May 7, 2026
2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request May 7, 2026
2 tasks done
@coderabbitai coderabbitai Bot mentioned this pull request May 9, 2026
8 of 9 tasks
JinHai-CN added a commit that referenced this pull request May 10, 2026
### What problem does this PR solve?

The OpenAI Go driver landed in #14605 with chat, list models, and check
connection. Encode was left as a stub that returns \`not implemented\`.

\`conf/models/openai.json\` already lists three embedding models out of
the box:

- text-embedding-ada-002
- text-embedding-3-small
- text-embedding-3-large

So a tenant who picked one of these in the Go layer could not actually
run an embedding call. This PR fills the gap.

### What this PR includes

- \`conf/models/openai.json\`: add \`\"embedding\": \"embeddings\"\`
under \`url_suffix\` so the driver can build the URL from config. This
matches the \`URLSuffix.Embedding\` field used by other drivers
(siliconflow, zhipu-ai).
- \`internal/entity/models/openai.go\`: replace the Encode stub with a
real implementation that POSTs to \`/v1/embeddings\`. Adds a small local
response type \`openaiEmbeddingResponse\`.

No factory change. No interface change.

### How the implementation works

- Validate \`apiConfig\` and the API key, validate the model name. Use
the existing \`baseURLForRegion\` helper so an unknown region fails fast
with a clear error.
- Wrap the request with \`context.WithTimeout(nonStreamCallTimeout)\` so
the call has a clear deadline. Same pattern as \`ChatWithMessages\` and
\`ListModels\` already use in this file.
- Send all input texts in one request. The OpenAI API accepts the
\`input\` field as an array.
- Parse \`data[*].embedding\` and copy each slice into a \`[][]float64\`
indexed by \`data[*].index\` so the output order matches the input order
even if the API returns items in a different order.
- Handle both \`float64\` and \`float32\` element types, the way the
SiliconFlow driver does.
- An empty input slice returns \`[][]float64{}\` with no HTTP call.
- Non-200 responses propagate the upstream status line and body.
- A final pass checks that every input slot got a vector. If any slot is
still nil, return a clear error so the caller does not silently use a
zero vector.

### 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.
- The full method set on \`OpenAIModel\` still matches the
\`ModelDriver\` interface.
- Pattern parity with the existing SiliconFlow Encode implementation
(\`internal/entity/models/siliconflow.go\`).

Closes #14629

---------

Co-authored-by: Jin Hai <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request May 11, 2026
9 of 10 tasks
tmimmanuel added a commit to tmimmanuel/ragflow that referenced this pull request May 12, 2026
CodeRabbit review on the stacked PR infiniflow#14811 flagged that the
ChatStreamlyWithSender comment promised "the client drops the
connection if it stalls", which is not actually implemented in the
current driver. Replace the comment with the more accurate wording
used in the merged OpenAI driver (infiniflow#14605): the background context
makes the request "cancellable in principle" but no hard deadline is
attached because SSE streams are long-lived, and threading a real
ctx through the ModelDriver interface is a wider change for a
follow-up.

Also add a nil-sender guard at the top of ChatStreamlyWithSender,
matching the fixes applied to Mistral (infiniflow#14805) and Upstage (infiniflow#14817)
on review feedback. The risk class is the same: invoking a nil
callback panics the process.
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?

The OpenAI Go driver landed in infiniflow#14605 with chat, list models, and check
connection. Encode was left as a stub that returns \`not implemented\`.

\`conf/models/openai.json\` already lists three embedding models out of
the box:

- text-embedding-ada-002
- text-embedding-3-small
- text-embedding-3-large

So a tenant who picked one of these in the Go layer could not actually
run an embedding call. This PR fills the gap.

### What this PR includes

- \`conf/models/openai.json\`: add \`\"embedding\": \"embeddings\"\`
under \`url_suffix\` so the driver can build the URL from config. This
matches the \`URLSuffix.Embedding\` field used by other drivers
(siliconflow, zhipu-ai).
- \`internal/entity/models/openai.go\`: replace the Encode stub with a
real implementation that POSTs to \`/v1/embeddings\`. Adds a small local
response type \`openaiEmbeddingResponse\`.

No factory change. No interface change.

### How the implementation works

- Validate \`apiConfig\` and the API key, validate the model name. Use
the existing \`baseURLForRegion\` helper so an unknown region fails fast
with a clear error.
- Wrap the request with \`context.WithTimeout(nonStreamCallTimeout)\` so
the call has a clear deadline. Same pattern as \`ChatWithMessages\` and
\`ListModels\` already use in this file.
- Send all input texts in one request. The OpenAI API accepts the
\`input\` field as an array.
- Parse \`data[*].embedding\` and copy each slice into a \`[][]float64\`
indexed by \`data[*].index\` so the output order matches the input order
even if the API returns items in a different order.
- Handle both \`float64\` and \`float32\` element types, the way the
SiliconFlow driver does.
- An empty input slice returns \`[][]float64{}\` with no HTTP call.
- Non-200 responses propagate the upstream status line and body.
- A final pass checks that every input slot got a vector. If any slot is
still nil, return a clear error so the caller does not silently use a
zero vector.

### 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.
- The full method set on \`OpenAIModel\` still matches the
\`ModelDriver\` interface.
- Pattern parity with the existing SiliconFlow Encode implementation
(\`internal/entity/models/siliconflow.go\`).

Closes infiniflow#14629

---------

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?

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:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Add Go driver for OpenAI model provider

3 participants