Skip to content

Studio: expose Anthropic / OpenAI sampling knobs per provider - #5711

Closed
danielhanchen wants to merge 62 commits into
mainfrom
feat/expose-sampling-params-core
Closed

danielhanchen wants to merge 62 commits into
mainfrom
feat/expose-sampling-params-core

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Studio's chat settings sheet only exposed seven sampling knobs (temperature, top_p, top_k, min_p, repetition_penalty, presence_penalty, max_tokens). The Anthropic Messages API and the two OpenAI endpoints (Chat Completions and Responses) accept a much larger surface; this PR ships the first batch of the missing ones, gated per provider so the picker never offers a field the upstream would 400 on.

What lands

Knob Anthropic OpenAI Chat OpenAI Responses
frequencyPenalty dropped YES (-2..2) dropped (rejected upstream)
seed dropped YES (int) dropped (rejected upstream)
stop YES (as stop_sequences) YES (truncated to 4) dropped (rejected upstream)
serviceTier YES (auto / standard_only) YES (auto / default / flex / priority / scale) YES (auto / default / flex / priority)
parallelToolCalls YES (inverted to disable_parallel_tool_use) YES (default true) YES (default true)

text.verbosity, response_format (JSON mode), logprobs / top_logprobs, and safety_identifier / metadata.user_id are out of scope here and will land in a follow-up PR per plans/hashed-riding-porcupine.md.

Implementation

  • frontend/src/features/chat/types/runtime.ts extends InferenceParams and DEFAULT_INFERENCE_PARAMS. PersistedInferenceParams = Partial<Omit<InferenceParams, \"checkpoint\">> picks them up automatically so they round-trip through the chat-settings server store.
  • frontend/src/features/chat/stores/chat-runtime-store.ts extends PERSISTED_INFERENCE_PARAM_KEYS so the new fields participate in getChangedInferenceParams / getHydratedSettingsState.
  • frontend/src/features/chat/provider-capabilities.ts extends ProviderCapabilities with per-knob booleans, populates per-provider rows, and adds getServiceTierOptions(providerType) for the enum-set resolver.
  • frontend/src/features/chat/api/chat-adapter.ts adds conditional-spread rows on the external path gated on the new capability flags, and unconditional pass-through on the local path.
  • frontend/src/features/chat/chat-settings-sheet.tsx adds show* derivations + rendering rows: ParamSlider for frequency penalty, plain Input for seed, the new StopSequencesInput chips component for stop sequences, Select for service tier, Switch for parallel tool calls. Each gates on the corresponding capability flag and stays hidden when not supported.
  • New components/ui/stop-sequences-input.tsx chips editor: type, press Enter or comma to commit a chip, backspace to delete the last one. Caps at 4 on OpenAI Chat / 16 on Anthropic per docs.
  • backend/models/inference.py extends ChatCompletionRequest with the new typed fields (Field(ge=, le=) for the range, Literal[...] for the service-tier enum). extra=\"allow\" is preserved so old clients still validate.
  • backend/routes/inference.py:1854 threads the new fields into the existing client.stream_chat_completion(...) call.
  • backend/core/inference/external_provider.py:
    • stream_chat_completion accepts the new kwargs and forwards them to the per-provider helpers.
    • _stream_anthropic translates stop to stop_sequences, only accepts auto / standard_only for service_tier, and inverts parallel_tool_calls=false to disable_parallel_tool_use=true. Anthropic-incompatible kwargs (frequency_penalty, seed) never reach this function.
    • _stream_openai_responses accepts service_tier (only auto|default|flex|priority) and parallel_tool_calls. Everything else Responses rejects (frequency_penalty, seed, stop) is silently dropped at the dispatch layer.
    • Default OpenAI-compat branch forwards every new field, truncating stop to 4 entries with a logged warning if longer, omitting empty arrays.

Test plan

  • 30 new tests in backend/tests/test_sampling_params_routing.py pinning the per-provider routing contract (every field reaches the body only when the upstream accepts it, translations and inversions stay correct, schema-level validation works).
  • 143 existing tests across test_anthropic_cache_ttl.py, test_anthropic_compaction.py, test_openai_compaction.py, test_anthropic_messages.py, test_openai_responses_translation.py, test_openai_image_generation.py pass with no regressions.
  • Frontend type-check clean (npx tsc -b --pretty false).
  • Manual end-to-end: connect Anthropic + OpenAI + a local llama.cpp, confirm the right rows appear / hide per provider, confirm outbound bodies carry the expected fields when set.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a12b48f2c0

