Repository navigation
Go: implement provider: OpenAI - #14605
Conversation
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
|
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! |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughThis 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 ChangesOpenAI Driver Implementation
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)
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]
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
internal/entity/models/openai.go (1)
427-428: 💤 Low value
Content-Typeheader 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
📒 Files selected for processing (3)
conf/models/openai.jsoninternal/entity/models/factory.gointernal/entity/models/openai.go
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.
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
### 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]>
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.
### 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
### 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
### 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]>
### 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
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
How the driver works
Type of change
How was this tested?
Closes #14604