chatsaver 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.
chatsaver/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+ from pkgutil import extend_path
3
+
4
+ __path__ = extend_path(__path__, __name__)
5
+
6
+ try:
7
+ __version__ = version("chatsaver")
8
+ except PackageNotFoundError: # running from a source tree that is not installed
9
+ __version__ = "0.0.0"
@@ -0,0 +1,141 @@
1
+ # A generic, single database configuration.
2
+
3
+ [alembic]
4
+ # path to migration scripts.
5
+ # this is typically a path given in POSIX (e.g. forward slashes)
6
+ # format, relative to the token %(here)s which refers to the location of this
7
+ # ini file
8
+ script_location = %(here)s
9
+
10
+ # template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
11
+ # Uncomment the line below if you want the files to be prepended with date and time
12
+ # see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
13
+ # for all available tokens
14
+ # file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
15
+
16
+ # sys.path path, will be prepended to sys.path if present.
17
+ # defaults to the current working directory. for multiple paths, the path separator
18
+ # is defined by "path_separator" below.
19
+ prepend_sys_path = .
20
+
21
+
22
+ # timezone to use when rendering the date within the migration file
23
+ # as well as the filename.
24
+ # If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
25
+ # Any required deps can installed by adding `alembic[tz]` to the pip requirements
26
+ # string value is passed to ZoneInfo()
27
+ # leave blank for localtime
28
+ # timezone =
29
+
30
+ # max length of characters to apply to the "slug" field
31
+ # truncate_slug_length = 40
32
+
33
+ # set to 'true' to run the environment during
34
+ # the 'revision' command, regardless of autogenerate
35
+ # revision_environment = false
36
+
37
+ # set to 'true' to allow .pyc and .pyo files without
38
+ # a source .py file to be detected as revisions in the
39
+ # versions/ directory
40
+ # sourceless = false
41
+
42
+ # version location specification; This defaults
43
+ # to <script_location>/versions. When using multiple version
44
+ # directories, initial revisions must be specified with --version-path.
45
+ # The path separator used here should be the separator specified by "path_separator"
46
+ # below.
47
+ # version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
48
+
49
+ # path_separator; This indicates what character is used to split lists of file
50
+ # paths, including version_locations and prepend_sys_path within configparser
51
+ # files such as alembic.ini.
52
+ # The default rendered in new alembic.ini files is "os", which uses os.pathsep
53
+ # to provide os-dependent path splitting.
54
+ #
55
+ # Note that in order to support legacy alembic.ini files, this default does NOT
56
+ # take place if path_separator is not present in alembic.ini. If this
57
+ # option is omitted entirely, fallback logic is as follows:
58
+ #
59
+ # 1. Parsing of the version_locations option falls back to using the legacy
60
+ # "version_path_separator" key, which if absent then falls back to the legacy
61
+ # behavior of splitting on spaces and/or commas.
62
+ # 2. Parsing of the prepend_sys_path option falls back to the legacy
63
+ # behavior of splitting on spaces, commas, or colons.
64
+ #
65
+ # Valid values for path_separator are:
66
+ #
67
+ # path_separator = :
68
+ # path_separator = ;
69
+ # path_separator = space
70
+ # path_separator = newline
71
+ #
72
+ # Use os.pathsep. Default configuration used for new projects.
73
+ path_separator = os
74
+
75
+ # set to 'true' to search source files recursively
76
+ # in each "version_locations" directory
77
+ # new in Alembic version 1.10
78
+ # recursive_version_locations = false
79
+
80
+ # the output encoding used when revision files
81
+ # are written from script.py.mako
82
+ # output_encoding = utf-8
83
+
84
+ # database URL. This is consumed by the user-maintained env.py script only.
85
+ # other means of configuring database URLs may be customized within the env.py
86
+ # file.
87
+ # sqlalchemy.url = sqlite:///database.db
88
+
89
+
90
+ [post_write_hooks]
91
+ # post_write_hooks defines scripts or Python functions that are run
92
+ # on newly generated revision scripts. See the documentation for further
93
+ # detail and examples
94
+
95
+ # format using "black" - use the console_scripts runner, against the "black" entrypoint
96
+ # hooks = black
97
+ # black.type = console_scripts
98
+ # black.entrypoint = black
99
+ # black.options = -l 79 REVISION_SCRIPT_FILENAME
100
+
101
+ # lint with attempts to fix using "ruff" - use the exec runner, execute a binary
102
+ # hooks = ruff
103
+ # ruff.type = exec
104
+ # ruff.executable = %(here)s/.venv/bin/ruff
105
+ # ruff.options = check --fix REVISION_SCRIPT_FILENAME
106
+
107
+ # Logging configuration. This is also consumed by the user-maintained
108
+ # env.py script only.
109
+ [loggers]
110
+ keys = root,sqlalchemy,alembic
111
+
112
+ [handlers]
113
+ keys = console
114
+
115
+ [formatters]
116
+ keys = generic
117
+
118
+ [logger_root]
119
+ level = WARNING
120
+ handlers = console
121
+ qualname =
122
+
123
+ [logger_sqlalchemy]
124
+ level = WARNING
125
+ handlers =
126
+ qualname = sqlalchemy.engine
127
+
128
+ [logger_alembic]
129
+ level = INFO
130
+ handlers =
131
+ qualname = alembic
132
+
133
+ [handler_console]
134
+ class = StreamHandler
135
+ args = (sys.stderr,)
136
+ level = NOTSET
137
+ formatter = generic
138
+
139
+ [formatter_generic]
140
+ format = %(levelname)-5.5s [%(name)s] %(message)s
141
+ datefmt = %H:%M:%S
@@ -0,0 +1,49 @@
1
+ """Alembic environment configuration."""
2
+
3
+ from logging.config import fileConfig
4
+
5
+ from alembic import context
6
+ from sqlalchemy import engine_from_config, pool
7
+
8
+ from chatsaver.server.models import DATABASE_URL, Base
9
+
10
+ config = context.config
11
+ config.set_main_option("sqlalchemy.url", DATABASE_URL)
12
+
13
+ if config.config_file_name is not None:
14
+ fileConfig(config.config_file_name)
15
+
16
+ target_metadata = Base.metadata
17
+
18
+
19
+ def run_migrations_offline() -> None:
20
+ url = config.get_main_option("sqlalchemy.url")
21
+ context.configure(
22
+ url=url,
23
+ target_metadata=target_metadata,
24
+ literal_binds=True,
25
+ dialect_opts={"paramstyle": "named"},
26
+ )
27
+
28
+ with context.begin_transaction():
29
+ context.run_migrations()
30
+
31
+
32
+ def run_migrations_online() -> None:
33
+ connectable = engine_from_config(
34
+ config.get_section(config.config_ini_section, {}),
35
+ prefix="sqlalchemy.",
36
+ poolclass=pool.NullPool,
37
+ )
38
+
39
+ with connectable.connect() as connection:
40
+ context.configure(connection=connection, target_metadata=target_metadata)
41
+
42
+ with context.begin_transaction():
43
+ context.run_migrations()
44
+
45
+
46
+ if context.is_offline_mode():
47
+ run_migrations_offline()
48
+ else:
49
+ run_migrations_online()
@@ -0,0 +1,26 @@
1
+ """${message}
2
+
3
+ Revision ID: ${up_revision}
4
+ Revises: ${down_revision | comma,n}
5
+ Create Date: ${create_date}
6
+
7
+ """
8
+ from typing import Sequence, Union
9
+
10
+ from alembic import op
11
+ import sqlalchemy as sa
12
+ ${imports if imports else ""}
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = ${repr(up_revision)}
16
+ down_revision: Union[str, None] = ${repr(down_revision)}
17
+ branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18
+ depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
19
+
20
+
21
+ def upgrade() -> None:
22
+ ${upgrades if upgrades else "pass"}
23
+
24
+
25
+ def downgrade() -> None:
26
+ ${downgrades if downgrades else "pass"}
File without changes
chatsaver/backends.py ADDED
@@ -0,0 +1,214 @@
1
+ """Launch and supervise an OpenAI-compatible LLM server (vLLM, llama.cpp, SGLang)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import shlex
8
+ import signal
9
+ import subprocess
10
+ import time
11
+ from pathlib import Path
12
+
13
+ import httpx
14
+
15
+
16
+ def vllm_command(model: str, host: str, port: int, extra: list[str]) -> list[str]:
17
+ return ["vllm", "serve", model, "--host", host, "--port", str(port), *extra]
18
+
19
+
20
+ def llamacpp_command(model: str, host: str, port: int, extra: list[str]) -> list[str]:
21
+ binary = os.environ.get("LLAMA_SERVER", "llama-server")
22
+ # a path to a .gguf file is a local model, anything else is a Hugging Face repo
23
+ flag = "-m" if model.endswith(".gguf") or os.path.exists(model) else "-hf"
24
+ return [binary, flag, model, "--host", host, "--port", str(port), *extra]
25
+
26
+
27
+ def sglang_command(model: str, host: str, port: int, extra: list[str]) -> list[str]:
28
+ return [
29
+ "python",
30
+ "-m",
31
+ "sglang.launch_server",
32
+ "--model-path",
33
+ model,
34
+ "--host",
35
+ host,
36
+ "--port",
37
+ str(port),
38
+ *extra,
39
+ ]
40
+
41
+
42
+ BACKENDS = {
43
+ "vllm": vllm_command,
44
+ "llamacpp": llamacpp_command,
45
+ "llama.cpp": llamacpp_command,
46
+ "sglang": sglang_command,
47
+ }
48
+
49
+
50
+ def launch_command(settings) -> list[str]:
51
+ """The LLM server command: ``llm_command`` verbatim, or built from ``backend``/``model``."""
52
+ if settings.llm_command and settings.backend:
53
+ raise ValueError("give either a backend or a raw LLM command, not both")
54
+ if settings.llm_command:
55
+ return settings.raw_command()
56
+ return build_command(settings.backend, settings.model, settings.llm_host, settings.llm_port, settings.llm_args)
57
+
58
+
59
+ def build_command(backend: str, model: str, host: str, port: int, extra: str | list[str] = "") -> list[str]:
60
+ try:
61
+ builder = BACKENDS[backend]
62
+ except KeyError:
63
+ raise ValueError(f"unknown backend {backend!r}, expected one of {sorted(BACKENDS)}") from None
64
+ if not model:
65
+ raise ValueError("a model is required to launch an LLM server")
66
+ if isinstance(extra, str):
67
+ extra = shlex.split(extra)
68
+ return builder(model, host, port, list(extra))
69
+
70
+
71
+ async def is_healthy(base_url: str, client: httpx.AsyncClient | None = None, timeout: float = 5.0) -> bool:
72
+ """vLLM/SGLang/llama.cpp all expose ``/health``; fall back on ``/v1/models``."""
73
+ own = client is None
74
+ client = client or httpx.AsyncClient(timeout=timeout)
75
+ try:
76
+ for path in ("/health", "/v1/models"):
77
+ try:
78
+ response = await client.get(base_url + path, timeout=timeout)
79
+ if response.status_code == 200:
80
+ return True
81
+ except httpx.HTTPError:
82
+ pass
83
+ return False
84
+ finally:
85
+ if own:
86
+ await client.aclose()
87
+
88
+
89
+ class LLMServer:
90
+ """A supervised LLM server subprocess.
91
+
92
+ ``start()`` launches the process and waits until it answers health checks,
93
+ ``watch()`` restarts it when it dies (or stops answering), ``stop()`` kills
94
+ the whole process group.
95
+ """
96
+
97
+ def __init__(
98
+ self,
99
+ command: list[str],
100
+ base_url: str,
101
+ log_path: str | os.PathLike,
102
+ startup_timeout: float = 1800.0,
103
+ restart: bool = True,
104
+ health_interval: float = 10.0,
105
+ unhealthy_after: int = 6,
106
+ ):
107
+ self.command = command
108
+ self.base_url = base_url
109
+ self.log_path = Path(log_path)
110
+ self.startup_timeout = startup_timeout
111
+ self.restart = restart
112
+ self.health_interval = health_interval
113
+ self.unhealthy_after = unhealthy_after
114
+ self.process: subprocess.Popen | None = None
115
+ self.restarts = 0
116
+ self.started_at: float | None = None
117
+ self.ready = asyncio.Event()
118
+ self._watcher: asyncio.Task | None = None
119
+ self._stopping = False
120
+
121
+ def status(self) -> dict:
122
+ return {
123
+ "command": self.command,
124
+ "base_url": self.base_url,
125
+ "pid": self.process.pid if self.process else None,
126
+ "running": self.process is not None and self.process.poll() is None,
127
+ "returncode": self.process.poll() if self.process else None,
128
+ "ready": self.ready.is_set(),
129
+ "restarts": self.restarts,
130
+ "started_at": self.started_at,
131
+ "log": str(self.log_path),
132
+ }
133
+
134
+ def _spawn(self) -> None:
135
+ self.log_path.parent.mkdir(parents=True, exist_ok=True)
136
+ log = open(self.log_path, "ab")
137
+ log.write(f"\n===== {time.ctime()} $ {shlex.join(self.command)}\n".encode())
138
+ log.flush()
139
+ self.ready.clear()
140
+ self.process = subprocess.Popen(
141
+ self.command,
142
+ stdout=log,
143
+ stderr=subprocess.STDOUT,
144
+ stdin=subprocess.DEVNULL,
145
+ start_new_session=True, # own process group, so stop() also kills the workers
146
+ )
147
+ log.close()
148
+ self.started_at = time.time()
149
+
150
+ async def wait_ready(self) -> None:
151
+ deadline = time.monotonic() + self.startup_timeout
152
+ async with httpx.AsyncClient() as client:
153
+ while time.monotonic() < deadline:
154
+ if self.process is not None and self.process.poll() is not None:
155
+ raise RuntimeError(f"LLM server exited with code {self.process.returncode}, see {self.log_path}")
156
+ if await is_healthy(self.base_url, client):
157
+ self.ready.set()
158
+ return
159
+ await asyncio.sleep(1.0)
160
+ raise TimeoutError(f"LLM server not healthy after {self.startup_timeout}s, see {self.log_path}")
161
+
162
+ async def start(self) -> None:
163
+ self._stopping = False
164
+ self._spawn()
165
+ await self.wait_ready()
166
+ if self.restart and self._watcher is None:
167
+ self._watcher = asyncio.create_task(self.watch())
168
+
169
+ async def restart_now(self) -> None:
170
+ self._kill()
171
+ self.restarts += 1
172
+ self._spawn()
173
+ await self.wait_ready()
174
+
175
+ async def watch(self) -> None:
176
+ failures = 0
177
+ async with httpx.AsyncClient() as client:
178
+ while not self._stopping:
179
+ await asyncio.sleep(self.health_interval)
180
+ if self._stopping:
181
+ return
182
+ dead = self.process is None or self.process.poll() is not None
183
+ if not dead and await is_healthy(self.base_url, client):
184
+ failures = 0
185
+ continue
186
+ failures += 1
187
+ if dead or failures >= self.unhealthy_after:
188
+ failures = 0
189
+ try:
190
+ await self.restart_now()
191
+ except Exception as exc: # keep watching, try again next round
192
+ with open(self.log_path, "a") as log:
193
+ log.write(f"\n===== restart failed: {exc}\n")
194
+
195
+ def _kill(self, timeout: float = 30.0) -> None:
196
+ self.ready.clear()
197
+ process, self.process = self.process, None
198
+ if process is None or process.poll() is not None:
199
+ return
200
+ try:
201
+ os.killpg(process.pid, signal.SIGTERM)
202
+ process.wait(timeout=timeout)
203
+ except subprocess.TimeoutExpired:
204
+ os.killpg(process.pid, signal.SIGKILL)
205
+ process.wait()
206
+ except ProcessLookupError:
207
+ pass
208
+
209
+ async def stop(self) -> None:
210
+ self._stopping = True
211
+ if self._watcher is not None:
212
+ self._watcher.cancel()
213
+ self._watcher = None
214
+ await asyncio.to_thread(self._kill)
@@ -0,0 +1,79 @@
1
+ """Command line interface.
2
+
3
+ Every module inside this package that defines ``COMMANDS`` is a subcommand,
4
+ as is every ``chatsaver.plugins.*`` module that defines ``COMMANDS``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import sys
11
+
12
+ from argklass.argformat import HelpAction, HelpActionException
13
+ from argklass.command import ParentCommand
14
+ from argklass.parallel import shutdown
15
+ from argklass.plugin import discover_module_commands, with_cache_location
16
+
17
+
18
+ def discover_commands():
19
+ import chatsaver.cli
20
+ import chatsaver.plugins
21
+
22
+ return discover_module_commands(
23
+ chatsaver.cli,
24
+ chatsaver.plugins,
25
+ ).found_commands
26
+
27
+
28
+ def build_parser(commands):
29
+ parser = argparse.ArgumentParser(
30
+ prog="chatsaver",
31
+ add_help=False,
32
+ description="Resumable session wrapper around LLM inference servers (vLLM, llama.cpp, ...)",
33
+ )
34
+ parser.add_argument("-h", "--help", action=HelpAction, help="show this help message and exit")
35
+
36
+ subparsers = parser.add_subparsers(dest="command")
37
+
38
+ ParentCommand.dispatch = dict()
39
+ for command in commands.values():
40
+ command.arguments(subparsers)
41
+
42
+ return parser
43
+
44
+
45
+ def main(argv=None) -> int:
46
+ """Entry point for the command line interface."""
47
+ import chatsaver
48
+
49
+ with with_cache_location(chatsaver):
50
+ commands = discover_commands()
51
+
52
+ try:
53
+ parser = build_parser(commands)
54
+ parsed_args = parser.parse_args(argv)
55
+ except HelpActionException:
56
+ return 0
57
+
58
+ cmd_name = parsed_args.command
59
+ if cmd_name is None:
60
+ parser.print_help()
61
+ return 0
62
+
63
+ command = commands.get(cmd_name)
64
+ if command is None:
65
+ print(f"Command `{cmd_name}` not implemented")
66
+ return 1
67
+
68
+ returncode = command.execute(parsed_args)
69
+ return returncode if returncode is not None else 0
70
+
71
+
72
+ def main_force(argv=None):
73
+ returncode = main(argv)
74
+ shutdown()
75
+ sys.exit(returncode)
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main_force()
chatsaver/cli/chat.py ADDED
@@ -0,0 +1,59 @@
1
+ """Interactive chat that survives disconnections and can be resumed later."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from argklass.command import Command
6
+
7
+
8
+ def run_chat(url: str, session_id: str | None, system: str | None, model: str | None, input_fn=input, out=print):
9
+ from chatsaver.client import Client, GenerationRestarted
10
+
11
+ def on_reconnect(exc, attempt):
12
+ out(f"\n[connection lost ({type(exc).__name__}), reconnecting #{attempt}]", flush=True)
13
+
14
+ client = Client(base_url=url, on_reconnect=on_reconnect)
15
+ session = client.session(session_id or None, system=system or None, model=model or None)
16
+ out(f"[session {session.id}]", flush=True)
17
+ for message in session.messages:
18
+ if message["role"] != "system":
19
+ out(f"{message['role']}> {message.get('content') or ''}", flush=True)
20
+
21
+ while True:
22
+ try:
23
+ text = input_fn("you> ")
24
+ except EOFError:
25
+ break
26
+ if text.strip() in ("/quit", "/exit"):
27
+ break
28
+ if not text.strip():
29
+ continue
30
+ out("assistant> ", end="", flush=True)
31
+ try:
32
+ for piece in session.stream(text):
33
+ out(piece, end="", flush=True)
34
+ except GenerationRestarted as exc:
35
+ out(f"\n[generation restarted by the server: {exc}; send your message again]", flush=True)
36
+ continue
37
+ out("", flush=True)
38
+ return session.id
39
+
40
+
41
+ class Chat(Command):
42
+ """Chat with the model through chatsaver; reconnects automatically, resume with --session."""
43
+
44
+ name: str = "chat"
45
+
46
+ @dataclass
47
+ class Arguments:
48
+ url: str = "http://localhost:8000/v1" # chatsaver OpenAI-compatible URL
49
+ session: str = "" # Session id to resume (or create with that id)
50
+ system: str = "" # System prompt for a new session
51
+ model: str = "" # Model (default: the first one the server lists)
52
+
53
+ def execute(self, args):
54
+ session_id = run_chat(args.url, args.session, args.system, args.model)
55
+ print(f"\n[resume with: chatsaver chat --session {session_id}]")
56
+ return 0
57
+
58
+
59
+ COMMANDS = Chat
@@ -0,0 +1,22 @@
1
+ """Database management (alembic migrations)."""
2
+
3
+ from pathlib import Path
4
+
5
+ from argklass.command import ParentCommand
6
+
7
+ ALEMBIC_INI = Path(__file__).resolve().parents[2] / "alembic" / "alembic.ini"
8
+
9
+
10
+ def alembic_config():
11
+ from alembic.config import Config
12
+
13
+ return Config(str(ALEMBIC_INI))
14
+
15
+
16
+ class Db(ParentCommand):
17
+ """Database management (alembic migrations)."""
18
+
19
+ name: str = "db"
20
+
21
+
22
+ COMMANDS = Db
@@ -0,0 +1,26 @@
1
+ """Create a new migration."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from argklass.command import Command
6
+
7
+
8
+ class Revision(Command):
9
+ """Create a new migration script."""
10
+
11
+ name: str = "revision"
12
+
13
+ @dataclass
14
+ class Arguments:
15
+ message: str # Short description of the migration
16
+ autogenerate: bool = False # Diff the models against the database
17
+
18
+ def execute(self, args):
19
+ from alembic import command
20
+
21
+ from . import alembic_config
22
+
23
+ command.revision(alembic_config(), message=args.message, autogenerate=args.autogenerate)
24
+
25
+
26
+ COMMANDS = Revision
@@ -0,0 +1,25 @@
1
+ """Apply migrations."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from argklass.command import Command
6
+
7
+
8
+ class Upgrade(Command):
9
+ """Upgrade the database to a revision (default: latest)."""
10
+
11
+ name: str = "upgrade"
12
+
13
+ @dataclass
14
+ class Arguments:
15
+ revision: str = "head" # Target revision
16
+
17
+ def execute(self, args):
18
+ from alembic import command
19
+
20
+ from . import alembic_config
21
+
22
+ command.upgrade(alembic_config(), args.revision)
23
+
24
+
25
+ COMMANDS = Upgrade