ℹ️ 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".

Comment on lines +84 to +86
if (providerType === "openai") {
return ["auto", "default", "flex", "priority", "scale"] as const;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Drop scale from OpenAI service-tier choices

The OpenAI provider in this codebase is routed through /v1/responses, but this option list still exposes scale, which _stream_openai_responses explicitly does not forward (it only accepts auto|default|flex|priority). That means users can select scale in the UI and think it is applied, while the backend silently drops it, making service-tier selection misleading for OpenAI runs.

Useful? React with 👍 / 👎.

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces several new sampling parameters—frequency penalty, seed, stop sequences, service tier, and parallel tool calls—across the backend and frontend. The changes include updating the inference models, routing logic for different providers (OpenAI, Anthropic), and adding a new UI component for managing stop sequences. Feedback focuses on improving the robustness of stop sequence handling in the backend by deduplicating and filtering entries, as well as enhancing the accessibility and stability of the new frontend components through better ARIA labeling and React key management.

Comment on lines +468 to +483
if stop is not None:
# OpenAI Chat caps the list at 4 entries. Truncate with a
# warning rather than letting the upstream 400; users editing
# chips in the picker shouldn't get a cryptic API error.
if isinstance(stop, list) and len(stop) > 4:
logger.warning(
"stop sequences truncated to 4 entries "
"(received %d, OpenAI's hard cap is 4)",
len(stop),
)
body["stop"] = stop[:4]
elif isinstance(stop, list) and len(stop) == 0:
# Empty list = unset; don't ship `stop: []`.
pass
else:
body["stop"] = stop

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.

medium

The stop sequence handling for the OpenAI-compatible branch should be more robust. It currently allows empty strings and duplicate entries in the list, which most upstream APIs reject or ignore. Additionally, if stop is an empty string, it is still forwarded.

Consider filtering empty strings, deduplicating the list, and omitting the field if the resulting value is empty.

Suggested change
if stop is not None:
# OpenAI Chat caps the list at 4 entries. Truncate with a
# warning rather than letting the upstream 400; users editing
# chips in the picker shouldn't get a cryptic API error.
if isinstance(stop, list) and len(stop) > 4:
logger.warning(
"stop sequences truncated to 4 entries "
"(received %d, OpenAI's hard cap is 4)",
len(stop),
)
body["stop"] = stop[:4]
elif isinstance(stop, list) and len(stop) == 0:
# Empty list = unset; don't ship `stop: []`.
pass
else:
body["stop"] = stop
if stop:
if isinstance(stop, str):
body["stop"] = stop
elif isinstance(stop, list):
# Filter empty/non-string entries and deduplicate while preserving order
sequences = list(dict.fromkeys(s for s in stop if isinstance(s, str) and s))
if sequences:
if len(sequences) > 4:
logger.warning(
"stop sequences truncated to 4 entries "
"(received %d, OpenAI's hard cap is 4)",
len(sequences),
)
body["stop"] = sequences[:4]
else:
body["stop"] = sequences
References
  1. When proxying chat completions to multiple LLM providers, always check for OpenAI compatibility and route to provider-specific implementations if the standard endpoint is not supported.

Comment on lines +1411 to +1418
if stop is not None:
sequences: list[str]
if isinstance(stop, str):
sequences = [stop] if stop else []
else:
sequences = [s for s in stop if isinstance(s, str) and s]
if sequences:
body["stop_sequences"] = sequences

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.

medium

Similar to the OpenAI branch, the Anthropic stop_sequences logic should deduplicate entries and enforce the documented hard cap (16 entries for Anthropic Messages API) to prevent unnecessary 400 errors from the upstream provider.

Suggested change
if stop is not None:
sequences: list[str]
if isinstance(stop, str):
sequences = [stop] if stop else []
else:
sequences = [s for s in stop if isinstance(s, str) and s]
if sequences:
body["stop_sequences"] = sequences
if stop:
sequences: list[str]
if isinstance(stop, str):
sequences = [stop]
else:
# Filter empty/non-string entries and deduplicate while preserving order
sequences = list(dict.fromkeys(s for s in stop if isinstance(s, str) and s))
if sequences:
if len(sequences) > 16:
logger.warning(
"stop sequences truncated to 16 entries "
"(received %d, Anthropic's hard cap is 16)",
len(sequences),
)
body["stop_sequences"] = sequences[:16]
else:
body["stop_sequences"] = sequences
References
  1. Route to provider-specific implementations for providers like Anthropic when standard OpenAI compatibility is not sufficient.

// Stop sequences are not guaranteed unique across edits (the
// user could enter "END" twice if the previous one was just
// deleted), so combine value + index for a stable key.
key={`${entry}-${index}`}

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.

medium

Using index in the React key is generally discouraged as it can cause unnecessary re-renders or component re-mounting when items are removed from the middle of the list. Since the commitDraft function already prevents duplicate entries, the entry value itself is guaranteed to be unique and is a more stable key.

Suggested change
key={`${entry}-${index}`}
key={entry}

Comment on lines +103 to +114
<Input
value={draft}
onChange={(event) => setDraft(event.target.value)}
onKeyDown={handleKeyDown}
onBlur={commitDraft}
placeholder={atCap ? `Max ${maxEntries} stops` : placeholder}
disabled={disabled || atCap}
className={cn(
"h-6 min-w-[8ch] flex-1 border-0 bg-transparent p-0 text-sm shadow-none",
"focus-visible:ring-0 focus-visible:border-0",
)}
/>

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.

medium

The internal Input component should have an aria-label to ensure accessibility for screen reader users, especially since it is part of a custom composite component.

      <Input
        value={draft}
        onChange={(event) => setDraft(event.target.value)}
        onKeyDown={handleKeyDown}
        onBlur={commitDraft}
        placeholder={atCap ? "Max " + maxEntries + " stops" : placeholder}
        disabled={disabled || atCap}
        aria-label={ariaLabel || placeholder}
        className={cn(
          "h-6 min-w-[8ch] flex-1 border-0 bg-transparent p-0 text-sm shadow-none",
          "focus-visible:ring-0 focus-visible:border-0",
        )}
      />
References
  1. Ensure accessibility for UI elements by providing appropriate ARIA attributes and keyboard handlers.

Comment on lines +1409 to +1413
aria-label={
params.parallelToolCalls
? "Disable parallel tool calls"
: "Enable parallel tool calls"
}

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.

medium

The aria-label on the Switch component should describe the setting itself rather than the action of the toggle. Screen readers already announce the state (checked/unchecked), so dynamic labels like "Enable/Disable" can be redundant or confusing. Using a static label matching the field name is more standard.

                  aria-label="Parallel tool calls"
References
  1. Maintain accessibility standards by using descriptive, static labels for interactive UI components.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2eb685283b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +1533 to +1536
...(params.frequencyPenalty !== 0
? { frequency_penalty: params.frequencyPenalty }
: {}),
...(params.seed !== null ? { seed: params.seed } : {}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Route local seed/frequency_penalty to llama passthrough

frequency_penalty and seed are now sent on the local request path, but the backend passthrough builder (_build_openai_passthrough_body → _build_passthrough_payload in studio/backend/routes/inference.py) does not forward either field, so both controls are silently ignored for local runs. This makes reproducibility and repetition tuning appear configurable in the UI while having no effect on generated output.

Useful? React with 👍 / 👎.

Comment on lines +1538 to +1539
...(params.parallelToolCalls === false
? { parallel_tool_calls: false }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Remove unsupported local parallel_tool_calls toggle

The local adapter now sends parallel_tool_calls: false, but the backend local passthrough path does not propagate this field to llama-server, so toggling this switch has no runtime effect for local models. Users can disable the setting in the panel and still get identical behavior, which is misleading for tool-calling workflows.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 38aa48655f

ℹ️ 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".

// OpenAI Chat docs cap `stop` at 4 entries; Anthropic accepts more.
// Pick the right ceiling per active connection so the chips editor's
// placeholder doesn't lie.
const stopMaxEntries = externalProviderType === "anthropic" ? 16 : 4;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid capping stop sequences to 4 for local/non-OpenAI backends

This cap applies to every non-Anthropic session (externalProviderType !== "anthropic"), including local models, so the new stop-sequence UI blocks users from entering more than 4 stops even though the local request path forwards stop verbatim (chat-adapter.ts) and backend passthrough does not enforce that limit. In practice this means valid local/OpenAI-compatible configurations are now impossible to express from the settings panel, which can break experiments that rely on larger stop lists.

Useful? React with 👍 / 👎.

danielhanchen and others added 5 commits May 23, 2026 15:33
Adds the missing sampling parameters that the upstream APIs accept and
that Studio's chat UI previously hid. Each knob is gated per provider
so the picker never offers a field the upstream would 400 on, and the
per-provider stream functions translate / drop fields to match each
API's naming.

New `InferenceParams` fields (round-trip through PersistedInferenceParams
and the chat-settings server store automatically):

- frequencyPenalty (-2..2): OpenAI Chat Completions only.
- seed (int | null): OpenAI Chat + OpenAI-compat local backends.
- stop (string[]): all OpenAI Chat + Anthropic Messages. Backend
  truncates to 4 entries on OpenAI Chat per docs and renames to
  `stop_sequences` on Anthropic.
- serviceTier (auto|default|flex|priority|scale|standard_only):
  per-provider enum sets resolved by getServiceTierOptions.
- parallelToolCalls (bool, default true): forwarded as
  `parallel_tool_calls` on both OpenAI APIs and inverted into
  `disable_parallel_tool_use` on Anthropic.

OpenAI Responses (gpt-5.x / o3) explicitly drops frequencyPenalty /
seed / stop alongside the existing temperature / top_p drop, since
the upstream 400s on all of them. service_tier on Responses accepts a
subset (no `scale`) which the dispatch already enforces.

UI rows land in the existing Sampling section of the chat settings
sheet using ParamSlider (frequency penalty), a numeric Input (seed),
a new chips editor `StopSequencesInput` (stop), Select (service tier),
and Switch (parallel tool calls). Each row's visibility follows the
new ProviderCapabilities flag.

Tests pin the gating contract: stop_sequences renamed on Anthropic,
4-entry truncation on OpenAI Chat, every Responses-rejected field
dropped, schema-level validation for the service_tier Literal and
frequency_penalty range.

Plan: plans/hashed-riding-porcupine.md
- Drop `scale` from the OpenAI service-tier picker (frontend types and
  picker option list). OpenAI in Studio routes through `/v1/responses`,
  which does not accept `scale`; offering it in the UI silently
  dropped the value at the backend and misled users into thinking
  their selection was applied. Backend Literal still accepts it on
  input so stale clients are not 422'd, and `_stream_openai_responses`
  continues to drop it from the wire body.
- Dedupe + drop empty entries for OpenAI Chat `stop` and Anthropic
  `stop_sequences` before forwarding so whitespace chips or accidental
  repeats do not waste the 4-entry OpenAI cap or the 16-entry
  Anthropic cap. Anthropic over-cap now logs and truncates, matching
  the OpenAI path.
- Static `aria-label="Parallel tool calls"` on the Switch; screen
  readers already announce checked / unchecked state, so the dynamic
  Enable/Disable label was redundant.
- Forward an `aria-label` onto the inner Input inside
  `StopSequencesInput` so screen-reader users can identify the field.
- Regression tests covering the new dedup, truncation, and the
  preserved silent-drop of `scale` on Responses.
…_accepted

This PR promoted frequency_penalty and seed from undeclared
chat-completion extras into explicit ChatCompletionRequest fields,
so they ride the attribute path now, not model_extra. The test
still asserted both via model_extra and failed on Linux Python
3.10-3.13 with 'assert None == 0.5'. response_format stays in
model_extra (still undeclared) so the extra='allow' contract is
covered by that branch.
@danielhanchen
danielhanchen force-pushed the feat/expose-sampling-params-core branch from 38aa486 to eefe40a Compare May 23, 2026 15:33

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: eefe40a6bf

ℹ️ 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".

Comment on lines +376 to +380
"frequencyPenalty",
"seed",
"stop",
"serviceTier",
"parallelToolCalls",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Persist new inference keys through settings sanitizer

Adding frequencyPenalty, seed, stop, serviceTier, and parallelToolCalls to persisted runtime keys here does not actually make them durable, because the save/load path still runs through sanitizeInferenceParams in studio/frontend/src/features/chat/utils/chat-settings-storage.ts, which only whitelists the older numeric fields plus systemPrompt/trustRemoteCode. As a result, savePersistedChatSettingsPatch strips these new keys before writing, and hydration drops them on reload, so users will lose these settings between sessions.

Useful? React with 👍 / 👎.

danielhanchen and others added 6 commits May 23, 2026 16:37
Codex P1: the runtime store added frequencyPenalty, seed, stop,
serviceTier, parallelToolCalls but the save/load path went through
sanitizeInferenceParams, which only whitelisted the older numeric set
plus systemPrompt / trustRemoteCode. The new keys were silently
stripped on save and dropped on reload.

Extend the whitelist:
- frequencyPenalty added to the numeric finite-number set.
- seed: integer or explicit null (null = "no seed field on the wire").
- stop: string array, capped at 4 entries per OpenAI's limit.
- serviceTier: nullable enum (auto/default/flex/priority/scale).
- parallelToolCalls: boolean.
…stence

Anthropic Messages API rejects `disable_parallel_tool_use` as a
top-level field; it is only accepted as a property on the `tool_choice`
object. Move the inversion into a tool_choice merge that defaults to
`{type:"auto"}` when no choice is supplied, and skip the field entirely
when no tools are defined (it is a no-op without tools).

The same path also dropped `stop` chips that contain only whitespace,
because Anthropic 400s with `each stop sequence must contain
non-whitespace` on entries like " ", "\n", and "\n\n". The previous
filter only dropped truly empty strings; switch to `s.strip()` so the
common newline-stop defaults are also filtered out client-side.

Frontend persistence had three round-trip data-loss bugs:

  - `VALID_SERVICE_TIERS` was missing `standard_only`, so any Anthropic
    user who picked that tier lost it on the next reload.
  - The settings sanitizer truncated `stop` to 4 entries on save,
    which defeated the Anthropic UI cap of 16. Use 16 here and let the
    per-provider stream helper cap to the wire's allowed length.
  - The chat-settings sheet's `stopMaxEntries` capped local backends
    (llama.cpp / vLLM / ollama / generic OpenAI-compat) at 4 even
    though those backends happily accept more. Match Anthropic's 16
    for the local path.

Preset policy now carries `frequencyPenalty` and `stop` so a saved
preset can fix a user's preferred decoding style. `seed`,
`serviceTier`, and `parallelToolCalls` stay out of presets because
they are per-request determinism / per-provider account / per-tool
state, not reusable preset values.

Drops the test that pinned the buggy top-level placement of
`disable_parallel_tool_use` and adds two tests for the nested shape
plus the without-tools skip path, plus a test pinning the
whitespace-stop filter against the documented Anthropic error.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3ef64c2d65

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +41 to +42
const trimmed = draft.trim();
if (!trimmed) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve whitespace in stop sequence chips

The stop-sequence editor normalizes every entry with trim() before storing it, which changes the literal sequence sent to the backend. This breaks valid configurations where leading/trailing whitespace is intentional (for example delimiters that include spaces or pasted newline boundaries), because the request no longer contains the exact stop string the user entered. Since stop matching is exact-substring based, this can cause generations to continue past the intended boundary.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits May 24, 2026 12:45
Round-2 round of review-feedback fixes for the sampling-knobs PR:

- studio/backend/routes/chat_history.py: ChatInferenceSettings still had
  the pre-PR field list with extra="forbid", so every settings save the
  new frontend issued would 422 on the new keys (frequencyPenalty,
  seed, stop, serviceTier, parallelToolCalls). Add the fields with the
  same range / enum constraints the chat-completions schema uses, so
  the settings-persistence path round-trips cleanly.

- studio/backend/routes/inference.py: _build_passthrough_payload and
  _build_openai_passthrough_body now thread frequency_penalty, seed,
  and parallel_tool_calls through to llama-server. The frontend exposes
  these knobs for local backends; without the forwarding the UI was a
  decoration. Each field is gated on `is not None` so 0 / False / "0"
  still reach the body.

- studio/backend/core/inference/external_provider.py: the Kimi
  $web_search bypass takes an early return into _stream_kimi_web_search
  before the default OAI-compat body builder runs, so the new sampling
  fields never landed on Kimi-with-search. Forward them through the
  helper, with the same dedupe / truncate behavior the main path
  applies to `stop`. Also extend the OpenAI Responses service_tier
  allowlist to include `scale` per the live openai-python SDK
  (response_create_params.py declares
  Literal["auto","default","flex","scale","priority"]).

- studio/frontend/src/features/chat/provider-capabilities.ts +
  types/runtime.ts: add `scale` to ServiceTier / ServiceTierOption and
  surface it on the OpenAI Responses options so the UI matches the
  upstream enum.

- studio/backend/tests/test_sampling_params_routing.py: add tests for
  every gap above: Kimi web-search bypass forwarding, local OpenAI
  passthrough forwarding, ChatSettingsPayload round-trip, and the full
  Responses service_tier enum (parametrized over the five accepted
  values plus a drop check for the Anthropic-only standard_only).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fdf0be484e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// for users who switch providers between sessions.
if (Array.isArray(value.stop)) {
const stops = value.stop.filter((s): s is string => typeof s === "string");
if (stops.length > 0) params.stop = stops.slice(0, 16);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve empty stop list when sanitizing settings patches

This sanitizer drops stop: [] by only persisting the field when stops.length > 0, which prevents users from clearing previously saved stop sequences. When a user removes all stop chips, savePersistedChatSettingsPatch strips the empty array before the PUT, so backend settings keep the old non-empty list and those stale stops reappear after reload (or continue affecting generations). The sanitizer should preserve an explicit empty array to represent "clear this value".

Useful? React with 👍 / 👎.

danielhanchen and others added 8 commits May 24, 2026 13:44
Round 2 reviewer feedback:

- studio/frontend/src/features/chat/types/api.ts: `OpenAIChatCompletionsRequest.service_tier` did not include `"scale"`, so the request builder in chat-adapter.ts failed typecheck after the runtime ServiceTier union widened (`Type 'ServiceTier | undefined' is not assignable...`). Widen the type to match the SDK and keep the typecheck green.

- studio/frontend/src/components/ui/stop-sequences-input.tsx: the chip editor used `draft.trim()` for storage, which silently mutated semantically meaningful stops like " End", "### ", and "\n\n". Keep the whitespace-only rejection (Anthropic 400s on those, OpenAI silently drops them) but persist the raw draft so leading/trailing whitespace inside otherwise-meaningful stops survives.

- studio/backend/core/inference/external_provider.py: the Kimi web-search bypass dropped a single string `stop="\n\n"` via `stop.strip()` while the normal default OAI-compat path forwards it verbatim. Mirror the default path's behavior here so kimi-with-search and kimi-without-search apply the same rules (asymmetric provider-path fix flagged in round-2 review).
Round 3 reviewer feedback:

- studio/backend/routes/inference.py: _build_chat_request (the
  /v1/responses → /v1/chat/completions translator) was dropping
  parallel_tool_calls on the floor. A Responses-API caller that set
  `parallel_tool_calls=false` saw the flag accepted at the schema
  layer but never reach llama-server because the translated
  ChatCompletionRequest had no first-class field for it. Now that
  parallel_tool_calls IS a first-class field on ChatCompletionRequest
  (added by this PR's earlier commits), translate it through the
  bridge so the preference actually fires.

- studio/frontend/src/features/chat/utils/chat-settings-storage.ts:
  the stop sanitizer silently dropped `stop: []` instead of persisting
  the empty array. That meant a user could not clear the last chip —
  on reload, the previously-persisted stops came back. Persist empty
  arrays explicitly so the cleared state round-trips.

- studio/backend/tests/test_sampling_params_routing.py: pin both with
  the raw reproductions reviewers cited.
Round 4 reviewer consensus (~9/20 independent reviewers) flagged
service_tier=scale as a 400 risk on /v1/responses. The earlier commit
added scale based on the openai-python SDK literal, but the live
OpenAI Responses API reference, the PR's own provider matrix, and the
9-reviewer round-4 consensus all agree the documented Responses enum
is auto|default|flex|priority only. Drop scale on this path to remove
the risk.

Keeps scale on the Chat Completions / OAI-compat path where the SDK
enum is honored and where users who want Scale Tier can still select
it. The widened TypeScript ServiceTier / ServiceTierOption / api.ts
union and the storage sanitizer allowlist remain permissive so legacy
persisted "scale" values do not get silently dropped on reload; the
runtime per-provider gate makes the routing decision.

Tests are updated to pin the restricted Responses enum and the
explicit drop of scale + standard_only + bogus values.
…ampling through GGUF direct path

Mistral chat completions uses random_seed not seed; map the field via a new seed_field on the provider registry so the new seed control actually works on Mistral. Default for other providers stays seed.

DeepSeek and Mistral both accept up to 16 stop sequences but the default OAI-compat branch was hard-capping at 4 (the OpenAI Chat limit). Studio routes the openai provider through /v1/responses not /v1/chat/completions so the 4-cap only applies if we explicitly added an openai entry. Raise the default to 16 and let per-provider stop_max overrides tighten if needed.

The local GGUF direct chat path (gguf_generate / gguf_generate_with_tools) bypassed _build_openai_passthrough_body and therefore dropped frequency_penalty, seed, stop, and parallel_tool_calls on the floor for users on the default no-tools and with-tools paths. Thread the new fields through LlamaCppBackend.generate_chat_completion and generate_chat_completion_with_tools and the two callsites that invoke them.

Also tighten comments to drop review-process narration that crept in and to remove the em dashes I had introduced in this PR's earlier commits.

Tests pin the Mistral random_seed rename, the DeepSeek 16-cap, and confirm the openai-compat default cap is 16.
Round 5 review flagged two asymmetries:

1. Kimi web-search bypass hard-capped stops at 4 while the default OAI-compat path honours provider_info["stop_max"]. Apply the same provider-aware logic in _stream_kimi_web_search so kimi-with-search and kimi-without-search match. Also add Kimi's documented 5-stop max (https://platform.kimi.ai/docs/api/chat) to the provider registry so the cap actually fires.

2. chat-settings-sheet.tsx caps every non-Anthropic external provider at 4 stops. Replace with a per-provider getProviderStopMax helper in provider-capabilities.ts so DeepSeek, Mistral, and local backends are not artificially restricted while OpenAI Chat still hits its 4-entry hard limit and Kimi hits its documented 5-entry cap.

Tests pin the Kimi 5-cap on both Kimi paths.
Kimi documents max 5 stop strings AND <= 32 bytes per string at
https://platform.kimi.ai/docs/api/chat. The previous code capped
count but forwarded oversize entries, which can produce upstream
400s. Add stop_max_bytes=32 on the Kimi registry entry and apply
both checks in a new _normalize_stop_for_provider helper shared
between the default OAI-compat path and the Kimi web-search bypass.

Tests pin the byte-cap drop on both Kimi paths.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@danielhanchen danielhanchen added still-needed# Stale but the problem is still present on main; review it refactor# labels Sep 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Closing this. It has drifted too far to rebase, and the two halves of it failed in different ways.

16 of the 22 files conflict against current main (49b48434), including every file carrying the core change. Anchor drift gives the scale: this patches models/inference.py:786 for ChatCompletionRequest, and on main that class starts at line 2081.

Already landed, so the diff is redundant here:

Overtaken by a different architecture, which is the bigger problem:

The 27 extended llama.cpp and vLLM samplers added mid-review (typical_p, mirostat, dynatemp, DRY, XTC and the rest) never landed anywhere, and they are the single largest source of conflict surface in chat-settings-sheet.tsx and chat-adapter.ts.

Genuinely still missing, and worth re-cutting in main's idiom by extending stream_chat_completion plus the providers.py registry and letting body_omit do the per-provider dropping:

  1. Outbound stop, translated to stop_sequences for Anthropic and truncated to 4 entries for OpenAI Chat. Highest value and the cleanest fit.
  2. Outbound frequency_penalty for OpenAI Chat. Absent from both the signature at external_provider.py:1256 and the body build at :1409.
  3. parallel_tool_calls, inverted to disable_parallel_tool_use for Anthropic. Present on the inbound schema only.

service_tier needs its own PR, since it has to resolve the interaction already flagged at external_provider.py:2585, where Anthropic fast mode is incompatible with the Priority tier. Fast mode landed in #5715, after this PR was written, so it was never accounted for here.

We are taking these over.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

affects UI# conflicts# new-feature# refactor# still-needed# Stale but the problem is still present on main; review it >3000#

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant