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.

unsloth start pi: add --max-tokens to set Pi's output token limit (#12393)

Lee Jacksonc3eef7639e2e
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.py
index 8a8cb0a9b6c..91299bd4d15 100644
--- a/unsloth_cli/commands/start.py
+++ b/unsloth_cli/commands/start.py
@@ -4609,6 +4609,17 @@ def opencode_output_limit(window: int, max_tokens: Optional[int] = None) -> int:
return max(1, min(window // 4, _OPENCODE_OUTPUT_TOKEN_MAX))
+def _agent_output_limit(window: int, max_tokens: Optional[int]) -> int:
+ output = opencode_output_limit(window, max_tokens)
+ if max_tokens and output < max_tokens:
+ typer.echo(
+ f"Warning: --max-tokens {max_tokens} leaves too little of the {window:,}-token "
+ f"context for the conversation; using {output:,}.",
+ err = True,
+ )
+ return output
+
+
def opencode_compaction_reserved(window: int, output: int) -> int:
return max(1, min(output, max(window // 10, 8192)))
@@ -4624,13 +4635,7 @@ def _opencode_output_env(model: dict, max_tokens: Optional[int]) -> dict:
err = True,
)
return {}
- output = opencode_output_limit(int(window), max_tokens)
- if output < max_tokens:
- typer.echo(
- f"Warning: --max-tokens {max_tokens} leaves too little of the {int(window):,}-token "
- f"context for the conversation; using {output:,}.",
- err = True,
- )
+ output = _agent_output_limit(int(window), max_tokens)
raw = os.environ.get(_OPENCODE_OUTPUT_TOKEN_MAX_ENV, "")
inherited = int(raw) if raw.isdigit() and int(raw) > 0 else None
ceiling = inherited or _OPENCODE_OUTPUT_TOKEN_MAX
@@ -4786,7 +4791,14 @@ def write_hermes_config(base: str, model: dict, path: Path) -> None:
typer.echo(f"Updated {path}")
-def write_pi_config(base: str, key: str, model: dict, path: Path) -> None:
+def write_pi_config(
+ base: str,
+ key: str,
+ model: dict,
+ path: Path,
+ *,
+ max_tokens: Optional[int] = None,
+) -> None:
config = _read_json_object(path)
if config is None:
typer.echo(
@@ -4803,7 +4815,9 @@ def write_pi_config(base: str, key: str, model: dict, path: Path) -> None:
window = int(window)
# An unspecified model defaults to contextWindow 128000 / maxTokens 16384, far larger than a small Unsloth context, so Pi compacts too late and overflows the server. Pin the real window and a sane output cap, mirroring OpenCode.
provider_model["contextWindow"] = window
- provider_model["maxTokens"] = opencode_output_limit(window)
+ provider_model["maxTokens"] = _agent_output_limit(window, max_tokens)
+ elif max_tokens:
+ provider_model["maxTokens"] = max_tokens
_subdict(config, "providers")[_PI_PROVIDER] = {
"api": "openai-completions",
"baseUrl": f"{base}/v1",
@@ -5073,6 +5087,7 @@ def write_pi_subagent_config(
model: dict,
path: Path,
approve: bool = False,
+ max_tokens: Optional[int] = None,
) -> None:
"""Write private bootstrap data for the bundled Pi extension."""
window = model.get("context_length") or model.get("max_context_length")
@@ -5084,7 +5099,7 @@ def write_pi_subagent_config(
"apiKey": key,
"model": model["id"],
"contextWindow": window,
- "maxTokens": opencode_output_limit(window),
+ "maxTokens": _agent_output_limit(window, max_tokens),
"approve": approve,
},
)
@@ -5714,6 +5729,7 @@ def pi(
launch: bool = _LAUNCH_OPTION,
gguf_variant: Optional[str] = _GGUF_VARIANT_OPTION,
max_seq_length: int = _CONTEXT_OPTION,
+ max_tokens: Optional[int] = _MAX_TOKENS_OPTION,
load_in_4bit: bool = _LOAD_4BIT_OPTION,
tensor_parallel: bool = _TENSOR_PARALLEL_OPTION,
gpu_memory_mode: Optional[Literal["auto", "manual"]] = _GPU_MEMORY_MODE_OPTION,
@@ -5777,6 +5793,7 @@ def pi(
subagent_model,
config_path,
approve = yolo,
+ max_tokens = max_tokens,
)
command = [
"pi",
@@ -5813,7 +5830,7 @@ def pi(
with _session_config("pi", launch, persist = persist) as home:
# Pi resolves its config dir from PI_CODING_AGENT_DIR first (getAgentDir() prefers it over $HOME/.pi/agent), so pin it at the session dir: an inherited PI_CODING_AGENT_DIR in the user's shell would otherwise send Pi to their real config and skip our provider/key. HOME is relocated too so any other ~/.pi paths stay in the session. The key rides in the config rather than the env.
pi_agent_dir = home / ".pi" / "agent"
- write_pi_config(base, key, entry, pi_agent_dir / "models.json")
+ write_pi_config(base, key, entry, pi_agent_dir / "models.json", max_tokens = max_tokens)
write_pi_user_resources(pi_agent_dir, home)
env = {"HOME": str(home), "PI_CODING_AGENT_DIR": str(pi_agent_dir)}
if os.name == "nt" or os.environ.get("WSL_DISTRO_NAME"):
diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.py
index 565da84c187..d823e349676 100644
--- a/unsloth_cli/tests/test_start.py
+++ b/unsloth_cli/tests/test_start.py
@@ -6307,6 +6307,60 @@ def test_connect_pi_as_subagent_preserves_cloud_parent(fake_studio, tmp_path, yo
assert "Ask Pi to spawn an Unsloth or local agent." in result.output
+def _pi_generated_model(tmp_path, as_subagent):
+ if as_subagent:
+ return json.loads((tmp_path / "agents" / "pi-subagent" / "subagent.json").read_text())
+ return json.loads((tmp_path / "agents" / "pi" / ".pi" / "agent" / "models.json").read_text())[
+ "providers"
+ ]["unsloth"]["models"][0]
+
+
[email protected]("as_subagent", [False, True])
+def test_connect_pi_output_limit(fake_studio, tmp_path, as_subagent):
+ args = ["pi", "--no-launch", "--max-tokens", "40000"]
+ if as_subagent:
+ args.append("--as-subagent")
+ # Each launch regenerates the config, so the second run must honour the flag too.
+ for _ in range(2):
+ result = CliRunner().invoke(start.start_app, args)
+ assert result.exit_code == 0, result.output
+ assert "--max-tokens" not in _launch_command(result.output)
+ config = _pi_generated_model(tmp_path, as_subagent)
+ assert config["maxTokens"] == 40000
+ assert config["contextWindow"] == MODEL["context_length"]
+
+
[email protected]("as_subagent", [False, True])
+def test_connect_pi_output_limit_capped_at_half_window(fake_studio, tmp_path, as_subagent):
+ args = ["pi", "--no-launch", "--max-tokens", "200000"]
+ if as_subagent:
+ args.append("--as-subagent")
+ result = CliRunner().invoke(start.start_app, args)
+ assert result.exit_code == 0, result.output
+ assert "leaves too little" in result.output
+ assert _pi_generated_model(tmp_path, as_subagent)["maxTokens"] == MODEL["context_length"] // 2
+
+
[email protected]("value", ["0", "-1", "abc"])
+def test_connect_pi_invalid_output_limit(fake_studio, tmp_path, value):
+ result = CliRunner().invoke(start.start_app, ["pi", "--no-launch", "--max-tokens", value])
+ assert result.exit_code != 0
+ assert "--max-tokens" in result.output
+ assert not list((tmp_path / "agents").rglob("models.json"))
+
+
[email protected]("context", [{}, {"max_context_length": 32768}])
+def test_write_pi_output_limit_context_metadata(tmp_path, context):
+ path = tmp_path / "models.json"
+ start.write_pi_config(BASE, "test-key", {"id": "test-model", **context}, path, max_tokens = 10000)
+ model = json.loads(path.read_text())["providers"]["unsloth"]["models"][0]
+ assert model["maxTokens"] == 10000
+ if context:
+ assert model["contextWindow"] == 32768
+ else:
+ assert "contextWindow" not in model
+
+
def test_connect_pi_no_launch_windows_relocates_userprofile(fake_studio, tmp_path, monkeypatch):
# On native Windows Node resolves ~/.pi via USERPROFILE, not HOME, so the session
# must point USERPROFILE at the relocated home or Pi reads the user's real ~/.pi.