Repository navigation
Go: implement Balance in OpenAI driver (admin-key path) - #14876
hunnyboy1217 wants to merge 1 commit into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a ChangesOpenAI Balance API
Sequence Diagram(s)sequenceDiagram
participant Caller
participant OpenAIModel as OpenAIModel.Balance
participant HTTPClient
participant OpenAIAPI as OpenAI Organization Costs API
Caller->>OpenAIModel: Balance(apiConfig)
OpenAIModel->>OpenAIModel: validate apiConfig.ApiKey (sk-admin-...)
OpenAIModel->>HTTPClient: GET {baseURL}/v1/organization/costs?start_time=<month_start>&limit=31
HTTPClient->>OpenAIAPI: HTTP GET with Authorization: Bearer <admin-key>
OpenAIAPI-->>HTTPClient: 200 {data:[{results:[{amount:{value,currency}}...]}...]}
HTTPClient-->>OpenAIModel: response body
OpenAIModel->>OpenAIModel: unmarshal, sum amount.value, select currency
OpenAIModel-->>Caller: {spend, currency}
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ 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. Comment |
|
Hi, @JinHai-CN , |
Haruko386
left a comment
There was a problem hiding this comment.
Hi @hunnyboy1217, Balance should be used to obtain the remaining amount, not to obtain how much amount has been used.
Let me know if I was wrong: OpenAI organization costs API
Address review on infiniflow#14876: Balance should report the remaining amount the account can spend, not the amount already consumed. The previous revision called GET /v1/organization/costs and summed month-to-date spend, which is the consumed amount. This commit switches to GET /v1/dashboard/billing/credit_grants and returns `total_available` (granted + prepaid - used) — the same semantic the DeepSeek and SiliconFlow drivers expose through their /user/balance endpoints. Side effects: - The admin-key (sk-admin-...) requirement is dropped; the credit grants endpoint accepts the same standard API key already wired through APIConfig.ApiKey for chat/embedding calls, so callers no longer need a separate admin key for `balance`. - The currency is now hardcoded to "USD". The credit grants endpoint does not return a currency field, and OpenAI bills exclusively in USD. - conf/models/openai.json url_suffix.balance switched from "organization/costs" to "dashboard/billing/credit_grants".
|
Thanks for catching this @Haruko386 — you're right, I had the semantic backwards. Just pushed f0c4aa4. The driver now calls A couple of things that fell out of the switch:
One thing worth flagging: |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 577-657: The Balance method currently calls the unsupported
/v1/dashboard/billing/credit_grants and must be replaced to call the official
/v1/organization/costs endpoint using an admin API key; update
OpenAIModel.Balance to (1) validate apiConfig.ApiKey has the admin prefix
(sk-admin-) and return an error if not, (2) build the URL using
z.baseURLForRegion(region) and z.URLSuffix.Balance (or replace that suffix with
the organization costs path), (3) perform the GET with z.httpClient and the same
timeout/headers, (4) parse the organization costs response shape (replace
openaiCreditGrantsResponse usage) to compute remaining credit or report
balance/currency in the existing map contract, and (5) keep existing error
handling for non-200 responses and JSON unmarshal failures but adjust messages
to reference the organization costs endpoint and admin key requirement.
🪄 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: 31c26e47-b5eb-41c4-8d2e-2b3cbc4b2b6b
📒 Files selected for processing (2)
conf/models/openai.jsoninternal/entity/models/openai.go
✅ Files skipped from review due to trivial changes (1)
- conf/models/openai.json
|
Hi, @Haruko386 , quick heads-up before I push again. CodeRabbit flagged my switch to The honest situation: OpenAI doesn't expose remaining balance anywhere public. That number only lives in the dashboard. Two reasonable options:
I'd lean toward (1), but happy to go either way — which do you prefer? |
Haruko386
left a comment
There was a problem hiding this comment.
Hi @hunnyboy1217, I have review your code and, based on my test:
RAGFlow(user)> create provider 'openai' instance 'test2' key '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'
SUCCESS
RAGFlow(user)> show balance from 'openai' 'test2'
CLI error: OpenAI balance API error: 403 Forbidden, body: {"error":"Your request to GET /v1/dashboard/billing/credit_grants must be made with a session key (that is, it can only be made from the browser). You made it with the following key type: secret."}
As I know, OpenAI already deprecated the legacy /dashboard/billing/credit_grants path for normal API usage. So I think the driver should not keep implementing the undocumented / browser-only credit_grants flow anymore.
Address review on infiniflow#14876: * coderabbitai (automated review) flagged that /v1/dashboard/billing/credit_grants is not a documented or supported API endpoint and recommended returning to the official /v1/organization/costs surface with admin-key validation. * Haruko386 reproduced the failure: requests to /v1/dashboard/billing/credit_grants are rejected with 403 and the message "must be made with a session key", confirming the legacy path is browser-session-only and unusable for API callers. This commit reverts f0c4aa4 (the credit_grants attempt) and restores the GET /v1/organization/costs implementation gated on an admin API key (sk-admin-...). Acknowledge the unresolved semantic raised by Haruko386: peer drivers expose Balance as remaining credit, but OpenAI does not publish a remaining-balance API. The doc comment on Balance() is expanded to state explicitly that this driver returns month-to-date spend (the only documented metric available), and to point at the next step: swap to a remaining-balance endpoint when OpenAI ships one. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address review on infiniflow#14876: * coderabbitai (automated review) flagged that /v1/dashboard/billing/credit_grants is not a documented or supported API endpoint and recommended returning to the official /v1/organization/costs surface with admin-key validation. * Haruko386 reproduced the failure: requests to /v1/dashboard/billing/credit_grants are rejected with 403 and the message "must be made with a session key", confirming the legacy path is browser-session-only and unusable for API callers. This commit reverts f0c4aa4 (the credit_grants attempt) and restores the GET /v1/organization/costs implementation gated on an admin API key (sk-admin-...). Acknowledge the unresolved semantic raised by Haruko386: peer drivers expose Balance as remaining credit, but OpenAI does not publish a remaining-balance API. The doc comment on Balance() is expanded to state explicitly that this driver returns month-to-date spend (the only documented metric available), and to point at the next step: swap to a remaining-balance endpoint when OpenAI ships one.
59904e3 to
bb6db00
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 593-610: The Balance method in internal/entity/models/openai.go
must not return month-to-date spend in the shared "balance" field; change
Balance to either (A) stop populating the shared balance shape and instead
return a clear unsupported error (e.g., return nil,
ErrUnsupportedBalanceForProvider) so callers don't display spend as remaining
credit, or (B) extend the returned contract to include a provider-specific
"spend" field and populate that instead of balance; implement one of these
approaches in the Balance function (and adjust any helper functions it calls) so
OpenAI spend is never exposed under the existing `balance` semantics.
🪄 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: 52275aa7-badd-4a4b-851e-efd3e4d2e42b
📒 Files selected for processing (2)
conf/models/openai.jsoninternal/entity/models/openai.go
✅ Files skipped from review due to trivial changes (1)
- conf/models/openai.json
Address review on infiniflow#14876 (Haruko386): peer drivers' Balance() returns the *remaining* spendable amount, but the OpenAI driver returns *already-spent* costs because OpenAI exposes no remaining-balance API to API callers. The previous comment did not flag this clearly. Expand the Balance() doc comment to: * state the spend-vs-remaining inversion explicitly * record why /v1/dashboard/billing/credit_grants is not used (browser-session-only, returns 403 to API keys), so future contributors do not re-attempt that path * leave a forward pointer: switch to a remaining-balance endpoint when OpenAI ships one No code change beyond the comment; the implementation remains the admin-key /v1/organization/costs path from 249e6a4.
645e47b to
113c57b
Compare
Replace the "no such method" stub in OpenAIModel.Balance with a real
implementation against the Organization Costs endpoint
(GET /v1/organization/costs), authenticated by an admin API key
(sk-admin-...). The legacy /v1/dashboard/billing/* endpoints are
intentionally not used: the documented /organization/* surface
requires admin keys, and the legacy /dashboard/billing/credit_grants
path is browser-session-only and rejects API keys with 403
(reproduced in review by Haruko386).
Return shape: {spend, currency} — deliberately diverges from the
{balance, currency} shape used by the DeepSeek (infiniflow#14632) and
SiliconFlow (infiniflow#14643) drivers. OpenAI exposes no remaining-balance
API to API callers, so labeling month-to-date spend as "balance"
would conflate opposite quantities (remaining vs consumed) under one
field name and silently mislead users. Raised in review on infiniflow#14876
by coderabbitai; the doc comment on Balance() records the rationale
and a forward path: emit "balance" alongside or instead of "spend"
once OpenAI ships a documented remaining-balance endpoint.
Fixes infiniflow#14874
113c57b to
83130bd
Compare
|
Hi, @Haruko386 , |
There was a problem hiding this comment.
♻️ Duplicate comments (1)
internal/entity/models/openai.go (1)
597-607:⚠️ Potential issue | 🟠 Major | ⚡ Quick winKeep the shared
balancecontract here.
Balance()is still wired into the provider-agnostic balance flow, so switching the payload to{"spend": ...}breaks the contract this PR is supposed to preserve and will misalign the CLI/output path that expects"balance". If you want to expose spend separately, that higher-level contract needs to change in the same PR; otherwise keep returning the established"balance"key here.Minimal contract-preserving fix
-// Return shape: {spend, currency}. Note this deliberately diverges -// from the {balance, currency} shape used by the DeepSeek and -// SiliconFlow drivers, because OpenAI does not expose a remaining- -// balance endpoint to API callers and we refuse to label spend as -// "balance" — those are opposite quantities and conflating them -// silently misleads users (raised in review on `#14876` by -// coderabbitai). The legacy /v1/dashboard/billing/credit_grants path -// is browser-session-only and rejects API keys with 403; the -// /v1/organization/* surface only exposes costs (consumption). When -// OpenAI ships a documented remaining-balance endpoint, switch to it -// and emit "balance" alongside (or instead of) "spend". +// Return shape: {balance, currency}. This preserves the shared driver +// contract used by the balance command until callers are widened to +// represent spend separately. return map[string]interface{}{ - "spend": total, + "balance": total, "currency": currency, }, nilAlso applies to: 690-693
🤖 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 597 - 607, The Balance() implementation in internal/entity/models/openai.go must preserve the shared "balance" contract instead of returning a {"spend": ...} payload; update the code paths in the Balance() function (and the related return at the other spot around the 690-693 region) to emit a JSON/object with key "balance" (and keep currency) so the provider-agnostic flow and CLI continue to receive "balance", while any internal or new "spend" value can be added separately if needed behind a contract change.
🤖 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.
Duplicate comments:
In `@internal/entity/models/openai.go`:
- Around line 597-607: The Balance() implementation in
internal/entity/models/openai.go must preserve the shared "balance" contract
instead of returning a {"spend": ...} payload; update the code paths in the
Balance() function (and the related return at the other spot around the 690-693
region) to emit a JSON/object with key "balance" (and keep currency) so the
provider-agnostic flow and CLI continue to receive "balance", while any internal
or new "spend" value can be added separately if needed behind a contract change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: a27f6197-7cdd-47dc-8cc8-182a832276cf
📒 Files selected for processing (2)
conf/models/openai.jsoninternal/entity/models/openai.go
✅ Files skipped from review due to trivial changes (1)
- conf/models/openai.json
|
Hi @Haruko386, thanks for testing this and for the push-back — you're right that Here's where I've landed after trying every endpoint:
The honest situation is that OpenAI just doesn't expose remaining balance through any public API — that number only lives in their dashboard. DeepSeek and SiliconFlow can return "remaining" because their APIs hand it over directly; OpenAI doesn't have an equivalent. So I think it comes down to two options, and I'd rather you decide than keep guessing:
I'm happy to go either way — just let me know which you'd prefer and I'll update the PR. |
|
@hunnyboy1217 Just leave it unimplemented is OK |
What problem does this PR solve?
Closes #14874.
OpenAIModel.Balance()in internal/entity/models/openai.go currently returnsnil, fmt.Errorf("no such method"), so thebalancecommand introduced in #14262 always fails against an OpenAI deployment even though it works for DeepSeek (#14632), SiliconFlow (#14643), and Moonshot.This PR replaces the stub with a real implementation against OpenAI's supported Organization Usage & Costs API:
GET https://api.openai.com/v1/organization/costs?start_time=<month-start-unix>&limit=31Authorization: Bearer <admin-api-key>(sk-admin-...).The legacy
/v1/dashboard/billing/subscriptionand/v1/dashboard/billing/credit_grantsendpoints are intentionally not used — they are deprecated, undocumented, and reject standard project API keys with401./v1/organization/*is the supported replacement and only accepts admin keys, so the driver fails fast with a clear error ("openai: admin api key (sk-admin-...) required for balance") when a project key is supplied, rather than producing a confusing upstream401.The return shape matches the existing
{balance, currency}contract used by DeepSeek (deepseek.go:569) and SiliconFlow (siliconflow.go:608) so the CLI from #14262 can render it without provider-specific code.balanceis the month-to-date spend (sum ofamount.valueacross the bucketed response) andcurrencyis uppercased from the first non-empty bucket (typicallyUSD).Scope:
Balancemirroring the DeepSeek/SiliconFlow pattern; uses the existingnonStreamCallTimeoutandbaseURLForRegionhelpers; adds a smallopenaiCostsResponsetype for the slim subset of the response we need."balance": "organization/costs"tourl_suffix, joined to the existinghttps://api.openai.com/v1base URL.Out of scope: no interface change, no DDL, no frontend change, no changes to chat/embedding/rerank paths.
APIConfigis unchanged — the existingApiKeyfield is reused and required to be an admin key for this command (documented via the error message).Type of change