Metadata-Version: 2.5
Name: chatsaver
Version: 0.1.0
Summary: Resumable session wrapper around LLM inference servers (vLLM, llama.cpp, ...)
Project-URL: Homepage, https://github.com/Delaunay/chatsaver
Project-URL: Issues, https://github.com/Delaunay/chatsaver/issues
Author-email: Pierre Delaunay <pierre.delaunay@mila.quebec>
License-Expression: BSD-3-Clause
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.12
Requires-Dist: alembic
Requires-Dist: argklass>=2.4
Requires-Dist: fastapi
Requires-Dist: httpx
Requires-Dist: python-multipart
Requires-Dist: sqlalchemy>=2.0
Requires-Dist: uvicorn[standard]
Provides-Extra: client
Requires-Dist: openai>=3.60.0; extra == 'client'
Description-Content-Type: text/markdown

# chatsaver

[![PyPI](https://img.shields.io/pypi/v/chatsaver.svg)](https://pypi.org/project/chatsaver/)
[![Python Versions](https://img.shields.io/pypi/pyversions/chatsaver.svg)](https://pypi.org/project/chatsaver/)
[![Tests](https://github.com/Delaunay/chatsaver/actions/workflows/test.yml/badge.svg)](https://github.com/Delaunay/chatsaver/actions/workflows/test.yml)

Resumable session wrapper around LLM inference servers (vLLM, llama.cpp, ...)

Clients talk to chatsaver instead of the LLM server. chatsaver launches and supervises
the LLM server, runs every generation in the background, and saves each conversation
to its own folder on disk. If the client loses its connection, it reconnects and picks up
the stream where it stopped. If the LLM server hangs or dies, chatsaver retries the turn.
If chatsaver itself is restarted, the conversations are still on disk.

```bash
pip install chatsaver     # or: uv tool install chatsaver

# launch vLLM (or --backend llamacpp / sglang) behind chatsaver on :8000
chatsaver serve --backend vllm --model Qwen/Qwen3-8B --llm-args "--max-model-len 32768"
# or wrap an LLM server that is already running
chatsaver serve --upstream http://gpu-node:8000

chatsaver chat --session my-run     # interactive, resumable chat
chatsaver sessions [--show my-run]  # inspect saved sessions (offline)
```

### Session folder

```
sessions/<session_id>/
    session.json                  model, default params, system prompt
    turns/000001/
        request.json              request_id + the full prompt sent to the LLM
        status.json               pending | running | done | failed | interrupted | cancelled
        chunks.jsonl              every streamed delta, append-only (line number = event id)
        response.json             final assistant message, finish_reason, usage
```

### Native API (resumable)

| Endpoint | |
|---|---|
| `POST /sessions` | create or resume a session (`session_id` optional) |
| `POST /sessions/{id}/turns` | `{messages, params, request_id, stream, wait}`; the same `request_id` reattaches to the same turn |
| `GET /sessions/{id}/turns/{n}/events?offset=k` | SSE replay from event `k`, then tail (`Last-Event-ID` works too) |
| `GET /sessions/{id}/turns/{n}` | status and final response |
| `POST /sessions/{id}/turns/{n}/retry` | restart the turn (`{"continue_partial": true}` keeps the partial answer) |
| `POST /sessions/{id}/turns/{n}/cancel` | stop a generation |
| `GET /sessions/{id}/messages` | conversation history |
| `GET /llm`, `POST /llm/restart` | status and restart of the launched LLM server |

### OpenAI-compatible API (no client change)

chatsaver listens on `:8000`, where clients expect vLLM, and starts the LLM server on `:8001`.
Existing clients keep calling `http://<host>:8000/v1`:

- `POST /v1/chat/completions` is recorded. chatsaver works out which session a request
  belongs to from its messages: a request that resends a saved conversation plus a new
  message is the next turn of that session. Going back to an earlier point of a
  conversation starts a new session whose `parent` points to the original.
- A request resent within `--dedup-window` seconds (same messages and params), for example
  after a timeout or a lost connection, reattaches to the generation in progress or gets
  the saved answer. Nothing is generated twice. Use `--dedup-window 0` if identical
  requests should produce independent samples.
- If a generation has to restart because the LLM server dropped, stalled or crashed, the
  stream ends with an error. The client's usual retry then gets the restarted generation.
- Every other `/v1/*` endpoint (models, completions, embeddings, ...) is forwarded unchanged.
  Requests with `n > 1` are forwarded but not recorded.

Clients that want to choose the session themselves can skip the matching with the header
`X-Chatsaver-Session: <id>`, or the body field `"chatsaver_session": "<id>"` (OpenAI SDK:
`extra_headers` / `extra_body`). `Idempotency-Key: <key>` (or `X-Request-Id`) sets the
request identity explicitly; a request resent with the same key always reattaches.
Responses carry `X-Chatsaver-Session` and `X-Chatsaver-Turn`.

### Python client: the OpenAI client, plus sessions

`chatsaver.client.Client` is an `openai.OpenAI` (`AsyncClient` is an `openai.AsyncOpenAI`),
so all existing OpenAI code works with it. It adds:

- an `Idempotency-Key` on every chat completion, so when the connection drops it reconnects,
  the server reattaches the request, and a stream continues from the chunk where it stopped;
- `client.session(id)`: a conversation pinned to one session that keeps its own history;
- `client.chatsaver`: the session store (`list`, `get`, `messages`, `turn`, `retry`, `cancel`).

```python
import chatsaver.client

session = chatsaver.client.session("my-agent")  # new, or resumed with its history
session.send("Hello!")  # -> answer text
for text in session.stream("Tell me more"):
    print(text, end="", flush=True)
session.messages  # the whole conversation

session.chat.completions.create(model=..., messages=[...])  # raw OpenAI call, recorded in the session

client = chatsaver.client.Client(base_url="http://gpu-node:8000/v1")  # or $CHATSAVER_URL
other = client.session("other-agent")  # sessions are independent, can run in parallel
```

`pip install chatsaver[client]` installs the `openai` dependency.

## Development

Requires [uv](https://docs.astral.sh/uv/) and Node.js LTS.

```bash
git clone https://github.com/Delaunay/chatsaver.git
cd chatsaver
make install   # creates ./.venv (uv sync) + npm install

make front     # terminal 1: UI on :3000
make back      # terminal 2: API on :8000

make test      # pytest
make format    # ruff
uv run chatsaver --help
```

## Release

```bash
git tag v0.1.0 && git push origin v0.1.0   # builds and publishes to PyPI
```

## License

BSD-3-Clause
