Skip to content

Studio: allow max output overrides for custom providers - #8512

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
omjha3125-ctrl:fix/custom-provider-max-output-tokens
Aug 13, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
omjha3125-ctrl:fix/custom-provider-max-output-tokens

Conversation

@omjha3125-ctrl

@omjha3125-ctrl omjha3125-ctrl commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #8509

Custom OpenAI-compatible providers currently use Studio's conservative
32,768-token max-output fallback, with no way to configure a higher limit
for a specific Custom connection.

This PR adds an explicit per-connection Max Tokens override for generic
Custom providers.

Changes

  • Keep the existing 32,768 default when no override is configured.
  • Add an optional Max Tokens limit to generic Custom connections.
  • Persist the override with the provider connection.
  • Warn that unsupported values may cause the upstream request to fail.
  • Apply the override to the Max Tokens slider and outgoing request clamp.
  • Clamp live Max Tokens when the connection limit is lowered.
  • Clamp saved preset values to the active connection limit without modifying
    the saved preset itself.
  • Leave non-Custom provider capability behavior unchanged.

Backward compatibility

Existing Custom connections have no override stored, so they continue using
the existing 32,768-token fallback.

The override applies only to the generic custom provider type.

An existing studio.db gains the column through ALTER TABLE, so an install
that upgrades in place keeps its connections and reads the 32,768 fallback
until an override is set. A home written by this build stays readable and
writable by the previous release.

Testing

  • Targeted frontend tests: 14/14 passed
  • Full frontend suite: 2019/2019 passed
  • npm run typecheck
  • npm run build
  • Targeted backend provider tests: 61/61 passed
  • Context-recount regression tests: 53/53 passed
  • git diff --check
  • Manual Studio verification using deepseek-v4-flash

Manual verification

Verified with a Custom OpenAI-compatible connection:

  • blank override → Max Tokens defaults to 32,768
  • configured override → slider uses the configured value
  • override persists after reopening the connection
  • clearing the override returns to 32,768
  • saved high-token presets are clamped to the current connection limit
  • lowering the connection limit immediately updates the live Max Tokens value
  • real inference through the Custom endpoint completed successfully

Maintainer follow-up (danielhanchen)

Two commits on top of the above, from driving the feature end to end against
three isolated Studio builds: this PR's merge base, its head, and the head plus
these fixes.

1. Unrelated edits of a legacy Custom connection returned 400.
resolveUiProviderTypeFromConfig reports UI type custom for a row STORED as
openai with a custom display name or base URL, so the new field rendered for
those, and a blank field serialises as null rather than as an omission. The
backend keys the contract on the stored type, so it rejected the null and every
save failed, including a plain rename. The backend now accepts an explicit null
on any provider type, and the dialog decides from the stored type, carried on
ExternalProviderConfig.backendProviderType.

2. The clamping effect could silently lower and persist a configured value.
isExternalModel comes from the checkpoint string while the cap comes from the
resolved provider, and the two disagree whenever the provider is momentarily
unavailable: connections toggled off, a cold browser where settings hydrate
before the sync lands, a connection disabled while selected. The cap collapsed
to 32,768 and the effect wrote it through permanently. It now waits for
settingsHydrated and a resolved provider.

3. The Max Tokens limit field is a text input, not type="number". The HTML
value sanitization algorithm hands JavaScript an empty string for anything the
engine does not read as a valid floating-point number, and empty means "no
override" here. Measured in Firefox: typing a stray character wiped the saved
override and reported success. Chromium and WebKit kept the digits. The raw
string now reaches the existing validator.

Verified on Linux with chromium, firefox and webkit, covering Chrome, Edge,
Firefox and Safari's engine. Not covered: Safari and Edge as shipped products,
Windows and macOS hosts, real upstream inference.

