Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: leave top_p out of external requests when set to Off (#10934)

Nilay54c76e1821ed
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 9c3ed68ffa6..e158660e300 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -1086,7 +1086,7 @@ class ExternalProviderClient:
messages: list[dict[str, Any]],
model: str,
temperature: float = 0.7,
- top_p: float = 0.95,
+ top_p: Optional[float] = 0.95,
max_tokens: Optional[int] = None,
presence_penalty: float = 0.0,
top_k: Optional[int] = None,
@@ -1240,10 +1240,11 @@ class ExternalProviderClient:
"messages": messages,
"stream": stream,
"temperature": temperature,
- "top_p": top_p,
"presence_penalty": presence_penalty,
**_continue_body,
}
+ if top_p is not None:
+ body["top_p"] = top_p
# Only alongside stream=True: the field is rejected on a non-streaming request.
if stream and self.provider_type in _USAGE_STREAM_OPTION_PROVIDERS:
body["stream_options"] = {"include_usage": True}
@@ -6174,7 +6175,7 @@ class ExternalProviderClient:
messages: list[dict[str, Any]],
model: str,
temperature: float = 0.7,
- top_p: float = 0.95,
+ top_p: Optional[float] = 0.95,
max_tokens: Optional[int] = None,
presence_penalty: float = 0.0,
) -> dict[str, Any]:
@@ -6187,9 +6188,10 @@ class ExternalProviderClient:
"messages": messages,
"stream": False,
"temperature": temperature,
- "top_p": top_p,
"presence_penalty": presence_penalty,
}
+ if top_p is not None:
+ body["top_p"] = top_p
if max_tokens is not None:
if self.provider_type == "openai":
body["max_completion_tokens"] = max_tokens
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 179dc5c55c9..da6cc38ff60 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -21735,6 +21735,7 @@ async def _proxy_to_external_provider(
# Schema defaults are non-None (20, 0.01, 1.0) for the local path, so only
# `model_fields_set` separates "asked for 20" from "said nothing", and the provider keeps
# its own default for the latter. Read before ANY write: a setattr marks a field explicit.
+ _top_p_explicit = payload.top_p if "top_p" in payload.model_fields_set else None
_top_k_explicit = payload.top_k if "top_k" in payload.model_fields_set else None
_min_p_explicit = payload.min_p if "min_p" in payload.model_fields_set else None
_repetition_penalty_explicit = (
@@ -21794,7 +21795,7 @@ async def _proxy_to_external_provider(
async def _stream():
_provider_kwargs = dict(
temperature = payload.temperature,
- top_p = payload.top_p,
+ top_p = _top_p_explicit,
# Honor max_completion_tokens when max_tokens is absent, so a
# provider-routed request capped only by the newer field still gets
# a limit instead of falling back to the provider default.
diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.py
index 44fee68b917..9f993895721 100644
--- a/studio/backend/routes/providers.py
+++ b/studio/backend/routes/providers.py
@@ -627,7 +627,7 @@ async def _test_custom_provider_connectivity(client, model_id: str) -> ProviderT
messages = [{"role": "user", "content": "ping"}],
model = model_id,
temperature = 0.0,
- top_p = 1.0,
+ top_p = None,
max_tokens = 1,
)
return ProviderTestResult(
diff --git a/studio/backend/tests/test_external_top_p_omission.py b/studio/backend/tests/test_external_top_p_omission.py
new file mode 100644
index 00000000000..a2c9c28944a
--- /dev/null
+++ b/studio/backend/tests/test_external_top_p_omission.py
@@ -0,0 +1,227 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import asyncio
+import json
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import httpx
+import pytest
+
+from core.inference import external_provider as ep_mod
+from core.inference.external_provider import ExternalProviderClient
+from models.inference import ChatCompletionRequest
+
+
+_SSE = (
+ 'data: {"choices":[{"index":0,"delta":{"content":"ok"}}]}\n\n'
+ 'data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n'
+ "data: [DONE]\n\n"
+).encode()
+
+
+class _Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *args, **kwargs) -> None:
+ return
+
+ def do_POST(self) -> None: # noqa: N802
+ length = int(self.headers.get("Content-Length") or 0)
+ body = json.loads(self.rfile.read(length).decode() if length else "{}")
+ self.server.recorded.append(body) # type: ignore[attr-defined]
+ if "temperature" in body and "top_p" in body:
+ payload = json.dumps(
+ {
+ "error": {
+ "message": "`temperature` and `top_p` cannot both be specified for this model."
+ }
+ }
+ ).encode()
+ self.send_response(400)
+ self.send_header("Content-Type", "application/json")
+ elif body.get("stream"):
+ payload = _SSE
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ else:
+ payload = json.dumps(
+ {"choices": [{"message": {"role": "assistant", "content": "ok"}}]}
+ ).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+
+class _Gateway:
+ def __enter__(self) -> "_Gateway":
+ self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
+ self._httpd.recorded = [] # type: ignore[attr-defined]
+ self._thread = threading.Thread(target = self._httpd.serve_forever, daemon = True)
+ self._thread.start()
+ return self
+
+ def __exit__(self, *exc) -> None:
+ self._httpd.shutdown()
+ self._httpd.server_close()
+ self._thread.join(timeout = 10)
+
+ @property
+ def base_url(self) -> str:
+ return f"http://127.0.0.1:{self._httpd.server_address[1]}/v1"
+
+ @property
+ def body(self) -> dict:
+ assert self._httpd.recorded, "nothing reached the gateway" # type: ignore[attr-defined]
+ return self._httpd.recorded[-1] # type: ignore[attr-defined]
+
+
+def _run(coro) -> None:
+ loop = asyncio.new_event_loop()
+ previous = ep_mod._http_client
+ client = httpx.AsyncClient()
+
+ async def wrapper() -> None:
+ try:
+ await coro()
+ finally:
+ await client.aclose()
+
+ ep_mod._http_client = client
+ try:
+ loop.run_until_complete(wrapper())
+ finally:
+ ep_mod._http_client = previous
+ loop.close()
+
+
+def _through_route(**fields) -> tuple[dict, str]:
+ import routes.inference as ri
+ from starlette.requests import Request
+
+ async def receive() -> dict:
+ return {"type": "http.disconnect"}
+
+ with _Gateway() as gateway:
+ payload = ChatCompletionRequest(
+ provider_type = "custom",
+ provider_base_url = gateway.base_url,
+ provider_api_key = "k",
+ messages = [{"role": "user", "content": "hi"}],
+ model = "claude-sonnet-4-6",
+ stream = True,
+ **fields,
+ )
+ request = Request(
+ {
+ "type": "http",
+ "http_version": "1.1",
+ "method": "POST",
+ "path": "/v1/chat/completions",
+ "raw_path": b"/v1/chat/completions",
+ "root_path": "",
+ "scheme": "http",
+ "query_string": b"",
+ "headers": [(b"content-type", b"application/json")],
+ "client": ("127.0.0.1", 12345),
+ "server": ("127.0.0.1", 8000),
+ },
+ receive,
+ )
+ chunks: list[str] = []
+
+ async def go() -> None:
+ response = await ri._proxy_to_external_provider(payload, request)
+ async for chunk in response.body_iterator:
+ chunks.append(chunk.decode() if isinstance(chunk, bytes) else chunk)
+
+ _run(go)
+ return gateway.body, "".join(chunks)
+
+
+def test_an_omitted_top_p_is_not_forwarded_and_the_gateway_accepts():
+ body, stream = _through_route(temperature = 0.7)
+ assert "top_p" not in body
+ assert body["temperature"] == 0.7
+ assert "cannot both be specified" not in stream
+ assert '"content":"ok"' in stream
+
+
[email protected]("top_p", [0.0, 0.9, 1.0])
+def test_an_explicit_top_p_still_reaches_the_gateway(top_p):
+ body, stream = _through_route(temperature = 0.7, top_p = top_p)
+ assert body["top_p"] == top_p
+ assert "cannot both be specified" in stream
+
+
+def test_the_client_omits_top_p_when_given_none():
+ with _Gateway() as gateway:
+ client = ExternalProviderClient(
+ provider_type = "custom", base_url = gateway.base_url, api_key = "k"
+ )
+
+ async def go() -> None:
+ async for _ in client.stream_chat_completion(
+ messages = [{"role": "user", "content": "hi"}],
+ model = "claude-sonnet-4-6",
+ temperature = 0.7,
+ top_p = None,
+ ):
+ pass
+
+ _run(go)
+ assert "top_p" not in gateway.body
+
+
+def test_the_non_streaming_helper_omits_top_p_when_given_none():
+ with _Gateway() as gateway:
+ client = ExternalProviderClient(
+ provider_type = "custom", base_url = gateway.base_url, api_key = "k"
+ )
+
+ async def go() -> None:
+ response = await client.chat_completion(
+ messages = [{"role": "user", "content": "ping"}],
+ model = "claude-sonnet-4-6",
+ temperature = 0.0,
+ top_p = None,
+ max_tokens = 1,
+ )
+ assert response["choices"][0]["message"]["content"] == "ok"
+
+ _run(go)
+ assert "top_p" not in gateway.body
+
+
+def test_the_connection_test_ping_omits_top_p():
+ from routes.providers import _test_custom_provider_connectivity
+ with _Gateway() as gateway:
+ real = ExternalProviderClient(
+ provider_type = "custom", base_url = gateway.base_url, api_key = "k"
+ )
+
+ class _NoModelsOrSpeech:
+ async def list_models(self):
+ raise RuntimeError("no /models")
+
+ async def create_speech(self, **kwargs):
+ raise RuntimeError("no /audio/speech")
+
+ async def chat_completion(self, **kwargs):
+ return await real.chat_completion(**kwargs)
+
+ results = []
+
+ async def go() -> None:
+ results.append(
+ await _test_custom_provider_connectivity(_NoModelsOrSpeech(), "claude-sonnet-4-6")
+ )
+
+ _run(go)
+ assert "top_p" not in gateway.body
+ assert results[0].success, results[0].message
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 7754c8230e1..8dd9f01cfa5 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -5910,7 +5910,7 @@ export function createOpenAIStreamAdapter(
...(externalCapabilities?.temperature !== false
? { temperature: params.temperature }
: {}),
- ...(externalCapabilities?.topP !== false
+ ...(externalCapabilities?.topP !== false && params.topP < 1
? { top_p: params.topP }
: {}),
// Floor at the provider's documented min (Kimi thinking needs >=16k); clamp at the per-model max.
diff --git a/studio/frontend/src/features/chat/research-inference-request.ts b/studio/frontend/src/features/chat/research-inference-request.ts
index d41446078bf..6e431847554 100644
--- a/studio/frontend/src/features/chat/research-inference-request.ts
+++ b/studio/frontend/src/features/chat/research-inference-request.ts
@@ -85,7 +85,12 @@ export function buildResearchInferenceRequest(input: {
if (Number.isFinite(input.temperature) && input.temperature >= 0 && input.temperature <= 2) {
request.temperature = input.temperature;
}
- if (Number.isFinite(input.topP) && input.topP > 0 && input.topP <= 1) {
+ // A connection leaves Off (1) out, as the chat request does; local runs still send it.
+ if (
+ Number.isFinite(input.topP) &&
+ input.topP > 0 &&
+ (input.external ? input.topP < 1 : input.topP <= 1)
+ ) {
request.topP = input.topP;
}
if (Number.isFinite(input.maxTokens) && input.maxTokens > 0) {
diff --git a/studio/frontend/tests/external-sampling-payload.test.ts b/studio/frontend/tests/external-sampling-payload.test.ts
index 791f2f3736f..67a5fe0177c 100644
--- a/studio/frontend/tests/external-sampling-payload.test.ts
+++ b/studio/frontend/tests/external-sampling-payload.test.ts
@@ -126,6 +126,15 @@ for (const providerType of ["vllm", "openrouter", "llama_cpp"]) {
});
}
+test("top_p at Off is left out so a provider that forbids it alongside temperature accepts the request", () => {
+ for (const providerType of ["custom", "vllm", "openrouter"]) {
+ const body = bodyFor(providerType, { ...PARAMS, topP: 1 });
+ assert.ok(!("top_p" in body), providerType);
+ assert.equal(body.temperature, PARAMS.temperature, providerType);
+ assert.equal(bodyFor(providerType).top_p, PARAMS.topP, providerType);
+ }
+});
+
test("custom stays on the OpenAI-compatible baseline", () => {
const body = bodyFor("custom");
assert.ok(!("min_p" in body));
diff --git a/studio/frontend/tests/research-inference-request.test.ts b/studio/frontend/tests/research-inference-request.test.ts
index 6b8aee8bb8d..f1dadbe1ef2 100644
--- a/studio/frontend/tests/research-inference-request.test.ts
+++ b/studio/frontend/tests/research-inference-request.test.ts
@@ -62,6 +62,34 @@ test("invalid optional settings do not leak into a local research request", () =
);
});
+test("top_p at Off is left out of a connection's research request but kept locally", () => {
+ const base = {
+ temperature: 0.2,
+ topP: 1,
+ maxTokens: 4096,
+ reasoningRequested: false,
+ reasoningStyle: "none",
+ reasoningEffort: "low" as const,
+ reasoningEffortLevels: ["low", "medium", "high"] as const,
+ clampReasoningEffort: clamp,
+ };
+ const external = buildResearchInferenceRequest({
+ ...base,
+ checkpoint: "external::p1::claude-sonnet-4-6",
+ external: {
+ providerId: "p1",
+ providerType: "custom",
+ modelId: "claude-sonnet-4-6",
+ maxOutputTokens: null,
+ maxOutputTokensFromSavedCap: false,
+ maxOutputTokensPublished: null,
+ },
+ });
+ assert.equal("topP" in external, false);
+ assert.equal(external.temperature, 0.2);
+ assert.equal(buildResearchInferenceRequest({ ...base, checkpoint: "local/model.gguf" }).topP, 1);
+});
+
test("the report ceiling the connection resolved reaches the run config", () => {
const request = buildResearchInferenceRequest({
checkpoint: "external::provider::gemini-3.6-flash",