diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9fe6c74..279f895 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -49,7 +49,7 @@ jobs: if: matrix.python-version == '3.12' run: | pip install -e .[server] httpx numpy - pytest tests/test_server.py + pytest tests/test_server.py tests/test_server_concurrency.py - name: Official SDK interoperability if: matrix.python-version == '3.12' && matrix.os == 'ubuntu-latest' diff --git a/CHANGELOG.md b/CHANGELOG.md index d214735..1f55922 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Transformers checks the tokenized prompt plus requested output against its context window before generation, including chat and streaming. Oversized requests raise a descriptive `ValueError` instead of reaching position-embedding failures. - Transformers streaming now propagates worker exceptions to the consumer, preserves successive text deltas and excludes the input prompt. Optional-dependency imports no longer fail while evaluating torch type annotations. +- Chat, legacy completion and embedding requests no longer run synchronous inference on the FastAPI event loop. Lazy model loading also runs in a worker and is initialized once across concurrent first requests; health checks remain responsive during blocking work (issue #18). ## [0.3.0] - 2026-10-17 diff --git a/docs/source/api_reference.rst b/docs/source/api_reference.rst index 5e2218c..2e80c17 100644 --- a/docs/source/api_reference.rst +++ b/docs/source/api_reference.rst @@ -143,5 +143,12 @@ validates generation options, forwards structured-output formats and preserves native embedding vectors. Remote tool execution defaults to disabled and requires an explicit ``execute_tools=true`` request. +The development version after 0.3.0 runs synchronous inference, embeddings and +lazy model loading in worker threads. Concurrent first requests construct one +model, and slow inference leaves the event loop available to health checks. +Streaming still uses synchronous iterators in workers. This does not add model +batching or make a backend safe for concurrent calls; cancelling a request does +not terminate synchronous work already running in a worker. + This bundled server is a development shim. Use a dedicated inference server for production serving requirements. diff --git a/local_llm_kit/server.py b/local_llm_kit/server.py index be45dee..cbf5347 100644 --- a/local_llm_kit/server.py +++ b/local_llm_kit/server.py @@ -40,6 +40,7 @@ import inspect import json import math +import threading import time import uuid from typing import Any, Dict, List, Optional @@ -659,25 +660,27 @@ def create_app( ) from exc state = {"llm": llm} # mutable holder so tests can swap llm after creation + model_lock = threading.Lock() def _get_llm() -> Any: - if state["llm"] is not None: - return state["llm"] - nonlocal_model_path = model_path - if nonlocal_model_path is None: - if (backend or "").lower() in ("echo", "mock"): - # Model-free backends work without a model id. - nonlocal_model_path = (backend or "echo").lower() - else: - raise RuntimeError( - "No LLM available: pass llm=... or model_path=... to create_app()." - ) - # Lazy import: keeps `import local_llm_kit.server` light and avoids - # pulling heavy backends (torch/llama.cpp) until first request. - from .llm import LLM + with model_lock: + if state["llm"] is not None: + return state["llm"] + nonlocal_model_path = model_path + if nonlocal_model_path is None: + if (backend or "").lower() in ("echo", "mock"): + # Model-free backends work without a model id. + nonlocal_model_path = (backend or "echo").lower() + else: + raise RuntimeError( + "No LLM available: pass llm=... or model_path=... to create_app()." + ) + # Lazy import: keeps `import local_llm_kit.server` light and avoids + # pulling heavy backends (torch/llama.cpp) until first request. + from .llm import LLM - state["llm"] = LLM(model_path=nonlocal_model_path, backend=backend, **llm_kwargs) - return state["llm"] + state["llm"] = LLM(model_path=nonlocal_model_path, backend=backend, **llm_kwargs) + return state["llm"] def _model_id() -> str: if state["llm"] is not None: @@ -764,7 +767,7 @@ async def chat_completions(request: Request): return _error("'messages' must be a non-empty list.") try: - llm_obj = _get_llm() + llm_obj = await asyncio.to_thread(_get_llm) except RuntimeError as exc: return _error(str(exc), status=503, err_type="server_error") @@ -805,7 +808,9 @@ async def chat_completions(request: Request): if not stream: try: - result = _call_llm_chat(llm_obj, dict(chat_kwargs, stream=False)) + result = await asyncio.to_thread( + _call_llm_chat, llm_obj, dict(chat_kwargs, stream=False) + ) except Exception as exc: return _error("Chat failed: %s" % exc, status=500, err_type="server_error") try: @@ -877,7 +882,7 @@ async def completions(request: Request): return _error("'prompt' must be a non-empty string.") try: - llm_obj = _get_llm() + llm_obj = await asyncio.to_thread(_get_llm) except RuntimeError as exc: return _error(str(exc), status=503, err_type="server_error") @@ -899,7 +904,9 @@ async def completions(request: Request): if not stream: try: - result = _call_llm_complete(llm_obj, dict(complete_kwargs, stream=False)) + result = await asyncio.to_thread( + _call_llm_complete, llm_obj, dict(complete_kwargs, stream=False) + ) except Exception as exc: return _error("Completion failed: %s" % exc, status=500, err_type="server_error") if isinstance(result, dict): @@ -1011,7 +1018,7 @@ async def responses(request: Request): except (TypeError, ValueError) as exc: return _error(str(exc)) try: - llm_obj = _get_llm() + llm_obj = await asyncio.to_thread(_get_llm) except RuntimeError as exc: return _error(str(exc), status=503, err_type="server_error") model = _model_id() @@ -1083,7 +1090,7 @@ async def embeddings(request: Request): return _error("'input' must be non-empty.") try: - llm_obj = _get_llm() + llm_obj = await asyncio.to_thread(_get_llm) except RuntimeError: llm_obj = None requested_model = body.get("model") or _model_id() @@ -1091,11 +1098,11 @@ async def embeddings(request: Request): vectors = None if llm_obj is not None: try: - vectors = _try_get_embeddings(llm_obj, texts) + vectors = await asyncio.to_thread(_try_get_embeddings, llm_obj, texts) except Exception: vectors = None if vectors is None: - vectors = [_pseudo_embedding(t) for t in texts] + vectors = await asyncio.to_thread(lambda: [_pseudo_embedding(t) for t in texts]) prompt_tokens = sum(len(t.split()) for t in texts) return { diff --git a/tests/test_server_concurrency.py b/tests/test_server_concurrency.py new file mode 100644 index 0000000..27ed258 --- /dev/null +++ b/tests/test_server_concurrency.py @@ -0,0 +1,151 @@ +"""Blocking inference and model loading must leave the ASGI loop responsive.""" + +import asyncio +import threading +import unittest +from unittest import mock + +try: + import httpx + from fastapi import FastAPI # noqa: F401 + + from local_llm_kit.server import create_app + + HAS_SERVER = True +except ImportError: + HAS_SERVER = False + + +class Gate: + def __init__(self): + self.entered = threading.Event() + self.release = threading.Event() + self.threads = [] + + def wait(self): + self.threads.append(threading.get_ident()) + self.entered.set() + self.release.wait(timeout=3) + + +class GatedLLM: + model_path = "fixture" + + def __init__(self, gate=None): + self.gate = gate + + def wait(self): + if self.gate is not None: + self.gate.wait() + + def chat(self, messages, **kwargs): + self.wait() + if kwargs.get("stream"): + return iter([{"choices": [{"delta": {"content": "works"}}]}]) + return {"choices": [{"message": {"role": "assistant", "content": "works"}}]} + + def complete(self, prompt, **kwargs): + self.wait() + result = {"choices": [{"text": "works"}]} + return iter([result]) if kwargs.get("stream") else result + + def embed(self, texts): + self.wait() + return [[1.0, 0.0] for _ in texts] + + +REQUESTS = ( + ("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}), + ("/v1/completions", {"prompt": "hi"}), + ("/v1/embeddings", {"input": "hi"}), + ("/v1/responses", {"input": "hi"}), +) + + +@unittest.skipUnless(HAS_SERVER, "requires optional fastapi and httpx packages") +class TestServerConcurrency(unittest.IsolatedAsyncioTestCase): + async def assert_health_while_blocked(self, app, gate, requests): + loop_thread = threading.get_ident() + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as client: + tasks = [asyncio.create_task(client.post(path, json=body)) for path, body in requests] + try: + self.assertTrue(await asyncio.to_thread(gate.entered.wait, 5)) + health = await asyncio.wait_for(client.get("/health"), timeout=2) + self.assertEqual(health.status_code, 200) + self.assertEqual(health.json(), {"status": "ok"}) + self.assertTrue(all(worker != loop_thread for worker in gate.threads)) + self.assertTrue(all(not task.done() for task in tasks)) + finally: + gate.release.set() + results = await asyncio.gather(*tasks) + for response in results: + self.assertEqual(response.status_code, 200, response.text) + return results + + async def test_chat_inference_does_not_block_health(self): + gate = Gate() + await self.assert_health_while_blocked(create_app(llm=GatedLLM(gate)), gate, [REQUESTS[0]]) + + async def test_completion_inference_does_not_block_health(self): + gate = Gate() + await self.assert_health_while_blocked(create_app(llm=GatedLLM(gate)), gate, [REQUESTS[1]]) + + async def test_native_embeddings_do_not_block_health(self): + gate = Gate() + await self.assert_health_while_blocked(create_app(llm=GatedLLM(gate)), gate, [REQUESTS[2]]) + + async def test_responses_inference_remains_nonblocking(self): + gate = Gate() + await self.assert_health_while_blocked(create_app(llm=GatedLLM(gate)), gate, [REQUESTS[3]]) + + async def test_streaming_routes_remain_nonblocking(self): + for path, body in (REQUESTS[0], REQUESTS[1], REQUESTS[3]): + with self.subTest(path=path): + gate = Gate() + responses = await self.assert_health_while_blocked( + create_app(llm=GatedLLM(gate)), gate, [(path, dict(body, stream=True))] + ) + self.assertIn("text/event-stream", responses[0].headers["content-type"]) + self.assertIn("works", responses[0].text) + if path != "/v1/responses": + self.assertIn("data: [DONE]", responses[0].text) + + async def test_lazy_loading_does_not_block_any_inference_route(self): + for request in REQUESTS: + with self.subTest(path=request[0]): + gate = Gate() + + def load(*args, gate=gate, **kwargs): + gate.wait() + return GatedLLM() + + with mock.patch("local_llm_kit.llm.LLM", side_effect=load) as factory: + await self.assert_health_while_blocked( + create_app(model_path="fixture"), gate, [request] + ) + self.assertEqual(factory.call_count, 1) + + async def test_concurrent_first_requests_construct_only_one_model(self): + gate = Gate() + + def load(*args, **kwargs): + gate.wait() + return GatedLLM() + + with mock.patch("local_llm_kit.llm.LLM", side_effect=load) as factory: + await self.assert_health_while_blocked( + create_app(model_path="fixture"), gate, [REQUESTS[0], REQUESTS[1]] + ) + self.assertEqual(factory.call_count, 1) + + async def test_fallback_embedding_work_does_not_block_health(self): + gate = Gate() + + def embed(text): + gate.wait() + return [1.0, 0.0] + + with mock.patch("local_llm_kit.server._pseudo_embedding", side_effect=embed): + await self.assert_health_while_blocked(create_app(llm=object()), gate, [REQUESTS[2]])