Two things left open deliberately, both needing a maintainer decision rather
than a patch here:

  • The MAX_SAFE_INTEGER upper bound makes the slider unusable at the top of its
    range: at 2**53-1 one pixel is about 40 trillion tokens and an arrow press
    moves the thumb 0.0px. The number input still works. A rendered ceiling near
    1,048,576, with the input still accepting the full range, would be kinder.
  • stores/chat-runtime-store.ts setCheckpoint clamps and persists maxTokens
    with no hydration or provider-availability guard, so an unfound provider
    yields 32,768. Same hazard as item 2, but it predates this PR.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@Lyxot
Lyxot force-pushed the fix/custom-provider-max-output-tokens branch from fd61a3c to 576fe0d Compare August 12, 2026 08:58
@Lyxot

Lyxot commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

Thanks for your contribution! Unfortunately, this isn’t a complete long-term fix. Inferring the limit would require special configuration for every model and may also depend on the provider serving it.
A better approach may be to let users override the Max Tokens limit for custom providers, with a warning that unsupported values could cause the upstream request to fail.

@omjha3125-ctrl

Copy link
Copy Markdown
Contributor Author

Thanks, that makes sense. Inferring limits from model IDs is too brittle, especially for aliases and provider-specific deployments. I'll revise this PR to keep the 32K default for Custom providers and add an explicit user override with a warning for unsupported values.

@omjha3125-ctrl
omjha3125-ctrl force-pushed the fix/custom-provider-max-output-tokens branch from 576fe0d to 6d4a9ff Compare August 12, 2026 14:25
@omjha3125-ctrl omjha3125-ctrl changed the title Studio: infer max output caps for known models on custom providers Studio: allow max output overrides for custom providers Aug 12, 2026
@omjha3125-ctrl

omjha3125-ctrl commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for your contribution! Unfortunately, this isn’t a complete long-term fix. Inferring the limit would require special configuration for every model and may also depend on the provider serving it. A better approach may be to let users override the Max Tokens limit for custom providers, with a warning that unsupported values could cause the upstream request to fail.

Thanks for the direction. I've revised the PR to use an explicit per-connection Max Tokens override for generic Custom providers instead of inferring limits from model IDs.

The 32,768 fallback remains the default when no override is configured, and Studio warns that unsupported values may be rejected by the upstream provider.

I also added persistence, runtime clamping, preset handling, regression coverage, and manual Studio verification. The previous model-family inference has been removed completely.

@danielhanchen

Copy link
Copy Markdown
Member

Thanks for reworking this, the explicit per-connection override is the right shape.

I built Studio twice, once at this PR's merge base 6d4a9ff4b and once at head b607a4c19, and drove the same flow against both. A Custom OpenAI-compatible connection was created over the REST API with max_output_tokens: 384000 and a single model deepseek-v4-flash, matching the report in #8509.

Settings, Connections, the Custom connection

connection form

Chat, run settings, Max Tokens pushed to its ceiling

max tokens ceiling

Numbers read from the same servers that were photographed:

base 6d4a9ff4b head b607a4c19
GET /api/providers/ -> max_output_tokens null 384000
Max Tokens slider aria-valuemax 32768 384000
Max Tokens after pressing End 32768 384000
Max Tokens limit field in the form absent present

The feature works as described. Two things I would like fixed before this lands.


1. Blocking: every save of a connection Studio shows as Custom, but stores as openai, now fails

resolveUiProviderTypeFromConfig (sync-external-providers.ts:47) maps a backend row with provider_type = "openai" and a non-default display name or base URL back to UI type custom. That covers connections created before generic Custom started storing provider_type = "custom", and any OpenAI connection pointed at a non-default base URL. The dialog renders the new field for those rows, because editProvider sets providerType from the UI type.

parseMaxOutputTokens("") returns null rather than undefined (chat-providers-dialog.tsx:471), so providers-api.ts:213 still emits the key, so model_fields_set contains it. The backend then validates the stored type (routes/providers.py:113) and rejects.

Reproduced on the head build, first over the API:

POST /api/providers/  {"provider_type": "openai", "display_name": "My OpenAI-compatible box",
                       "base_url": "https://example.com/v1", ...}   -> 201

PUT  /api/providers/{id} {"display_name": "Renamed", "max_output_tokens": null}
  -> 400 {"detail":"Max Tokens limit can only be overridden for generic Custom providers."}

