byom 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
byom/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ try:
4
+ __version__ = version("byom")
5
+ except PackageNotFoundError:
6
+ __version__ = "0.0.0"
byom/cli.py ADDED
@@ -0,0 +1,106 @@
1
+ from __future__ import annotations
2
+
3
+ from types import ModuleType
4
+ from typing import Annotated
5
+
6
+ import typer
7
+
8
+ from byom import proxy
9
+ from byom.deploy import DeployError, Deployment, names
10
+ from byom.profiles import list_profiles, load_profile
11
+
12
+ app = typer.Typer(no_args_is_help=True, add_completion=False, pretty_exceptions_enable=False,
13
+ help="Deploy SGLang and put Claude Code (and friends) in front of it.")
14
+
15
+
16
+ @app.command()
17
+ def serve(
18
+ upstream: Annotated[str, typer.Option(help="SGLang URL, e.g. http://localhost:30000")],
19
+ host: str = "127.0.0.1",
20
+ port: int = 8080,
21
+ drop_thinking: Annotated[bool, typer.Option(
22
+ help="Drop `thinking` (for models served without a reasoning parser).")] = False,
23
+ hold: Annotated[float, typer.Option(
24
+ help="Seconds to retry while the upstream is starting (503 / refused).")] = 0,
25
+ ) -> None:
26
+ """Run the proxy in front of an SGLang server."""
27
+ proxy.serve(upstream, host=host, port=port, drop_thinking=drop_thinking, hold_s=hold)
28
+
29
+
30
+ @app.command()
31
+ def deploy(
32
+ target: Annotated[str, typer.Argument(help="docker or modal")],
33
+ profile: Annotated[str, typer.Option(help="Profile name or path to a .yaml")],
34
+ name: Annotated[str | None, typer.Option(help="Defaults to the profile name.")] = None,
35
+ context: Annotated[str | None, typer.Option(help="docker: remote Docker context.")] = None,
36
+ port: Annotated[int, typer.Option(help="docker: host port for the proxy.")] = 8080,
37
+ public: Annotated[bool, typer.Option(help="docker: listen on 0.0.0.0.")] = False,
38
+ region: Annotated[str, typer.Option(help="modal: routing region.")] = "us-east",
39
+ ) -> None:
40
+ """Deploy SGLang + the proxy, then print the Claude Code settings."""
41
+ prof = load_profile(profile)
42
+ name = name or prof.name
43
+ if target == "docker":
44
+ from byom.deploy import docker
45
+
46
+ dep = docker.up(prof, name, context=context, port=port, public=public)
47
+ elif target == "modal":
48
+ from byom.deploy import modal
49
+
50
+ dep = modal.up(prof, name, region=region)
51
+ else:
52
+ raise DeployError(f"unknown target {target!r}; use docker or modal")
53
+ typer.secho(f"\n{dep.name} is up at {dep.url}", fg="green")
54
+ typer.echo("The first request after idle waits for the GPU to start (a few minutes).")
55
+ typer.echo("Claude Code settings (also: `byom env " + dep.name + "`):\n")
56
+ typer.echo(dep.claude_code_env())
57
+
58
+
59
+ @app.command()
60
+ def env(name: str) -> None:
61
+ """Print the Claude Code environment for a deployment."""
62
+ typer.echo(Deployment.load(name).claude_code_env())
63
+
64
+
65
+ @app.command()
66
+ def down(name: str) -> None:
67
+ """Stop a deployment and forget it."""
68
+ dep = Deployment.load(name)
69
+ _target(dep).down(dep)
70
+ dep.remove()
71
+ typer.echo(f"stopped {name}")
72
+
73
+
74
+ @app.command()
75
+ def logs(name: str, follow: Annotated[bool, typer.Option("--follow", "-f")] = False) -> None:
76
+ """Show deployment logs."""
77
+ dep = Deployment.load(name)
78
+ for line in _target(dep).logs(dep, follow):
79
+ typer.echo(line, nl=False)
80
+
81
+
82
+ @app.command("list")
83
+ def list_() -> None:
84
+ """Saved deployments and bundled profiles."""
85
+ for n in names():
86
+ dep = Deployment.load(n)
87
+ typer.echo(f"{n:24} {dep.target:7} {dep.url}")
88
+ typer.echo(f"profiles: {', '.join(list_profiles())}")
89
+
90
+
91
+ def _target(dep: Deployment) -> ModuleType:
92
+ if dep.target == "docker":
93
+ from byom.deploy import docker
94
+
95
+ return docker
96
+ from byom.deploy import modal
97
+
98
+ return modal
99
+
100
+
101
+ def main() -> None:
102
+ try:
103
+ app()
104
+ except (DeployError, ValueError) as e:
105
+ typer.secho(f"error: {e}", fg="red", err=True)
106
+ raise SystemExit(1) from None
@@ -0,0 +1,83 @@
1
+ """Deployments (SGLang + proxy on Docker or Modal), each saved as a small JSON record."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import secrets
8
+ import shlex
9
+ from dataclasses import asdict, dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ STATE_DIR = Path(os.environ.get("XDG_STATE_HOME", "~/.local/state")).expanduser() / "byom"
14
+ REPO_ROOT = Path(__file__).resolve().parents[2]
15
+
16
+
17
+ class DeployError(Exception):
18
+ pass
19
+
20
+
21
+ @dataclass
22
+ class Deployment:
23
+ name: str
24
+ target: str
25
+ url: str
26
+ api_key: str = field(repr=False)
27
+ model: str
28
+ extra: dict[str, Any] = field(default_factory=dict)
29
+
30
+ @property
31
+ def dir(self) -> Path:
32
+ return STATE_DIR / self.name
33
+
34
+ def save(self) -> None:
35
+ self.dir.mkdir(parents=True, exist_ok=True)
36
+ path = self.dir / "deployment.json"
37
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
38
+ with os.fdopen(fd, "w") as f:
39
+ json.dump(asdict(self), f, indent=2)
40
+
41
+ @classmethod
42
+ def load(cls, name: str) -> Deployment:
43
+ path = STATE_DIR / name / "deployment.json"
44
+ if not path.is_file():
45
+ have = ", ".join(names()) or "none"
46
+ raise DeployError(f"no deployment named {name!r} (have: {have})")
47
+ return cls(**json.loads(path.read_text()))
48
+
49
+ def remove(self) -> None:
50
+ (self.dir / "deployment.json").unlink(missing_ok=True)
51
+
52
+ def claude_code_env(self) -> str:
53
+ env = {
54
+ "ANTHROPIC_BASE_URL": self.url,
55
+ "ANTHROPIC_AUTH_TOKEN": self.api_key,
56
+ "ANTHROPIC_MODEL": self.model,
57
+ "ANTHROPIC_DEFAULT_OPUS_MODEL": self.model,
58
+ "ANTHROPIC_DEFAULT_SONNET_MODEL": self.model,
59
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL": self.model,
60
+ "CLAUDE_CODE_ATTRIBUTION_HEADER": "0",
61
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
62
+ "API_TIMEOUT_MS": "3000000",
63
+ }
64
+ return "\n".join(f"export {k}={shlex.quote(v)}" for k, v in env.items())
65
+
66
+
67
+ def names() -> list[str]:
68
+ if not STATE_DIR.is_dir():
69
+ return []
70
+ return sorted(p.parent.name for p in STATE_DIR.glob("*/deployment.json"))
71
+
72
+
73
+ def api_key_for(name: str) -> str:
74
+ """Reuse the key on redeploy so clients keep working."""
75
+ try:
76
+ return Deployment.load(name).api_key
77
+ except DeployError:
78
+ return "sk-byom-" + secrets.token_urlsafe(24)
79
+
80
+
81
+ def local_checkout() -> Path | None:
82
+ """The repo root when running from a git checkout (the proxy is then built from source)."""
83
+ return REPO_ROOT if (REPO_ROOT / "docker" / "proxy.Dockerfile").is_file() else None
byom/deploy/docker.py ADDED
@@ -0,0 +1,107 @@
1
+ """SGLang + proxy as a Docker Compose project, on this machine or a remote Docker context."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ from collections.abc import Iterator
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import yaml
13
+
14
+ from byom import __version__
15
+ from byom.deploy import (
16
+ DeployError,
17
+ Deployment,
18
+ api_key_for,
19
+ local_checkout,
20
+ )
21
+ from byom.profiles import Profile
22
+
23
+ HF_CACHE_VOLUME = "byom-hf-cache"
24
+
25
+
26
+ def render_compose(profile: Profile, *, port: int = 8080, public: bool = False,
27
+ hf_cache: str = HF_CACHE_VOLUME,
28
+ build_root: Path | None = None) -> dict[str, Any]:
29
+ proxy_cmd = ["byom", "serve", "--upstream", "http://sglang:30000", "--host", "0.0.0.0",
30
+ "--port", "8080", "--hold", str(profile.startup_timeout_min * 60)]
31
+ if profile.drop_thinking:
32
+ proxy_cmd.append("--drop-thinking")
33
+ proxy: dict[str, Any] = {
34
+ "command": proxy_cmd,
35
+ "ports": [f"{'0.0.0.0' if public else '127.0.0.1'}:{port}:8080"],
36
+ "restart": "unless-stopped",
37
+ }
38
+ if build_root:
39
+ proxy["build"] = {"context": str(build_root), "dockerfile": "docker/proxy.Dockerfile"}
40
+ else:
41
+ proxy["build"] = {"context": ".", "dockerfile_inline": (
42
+ f"FROM python:3.12-slim\nRUN pip install --no-cache-dir byom=={__version__}\n")}
43
+ compose: dict[str, Any] = {
44
+ "services": {
45
+ "sglang": {
46
+ "image": profile.image,
47
+ "command": [*profile.sglang_command(), "--api-key", "${BYOM_API_KEY}"],
48
+ "env_file": [".env"],
49
+ "volumes": [f"{hf_cache}:/root/.cache/huggingface"],
50
+ "ipc": "host",
51
+ "shm_size": "32g",
52
+ "deploy": {"resources": {"reservations": {"devices": [
53
+ {"driver": "nvidia", "count": profile.gpu_count, "capabilities": ["gpu"]},
54
+ ]}}},
55
+ "restart": "unless-stopped",
56
+ },
57
+ "proxy": proxy,
58
+ },
59
+ }
60
+ if hf_cache == HF_CACHE_VOLUME:
61
+ compose["volumes"] = {HF_CACHE_VOLUME: {"name": HF_CACHE_VOLUME}}
62
+ return compose
63
+
64
+
65
+ def up(profile: Profile, name: str, *, context: str | None = None, port: int = 8080,
66
+ public: bool = False) -> Deployment:
67
+ if context is None and sys.platform == "darwin":
68
+ raise DeployError("Docker on macOS has no NVIDIA GPU; use --context <remote GPU host> "
69
+ "or deploy to modal")
70
+ hf_cache = (str(Path(os.environ.get("HF_HOME", "~/.cache/huggingface")).expanduser())
71
+ if context is None else HF_CACHE_VOLUME)
72
+ dep = Deployment(name, "docker", f"http://127.0.0.1:{port}", api_key_for(name),
73
+ profile.served_name, {"context": context})
74
+ dep.save()
75
+ compose = render_compose(profile, port=port, public=public, hf_cache=hf_cache,
76
+ build_root=local_checkout())
77
+ (dep.dir / "compose.yaml").write_text(yaml.safe_dump(compose, sort_keys=False, width=1000))
78
+ env_lines = [f"BYOM_API_KEY={dep.api_key}"]
79
+ if token := os.environ.get("HF_TOKEN"):
80
+ env_lines.append(f"HF_TOKEN={token}")
81
+ fd = os.open(dep.dir / ".env", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
82
+ with os.fdopen(fd, "w") as f:
83
+ f.write("\n".join(env_lines) + "\n")
84
+ _compose(dep, "up", "-d", "--build", "--remove-orphans")
85
+ return dep
86
+
87
+
88
+ def down(dep: Deployment) -> None:
89
+ _compose(dep, "down", "--remove-orphans")
90
+
91
+
92
+ def logs(dep: Deployment, follow: bool = False) -> Iterator[str]:
93
+ with subprocess.Popen([*_base(dep), "logs", "--no-color", *(["-f"] if follow else [])],
94
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) as proc:
95
+ assert proc.stdout is not None
96
+ yield from proc.stdout
97
+
98
+
99
+ def _compose(dep: Deployment, *args: str) -> None:
100
+ if subprocess.run([*_base(dep), *args]).returncode != 0:
101
+ raise DeployError(f"docker compose {args[0]} failed")
102
+
103
+
104
+ def _base(dep: Deployment) -> list[str]:
105
+ context = dep.extra.get("context")
106
+ return ["docker", *(["--context", context] if context else []), "compose",
107
+ "-p", f"byom-{dep.name}", "--project-directory", str(dep.dir)]
@@ -0,0 +1,86 @@
1
+ """Deploy to Modal: create the secret, `modal deploy` app.py, download the weights."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+ from collections.abc import Iterator
12
+ from pathlib import Path
13
+
14
+ from byom import __version__
15
+ from byom.deploy import DeployError, Deployment, api_key_for, local_checkout
16
+ from byom.profiles import Profile
17
+
18
+ # Older Modal image builders install modal's own deps (pydantic 1.x) into registry images,
19
+ # which breaks SGLang.
20
+ IMAGE_BUILDER_VERSION = "2026.10"
21
+
22
+
23
+ def up(profile: Profile, name: str, *, region: str = "us-east") -> Deployment:
24
+ try:
25
+ import modal
26
+ except ImportError:
27
+ raise DeployError("the modal package is not installed: pip install 'byom[modal]'") \
28
+ from None
29
+ app_name = f"byom-{name}"
30
+ api_key = api_key_for(name)
31
+ secret = {"BYOM_API_KEY": api_key}
32
+ if token := os.environ.get("HF_TOKEN"):
33
+ secret["HF_TOKEN"] = token
34
+ modal.Secret.objects.delete(app_name, allow_missing=True)
35
+ modal.Secret.objects.create(app_name, secret)
36
+
37
+ checkout = local_checkout()
38
+ spec = {
39
+ "app": app_name,
40
+ "image": profile.image,
41
+ "command": profile.sglang_command(),
42
+ "gpu": profile.gpu,
43
+ "model": profile.model,
44
+ "revision": profile.revision,
45
+ "startup_s": profile.startup_timeout_min * 60,
46
+ "idle_s": profile.idle_timeout_min * 60,
47
+ "drop_thinking": profile.drop_thinking,
48
+ "region": region,
49
+ "local_root": str(checkout) if checkout else None,
50
+ "version": __version__,
51
+ "modal_version": modal.__version__,
52
+ }
53
+ with tempfile.TemporaryDirectory() as tmp:
54
+ app_file = Path(tmp) / f"byom_{name.replace('-', '_')}.py"
55
+ shutil.copy(Path(__file__).with_name("app.py"), app_file)
56
+ env = {**os.environ, "BYOM_MODAL_SPEC": json.dumps(spec),
57
+ "MODAL_IMAGE_BUILDER_VERSION": IMAGE_BUILDER_VERSION}
58
+ if subprocess.run([sys.executable, "-m", "modal", "deploy", str(app_file)],
59
+ env=env).returncode != 0:
60
+ raise DeployError("modal deploy failed")
61
+ print("downloading weights to the byom-hf-cache volume...", flush=True)
62
+ modal.Function.from_name(app_name, "prefetch").remote()
63
+ url = modal.Server.from_name(app_name, "Proxy").get_url()
64
+ if not url:
65
+ raise DeployError(f"could not find the URL of {app_name}/Proxy")
66
+ dep = Deployment(name, "modal", url.rstrip("/"), api_key, profile.served_name,
67
+ {"app": app_name})
68
+ dep.save()
69
+ return dep
70
+
71
+
72
+ def down(dep: Deployment) -> None:
73
+ app = dep.extra["app"]
74
+ subprocess.run([sys.executable, "-m", "modal", "app", "stop", "--yes", app], check=False)
75
+ import modal
76
+
77
+ modal.Secret.objects.delete(app, allow_missing=True)
78
+
79
+
80
+ def logs(dep: Deployment, follow: bool = False) -> Iterator[str]:
81
+ cmd = [sys.executable, "-m", "modal", "app", "logs", dep.extra["app"],
82
+ *(["-f"] if follow else [])]
83
+ with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
84
+ text=True) as proc:
85
+ assert proc.stdout is not None
86
+ yield from proc.stdout
@@ -0,0 +1,95 @@
1
+ """Modal app for one deployment: a scale-to-zero SGLang server behind an always-on proxy server.
2
+
3
+ `modal deploy` runs a copy of this file outside the package, configured by BYOM_MODAL_SPEC. It may
4
+ only import the stdlib and modal, because Modal also imports it inside the SGLang image.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import subprocess
10
+
11
+ import modal
12
+
13
+ SPEC_JSON = os.environ["BYOM_MODAL_SPEC"]
14
+ SPEC = json.loads(SPEC_JSON)
15
+ # Not /root/.cache/huggingface: the SGLang image already has files there and Modal only mounts
16
+ # volumes on empty paths.
17
+ CACHE = "/byom-cache"
18
+ CACHE_ENV = {
19
+ "HF_HOME": CACHE,
20
+ "HF_HUB_CACHE": f"{CACHE}/hub",
21
+ # compiled kernels (DeepGEMM, Triton, FlashInfer); otherwise every cold start recompiles them
22
+ "SGLANG_CACHE_DIR": f"{CACHE}/sglang",
23
+ }
24
+
25
+ app = modal.App(SPEC["app"])
26
+ secrets = [modal.Secret.from_name(SPEC["app"])]
27
+ cache = modal.Volume.from_name("byom-hf-cache", create_if_missing=True)
28
+
29
+ proxy_image = modal.Image.debian_slim(python_version="3.12")
30
+ if SPEC["local_root"]:
31
+ proxy_image = proxy_image.add_local_dir(
32
+ SPEC["local_root"], "/src", copy=True,
33
+ ignore=[".git", ".venv", "**/__pycache__", "docs", "tests"],
34
+ ).run_commands("pip install --no-cache-dir /src")
35
+ else:
36
+ proxy_image = proxy_image.uv_pip_install(f"byom=={SPEC['version']}")
37
+ proxy_image = proxy_image.uv_pip_install(
38
+ f"modal=={SPEC['modal_version']}", "huggingface_hub[hf_xet]"
39
+ ).env({**CACHE_ENV, "BYOM_MODAL_SPEC": SPEC_JSON})
40
+
41
+ sglang_image = (
42
+ modal.Image.from_registry(SPEC["image"])
43
+ .entrypoint([])
44
+ .env({**CACHE_ENV, "HF_XET_HIGH_PERFORMANCE": "1", "BYOM_MODAL_SPEC": SPEC_JSON})
45
+ )
46
+
47
+
48
+ @app.server(
49
+ image=sglang_image,
50
+ gpu=SPEC["gpu"],
51
+ port=30000,
52
+ secrets=secrets,
53
+ volumes={CACHE: cache},
54
+ startup_timeout=SPEC["startup_s"],
55
+ scaledown_window=SPEC["idle_s"],
56
+ max_containers=1,
57
+ routing_region=SPEC["region"],
58
+ unauthenticated=True,
59
+ )
60
+ class SGLang:
61
+ @modal.enter()
62
+ def start(self) -> None:
63
+ self.proc = subprocess.Popen(
64
+ [*SPEC["command"], "--api-key", os.environ["BYOM_API_KEY"]]
65
+ )
66
+
67
+
68
+ @app.server(
69
+ image=proxy_image,
70
+ port=8080,
71
+ min_containers=1,
72
+ max_containers=1,
73
+ startup_timeout=120,
74
+ routing_region=SPEC["region"],
75
+ unauthenticated=True,
76
+ )
77
+ class Proxy:
78
+ @modal.enter()
79
+ def start(self) -> None:
80
+ upstream = modal.Server.from_name(SPEC["app"], "SGLang").get_url()
81
+ if not upstream:
82
+ raise RuntimeError("could not resolve the SGLang server URL")
83
+ cmd = ["byom", "serve", "--upstream", upstream, "--host", "0.0.0.0",
84
+ "--port", "8080", "--hold", str(SPEC["startup_s"])]
85
+ if SPEC["drop_thinking"]:
86
+ cmd.append("--drop-thinking")
87
+ self.proc = subprocess.Popen(cmd)
88
+
89
+
90
+ @app.function(image=proxy_image, secrets=secrets, volumes={CACHE: cache}, timeout=3600)
91
+ def prefetch() -> None:
92
+ from huggingface_hub import snapshot_download
93
+
94
+ snapshot_download(SPEC["model"], revision=SPEC["revision"])
95
+ cache.commit()
@@ -0,0 +1,61 @@
1
+ """Model profiles: which model, which SGLang image and flags, what GPU."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from importlib.resources import files
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import yaml
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Profile:
15
+ name: str
16
+ model: str
17
+ revision: str
18
+ image: str
19
+ served_name: str
20
+ gpu: str = "H100:1"
21
+ args: dict[str, Any] = field(default_factory=dict)
22
+ drop_thinking: bool = False
23
+ startup_timeout_min: int = 20
24
+ idle_timeout_min: int = 20
25
+
26
+ @property
27
+ def gpu_count(self) -> int:
28
+ return int(self.gpu.partition(":")[2] or 1)
29
+
30
+ def sglang_command(self, port: int = 30000) -> list[str]:
31
+ cmd = ["python3", "-m", "sglang.launch_server", "--model-path", self.model,
32
+ "--revision", self.revision, "--served-model-name", self.served_name,
33
+ "--host", "0.0.0.0", "--port", str(port)]
34
+ args = dict(self.args)
35
+ if self.gpu_count > 1:
36
+ args.setdefault("tp", self.gpu_count)
37
+ for key, value in args.items():
38
+ flag = "--" + key.replace("_", "-")
39
+ if value is True:
40
+ cmd.append(flag)
41
+ elif value not in (False, None):
42
+ cmd += [flag, str(value)]
43
+ return cmd
44
+
45
+
46
+ def load_profile(name_or_path: str) -> Profile:
47
+ path = Path(name_or_path)
48
+ if path.suffix in (".yaml", ".yml") and path.is_file():
49
+ text = path.read_text()
50
+ else:
51
+ bundled = files(__package__).joinpath(f"{name_or_path}.yaml")
52
+ if not bundled.is_file():
53
+ raise ValueError(f"unknown profile {name_or_path!r} (available: "
54
+ f"{', '.join(list_profiles())}, or a path to a .yaml file)")
55
+ text = bundled.read_text()
56
+ return Profile(**yaml.safe_load(text))
57
+
58
+
59
+ def list_profiles() -> list[str]:
60
+ return sorted(p.name.removesuffix(".yaml") for p in files(__package__).iterdir()
61
+ if p.name.endswith(".yaml"))
@@ -0,0 +1,13 @@
1
+ # SGLang flags from the Qwen3-Coder cookbook (https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3-Coder.md).
2
+ # Instruct model: no reasoning parser, so the proxy drops Claude Code's `thinking` field.
3
+ # FP8 weights are ~31 GB, leaving KV-cache room on one 80 GB GPU.
4
+ name: qwen3-coder-30b
5
+ model: Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8
6
+ revision: dcaee4d4dfc5ee71ad501f01f530e5652438fde0
7
+ image: lmsysorg/sglang:v0.5.23-runtime
8
+ served_name: qwen3-coder
9
+ gpu: H100:1
10
+ args:
11
+ tool_call_parser: qwen3_coder
12
+ context_length: 131072
13
+ drop_thinking: true
byom/proxy.py ADDED
@@ -0,0 +1,127 @@
1
+ """Forwards every request to SGLang unchanged, apart from two fixes for Claude Code requests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import logging
8
+ import time
9
+ from collections.abc import AsyncIterator
10
+ from contextlib import asynccontextmanager
11
+ from typing import Any
12
+
13
+ import httpx
14
+ import uvicorn
15
+ from starlette.applications import Starlette
16
+ from starlette.background import BackgroundTask
17
+ from starlette.requests import Request
18
+ from starlette.responses import JSONResponse, Response, StreamingResponse
19
+ from starlette.routing import Route
20
+
21
+ log = logging.getLogger("byom")
22
+
23
+ HOP_BY_HOP = {
24
+ "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers",
25
+ "transfer-encoding", "upgrade", "host", "content-length",
26
+ }
27
+ DROP_REQUEST_HEADERS = HOP_BY_HOP | {"accept-encoding"}
28
+ DROP_RESPONSE_HEADERS = HOP_BY_HOP | {"content-encoding"}
29
+ ATTRIBUTION_PREFIX = "x-anthropic-billing-header:"
30
+ METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
31
+
32
+
33
+ def fix_request(path: str, body: bytes, drop_thinking: bool) -> bytes:
34
+ """Rewrite an Anthropic Messages body; returns it untouched if nothing needed changing.
35
+
36
+ - `thinking`: Claude Code always sends it, and SGLang returns 400 for models served without
37
+ a reasoning parser.
38
+ - The attribution line Claude Code puts first in `system` changes on every request, which
39
+ defeats SGLang's prefix cache.
40
+ """
41
+ if not path.rstrip("/").endswith(("/messages", "/messages/count_tokens")):
42
+ return body
43
+ try:
44
+ data = json.loads(body)
45
+ except ValueError:
46
+ return body
47
+ if not isinstance(data, dict):
48
+ return body
49
+ changed = drop_thinking and data.pop("thinking", None) is not None
50
+ system = data.get("system")
51
+ if isinstance(system, str) and _is_attribution(system):
52
+ data["system"] = _strip_attribution(system)
53
+ changed = True
54
+ elif isinstance(system, list) and system and isinstance(system[0], dict):
55
+ text = system[0].get("text")
56
+ if isinstance(text, str) and _is_attribution(text):
57
+ rest = _strip_attribution(text)
58
+ data["system"] = [{**system[0], "text": rest}, *system[1:]] if rest else system[1:]
59
+ changed = True
60
+ return json.dumps(data, ensure_ascii=False).encode() if changed else body
61
+
62
+
63
+ def _is_attribution(text: str) -> bool:
64
+ return text.lstrip().startswith(ATTRIBUTION_PREFIX)
65
+
66
+
67
+ def _strip_attribution(text: str) -> str:
68
+ return text.lstrip().partition("\n")[2].lstrip("\n")
69
+
70
+
71
+ def create_app(upstream: str, *, drop_thinking: bool = False, hold_s: float = 0,
72
+ transport: httpx.AsyncBaseTransport | None = None) -> Starlette:
73
+ """`hold_s` > 0 retries 503s and connection errors that long (a backend cold-starting)."""
74
+ client = httpx.AsyncClient(base_url=upstream.rstrip("/"), transport=transport,
75
+ timeout=httpx.Timeout(10, read=None))
76
+
77
+ async def send(req: httpx.Request) -> httpx.Response | None:
78
+ deadline = time.monotonic() + hold_s
79
+ delay = 1.0
80
+ while True:
81
+ try:
82
+ resp = await client.send(req, stream=True)
83
+ if resp.status_code != 503 or time.monotonic() >= deadline:
84
+ return resp
85
+ await resp.aclose()
86
+ except httpx.TransportError as e:
87
+ if time.monotonic() >= deadline:
88
+ log.warning("upstream %s unreachable: %s", upstream, e)
89
+ return None
90
+ await asyncio.sleep(delay)
91
+ delay = min(delay * 2, 10)
92
+
93
+ async def forward(request: Request) -> Response:
94
+ body = await request.body()
95
+ if request.method == "POST":
96
+ body = fix_request(request.url.path, body, drop_thinking)
97
+ headers = {k: v for k, v in request.headers.items() if k not in DROP_REQUEST_HEADERS}
98
+ # Bodies are relayed raw and Content-Encoding is dropped, so they must arrive uncompressed.
99
+ headers["accept-encoding"] = "identity"
100
+ if "authorization" not in headers and "x-api-key" in headers:
101
+ headers["authorization"] = f"Bearer {headers['x-api-key']}"
102
+ req = client.build_request(request.method, request.url.path,
103
+ params=request.query_params, headers=headers, content=body)
104
+ resp = await send(req)
105
+ if resp is None:
106
+ return JSONResponse({"error": {"type": "api_error",
107
+ "message": f"upstream {upstream} is not reachable"}},
108
+ status_code=502)
109
+ return StreamingResponse(
110
+ resp.aiter_raw(), status_code=resp.status_code,
111
+ headers={k: v for k, v in resp.headers.items() if k not in DROP_RESPONSE_HEADERS},
112
+ background=BackgroundTask(resp.aclose),
113
+ )
114
+
115
+ @asynccontextmanager
116
+ async def lifespan(app: Any) -> AsyncIterator[None]:
117
+ yield
118
+ await client.aclose()
119
+
120
+ return Starlette(routes=[Route("/{path:path}", forward, methods=METHODS)], lifespan=lifespan)
121
+
122
+
123
+ def serve(upstream: str, *, host: str = "127.0.0.1", port: int = 8080,
124
+ drop_thinking: bool = False, hold_s: float = 0) -> None:
125
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(message)s")
126
+ uvicorn.run(create_app(upstream, drop_thinking=drop_thinking, hold_s=hold_s),
127
+ host=host, port=port)
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.5
2
+ Name: byom
3
+ Version: 0.2.0
4
+ Summary: Bring your own model to Claude Code: deploy SGLang on Modal or Docker, with a proxy in front.
5
+ Project-URL: Repository, https://github.com/shyamsn97/byom
6
+ Author-email: Shyam Sudhakaran <shyamsnair@protonmail.com>
7
+ License: The MIT License (MIT)
8
+
9
+ Copyright (c) 2026 Shyam Sudhakaran
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+ License-File: LICENSE
29
+ Keywords: claude-code,inference,llm,modal,sglang
30
+ Classifier: License :: OSI Approved :: MIT License
31
+ Classifier: Programming Language :: Python :: 3
32
+ Classifier: Topic :: Software Development
33
+ Requires-Python: >=3.11
34
+ Requires-Dist: httpx>=0.28
35
+ Requires-Dist: pyyaml>=6
36
+ Requires-Dist: starlette>=0.41
37
+ Requires-Dist: typer>=0.15
38
+ Requires-Dist: uvicorn>=0.32
39
+ Provides-Extra: modal
40
+ Requires-Dist: modal>=1.6; extra == 'modal'
41
+ Description-Content-Type: text/markdown
42
+
43
+ # byom
44
+
45
+ Bring your own model to Claude Code and other coding agents. byom deploys
46
+ [SGLang](https://github.com/sgl-project/sglang) on Modal or Docker and puts a small proxy in front
47
+ of it that smooths over the few places where Claude Code and SGLang disagree.
48
+
49
+ ```bash
50
+ pip install 'byom[modal]'
51
+ byom deploy modal --profile qwen3-coder-30b
52
+ ```
53
+
54
+ `deploy` prints the environment variables for Claude Code:
55
+
56
+ ```bash
57
+ export ANTHROPIC_BASE_URL=https://<you>--byom-qwen3-coder-30b-proxy.us-east.modal.direct
58
+ export ANTHROPIC_AUTH_TOKEN=sk-byom-...
59
+ export ANTHROPIC_MODEL=qwen3-coder
60
+ ...
61
+ claude
62
+ ```
63
+
64
+ Requests go straight from Claude Code to your deployment, so nothing goes to Anthropic. You pay
65
+ only for the GPU.
66
+
67
+ ## Targets
68
+
69
+ **Modal** (`byom deploy modal`): the GPU server scales to zero after 20 idle minutes, and a
70
+ small always-on CPU proxy keeps the URL stable. The first request after idle waits for the GPU to
71
+ boot (about 4 minutes with cached weights) instead of failing. Needs `modal setup` first.
72
+
73
+ **Docker** (`byom deploy docker`): SGLang and the proxy as a Compose project on an NVIDIA
74
+ machine, reachable at `http://127.0.0.1:8080`. Use `--context <docker context>` to deploy to a
75
+ remote GPU box from your laptop.
76
+
77
+ **Your own SGLang server**: `byom serve --upstream http://localhost:30000 --drop-thinking`.
78
+
79
+ ```bash
80
+ byom list # deployments and profiles
81
+ byom env NAME # print the Claude Code settings again
82
+ byom logs NAME -f
83
+ byom down NAME
84
+ ```
85
+
86
+ Gated models need `HF_TOKEN` set when you deploy.
87
+
88
+ ## What the proxy changes
89
+
90
+ Everything is forwarded to SGLang byte for byte, except:
91
+
92
+ - `thinking` is dropped for models served without a reasoning parser (Claude Code always sends
93
+ it; SGLang rejects it).
94
+ - Claude Code's per-request attribution line is removed from the system prompt so SGLang's prefix
95
+ cache works.
96
+ - `x-api-key` is also sent as `Authorization: Bearer`, which is what SGLang checks.
97
+ - While the backend is starting, 503s and refused connections are retried instead of returned.
98
+
99
+ ## Profiles
100
+
101
+ A profile is a YAML file naming the model, the SGLang image and flags, and the GPU:
102
+
103
+ ```yaml
104
+ name: qwen3-coder-30b
105
+ model: Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8
106
+ revision: dcaee4d4dfc5ee71ad501f01f530e5652438fde0
107
+ image: lmsysorg/sglang:v0.5.23-runtime
108
+ served_name: qwen3-coder
109
+ gpu: H100:1
110
+ args:
111
+ tool_call_parser: qwen3_coder
112
+ context_length: 131072
113
+ drop_thinking: true
114
+ ```
115
+
116
+ Pass your own with `--profile path/to/model.yaml`. The model needs an SGLang
117
+ `--tool-call-parser`, since Claude Code does everything through tool calls.
118
+
119
+ ## Using it from code
120
+
121
+ The same URL serves the OpenAI API under `/v1`, so the OpenAI SDK, Cursor and most other tools work
122
+ too, including streaming, structured outputs and tool calls:
123
+
124
+ ```python
125
+ from openai import OpenAI
126
+ from byom.deploy import Deployment
127
+
128
+ dep = Deployment.load("qwen3-coder-30b")
129
+ client = OpenAI(base_url=f"{dep.url}/v1", api_key=dep.api_key, timeout=900)
130
+
131
+ for chunk in client.chat.completions.create(
132
+ model=dep.model, stream=True,
133
+ messages=[{"role": "user", "content": "Explain Python's GIL in two sentences."}],
134
+ ):
135
+ if chunk.choices and chunk.choices[0].delta.content:
136
+ print(chunk.choices[0].delta.content, end="")
137
+ ```
138
+
139
+ [docs/usage.md](https://github.com/shyamsn97/byom/blob/main/docs/usage.md) covers the OpenAI and Anthropic SDKs, structured outputs, tool
140
+ calls, curl and Cursor. Runnable versions are in [examples/](https://github.com/shyamsn97/byom/tree/main/examples):
141
+
142
+ - [`claude_code_qwen.sh`](https://github.com/shyamsn97/byom/blob/main/examples/claude_code_qwen.sh): deploy, then have Claude Code write and
143
+ test a small program.
144
+ - [`openai_sdk.py`](https://github.com/shyamsn97/byom/blob/main/examples/openai_sdk.py): chat, streaming, structured outputs, JSON mode, tool
145
+ calls.
146
+ - [`anthropic_sdk.py`](https://github.com/shyamsn97/byom/blob/main/examples/anthropic_sdk.py): messages, streaming, tool use.
147
+ - [`d1_snake.py`](https://github.com/shyamsn97/byom/blob/main/examples/d1_snake.py): LiquidAI's
148
+ d1-2B decision model playing snake from rendered frames on a Modal GPU
149
+ (`modal run examples/d1_snake.py`). d1 doesn't generate text, so it runs in Transformers
150
+ rather than through byom.
151
+
152
+ `make live NAME=<deployment>` runs all of these checks against a deployment as tests.
153
+
154
+ ## Agent skill
155
+
156
+ [`skills/byom/SKILL.md`](https://github.com/shyamsn97/byom/blob/main/skills/byom/SKILL.md) teaches
157
+ coding agents to deploy and connect to byom. Copy the `skills/byom` folder into
158
+ `~/.claude/skills/` for Claude Code or `~/.cursor/skills/` for Cursor.
159
+
160
+ ## Development
161
+
162
+ ```bash
163
+ make install # uv sync
164
+ make check # ruff, mypy, pytest
165
+ make live NAME=qwen3-coder-30b # end-to-end tests against a real deployment
166
+ make bump PART=minor # bump the version in pyproject.toml (patch, minor or major)
167
+ ```
168
+
169
+ To release, commit the bump and publish a GitHub release tagged `v<version>`; the publish
170
+ workflow checks the tag matches and uploads to PyPI.
@@ -0,0 +1,14 @@
1
+ byom/__init__.py,sha256=XXDHfrfZ9WShfVb2tXAM-pIhc61hSyTCGxuNABSefSg,156
2
+ byom/cli.py,sha256=M7YxFzLZzfQtqQ2blxms13dMhUCDvDrVdq3ImDkucJ8,3668
3
+ byom/proxy.py,sha256=k4UtXEsRtPQuRLd-OjAPioqiFYIoc3Hdx5lnYFSAt7U,5430
4
+ byom/deploy/__init__.py,sha256=OZzQkoND9V0HVJ8pTa-FSyfT-tH0Soxpc8xcH1Z5dQY,2632
5
+ byom/deploy/docker.py,sha256=Gt4lVQx75Amg2lPwbqO3NkhCvS77HGvJ7Y-TkenIYJU,4249
6
+ byom/deploy/modal/__init__.py,sha256=sf4WIRTSRT1IeaA5purFh7_0tEl_rBLs-ksR6b4wqPE,3221
7
+ byom/deploy/modal/app.py,sha256=ZDajg8vN64Qll4UGt9JYVStev8yOf_PuDR8TIEv8xtU,3031
8
+ byom/profiles/__init__.py,sha256=BeEG3uVyE13373UeqnOhTMrCSkgIva8YCPDtZm5I5io,2009
9
+ byom/profiles/qwen3-coder-30b.yaml,sha256=20SKTY1i_w9uvM3kksTibLAKgmbvVqNqUfcdXFCSFRE,548
10
+ byom-0.2.0.dist-info/METADATA,sha256=aKsYR48l5H4l32NDV4LBz2ANWWGFCEyXa8wn3ypDuq4,6960
11
+ byom-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ byom-0.2.0.dist-info/entry_points.txt,sha256=cSRovxEsndNOAV0uH5kPMAStbgdhdCIa5ihYXdTxL_k,39
13
+ byom-0.2.0.dist-info/licenses/LICENSE,sha256=XY_9XDbXsRgGJBJJpkeq3HASn6RrHiGVP7WGuHogE60,1082
14
+ byom-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ byom = byom.cli:main
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Shyam Sudhakaran
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.