Metadata-Version: 2.4
Name: perchance-chat-api
Version: 0.1.1
Summary: Local REST API for Perchance-style character chat
Author: Enginestein
License-Expression: MIT
Project-URL: Homepage, https://github.com/enginestein/perchance-api
Project-URL: Source, https://github.com/enginestein/perchance-api
Project-URL: Issues, https://github.com/enginestein/perchance-api/issues
Keywords: perchance,character-chat,fastapi,local-api
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: FastAPI
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi<1,>=0.110
Requires-Dist: uvicorn[standard]>=0.27
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic>=2.6
Requires-Dist: pydantic-settings>=2.2
Requires-Dist: aiosqlite>=0.20
Requires-Dist: playwright>=1.44
Requires-Dist: rich>=13
Requires-Dist: prompt-toolkit>=3
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Dynamic: license-file

# Perchance Character Chat API

A local FastAPI server for Perchance-style character chat: define characters, build
multi-character conversations, keep lorebook/memory state, generate replies, and attach
generated images to chats.

> This project is not affiliated with Perchance. It drives the web endpoints used by
> Perchance's own pages through a browser because direct HTTP requests are blocked by
> Cloudflare. Those endpoints and their prompt format can change without notice; respect
> Perchance's terms and avoid heavy automated traffic.

## Features

- Character records with description, instruction, reminder, greeting, and strict rules.
- Per-character lorebook entries with keys, position (`before` / `after`), and priority.
- Chats with multiple characters, configurable user name, memory, and generation settings.
- Perchance-compatible prompt assembly (`<MESSAGES>`, `>>> TASK`, `startWith`, stop sequences).
- Non-streaming and SSE streaming generation endpoints.
- Automatic or manual memory summaries.
- Image generation attached to chat messages, with a pluggable HTTP image backend.
- SQLite persistence in a single local file.
- Optional Bearer-token protection for local network use.

## Install

Python 3.10+ and Chrome are required. Perchance uses Cloudflare Turnstile, so headful
Chrome is the reliable path. Its window can be kept off-screen.

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install perchance-chat-api
playwright install chromium   # optional fallback if Chrome is unavailable
```

Settings come from environment variables or a `.env` file in the current directory.
See [Configuration](#configuration) for the full list. Start the server:

```bash
perchance-chat-api
```

To work from a source checkout:

```bash
git clone https://github.com/enginestein/perchance-api.git
cd perchance-api
pip install -e ".[dev]"
cp .env.example .env
uvicorn perchance_chat_api.main:app --host 127.0.0.1 --port 8000
```

Interactive docs: <http://127.0.0.1:8000/docs>  
OpenAPI JSON: <http://127.0.0.1:8000/openapi.json>

The first `/v1/chats/{id}/generate` call starts Chrome. Set `ACC_BROWSER_OFFSCREEN=true`
to place its window off-screen. If Turnstile asks for interaction, move the mouse over
the window. The browser session stays warm between requests.

If `ACC_API_KEY` is set, send `Authorization: Bearer <key>` with every request.

## Quick start

```bash
# Create a character
CHAR=$(curl -s -X POST http://127.0.0.1:8000/v1/characters \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "Chloe",
    "description": "A friendly, curious assistant who speaks in short, warm sentences.",
    "instruction": "Ask thoughtful follow-up questions.",
    "reminder": "Stay in character.",
    "greeting": "Hi! What are you working on today?",
    "strict_rules": ["Chloe speaks in first person.", "Never claim to be human."]
  }' | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')

# Add a lorebook fact
curl -s -X POST "http://127.0.0.1:8000/v1/characters/$CHAR/lore" \
  -H 'Content-Type: application/json' \
  -d '{"keys":["tea","coffee"],"content":"Chloe likes tea and dislikes coffee.","position":"before"}'

