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.
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 for the full list. Start the server:
perchance-chat-api
To work from a source checkout:
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
# 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 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.
assistant-chat
It checks ports 8080, 8000, and 3000. To choose one:
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:
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:
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.
| 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:
{
"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:
google-chrome --remote-debugging-port=9222 --user-data-dir="$HOME/.config/google-chrome-perchance-api"
Then set in .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:
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:
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. Updateperchance_chat_api/perchance.pyto match the current/api/generatequery 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=httpwith 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
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:
python3 -m build
python3 -m twine check dist/*
python3 -m twine upload dist/*
Metadata
Release files for perchance-chat-api 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| perchance_chat_api-0.1.1.tar.gz | 36.7 kB | Without provenance | Details for perchance_chat_api-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| perchance_chat_api-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for perchance_chat_api-0.1.1-py3-none-any.whl |
Total release size: 71.3 kB
Release files / perchance_chat_api-0.1.1.tar.gz
| Download URL | perchance_chat_api-0.1.1.tar.gz |
|---|---|
| Size | 36.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
77a7a54816888297855ba69346cea2e8f720730d1271be32fd0150e6959776ff
|
|
BLAKE2b-256 checksum How to use checksums |
3790e7c02f86b5284325f18a71e91f7e0072ca8285ac5b447597f5849355f147
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.10.12
|
Release files / perchance_chat_api-0.1.1-py3-none-any.whl
| Download URL | perchance_chat_api-0.1.1-py3-none-any.whl |
|---|---|
| Size | 34.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
bd04217f2a6e1365744cb1744b3f341dca93f3d202d415cb9e748b121fac83d1
|
|
BLAKE2b-256 checksum How to use checksums |
3124a943feb380f20aab70fc13394cb40a988a95500dd32767d53279452ea3b3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.10.12
|
Security for perchance-chat-api 0.1.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.