local-llm-server 0.1.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.
- local_llm_server/__init__.py +22 -0
- local_llm_server/cli.py +282 -0
- local_llm_server/constants.py +26 -0
- local_llm_server/router.py +136 -0
- local_llm_server/server.py +495 -0
- local_llm_server-0.1.0.dist-info/METADATA +68 -0
- local_llm_server-0.1.0.dist-info/RECORD +11 -0
- local_llm_server-0.1.0.dist-info/WHEEL +5 -0
- local_llm_server-0.1.0.dist-info/entry_points.txt +2 -0
- local_llm_server-0.1.0.dist-info/licenses/LICENSE +201 -0
- local_llm_server-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""local-llm-server — ローカルLLMを OpenAI 互換 API として起動・管理する。
|
|
2
|
+
|
|
3
|
+
mlx / mlx-vlm / llama.cpp、および画像とテキストを自動振り分けする router を
|
|
4
|
+
サブプロセスとして起動・監視する。依存は標準ライブラリのみで、任意の
|
|
5
|
+
OpenAI 互換クライアントから利用できる。
|
|
6
|
+
|
|
7
|
+
公開 API:
|
|
8
|
+
- サーバー管理: LocalServer / ServerConfig / ServerPool / build_command など
|
|
9
|
+
- 起動状態の確認: is_ready / list_models / models_match / parse_host_port
|
|
10
|
+
- 既定値・定数: DEFAULT_MODEL / DEFAULT_VISION_MODEL / DEFAULT_BACKEND / BACKENDS
|
|
11
|
+
- router: RouterServer
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from .constants import ( # noqa: F401
|
|
16
|
+
BACKENDS,
|
|
17
|
+
DEFAULT_MODEL,
|
|
18
|
+
DEFAULT_VISION_MODEL,
|
|
19
|
+
_env_bool,
|
|
20
|
+
)
|
|
21
|
+
from .server import * # noqa: F401,F403
|
|
22
|
+
from .router import * # noqa: F401,F403
|
local_llm_server/cli.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import threading
|
|
7
|
+
|
|
8
|
+
from .constants import DEFAULT_MODEL, DEFAULT_VISION_MODEL, _env_bool
|
|
9
|
+
from .router import RouterServer
|
|
10
|
+
from .server import (
|
|
11
|
+
BACKENDS,
|
|
12
|
+
DEFAULT_BACKEND,
|
|
13
|
+
ServerConfig,
|
|
14
|
+
ServerPool,
|
|
15
|
+
build_command,
|
|
16
|
+
build_pool_configs,
|
|
17
|
+
find_pids_on_port,
|
|
18
|
+
install_shutdown_handlers,
|
|
19
|
+
parallel_supported,
|
|
20
|
+
stop_pid,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
# CLI で選べるバックエンド。router は内部でテキスト LLM と vision VLM を
|
|
24
|
+
# 同時起動し、リクエスト内容で自動振り分けする特別モード。
|
|
25
|
+
ROUTER = "router"
|
|
26
|
+
CLI_BACKENDS = (*BACKENDS, ROUTER)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _run_router(args, extra: list[str], enable_thinking: bool) -> int:
|
|
30
|
+
"""router モード: テキスト LLM と vision VLM を同時起動し、プロキシで振り分ける。
|
|
31
|
+
|
|
32
|
+
公開ポート(args.port)にルーターを立て、テキストを port+1、vision を port+2 で
|
|
33
|
+
起動する。クライアントは公開ポートの 1 つだけを base_url に指定すればよい。
|
|
34
|
+
vision バックエンドは mlx-vlm(Apple Silicon 前提)、テキストは mlx を使う。
|
|
35
|
+
"""
|
|
36
|
+
text_port = args.port + 1
|
|
37
|
+
vision_port = args.port + 2
|
|
38
|
+
text_cfg = ServerConfig(
|
|
39
|
+
backend="mlx",
|
|
40
|
+
model=args.model,
|
|
41
|
+
host=args.host,
|
|
42
|
+
port=text_port,
|
|
43
|
+
disable_thinking=not enable_thinking,
|
|
44
|
+
extra_args=extra,
|
|
45
|
+
)
|
|
46
|
+
vision_cfg = ServerConfig(
|
|
47
|
+
backend="mlx-vlm",
|
|
48
|
+
model=args.vision_model,
|
|
49
|
+
host=args.host,
|
|
50
|
+
port=vision_port,
|
|
51
|
+
)
|
|
52
|
+
pool = ServerPool([text_cfg, vision_cfg])
|
|
53
|
+
print(f"Starting (text): {' '.join(build_command(text_cfg))}", file=sys.stderr)
|
|
54
|
+
print(f"Starting (vision): {' '.join(build_command(vision_cfg))}", file=sys.stderr)
|
|
55
|
+
try:
|
|
56
|
+
pool.start()
|
|
57
|
+
pool.wait_until_ready()
|
|
58
|
+
except (RuntimeError, TimeoutError) as exc:
|
|
59
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
60
|
+
pool.stop()
|
|
61
|
+
return 1
|
|
62
|
+
|
|
63
|
+
router = RouterServer(
|
|
64
|
+
(args.host, args.port),
|
|
65
|
+
(args.host, text_port),
|
|
66
|
+
(args.host, vision_port),
|
|
67
|
+
)
|
|
68
|
+
public_url = f"http://{args.host}:{args.port}/v1"
|
|
69
|
+
print("Ready (automatic routing):", file=sys.stderr)
|
|
70
|
+
print(f" - public: {public_url}", file=sys.stderr)
|
|
71
|
+
print(f" text -> http://{args.host}:{text_port}/v1", file=sys.stderr)
|
|
72
|
+
print(f" image/media -> http://{args.host}:{vision_port}/v1", file=sys.stderr)
|
|
73
|
+
print(
|
|
74
|
+
f'In agent.toml, set only the single base_url = "{public_url}". '
|
|
75
|
+
"Text-only requests are routed to the LLM, requests with images to the VLM, automatically.",
|
|
76
|
+
file=sys.stderr,
|
|
77
|
+
)
|
|
78
|
+
print(
|
|
79
|
+
"Note: if the VLM does not support function calling (tools), "
|
|
80
|
+
'set tool_mode = "prompt" when using images.',
|
|
81
|
+
file=sys.stderr,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
thread = threading.Thread(target=router.serve_forever, daemon=True)
|
|
85
|
+
thread.start()
|
|
86
|
+
try:
|
|
87
|
+
pool.wait() # 子サーバーが終了するまでブロック
|
|
88
|
+
except KeyboardInterrupt:
|
|
89
|
+
pass
|
|
90
|
+
finally:
|
|
91
|
+
router.shutdown()
|
|
92
|
+
router.server_close()
|
|
93
|
+
pool.stop()
|
|
94
|
+
return 0
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _stop_servers(ports: list[int]) -> int:
|
|
98
|
+
"""指定ポートで動いているローカルサーバーを探して停止する(--stop 用)。
|
|
99
|
+
|
|
100
|
+
各ポートを LISTEN しているプロセスを lsof で特定し、プロセスグループごと
|
|
101
|
+
SIGTERM→SIGKILL で止める。1つでも止めれば 0、見つからなければ 1 を返す。
|
|
102
|
+
"""
|
|
103
|
+
if os.name != "posix":
|
|
104
|
+
print(
|
|
105
|
+
"--stop is supported on macOS / Linux only. On Windows, stop the server "
|
|
106
|
+
"from its own window (Ctrl+C) or via Task Manager.",
|
|
107
|
+
file=sys.stderr,
|
|
108
|
+
)
|
|
109
|
+
return 1
|
|
110
|
+
stopped = False
|
|
111
|
+
for port in ports:
|
|
112
|
+
pids = find_pids_on_port(port)
|
|
113
|
+
for pid in pids:
|
|
114
|
+
print(f"Stopping the server on port {port} (pid {pid})...", file=sys.stderr)
|
|
115
|
+
if stop_pid(pid):
|
|
116
|
+
stopped = True
|
|
117
|
+
if not stopped:
|
|
118
|
+
ports_str = ", ".join(str(p) for p in ports)
|
|
119
|
+
print(f"No running server found on port(s): {ports_str}.", file=sys.stderr)
|
|
120
|
+
return 1
|
|
121
|
+
print("Stopped.", file=sys.stderr)
|
|
122
|
+
return 0
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def main(argv: list[str] | None = None) -> int:
|
|
126
|
+
parser = argparse.ArgumentParser(
|
|
127
|
+
prog="local-llm-server",
|
|
128
|
+
description=(
|
|
129
|
+
"Start a local LLM server (mlx / mlx-vlm / llama.cpp / router). "
|
|
130
|
+
"Use the vision-capable mlx-vlm for image input (--backend mlx-vlm). "
|
|
131
|
+
"With --backend router, start a text LLM and a VLM together and route requests automatically based on their content."
|
|
132
|
+
),
|
|
133
|
+
epilog="Backend-specific extra arguments can be passed after --.",
|
|
134
|
+
)
|
|
135
|
+
parser.add_argument(
|
|
136
|
+
"--backend",
|
|
137
|
+
choices=CLI_BACKENDS,
|
|
138
|
+
default=os.environ.get("CODER_BACKEND", DEFAULT_BACKEND),
|
|
139
|
+
help="Backend to use (env: CODER_BACKEND, default: %(default)s)",
|
|
140
|
+
)
|
|
141
|
+
parser.add_argument(
|
|
142
|
+
"--model",
|
|
143
|
+
default=os.environ.get("CODER_MODEL", DEFAULT_MODEL),
|
|
144
|
+
help="Model (mlx: name/path, llama-cpp: .gguf path; used as the text model in router mode). env: CODER_MODEL, default: %(default)s",
|
|
145
|
+
)
|
|
146
|
+
parser.add_argument(
|
|
147
|
+
"--vision-model",
|
|
148
|
+
default=os.environ.get("CODER_VISION_MODEL", DEFAULT_VISION_MODEL),
|
|
149
|
+
help="Vision model that handles images/media in router mode. env: CODER_VISION_MODEL, default: %(default)s",
|
|
150
|
+
)
|
|
151
|
+
parser.add_argument("--host", default="127.0.0.1", help="Host to bind to")
|
|
152
|
+
parser.add_argument("--port", type=int, default=8080, help="Port to bind to (the first port when using a pool)")
|
|
153
|
+
parser.add_argument(
|
|
154
|
+
"--stop",
|
|
155
|
+
action="store_true",
|
|
156
|
+
help="Stop a server already running on --port instead of starting one "
|
|
157
|
+
"(use the same --port / --instances / --backend router as when you started it). macOS / Linux only.",
|
|
158
|
+
)
|
|
159
|
+
parser.add_argument(
|
|
160
|
+
"--parallel",
|
|
161
|
+
type=int,
|
|
162
|
+
help="Number of concurrent processing slots (llama.cpp only; mlx processes sequentially)",
|
|
163
|
+
)
|
|
164
|
+
parser.add_argument(
|
|
165
|
+
"--instances",
|
|
166
|
+
type=int,
|
|
167
|
+
default=1,
|
|
168
|
+
help="Number of servers to start on consecutive ports (to gain parallelism with mlx; each loads its own model)",
|
|
169
|
+
)
|
|
170
|
+
parser.add_argument(
|
|
171
|
+
"--thinking",
|
|
172
|
+
action=argparse.BooleanOptionalAction,
|
|
173
|
+
default=None,
|
|
174
|
+
help="Thinking mode. Use --no-thinking to disable (env: CODER_ENABLE_THINKING)",
|
|
175
|
+
)
|
|
176
|
+
parser.add_argument(
|
|
177
|
+
"--draft-model",
|
|
178
|
+
default=os.environ.get("CODER_DRAFT_MODEL"),
|
|
179
|
+
help="MTP drafter for Gemma 4 (HF id/path, e.g. "
|
|
180
|
+
"mlx-community/gemma-4-E4B-it-qat-assistant-bf16). Use 'auto' to select automatically from the main model name. "
|
|
181
|
+
"Speeds up inference without changing the main model's output. mlx-vlm backend only. env: CODER_DRAFT_MODEL",
|
|
182
|
+
)
|
|
183
|
+
args, extra = parser.parse_known_args(argv)
|
|
184
|
+
|
|
185
|
+
if args.instances < 1:
|
|
186
|
+
parser.error("--instances must be 1 or greater")
|
|
187
|
+
|
|
188
|
+
# --stop: 起動の代わりに、起動時と同じポート割り当てを再現して停止する。
|
|
189
|
+
# router は public(port) / text(port+1) / vision(port+2)、通常は連番ポート。
|
|
190
|
+
if args.stop:
|
|
191
|
+
if args.backend == ROUTER:
|
|
192
|
+
ports = [args.port, args.port + 1, args.port + 2]
|
|
193
|
+
else:
|
|
194
|
+
ports = [args.port + i for i in range(args.instances)]
|
|
195
|
+
return _stop_servers(ports)
|
|
196
|
+
|
|
197
|
+
# kill / ターミナルを閉じる(SIGTERM・SIGHUP)でも下流の finally(pool.stop)を
|
|
198
|
+
# 必ず通し、起動したバックエンドを孫プロセスとして残さない。
|
|
199
|
+
install_shutdown_handlers()
|
|
200
|
+
|
|
201
|
+
if args.parallel is not None:
|
|
202
|
+
if args.parallel < 1:
|
|
203
|
+
parser.error("--parallel must be 1 or greater")
|
|
204
|
+
if not parallel_supported(args.backend):
|
|
205
|
+
print(
|
|
206
|
+
f"Warning: {args.backend} does not support parallel slots "
|
|
207
|
+
"(sequential processing). --parallel is ignored.",
|
|
208
|
+
file=sys.stderr,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
if args.backend == "mlx-vlm":
|
|
212
|
+
print(
|
|
213
|
+
"Info: starting with the vision backend (mlx-vlm). It supports image input (image_url), "
|
|
214
|
+
"but some models do not support function calling (tools)/streaming. "
|
|
215
|
+
'In that case, set tool_mode = "prompt" in agent.toml.',
|
|
216
|
+
file=sys.stderr,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
enable_thinking = (
|
|
220
|
+
args.thinking if args.thinking is not None
|
|
221
|
+
else _env_bool("CODER_ENABLE_THINKING", False)
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
# argparse が拾った先頭の "--" を除去してバックエンドへ素通し
|
|
225
|
+
if extra and extra[0] == "--":
|
|
226
|
+
extra = extra[1:]
|
|
227
|
+
|
|
228
|
+
if args.backend == ROUTER:
|
|
229
|
+
if args.instances != 1:
|
|
230
|
+
parser.error("--instances cannot be used with --backend router")
|
|
231
|
+
return _run_router(args, extra, enable_thinking)
|
|
232
|
+
|
|
233
|
+
base = ServerConfig(
|
|
234
|
+
backend=args.backend,
|
|
235
|
+
model=args.model,
|
|
236
|
+
host=args.host,
|
|
237
|
+
port=args.port,
|
|
238
|
+
parallel=args.parallel,
|
|
239
|
+
disable_thinking=not enable_thinking,
|
|
240
|
+
draft_model=args.draft_model,
|
|
241
|
+
extra_args=extra,
|
|
242
|
+
)
|
|
243
|
+
configs = build_pool_configs(base, args.instances)
|
|
244
|
+
pool = ServerPool(configs)
|
|
245
|
+
|
|
246
|
+
for config in configs:
|
|
247
|
+
print(f"Starting: {' '.join(build_command(config))}", file=sys.stderr)
|
|
248
|
+
try:
|
|
249
|
+
pool.start()
|
|
250
|
+
pool.wait_until_ready()
|
|
251
|
+
except (RuntimeError, TimeoutError) as exc:
|
|
252
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
253
|
+
pool.stop()
|
|
254
|
+
return 1
|
|
255
|
+
|
|
256
|
+
print("Ready:", file=sys.stderr)
|
|
257
|
+
for url in pool.base_urls:
|
|
258
|
+
print(f" - {url}", file=sys.stderr)
|
|
259
|
+
if args.instances > 1:
|
|
260
|
+
print(
|
|
261
|
+
"Point each OpenAI-compatible client at one of the base URLs above. "
|
|
262
|
+
f'Example: base_url = "{pool.base_urls[0]}"',
|
|
263
|
+
file=sys.stderr,
|
|
264
|
+
)
|
|
265
|
+
else:
|
|
266
|
+
print(
|
|
267
|
+
"Point your OpenAI-compatible client at "
|
|
268
|
+
f'base_url = "{pool.base_urls[0]}".',
|
|
269
|
+
file=sys.stderr,
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
try:
|
|
273
|
+
pool.wait()
|
|
274
|
+
except KeyboardInterrupt:
|
|
275
|
+
pass
|
|
276
|
+
finally:
|
|
277
|
+
pool.stop()
|
|
278
|
+
return 0
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
if __name__ == "__main__":
|
|
282
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""エージェント側(agent/)とサーバー側(server/)で共有する中立な定数・ヘルパー。
|
|
2
|
+
|
|
3
|
+
どちらのサブパッケージにも依存しないため、ここを基点に server/ と agent/ を
|
|
4
|
+
完全に分離できる(server/ が agent/ を import する逆向き依存を作らないための層)。
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
# サーバー・モデルが明示されないときに使う既定モデル
|
|
11
|
+
DEFAULT_MODEL = "mlx-community/Qwen3.6-27B-4bit"
|
|
12
|
+
|
|
13
|
+
# 画像・メディアを処理する vision モデルの既定。
|
|
14
|
+
# 既定モデル(Qwen3.6)はマルチモーダルなので、テキストと共通のものを使う。
|
|
15
|
+
DEFAULT_VISION_MODEL = DEFAULT_MODEL
|
|
16
|
+
|
|
17
|
+
# 起動可能なローカルLLMサーバーのバックエンド一覧。
|
|
18
|
+
# server/ が実装し、agent/ は agent.toml の backend 検証に使う(共有値)。
|
|
19
|
+
BACKENDS = ("mlx", "mlx-vlm", "llama-cpp")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _env_bool(name: str, default: bool) -> bool:
|
|
23
|
+
value = os.environ.get(name)
|
|
24
|
+
if value is None:
|
|
25
|
+
return default
|
|
26
|
+
return value.strip().lower() in ("1", "true", "yes", "on")
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""テキスト LLM と vision VLM を内部で振り分けるルーティングプロキシ。
|
|
2
|
+
|
|
3
|
+
`local-llm-server --backend router` で起動する。1 つの OpenAI 互換
|
|
4
|
+
エンドポイント(例 http://127.0.0.1:8080/v1)を公開し、受信した
|
|
5
|
+
`/v1/chat/completions` の `messages` を検査して:
|
|
6
|
+
|
|
7
|
+
- 画像など非テキストのコンテンツパートを含む → vision バックエンド(VLM)
|
|
8
|
+
- テキストのみ → テキスト LLM
|
|
9
|
+
|
|
10
|
+
へ転送する(ストリーミングはそのまま中継)。クライアントの base_url は
|
|
11
|
+
1 つのままで、内部の 2 プロセスを意識しなくてよい。
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import http.client
|
|
16
|
+
import json
|
|
17
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def needs_vision(messages: Any) -> bool:
|
|
22
|
+
"""messages に非テキストのコンテンツパート(画像など)が含まれるか。
|
|
23
|
+
|
|
24
|
+
OpenAI 互換の content は文字列か、{"type": "text"|"image_url"|...} の配列。
|
|
25
|
+
type が text 以外のパートが 1 つでもあれば vision 扱いにする。
|
|
26
|
+
"""
|
|
27
|
+
if not isinstance(messages, list):
|
|
28
|
+
return False
|
|
29
|
+
for message in messages:
|
|
30
|
+
if not isinstance(message, dict):
|
|
31
|
+
continue
|
|
32
|
+
content = message.get("content")
|
|
33
|
+
if not isinstance(content, list):
|
|
34
|
+
continue
|
|
35
|
+
for part in content:
|
|
36
|
+
if isinstance(part, dict) and part.get("type") not in (None, "text"):
|
|
37
|
+
return True
|
|
38
|
+
return False
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _RouterHandler(BaseHTTPRequestHandler):
|
|
42
|
+
server_version = "local-llm-router"
|
|
43
|
+
|
|
44
|
+
# HTTP/1.0: 応答ボディは接続クローズ区切り。ストリーミング/非ストリーミングを
|
|
45
|
+
# 一律に「上流を読み切るまで中継して閉じる」形で扱え、Content-Length 計算が不要。
|
|
46
|
+
protocol_version = "HTTP/1.0"
|
|
47
|
+
|
|
48
|
+
def log_message(self, *_args) -> None: # アクセスログは出さない
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
# --- ルーティング ---------------------------------------------------
|
|
52
|
+
def do_GET(self) -> None:
|
|
53
|
+
# is_ready 用の /v1/models など。読み取り系はテキスト上流へ。
|
|
54
|
+
self._proxy(self.server.text_addr, body=b"") # type: ignore[attr-defined]
|
|
55
|
+
|
|
56
|
+
def do_POST(self) -> None:
|
|
57
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
58
|
+
body = self.rfile.read(length) if length else b""
|
|
59
|
+
target = self._select_target(body)
|
|
60
|
+
self._proxy(target, body)
|
|
61
|
+
|
|
62
|
+
def _select_target(self, body: bytes) -> tuple[str, int]:
|
|
63
|
+
srv = self.server # type: ignore[assignment]
|
|
64
|
+
# chat/completions 以外(埋め込み等)はテキスト上流へ素通し。
|
|
65
|
+
if not self.path.rstrip("/").endswith("/chat/completions"):
|
|
66
|
+
return srv.text_addr
|
|
67
|
+
try:
|
|
68
|
+
payload = json.loads(body or b"{}")
|
|
69
|
+
except (json.JSONDecodeError, ValueError):
|
|
70
|
+
return srv.text_addr
|
|
71
|
+
if needs_vision(payload.get("messages")):
|
|
72
|
+
return srv.vision_addr
|
|
73
|
+
return srv.text_addr
|
|
74
|
+
|
|
75
|
+
# --- 転送 -----------------------------------------------------------
|
|
76
|
+
def _proxy(self, addr: tuple[str, int], body: bytes) -> None:
|
|
77
|
+
host, port = addr
|
|
78
|
+
headers = {"Content-Type": self.headers.get("Content-Type", "application/json")}
|
|
79
|
+
auth = self.headers.get("Authorization")
|
|
80
|
+
if auth:
|
|
81
|
+
headers["Authorization"] = auth
|
|
82
|
+
if self.command == "POST":
|
|
83
|
+
headers["Content-Length"] = str(len(body))
|
|
84
|
+
try:
|
|
85
|
+
conn = http.client.HTTPConnection(host, port, timeout=self.server.timeout_s) # type: ignore[attr-defined]
|
|
86
|
+
conn.request(self.command, self.path, body=body or None, headers=headers)
|
|
87
|
+
resp = conn.getresponse()
|
|
88
|
+
except OSError as exc:
|
|
89
|
+
self._error(502, f"upstream {host}:{port} unreachable: {exc}")
|
|
90
|
+
return
|
|
91
|
+
try:
|
|
92
|
+
self.send_response(resp.status)
|
|
93
|
+
ctype = resp.getheader("Content-Type")
|
|
94
|
+
if ctype:
|
|
95
|
+
self.send_header("Content-Type", ctype)
|
|
96
|
+
self.end_headers()
|
|
97
|
+
while True:
|
|
98
|
+
chunk = resp.read(8192)
|
|
99
|
+
if not chunk:
|
|
100
|
+
break
|
|
101
|
+
self.wfile.write(chunk)
|
|
102
|
+
self.wfile.flush()
|
|
103
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
104
|
+
pass # クライアント切断
|
|
105
|
+
finally:
|
|
106
|
+
conn.close()
|
|
107
|
+
|
|
108
|
+
def _error(self, status: int, message: str) -> None:
|
|
109
|
+
payload = json.dumps({"error": message}).encode("utf-8")
|
|
110
|
+
try:
|
|
111
|
+
self.send_response(status)
|
|
112
|
+
self.send_header("Content-Type", "application/json")
|
|
113
|
+
self.end_headers()
|
|
114
|
+
self.wfile.write(payload)
|
|
115
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
116
|
+
pass
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class RouterServer(ThreadingHTTPServer):
|
|
120
|
+
"""テキスト/vision 上流へ振り分けるプロキシ HTTP サーバー。"""
|
|
121
|
+
|
|
122
|
+
daemon_threads = True
|
|
123
|
+
allow_reuse_address = True
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
addr: tuple[str, int],
|
|
128
|
+
text_addr: tuple[str, int],
|
|
129
|
+
vision_addr: tuple[str, int],
|
|
130
|
+
timeout_s: float | None = None,
|
|
131
|
+
) -> None:
|
|
132
|
+
super().__init__(addr, _RouterHandler)
|
|
133
|
+
self.text_addr = text_addr
|
|
134
|
+
self.vision_addr = vision_addr
|
|
135
|
+
# None なら無制限(長時間生成に備える)。
|
|
136
|
+
self.timeout_s = timeout_s
|
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import platform
|
|
6
|
+
import signal
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import tempfile
|
|
10
|
+
import time
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.parse
|
|
13
|
+
import urllib.request
|
|
14
|
+
from dataclasses import dataclass, field, replace
|
|
15
|
+
|
|
16
|
+
# 起動可能なバックエンド一覧は同梱の constants から取得(OpenAI互換APIの公開値)。
|
|
17
|
+
from .constants import BACKENDS # noqa: F401
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def default_backend() -> str:
|
|
21
|
+
"""OS に応じた既定バックエンド。
|
|
22
|
+
|
|
23
|
+
Apple Silicon の macOS なら mlx-vlm(vision 対応)を既定にする。既定モデルの
|
|
24
|
+
Qwen3.6 はマルチモーダルなので、1プロセスでテキストも画像も扱え、画像・動画
|
|
25
|
+
入力がそのまま動く。テキスト専用で軽くしたい場合は backend="mlx" を選ぶ。
|
|
26
|
+
それ以外(Linux / Windows / Intel Mac)は llama.cpp を既定にする。
|
|
27
|
+
"""
|
|
28
|
+
if sys.platform == "darwin" and platform.machine() == "arm64":
|
|
29
|
+
return "mlx-vlm"
|
|
30
|
+
return "llama-cpp"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# サーバー未起動・バックエンド未指定のときに使う既定バックエンド(OSで自動判定)
|
|
34
|
+
DEFAULT_BACKEND = default_backend()
|
|
35
|
+
|
|
36
|
+
# POSIX(macOS / Linux)か。プロセスグループ操作(killpg / setsid)の可否に使う。
|
|
37
|
+
_POSIX = os.name == "posix"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def install_shutdown_handlers() -> None:
|
|
41
|
+
"""SIGTERM / SIGHUP を Ctrl+C と同じ KeyboardInterrupt に変換する。
|
|
42
|
+
|
|
43
|
+
既定では Python は SIGTERM を受け取ると finally を実行せずに即終了するため、
|
|
44
|
+
`kill <pid>` やターミナルを閉じた(SIGHUP)ときに、自動起動した LLM サーバーが
|
|
45
|
+
孫プロセスとして置き去りになる。これらのシグナルを KeyboardInterrupt として
|
|
46
|
+
送出することで、各エントリポイントの既存 try/finally(= server.stop())を必ず通す。
|
|
47
|
+
シグナルハンドラはメインスレッドからのみ登録できる(それ以外では黙って無視)。
|
|
48
|
+
"""
|
|
49
|
+
def _raise_keyboard_interrupt(signum, frame): # noqa: ANN001
|
|
50
|
+
raise KeyboardInterrupt
|
|
51
|
+
|
|
52
|
+
for name in ("SIGTERM", "SIGHUP"):
|
|
53
|
+
sig = getattr(signal, name, None) # SIGHUP は Windows に無い
|
|
54
|
+
if sig is None:
|
|
55
|
+
continue
|
|
56
|
+
try:
|
|
57
|
+
signal.signal(sig, _raise_keyboard_interrupt)
|
|
58
|
+
except (ValueError, OSError):
|
|
59
|
+
pass # メインスレッド以外などでは登録できない
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _signal_process_tree(proc: subprocess.Popen, *, kill: bool) -> None:
|
|
63
|
+
"""proc とその子孫(プロセスグループ)へ終了シグナルを送る。
|
|
64
|
+
|
|
65
|
+
POSIX では start() が start_new_session=True で子を独立したプロセスグループに
|
|
66
|
+
しているため、killpg でグループ全体へ一括送信できる。これによりバックエンドが
|
|
67
|
+
内部で起こすワーカー等の孫プロセスも取りこぼさない。Windows には killpg が無い
|
|
68
|
+
ので proc 自身を terminate / kill する。
|
|
69
|
+
"""
|
|
70
|
+
if proc.poll() is not None:
|
|
71
|
+
return # 既に終了している
|
|
72
|
+
if _POSIX:
|
|
73
|
+
sig = signal.SIGKILL if kill else signal.SIGTERM
|
|
74
|
+
try:
|
|
75
|
+
os.killpg(os.getpgid(proc.pid), sig)
|
|
76
|
+
return
|
|
77
|
+
except (ProcessLookupError, PermissionError, OSError):
|
|
78
|
+
pass # グループ送信に失敗したら単体送信にフォールバック
|
|
79
|
+
if kill:
|
|
80
|
+
proc.kill()
|
|
81
|
+
else:
|
|
82
|
+
proc.terminate()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def find_pids_on_port(port: int) -> list[int]:
|
|
86
|
+
"""指定ポートを LISTEN しているプロセスの PID 一覧を返す(POSIX のみ、lsof を利用)。
|
|
87
|
+
|
|
88
|
+
lsof が無い / Windows などでは空リストを返す(呼び出し側で案内する)。
|
|
89
|
+
"""
|
|
90
|
+
if not _POSIX:
|
|
91
|
+
return []
|
|
92
|
+
try:
|
|
93
|
+
# プロトコルとポートは 1 つの -i セレクタにまとめる。-iTCP と -i:PORT を
|
|
94
|
+
# 分けると lsof は両者を OR 解釈し、全 TCP プロセスにマッチしてしまう。
|
|
95
|
+
result = subprocess.run(
|
|
96
|
+
["lsof", "-t", f"-iTCP:{port}", "-sTCP:LISTEN"],
|
|
97
|
+
capture_output=True, text=True, timeout=5,
|
|
98
|
+
)
|
|
99
|
+
except (FileNotFoundError, subprocess.SubprocessError):
|
|
100
|
+
return []
|
|
101
|
+
pids: list[int] = []
|
|
102
|
+
for token in result.stdout.split():
|
|
103
|
+
try:
|
|
104
|
+
pids.append(int(token))
|
|
105
|
+
except ValueError:
|
|
106
|
+
pass
|
|
107
|
+
return pids
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def stop_pid(pid: int, timeout: float = 10.0) -> bool:
|
|
111
|
+
"""PID とそのプロセスグループへ SIGTERM→(猶予後)SIGKILL を送って停止する。
|
|
112
|
+
|
|
113
|
+
停止を試みたら True、対象が既にいなければ False(POSIX 以外も False)。
|
|
114
|
+
"""
|
|
115
|
+
if not _POSIX:
|
|
116
|
+
return False
|
|
117
|
+
try:
|
|
118
|
+
pgid = os.getpgid(pid)
|
|
119
|
+
except ProcessLookupError:
|
|
120
|
+
return False
|
|
121
|
+
|
|
122
|
+
def _alive() -> bool:
|
|
123
|
+
try:
|
|
124
|
+
os.kill(pid, 0)
|
|
125
|
+
return True
|
|
126
|
+
except ProcessLookupError:
|
|
127
|
+
return False
|
|
128
|
+
except PermissionError:
|
|
129
|
+
return True
|
|
130
|
+
|
|
131
|
+
try:
|
|
132
|
+
os.killpg(pgid, signal.SIGTERM)
|
|
133
|
+
except ProcessLookupError:
|
|
134
|
+
return False
|
|
135
|
+
except PermissionError:
|
|
136
|
+
return False # 権限が無い(他ユーザーの)プロセスには手を出さない
|
|
137
|
+
deadline = time.monotonic() + timeout
|
|
138
|
+
while time.monotonic() < deadline:
|
|
139
|
+
if not _alive():
|
|
140
|
+
return True
|
|
141
|
+
time.sleep(0.2)
|
|
142
|
+
try:
|
|
143
|
+
os.killpg(pgid, signal.SIGKILL) # 猶予内に終わらなければ強制終了
|
|
144
|
+
except (ProcessLookupError, PermissionError):
|
|
145
|
+
pass
|
|
146
|
+
return True
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass
|
|
150
|
+
class ServerConfig:
|
|
151
|
+
"""起動するローカルLLMサーバーの設定。"""
|
|
152
|
+
|
|
153
|
+
backend: str # "mlx" | "llama-cpp"
|
|
154
|
+
model: str
|
|
155
|
+
host: str = "127.0.0.1"
|
|
156
|
+
port: int = 8080
|
|
157
|
+
parallel: int | None = None # 同時処理スロット数(llama.cpp のみ)
|
|
158
|
+
disable_thinking: bool = False # Qwen3 系の思考モードを無効化して起動
|
|
159
|
+
# 投機的デコード(speculative decoding)用ドラフター。今回は公式対応する
|
|
160
|
+
# Gemma 4 の MTP(Multi-Token Prediction)ドラフターに限定する。
|
|
161
|
+
# draft_model にドラフターの HF id / パス(例
|
|
162
|
+
# mlx-community/gemma-4-E4B-it-qat-assistant-bf16)を指定すると、本体の出力を
|
|
163
|
+
# 変えずに高速化する。"auto" にすると本体名から対応ドラフターを自動選択する
|
|
164
|
+
# (MTP_DRAFTERS の対応表)。指定時は本体+ドラフターの2モデルを mlx-vlm が
|
|
165
|
+
# 初回に自動ダウンロードする。MTP は vision 対応の mlx-vlm バックエンドのみ対応。
|
|
166
|
+
draft_model: str | None = None
|
|
167
|
+
extra_args: list[str] = field(default_factory=list)
|
|
168
|
+
|
|
169
|
+
@property
|
|
170
|
+
def base_url(self) -> str:
|
|
171
|
+
return f"http://{self.host}:{self.port}/v1"
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def parallel_supported(backend: str) -> bool:
|
|
175
|
+
"""そのバックエンドが並列スロット指定に対応するか。"""
|
|
176
|
+
return backend == "llama-cpp"
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# 本体(target)→ 対応する MTP ドラフター(assistant)の内蔵対応表。
|
|
180
|
+
# mlx-community のペアで、いずれも実機で検証済み。draft_model = "auto" のときに
|
|
181
|
+
# 本体名から対応ドラフターを引く(明示指定すればここを介さない)。未収載のモデルを
|
|
182
|
+
# auto にした場合はエラーで明示指定を促す(MTP 自体は非収載でも明示すれば使える)。
|
|
183
|
+
# Gemma 4 が中心だが、Qwen3.6 も MTP 方式で動作確認済み(mlx_vlm --draft-kind mtp)。
|
|
184
|
+
MTP_DRAFTERS = {
|
|
185
|
+
"mlx-community/gemma-4-E4B-it-qat-4bit":
|
|
186
|
+
"mlx-community/gemma-4-E4B-it-qat-assistant-bf16",
|
|
187
|
+
"mlx-community/gemma-4-12B-it-qat-4bit":
|
|
188
|
+
"mlx-community/gemma-4-12B-it-qat-assistant-4bit",
|
|
189
|
+
"mlx-community/gemma-4-26B-A4B-it-qat-4bit":
|
|
190
|
+
"mlx-community/gemma-4-26B-A4B-it-qat-assistant-nvfp4",
|
|
191
|
+
"mlx-community/gemma-4-31B-it-qat-4bit":
|
|
192
|
+
"mlx-community/gemma-4-31B-it-qat-assistant-bf16",
|
|
193
|
+
# 非QAT 8bit(26B-A4B)。ドラフターは非QAT の assistant-bf16。
|
|
194
|
+
"mlx-community/gemma-4-26b-a4b-it-8bit":
|
|
195
|
+
"mlx-community/gemma-4-26B-A4B-it-assistant-bf16",
|
|
196
|
+
# Qwen3.6-27B(既定モデル)の MTP ドラフター。実測 ~2倍速(38→75 tok/s, 採択93%)。
|
|
197
|
+
"mlx-community/Qwen3.6-27B-4bit":
|
|
198
|
+
"mlx-community/Qwen3.6-27B-MTP-4bit",
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def resolve_drafter(model: str, draft_model: str | None) -> str | None:
|
|
203
|
+
"""draft_model を解決する。
|
|
204
|
+
|
|
205
|
+
- None / 空 … ドラフター無し(投機的デコードを使わない)。
|
|
206
|
+
- "auto" … 本体名 model から対応する MTP ドラフター(Gemma 4 / Qwen3.6)を
|
|
207
|
+
内蔵表で引く。未収載なら ValueError(HF id を明示するよう促す)。
|
|
208
|
+
- それ以外 … その値(ドラフターの HF id / パス)をそのまま使う。
|
|
209
|
+
"""
|
|
210
|
+
if not draft_model:
|
|
211
|
+
return None
|
|
212
|
+
if draft_model != "auto":
|
|
213
|
+
return draft_model
|
|
214
|
+
drafter = MTP_DRAFTERS.get(model)
|
|
215
|
+
if drafter is None:
|
|
216
|
+
known = ", ".join(sorted(MTP_DRAFTERS))
|
|
217
|
+
raise ValueError(
|
|
218
|
+
f'draft_model="auto" に対応するドラフターが見つかりません(model={model!r})。'
|
|
219
|
+
f" 自動対応している本体: {known}。"
|
|
220
|
+
" 他のモデルでは draft_model にドラフターの HF id を明示してください。"
|
|
221
|
+
)
|
|
222
|
+
return drafter
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def build_command(config: ServerConfig) -> list[str]:
|
|
226
|
+
"""バックエンドに応じた起動コマンドを組み立てる。
|
|
227
|
+
|
|
228
|
+
いずれも OpenAI 互換サーバーを立ち上げる:
|
|
229
|
+
- mlx : mlx_lm.server(テキスト専用。逐次処理。並列スロットの概念なし)
|
|
230
|
+
- mlx-vlm : mlx_vlm.server(vision 対応。画像入力 image_url を受けられる)
|
|
231
|
+
- llama-cpp : llama-server(--parallel で並列スロットを確保)
|
|
232
|
+
"""
|
|
233
|
+
if config.backend == "mlx":
|
|
234
|
+
command = [
|
|
235
|
+
"mlx_lm.server",
|
|
236
|
+
"--model", config.model,
|
|
237
|
+
"--host", config.host,
|
|
238
|
+
"--port", str(config.port),
|
|
239
|
+
]
|
|
240
|
+
if config.disable_thinking:
|
|
241
|
+
command += ["--chat-template-args", '{"enable_thinking": false}']
|
|
242
|
+
elif config.backend == "mlx-vlm":
|
|
243
|
+
# mlx_vlm の OpenAI 互換サーバー(vision 対応)。コンソールスクリプトが
|
|
244
|
+
# 無い環境もあるため `python -m` で確実に起動する。逐次処理で並列スロットの
|
|
245
|
+
# 概念はないため --parallel は渡さない。thinking はサーバー既定が OFF
|
|
246
|
+
# (--enable-thinking を渡さなければ無効)であり、リクエスト毎の明示制御は
|
|
247
|
+
# クライアントがトップレベル enable_thinking で行う(llm.py 参照)。
|
|
248
|
+
command = [
|
|
249
|
+
sys.executable, "-m", "mlx_vlm.server",
|
|
250
|
+
"--model", config.model,
|
|
251
|
+
"--host", config.host,
|
|
252
|
+
"--port", str(config.port),
|
|
253
|
+
]
|
|
254
|
+
# Gemma 4 の MTP ドラフターによる投機的デコード。draft_kind は mtp に固定する
|
|
255
|
+
# (他種別=dflash / eagle3 は今回は対象外)。draft_model="auto" は本体名から
|
|
256
|
+
# 対応ドラフターを自動選択する。指定があれば本体とドラフターの両方を mlx-vlm が
|
|
257
|
+
# 初回に自動ダウンロードする。
|
|
258
|
+
drafter = resolve_drafter(config.model, config.draft_model)
|
|
259
|
+
if drafter:
|
|
260
|
+
command += ["--draft-model", drafter, "--draft-kind", "mtp"]
|
|
261
|
+
elif config.backend == "llama-cpp":
|
|
262
|
+
command = [
|
|
263
|
+
"llama-server",
|
|
264
|
+
"-m", config.model,
|
|
265
|
+
"--host", config.host,
|
|
266
|
+
"--port", str(config.port),
|
|
267
|
+
]
|
|
268
|
+
if config.parallel is not None:
|
|
269
|
+
command += ["--parallel", str(config.parallel)]
|
|
270
|
+
if config.disable_thinking:
|
|
271
|
+
command += ["--chat-template-kwargs", '{"enable_thinking": false}']
|
|
272
|
+
else:
|
|
273
|
+
raise ValueError(
|
|
274
|
+
f"unknown backend: {config.backend!r} (choose from {BACKENDS})"
|
|
275
|
+
)
|
|
276
|
+
return command + config.extra_args
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def is_ready(base_url: str, timeout: float = 1.0) -> bool:
|
|
280
|
+
"""OpenAI互換サーバーが応答可能かを判定する。"""
|
|
281
|
+
try:
|
|
282
|
+
with urllib.request.urlopen(f"{base_url}/models", timeout=timeout) as resp:
|
|
283
|
+
return resp.status == 200
|
|
284
|
+
except (urllib.error.URLError, OSError):
|
|
285
|
+
return False
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def list_models(base_url: str, timeout: float = 5.0) -> list[str]:
|
|
289
|
+
"""サーバーが公開する全モデル id を /v1/models から返す(取得失敗時は [])。
|
|
290
|
+
|
|
291
|
+
単一モデルサーバーはロード済みの1件を返す。一方、複数モデルを束ねるルーター型
|
|
292
|
+
サーバーはカタログとして多数を並べる(先頭が必ずしもアクティブとは限らない)ので、
|
|
293
|
+
モデルの提供有無は「リストに含まれるか」で判定する(→ model_available)。
|
|
294
|
+
"""
|
|
295
|
+
try:
|
|
296
|
+
with urllib.request.urlopen(f"{base_url}/models", timeout=timeout) as resp:
|
|
297
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
298
|
+
except (urllib.error.URLError, OSError, ValueError):
|
|
299
|
+
return []
|
|
300
|
+
items = data.get("data") if isinstance(data, dict) else None
|
|
301
|
+
if not isinstance(items, list):
|
|
302
|
+
return []
|
|
303
|
+
out: list[str] = []
|
|
304
|
+
for it in items:
|
|
305
|
+
if isinstance(it, dict):
|
|
306
|
+
mid = it.get("id")
|
|
307
|
+
if isinstance(mid, str) and mid:
|
|
308
|
+
out.append(mid)
|
|
309
|
+
return out
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def running_model(base_url: str, timeout: float = 5.0) -> str | None:
|
|
313
|
+
"""起動中サーバーの代表モデル(/v1/models の最初の id)を返す。取得不可は None。
|
|
314
|
+
|
|
315
|
+
注意: ルーター型(多モデル)サーバーでは先頭が必ずしもアクティブとは限らない。
|
|
316
|
+
設定モデルが使えるかの判定には model_available(リスト全体を見る)を使うこと。
|
|
317
|
+
"""
|
|
318
|
+
models = list_models(base_url, timeout)
|
|
319
|
+
return models[0] if models else None
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def model_available(base_url: str, model: str | None, timeout: float = 5.0) -> bool | None:
|
|
323
|
+
"""設定モデル model がサーバーで提供されているかを返す。
|
|
324
|
+
|
|
325
|
+
- True … /v1/models のいずれかと一致(単一モデル一致/ルーターのカタログに存在)
|
|
326
|
+
- False … モデル一覧は取れたが、その中に一致が無い
|
|
327
|
+
- None … 判定不能(model 未指定、または一覧を取得できない)→ 警告しない
|
|
328
|
+
"""
|
|
329
|
+
if not model:
|
|
330
|
+
return None
|
|
331
|
+
models = list_models(base_url, timeout)
|
|
332
|
+
if not models:
|
|
333
|
+
return None
|
|
334
|
+
return any(models_match(m, model) for m in models)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def models_match(a: str | None, b: str | None) -> bool:
|
|
338
|
+
"""2つのモデル名が同じものを指すかを大まかに判定する。
|
|
339
|
+
|
|
340
|
+
パス指定とリポジトリ名のゆれ(例 /abs/path/Foo と org/Foo)を吸収するため、
|
|
341
|
+
末尾要素(basename)を小文字で比較する。
|
|
342
|
+
"""
|
|
343
|
+
if not a or not b:
|
|
344
|
+
return True # どちらか不明なら警告しない(誤検知を避ける)
|
|
345
|
+
if a == b:
|
|
346
|
+
return True
|
|
347
|
+
base = lambda s: s.rstrip("/").split("/")[-1].lower() # noqa: E731
|
|
348
|
+
return base(a) == base(b)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def parse_host_port(base_url: str, default_port: int = 8080) -> tuple[str, int]:
|
|
352
|
+
"""base_url(例 http://127.0.0.1:8080/v1)から host と port を取り出す。"""
|
|
353
|
+
parsed = urllib.parse.urlparse(base_url)
|
|
354
|
+
return parsed.hostname or "127.0.0.1", parsed.port or default_port
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
class LocalServer:
|
|
358
|
+
"""ローカルLLMサーバーをサブプロセスとして管理する。"""
|
|
359
|
+
|
|
360
|
+
def __init__(self, config: ServerConfig, log_path: str | None = None) -> None:
|
|
361
|
+
self.config = config
|
|
362
|
+
self._proc: subprocess.Popen | None = None
|
|
363
|
+
self._log_file = None
|
|
364
|
+
# サーバーの大量ログ(INFO/Stream finished 等)で対話画面が乱れないよう、
|
|
365
|
+
# 標準出力・標準エラーはこのログファイルへ逃がす(端末には流さない)。
|
|
366
|
+
self.log_path = log_path
|
|
367
|
+
|
|
368
|
+
@property
|
|
369
|
+
def base_url(self) -> str:
|
|
370
|
+
return self.config.base_url
|
|
371
|
+
|
|
372
|
+
def start(self) -> None:
|
|
373
|
+
if self._proc is not None:
|
|
374
|
+
raise RuntimeError("server already started")
|
|
375
|
+
if self.log_path is None:
|
|
376
|
+
fd, self.log_path = tempfile.mkstemp(
|
|
377
|
+
prefix="local-llm-server-", suffix=".log"
|
|
378
|
+
)
|
|
379
|
+
os.close(fd)
|
|
380
|
+
try:
|
|
381
|
+
self._log_file = open(self.log_path, "a", encoding="utf-8")
|
|
382
|
+
self._proc = subprocess.Popen(
|
|
383
|
+
build_command(self.config),
|
|
384
|
+
stdout=self._log_file,
|
|
385
|
+
stderr=subprocess.STDOUT,
|
|
386
|
+
# 子を独立したプロセスグループにして、停止時に孫まで一括終了できるようにする
|
|
387
|
+
# (POSIX のみ。Windows では無視される)。stop() の killpg と対になる。
|
|
388
|
+
start_new_session=_POSIX,
|
|
389
|
+
)
|
|
390
|
+
except FileNotFoundError as exc:
|
|
391
|
+
self._close_log()
|
|
392
|
+
raise RuntimeError(
|
|
393
|
+
f"バックエンド実行ファイルが見つかりません: {exc.filename}。"
|
|
394
|
+
" mlx_lm / mlx_vlm / llama.cpp がインストール・PATH 上にあるか確認してください。"
|
|
395
|
+
) from exc
|
|
396
|
+
|
|
397
|
+
def _close_log(self) -> None:
|
|
398
|
+
if self._log_file is not None:
|
|
399
|
+
try:
|
|
400
|
+
self._log_file.close()
|
|
401
|
+
except OSError:
|
|
402
|
+
pass
|
|
403
|
+
self._log_file = None
|
|
404
|
+
|
|
405
|
+
def wait_until_ready(self, timeout: float = 120.0, interval: float = 1.0) -> None:
|
|
406
|
+
deadline = time.monotonic() + timeout
|
|
407
|
+
while time.monotonic() < deadline:
|
|
408
|
+
if self._proc is not None and self._proc.poll() is not None:
|
|
409
|
+
raise RuntimeError(
|
|
410
|
+
f"server exited early (code {self._proc.returncode})"
|
|
411
|
+
)
|
|
412
|
+
if is_ready(self.config.base_url):
|
|
413
|
+
return
|
|
414
|
+
time.sleep(interval)
|
|
415
|
+
raise TimeoutError(
|
|
416
|
+
f"server not ready within {timeout}s at {self.config.base_url}"
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
def wait(self) -> int:
|
|
420
|
+
"""サーバープロセスが終了するまでブロックする。"""
|
|
421
|
+
if self._proc is None:
|
|
422
|
+
raise RuntimeError("server not started")
|
|
423
|
+
return self._proc.wait()
|
|
424
|
+
|
|
425
|
+
def stop(self) -> None:
|
|
426
|
+
if self._proc is None:
|
|
427
|
+
self._close_log()
|
|
428
|
+
return
|
|
429
|
+
proc = self._proc
|
|
430
|
+
# graceful: プロセスグループ全体へ SIGTERM を送って 10 秒待つ
|
|
431
|
+
_signal_process_tree(proc, kill=False)
|
|
432
|
+
try:
|
|
433
|
+
proc.wait(timeout=10)
|
|
434
|
+
except subprocess.TimeoutExpired:
|
|
435
|
+
# 終わらなければグループ全体へ SIGKILL で強制終了
|
|
436
|
+
_signal_process_tree(proc, kill=True)
|
|
437
|
+
try:
|
|
438
|
+
proc.wait(timeout=5)
|
|
439
|
+
except subprocess.TimeoutExpired:
|
|
440
|
+
pass
|
|
441
|
+
self._proc = None
|
|
442
|
+
self._close_log()
|
|
443
|
+
|
|
444
|
+
def __enter__(self) -> "LocalServer":
|
|
445
|
+
self.start()
|
|
446
|
+
self.wait_until_ready()
|
|
447
|
+
return self
|
|
448
|
+
|
|
449
|
+
def __exit__(self, *exc: object) -> None:
|
|
450
|
+
self.stop()
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def build_pool_configs(base: ServerConfig, instances: int) -> list[ServerConfig]:
|
|
454
|
+
"""base を起点に、連番ポート(port, port+1, ...)の設定を instances 個作る。"""
|
|
455
|
+
return [replace(base, port=base.port + i) for i in range(instances)]
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
class ServerPool:
|
|
459
|
+
"""複数のローカルLLMサーバーをまとめて起動・管理する。
|
|
460
|
+
|
|
461
|
+
mlx のように1プロセスが逐次処理のバックエンドで並列性を得る用途を想定。
|
|
462
|
+
各インスタンスは別ポートで起動し、それぞれモデルを個別にロードする
|
|
463
|
+
(= 重みのメモリはインスタンス数分かかる)。
|
|
464
|
+
"""
|
|
465
|
+
|
|
466
|
+
def __init__(self, configs: list[ServerConfig]) -> None:
|
|
467
|
+
self._servers = [LocalServer(c) for c in configs]
|
|
468
|
+
|
|
469
|
+
@property
|
|
470
|
+
def base_urls(self) -> list[str]:
|
|
471
|
+
return [server.base_url for server in self._servers]
|
|
472
|
+
|
|
473
|
+
def start(self) -> None:
|
|
474
|
+
for server in self._servers:
|
|
475
|
+
server.start()
|
|
476
|
+
|
|
477
|
+
def wait_until_ready(self, timeout: float = 120.0) -> None:
|
|
478
|
+
for server in self._servers:
|
|
479
|
+
server.wait_until_ready(timeout=timeout)
|
|
480
|
+
|
|
481
|
+
def wait(self) -> None:
|
|
482
|
+
for server in self._servers:
|
|
483
|
+
server.wait()
|
|
484
|
+
|
|
485
|
+
def stop(self) -> None:
|
|
486
|
+
for server in self._servers:
|
|
487
|
+
server.stop()
|
|
488
|
+
|
|
489
|
+
def __enter__(self) -> "ServerPool":
|
|
490
|
+
self.start()
|
|
491
|
+
self.wait_until_ready()
|
|
492
|
+
return self
|
|
493
|
+
|
|
494
|
+
def __exit__(self, *exc: object) -> None:
|
|
495
|
+
self.stop()
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: local-llm-server
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: ローカルLLM(mlx / mlx-vlm / llama.cpp / router)を OpenAI 互換 API として起動・管理する軽量サーバー
|
|
5
|
+
Author: ToPo-ToPo-ToPo
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/ToPo-ToPo-ToPo/local-llm-server
|
|
8
|
+
Keywords: llm,local-llm,mlx,mlx-vlm,llama.cpp,openai,server,inference
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Topic :: Software Development
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Provides-Extra: mlx
|
|
20
|
+
Requires-Dist: mlx-lm>=0.31.3; (sys_platform == "darwin" and platform_machine == "arm64") and extra == "mlx"
|
|
21
|
+
Requires-Dist: mlx-vlm>=0.5.0; (sys_platform == "darwin" and platform_machine == "arm64") and extra == "mlx"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# local-llm-server
|
|
25
|
+
|
|
26
|
+
ローカルLLM(**mlx** / **mlx-vlm** / **llama.cpp**)を **OpenAI 互換 API** として
|
|
27
|
+
起動・管理する軽量サーバー。テキストと画像(vision)を自動で振り分ける
|
|
28
|
+
**router** モードを備え、任意の OpenAI 互換クライアントからそのまま利用できる。
|
|
29
|
+
|
|
30
|
+
- コア機能(プロセスの起動・監視・graceful shutdown・router プロキシ)は
|
|
31
|
+
**標準ライブラリのみ**で動作。
|
|
32
|
+
- 実際の推論バックエンドは extras で導入(Apple Silicon では `mlx` を自動選択)。
|
|
33
|
+
|
|
34
|
+
## インストール
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install local-llm-server # コア(バックエンドは別途用意)
|
|
38
|
+
pip install "local-llm-server[mlx]" # Apple Silicon 向け mlx / mlx-vlm 同梱
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## 使い方
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
# テキストLLMを起動(既定バックエンドは環境に応じて自動選択)
|
|
45
|
+
local-llm-server --backend mlx
|
|
46
|
+
|
|
47
|
+
# 画像入力対応(vision)
|
|
48
|
+
local-llm-server --backend mlx-vlm
|
|
49
|
+
|
|
50
|
+
# テキストLLMとVLMを同時起動し、リクエスト内容で自動振り分け
|
|
51
|
+
local-llm-server --backend router
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
起動後、表示される `base_url`(例 `http://127.0.0.1:8080/v1`)を
|
|
55
|
+
OpenAI 互換クライアントに設定する。
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import local_llm_server as srv
|
|
59
|
+
|
|
60
|
+
config = srv.ServerConfig(model="mlx-community/Qwen3.6-27B-4bit", backend="mlx")
|
|
61
|
+
with srv.LocalServer(config) as server:
|
|
62
|
+
server.wait_until_ready()
|
|
63
|
+
print(srv.list_models(server.base_url))
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## ライセンス
|
|
67
|
+
|
|
68
|
+
Apache-2.0
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
local_llm_server/__init__.py,sha256=LJGIg6QjQQgK0eR4hh1X1Wf2RJyj1c7ZHFsJoTMAMcs,887
|
|
2
|
+
local_llm_server/cli.py,sha256=Ss2ZKaPp1Lv1iX2wSxgrphHH0h9Ec-h7eszo8cOisIk,10338
|
|
3
|
+
local_llm_server/constants.py,sha256=u5i6eKTMMgjmzD9uqfA0V7TNb15EDeoWt4VLDgtSKS4,1127
|
|
4
|
+
local_llm_server/router.py,sha256=kRDdSVIO8LJxlIsYhiNSYFTJj_tmNY3X7MqWaM3AZ-8,5485
|
|
5
|
+
local_llm_server/server.py,sha256=f_9IrVdv9HcJX0cak5q9UWwRubK3KMhL-vLgrU_erjY,20795
|
|
6
|
+
local_llm_server-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
7
|
+
local_llm_server-0.1.0.dist-info/METADATA,sha256=AY7Du5iQxBYjcwywAnuCUwOJenfWshUr83AGT6w0Rlw,2592
|
|
8
|
+
local_llm_server-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
9
|
+
local_llm_server-0.1.0.dist-info/entry_points.txt,sha256=ucTzyiXpSFkjlzhAMYE2ACKI6Yw69a9ZHQex5_74gYA,63
|
|
10
|
+
local_llm_server-0.1.0.dist-info/top_level.txt,sha256=zKFVIO_D2dl7AzNgAyiF8NSCmjG0jG26HgxX7fPG9Cs,17
|
|
11
|
+
local_llm_server-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
local_llm_server
|