PUT  /api/providers/{id} {"display_name": "Renamed2"}
  -> 200

and then in the browser: opening that connection in Settings, Connections shows the Max Tokens limit field with a blank value, and clicking Save connection without touching anything raises

Failed to update connection: Max Tokens limit can only be overridden for generic Custom providers.

So renaming, changing the model list and rotating the API key are all blocked on those connections, with an error about a field the user never touched. test_known_provider_rejects_max_output_override_update asserts the backend half of this, so the suite stays green.

Two changes needed:

  • routes/providers.py:113, only reject a non-null value:
    def _validate_max_output_tokens_contract(provider_type, field_was_set, value):
        if field_was_set and value is not None and provider_type != "custom":
            raise HTTPException(...)
    An explicit null on a non-custom provider is a no-op and should not fail the request.
  • In the dialog, gate the field and the payload on the backend provider type rather than the UI one. sync-external-providers.ts:228 already has config.provider_type in hand and could carry it on ExternalProviderConfig.

2. Blocking: the new clamp effect can silently lower and persist a saved Max Tokens

chat-settings-sheet.tsx:764 guards on isExternalModel, which comes only from inferenceParams.checkpoint, while maxTokensMax comes from activeExternalProvider. Whenever those two disagree the cap falls back to 32768 and the effect writes the lower value through onParamsChange, which persists it. Nothing raises it again when the provider reappears.

Reachable at least three ways:

  • Connections toggled off. externalProvidersForChat becomes [] (chat-page.tsx:1885) while the checkpoint is still external. React flushes the child effect before the parent effect that clears the checkpoint, so the clamp runs first.
  • A cold browser or a second device, where settings hydrate before syncExternalProvidersFromBackend resolves.
  • The provider being disabled or deleted while selected.

The effect is also not gated on settingsHydrated, unlike applyPreset next to it, and setParams bumps the settings version unconditionally, so a pre-hydration write wins over the value coming back from the server. Since the whole point of this PR is to let a user set 131072 or 384000 and keep it, this one bites the feature itself.

useEffect(() => {
  if (!settingsHydrated) return;
  if (!isExternalModel || activeExternalProvider == null) return;
  if (params.maxTokens <= maxTokensMax) return;
  ...
}, [..., settingsHydrated, activeExternalProvider]);

The activeExternalProvider != null check is the important half. For the record there is no render loop here, the guard is idempotent and the dependency array is complete.