# Create a chat (greeting is inserted automatically)
CHAT=$(curl -s -X POST http://127.0.0.1:8000/v1/chats \
  -H 'Content-Type: application/json' \
  -d "{\"title\":\"First chat\",\"character_ids\":[\"$CHAR\"]}" \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')

# Add a user message
curl -s -X POST "http://127.0.0.1:8000/v1/chats/$CHAT/messages" \
  -H 'Content-Type: application/json' \
  -d '{"role":"user","content":"I am building a local chatbot API."}'

# Generate a reply
curl -s -X POST "http://127.0.0.1:8000/v1/chats/$CHAT/generate" \
  -H 'Content-Type: application/json' \
  -d '{"num_messages":1}'
```

See [`examples/curl.sh`](examples/curl.sh) for a complete scripted walkthrough. It auto-detects
a server on ports 8000, 8080, or 3000; override with `BASE=http://127.0.0.1:PORT bash examples/curl.sh`.

## Terminal chat client

`assistant-chat` is a terminal client for a character named **assistant**. It reuses the
same character and chat between runs, streams replies, and keeps memory in the API.

```bash
assistant-chat
```

It checks ports 8080, 8000, and 3000. To choose one:

```bash
ASSISTANT_API_BASE=http://127.0.0.1:8080 assistant-chat
```

From a source checkout, `python3 examples/assistant_chat.py` runs the same client.

Character and chat IDs are stored in `~/.assistant_chat.json`. Use `--state PATH` for another
session.

Commands:

| Command | Meaning |
| --- | --- |
| `/help` | list commands |
| `/memory` | show stored memory |
| `/remember <text>` | add a durable memory |
| `/forget` | clear memory |
| `/summarize` | summarize recent chat into memory |
| `/history` | show the last 12 messages |
| `/image <prompt>` | generate an image into the chat |
| `/reset` | start a fresh chat |
| `/clear` | clear screen |
| `/exit` | leave |

One-shot flags:

```bash
assistant-chat --remember "I prefer tea over coffee."
assistant-chat --show-memory
assistant-chat --once "What do I prefer to drink?"
```

## Endpoints

| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/v1/health` | Server and backend status |
| POST/GET | `/v1/characters` | Create/list characters |
| GET/PATCH/DELETE | `/v1/characters/{id}` | Read/update/delete character |
| POST/GET | `/v1/characters/{id}/lore` | Create/list lorebook entries |
| PATCH/DELETE | `/v1/lore/{id}` | Update/delete lorebook entry |
| POST/GET | `/v1/chats` | Create/list chats |
| GET/PATCH/DELETE | `/v1/chats/{id}` | Read/update/delete chat |
| GET/POST | `/v1/chats/{id}/messages` | List/add messages |
| PUT | `/v1/chats/{id}/memory` | Replace chat memory |
| POST | `/v1/chats/{id}/memory/summarize` | Summarize recent messages into memory |
| POST | `/v1/chats/{id}/generate` | Generate and persist assistant messages |
| POST | `/v1/chats/{id}/generate/stream` | Same, streamed as SSE |
| POST | `/v1/images` | Generate a standalone image |
| POST | `/v1/chats/{id}/images` | Generate an image and attach it to a chat message |
| GET | `/v1/images` | List images |
| GET | `/v1/images/{id}` | Image metadata (includes `data_url`) |
| GET | `/v1/images/{id}/download` | Raw image bytes |

### Streaming

`POST /v1/chats/{id}/generate/stream` returns Server-Sent Events:

```text
data: {"type":"token","text":" Hi"}

data: {"type":"token","text":" there"}

data: {"type":"done","raw_text":" Hi there","messages":[...],"prompt_chars":1234}
```

Errors arrive as `{"type":"error","detail":"...","code":"..."}`.

### Multi-character chats

Provide several character IDs when creating a chat. By default the first character speaks.
Override with `"speaker": "Name"` in the chat settings or an individual generate request.
Each character's description, instruction, reminder, and rules are included in the prompt;
all characters can speak in the same conversation.

### Lorebook and memory

Lorebook entries are matched against the last 10 messages using case-insensitive substring
matching on their keys. `before` entries are placed with the character notes; `after` entries
are placed just after the `<MESSAGES>` block. Higher `priority` entries are considered first.

Set `"settings": {"auto_memory": true, "auto_memory_every": 20}` on a chat to summarize every
20 messages automatically. You can also call the summarize endpoint manually.

## Configuration

All settings are read from `.env` with the `ACC_` prefix. See [`.env.example`](.env.example).

| Variable | Default | Description |
| --- | --- | --- |
| `ACC_HOST` / `ACC_PORT` | `127.0.0.1` / `8000` | Recommended uvicorn bind values |
| `ACC_DB_PATH` | `./data/perchance-chat.db` | SQLite database location |
| `ACC_API_KEY` | empty | Optional Bearer token |
| `ACC_HEADLESS` | `false` | Headless Chrome is often blocked by Cloudflare |
| `ACC_BROWSER_OFFSCREEN` | `false` | Keep Chrome headful but move its window off-screen |
| `ACC_CHROME_CHANNEL` | `chrome` | Chrome channel; clear it to use Playwright Chromium |
| `ACC_CHROME_CDP_URL` | empty | Attach to an existing Chrome via CDP (for example `http://127.0.0.1:9222`) |
| `ACC_VERIFY_TIMEOUT_SECONDS` | `60` | Turnstile wait time |
| `ACC_GENERATE_TIMEOUT_SECONDS` | `180` | Text generation timeout |
| `ACC_IMAGE_PROVIDER` | `perchance` | `perchance` browser UI or `http` custom endpoint |
| `ACC_IMAGE_API_URL` | empty | Required when `ACC_IMAGE_PROVIDER=http` |
| `ACC_IMAGE_API_KEY` | empty | Optional Bearer token for the HTTP image endpoint |

The HTTP image endpoint receives JSON:

```json
{
  "prompt": "...",
  "negative_prompt": "...",
  "shape": "square",
  "resolution": "768x768",
  "seed": -1,
  "guidance_scale": 7.0,
  "style": ""
}
```

It should return `{"data_url": "data:image/png;base64,...", "width": 768, "height": 768}`
or `{"url": "https://..."}`.

## Connecting to your own Chrome / Perchance session

By default the API launches its own headful Chrome profile. If you want it to use **your**
browser profile, cookies, and existing Perchance `userKey`, start Chrome with remote debugging:

```bash
google-chrome --remote-debugging-port=9222 --user-data-dir="$HOME/.config/google-chrome-perchance-api"
```

Then set in `.env`:

```env
ACC_CHROME_CDP_URL=http://127.0.0.1:9222
```

The API attaches to that browser and opens its own tab inside it. That tab shares the same
profile storage as your normal Perchance tabs, so an already-verified session is reused. It
does **not** take over or type into an existing chat tab; it drives its own tab through the
same origin so your identity carries over.

Restart the API after changing this setting. `GET /v1/health` reports
`"backend": {"mode": "attached"}` when CDP mode is active.

## Scope

Included:

- per-character instruction, reminder, greeting, strict rules, and description
- lorebook and persistent summary memory
- multi-character group chats
- streaming replies for chat UIs

Limits:

- This is an unofficial wrapper around Perchance's web endpoints, not a supported public API.
- Cloudflare/Turnstile, Perchance rate limits, and prompt-format changes can break it.
- Image generation through Perchance is best-effort because of their ad-access/one-time setup.
- Attach-to-browser shares your profile, but the server still automates its own tab; it does
  not expose Perchance's full website UI or your existing chat history in a supported way.

## Running without a visible window

Cloudflare blocks normal headless Chrome here, so the browser still needs to run headful.
You can keep its window out of sight:

```env
ACC_HEADLESS=false
ACC_BROWSER_OFFSCREEN=true
```

This launches Chrome at an off-screen position. It works with the same verification path as a
visible window. If you attach with `ACC_CHROME_CDP_URL`, use your existing browser and its window
settings instead.

On a server without a desktop, Xvfb is another option:

```bash
xvfb-run -a perchance-chat-api
```

## Troubleshooting

- **Cloudflare block / verification timeout:** keep `ACC_HEADLESS=false`, use a real Chrome
  window, and move the mouse when asked. Do not hammer the endpoint; Perchance rate-limits.
- **`client_update_required`:** the live client changed. Update
  `perchance_chat_api/perchance.py` to match the current `/api/generate` query and body fields.
- **`invalid_key`:** the backend automatically clears the key and retries verification.
- **Image generation stuck at "One-time setup":** Perchance currently gates this behind an
  ad-access code and a one-time setup step that may not complete in an automated fresh profile.
  Use `ACC_IMAGE_PROVIDER=http` with your own image endpoint for reliable image generation.
- **No display on a server:** run under Xvfb (`xvfb-run -a uvicorn ...`) or use a machine with
  a desktop session. Headless mode may still be challenged.

## Tests

```bash
python3 -m pytest -q
```

## Notes on compatibility

The prompt template and stream format deliberately mirror Perchance's character-chat client
so existing character prompts behave similarly. This is a best-effort reimplementation,
not a guaranteed API contract. Because generation runs in Chrome, each server instance
serializes requests through a lock to avoid Perchance's `network_busy` errors.

## Build and publish

Bump the version in `pyproject.toml` and `perchance_chat_api/__init__.py`, then:

```bash
python3 -m build
python3 -m twine check dist/*
python3 -m twine upload dist/*
```