Smaller things

  • le = MAX_JSON_SAFE_INTEGER (models/providers.py:66) flows straight into <ParamSlider max={maxTokensMax} step={64}>. With a very large override one pixel of slider travel is billions of tokens and the control stops being usable. A ceiling of 1048576 would still cover DeepSeek's 384000, the largest cap in the existing table.
  • The auto-clamp flips activePresetSource to "modified" with no user action, which reads a little oddly beside "clamp saved preset values without modifying the saved preset itself".
  • Visible in the second screenshot: the Max Tokens number input is four characters wide, so a six-digit ceiling renders clipped as 38400(. Pre-existing, but this PR is what makes six-digit values reachable.

Confirmed correct, no need to look again

  • The sqlite migration. ALTER TABLE llm_providers ADD COLUMN max_output_tokens INTEGER is guarded on PRAGMA table_info, runs for existing homes as well as new ones, and is idempotent.
  • Omitted versus explicit null on update. The _UNSET sentinel in update_provider does the right thing, an unrelated update preserves the override, and clearing back to blank works.
  • undefined meaning "key omitted" in providers-api.ts.
  • The override cannot leak to named providers, the early return is keyed on the provider type and normalizeCustomMaxOutputTokens re-checks it.
  • All three cap consumers updated, including the outgoing request clamp in chat-adapter.ts.
  • maxOutputTokens survives a reload and is not dropped anywhere in the sync path.

@danielhanchen

danielhanchen commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

I pushed two commits fixing the two items above, plus a third issue that only appears in one browser engine. Details are in the PR description now, so this is the evidence behind them.

Firefox silently wiped a saved override. The field was an <input type="number">, and per the HTML value sanitization algorithm a number input whose contents are not a valid floating-point number hands JavaScript an empty string. Blank means "clear the override" here. Measured by typing into the built UI and saving:

typed Chromium Firefox WebKit
384000abc keeps 384000 wiped to null, toast said "Connection updated." keeps 384000
384000 keeps 384000 wiped keeps 384000

With a text input, all three engines reject every bad case with a reason and leave the stored value alone: 0 silent wipes out of 7 inputs (384000abc, 384000 , 131,072, 1e5, -5, 12.5, a 17-digit number) in each engine.

Upgrade and downgrade, 37/37 checks. A home built and populated by the pre-PR build, upgraded in place to this code: boots, the existing password still authenticates, the ALTER TABLE lands, all four pre-existing connections list with their models intact, their cap reads the 32,768 fallback, and setting an override afterwards works. The same home reopened by the pre-PR build still lists, edits and creates, with no traceback and no console errors, and the override survives an old-build update. Worth knowing: the migration is lazy, running on the first request that touches studio.db rather than at boot, so reading the schema straight after login looks like a failed migration when it is not.

Both regressions, before and after. On this branch before the fixes, opening a connection stored as openai but displayed as Custom and pressing Save untouched raised Failed to update connection: Max Tokens limit can only be overridden for generic Custom providers. After, the row is correctly hidden for that connection and the save succeeds, while a genuine custom connection still shows it. For the clamp: set 384000, toggle Connections off and on, read back. Before the fixes 384000 becomes 32768; after, it stays 384000.

Tests. 61 backend and 2019 frontend passing, typecheck and build clean. I also updated test_known_and_custom_preset_providers_reject_max_output_override, which pinned the old behaviour by asserting a null is rejected; it now pins "reject only a non-null value", with two tests asserting an explicit null is accepted on create and on update.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@omjha3125-ctrl

Copy link
Copy Markdown
Contributor Author

Thanks for the fixes and the thorough verification. I've synced the two commits locally as well. I also see the new Codex note about preset clamping before the active provider resolves; I'll hold off on further changes unless you'd like me to address it.

…edits

Three problems found while driving the override end to end against isolated
Studio builds.

1. Every save of a connection Studio DISPLAYS as Custom but STORES as `openai`
   returned 400. `resolveUiProviderTypeFromConfig` maps a row saved as `openai`
   with a custom display name or base URL back to UI type `custom`, so the new
   Max Tokens limit row rendered for it, and `parseMaxOutputTokens("")` returns
   null rather than undefined, so the key was still sent and the backend, which
   keys the contract on the STORED type, rejected it. A plain rename, a model
   change or a key rotation all failed with an error about a field the user
   never touched. The backend now accepts an explicit null on any provider type
   (clearing an override that cannot exist is a no-op) and the dialog decides
   from the stored type, carried on `ExternalProviderConfig.backendProviderType`.

2. The new clamping effect could silently lower and PERSIST a configured Max
   Tokens. `isExternalModel` comes from the checkpoint string while the cap comes
   from the resolved provider, and the two disagree whenever the provider is
   momentarily unavailable: connections toggled off, a cold browser where
   settings hydrate before the provider sync lands, or a connection disabled
   while selected. The cap then collapsed to the 32,768 fallback and the effect
   wrote it through, permanently, which defeats the feature it belongs to. It now
   waits for `settingsHydrated` and a resolved provider: no provider means the cap
   is unknown, not 32,768.

3. The Max Tokens limit field is a text input rather than `type="number"`. The
   HTML value sanitization algorithm replaces anything the engine does not read
   as a valid floating-point number with the empty string, and empty means "no
   override" here, so a grouped entry like "131,072" left the box looking filled
   and silently cleared the saved override. Observed in Firefox, where a stray
   character reported "" and the save reported success; Chromium and WebKit kept
   the digits. The raw string now reaches the existing validator, which rejects
   it with a reason. This matches NumericValueInput in the run-settings panel.

The two decisions are pure functions, `supportsCustomMaxOutputTokens` and
`resolveExternalMaxTokensClamp`, so they can be tested without a DOM.
…aths

Backend: an existing studio.db written before this column exists, opened by this
build and then opened AGAIN by a build that has never heard of the column, which
is what reverting to the previous release does; migration idempotence, since
ALTER TABLE has no IF NOT EXISTS; the route contract per provider type, where an
explicit null has to be accepted everywhere and a real override still refused
outside generic Custom; the set, preserve and clear lifecycle asserted against
the stored row; exact round-tripping at the top of the accepted range; and the
metadata rollback when a credential write fails.

`test_credential_routes.py`: the test that pinned "reject the field on any
non-custom provider" now pins "reject only a non-null value", plus two tests
asserting an explicit null is accepted on create and on update.

Frontend: the stored-versus-displayed provider type truth table including the
unknown-type fallback, normalization of anything an older localStorage entry
could hold, a golden slice of the capability table proving no named provider's
cap moved, the clamp guards, and a pre-feature entry loading without gaining a
cap.

Verified against three isolated installs (merge base, this branch before these
fixes, and after) on Linux with chromium, firefox and webkit, which covers
Chrome, Edge, Firefox and Safari's engine. An old home upgraded in place keeps
its connections, migrates its schema and reads the 32,768 fallback; the same home
opened again by the previous build still lists, edits and creates.
@danielhanchen
danielhanchen force-pushed the fix/custom-provider-max-output-tokens branch from 0f5982e to 67efd37 Compare August 13, 2026 07:27
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ider

Two more places applied a cap derived from provider data that may not be there
yet, and both only ever lower, so a blink in the provider list cost the user
their configured value permanently.

`applyPresetParamsWithinCurrentLimits` was gated on `isExternalModel` alone, so
applying or falling back to a preset while the connection was unresolved wrote
the 32,768 fallback into the live params.

`setCheckpoint` looked the provider up and clamped whether or not it found one,
so a checkpoint restored or selected before the provider store hydrated read the
fallback instead of the connection's cap. That path predates this feature, but
the override is what gives it something to destroy: without one, a Custom
connection could never exceed 32,768 and the clamp was a no-op.

Both now take the rule the settings-panel effect already uses: no provider means
the cap is unknown, not 32,768.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 1400a8fadd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 5ba89d1a03

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Re-shot the before/after evidence at the current head after this round's fixes, so the pair matches what is actually on the branch now rather than the state I first photographed.

Merge base 6d4a9ff4b against head 5ba89d1a0, two isolated installs, same scene both sides.

connection form

max tokens ceiling

Same numbers as before, read from the photographed servers: max_output_tokens null to 384000, slider aria-valuemax 32768 to 384000, and the value at the ceiling 32768 to 384000. That is the point of re-shooting: the three fixes landed this round did not disturb the visible feature. The Max Tokens limit field is a text input now rather than type="number", which looks identical and is exactly why it needed a test rather than a screenshot.

Cross-platform staging CI on this head: ubuntu-latest, macos-14 and windows-latest all green, plus the studio-live Playwright job across chromium, firefox and webkit. Two failures on the sibling staging branch are unrelated to this change and pass on the branch that carries the same code: a process-kill timing test in test_local_llama_cpp_link.py (1 failed of 23050) and a Voice-tab wheel-scroll assertion. Both re-running to confirm.

`max_output_tokens: int | None | object = _UNSET` is the module's first PEP 604
annotation, and annotations evaluate at def time, so the module stopped importing
on 3.9 while pyproject still declares >=3.9. tests/test_python39_compatibility.py
enforces this with a debt counter and caught it at 36 files, up from 35.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from omjha3125-ctrl Aug 13, 2026
@unslothai unslothai deleted a comment from Lyxot Aug 13, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 0c73a5f0ed

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 5e184f5 into unslothai:main Aug 13, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Studio custom OpenAI-compatible providers fall back to 32K max output even for known model families

3 participants