perchance-chat-api 0.1.1__tar.gz

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.
Files changed (25) hide show
  1. perchance_chat_api-0.1.1/LICENSE +21 -0
  2. perchance_chat_api-0.1.1/PKG-INFO +362 -0
  3. perchance_chat_api-0.1.1/README.md +327 -0
  4. perchance_chat_api-0.1.1/perchance_chat_api/__init__.py +3 -0
  5. perchance_chat_api-0.1.1/perchance_chat_api/browser.py +76 -0
  6. perchance_chat_api-0.1.1/perchance_chat_api/cli.py +13 -0
  7. perchance_chat_api-0.1.1/perchance_chat_api/config.py +41 -0
  8. perchance_chat_api-0.1.1/perchance_chat_api/db.py +130 -0
  9. perchance_chat_api-0.1.1/perchance_chat_api/images.py +220 -0
  10. perchance_chat_api-0.1.1/perchance_chat_api/main.py +729 -0
  11. perchance_chat_api-0.1.1/perchance_chat_api/models.py +165 -0
  12. perchance_chat_api-0.1.1/perchance_chat_api/perchance.py +283 -0
  13. perchance_chat_api-0.1.1/perchance_chat_api/prompt.py +130 -0
  14. perchance_chat_api-0.1.1/perchance_chat_api/terminal.py +509 -0
  15. perchance_chat_api-0.1.1/perchance_chat_api/utils.py +92 -0
  16. perchance_chat_api-0.1.1/perchance_chat_api.egg-info/PKG-INFO +362 -0
  17. perchance_chat_api-0.1.1/perchance_chat_api.egg-info/SOURCES.txt +23 -0
  18. perchance_chat_api-0.1.1/perchance_chat_api.egg-info/dependency_links.txt +1 -0
  19. perchance_chat_api-0.1.1/perchance_chat_api.egg-info/entry_points.txt +3 -0
  20. perchance_chat_api-0.1.1/perchance_chat_api.egg-info/requires.txt +13 -0
  21. perchance_chat_api-0.1.1/perchance_chat_api.egg-info/top_level.txt +1 -0
  22. perchance_chat_api-0.1.1/pyproject.toml +50 -0
  23. perchance_chat_api-0.1.1/setup.cfg +4 -0
  24. perchance_chat_api-0.1.1/tests/test_prompt.py +63 -0
  25. perchance_chat_api-0.1.1/tests/test_utils.py +40 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Enginestein
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,362 @@
1
+ Metadata-Version: 2.4
2
+ Name: perchance-chat-api
3
+ Version: 0.1.1
4
+ Summary: Local REST API for Perchance-style character chat
5
+ Author: Enginestein
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/enginestein/perchance-api
8
+ Project-URL: Source, https://github.com/enginestein/perchance-api
9
+ Project-URL: Issues, https://github.com/enginestein/perchance-api/issues
10
+ Keywords: perchance,character-chat,fastapi,local-api
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Framework :: FastAPI
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: fastapi<1,>=0.110
23
+ Requires-Dist: uvicorn[standard]>=0.27
24
+ Requires-Dist: httpx>=0.27
25
+ Requires-Dist: pydantic>=2.6
26
+ Requires-Dist: pydantic-settings>=2.2
27
+ Requires-Dist: aiosqlite>=0.20
28
+ Requires-Dist: playwright>=1.44
29
+ Requires-Dist: rich>=13
30
+ Requires-Dist: prompt-toolkit>=3
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=8; extra == "dev"
33
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # Perchance Character Chat API
37
+
38
+ A local FastAPI server for Perchance-style character chat: define characters, build
39
+ multi-character conversations, keep lorebook/memory state, generate replies, and attach
40
+ generated images to chats.
41
+
42
+ > This project is not affiliated with Perchance. It drives the web endpoints used by
43
+ > Perchance's own pages through a browser because direct HTTP requests are blocked by
44
+ > Cloudflare. Those endpoints and their prompt format can change without notice; respect
45
+ > Perchance's terms and avoid heavy automated traffic.
46
+
47
+ ## Features
48
+
49
+ - Character records with description, instruction, reminder, greeting, and strict rules.
50
+ - Per-character lorebook entries with keys, position (`before` / `after`), and priority.
51
+ - Chats with multiple characters, configurable user name, memory, and generation settings.
52
+ - Perchance-compatible prompt assembly (`<MESSAGES>`, `>>> TASK`, `startWith`, stop sequences).
53
+ - Non-streaming and SSE streaming generation endpoints.
54
+ - Automatic or manual memory summaries.
55
+ - Image generation attached to chat messages, with a pluggable HTTP image backend.
56
+ - SQLite persistence in a single local file.
57
+ - Optional Bearer-token protection for local network use.
58
+
59
+ ## Install
60
+
61
+ Python 3.10+ and Chrome are required. Perchance uses Cloudflare Turnstile, so headful
62
+ Chrome is the reliable path. Its window can be kept off-screen.
63
+
64
+ ```bash
65
+ python3 -m venv .venv
66
+ source .venv/bin/activate
67
+ pip install perchance-chat-api
68
+ playwright install chromium # optional fallback if Chrome is unavailable
69
+ ```
70
+
71
+ Settings come from environment variables or a `.env` file in the current directory.
72
+ See [Configuration](#configuration) for the full list. Start the server:
73
+
74
+ ```bash
75
+ perchance-chat-api
76
+ ```
77
+
78
+ To work from a source checkout:
79
+
80
+ ```bash
81
+ git clone https://github.com/enginestein/perchance-api.git
82
+ cd perchance-api
83
+ pip install -e ".[dev]"
84
+ cp .env.example .env
85
+ uvicorn perchance_chat_api.main:app --host 127.0.0.1 --port 8000
86
+ ```
87
+
88
+ Interactive docs: <http://127.0.0.1:8000/docs>
89
+ OpenAPI JSON: <http://127.0.0.1:8000/openapi.json>
90
+
91
+ The first `/v1/chats/{id}/generate` call starts Chrome. Set `ACC_BROWSER_OFFSCREEN=true`
92
+ to place its window off-screen. If Turnstile asks for interaction, move the mouse over
93
+ the window. The browser session stays warm between requests.
94
+
95
+ If `ACC_API_KEY` is set, send `Authorization: Bearer <key>` with every request.
96
+
97
+ ## Quick start
98
+
99
+ ```bash
100
+ # Create a character
101
+ CHAR=$(curl -s -X POST http://127.0.0.1:8000/v1/characters \
102
+ -H 'Content-Type: application/json' \
103
+ -d '{
104
+ "name": "Chloe",
105
+ "description": "A friendly, curious assistant who speaks in short, warm sentences.",
106
+ "instruction": "Ask thoughtful follow-up questions.",
107
+ "reminder": "Stay in character.",
108
+ "greeting": "Hi! What are you working on today?",
109
+ "strict_rules": ["Chloe speaks in first person.", "Never claim to be human."]
110
+ }' | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')
111
+
112
+ # Add a lorebook fact
113
+ curl -s -X POST "http://127.0.0.1:8000/v1/characters/$CHAR/lore" \
114
+ -H 'Content-Type: application/json' \
115
+ -d '{"keys":["tea","coffee"],"content":"Chloe likes tea and dislikes coffee.","position":"before"}'
116
+
117
+ # Create a chat (greeting is inserted automatically)
118
+ CHAT=$(curl -s -X POST http://127.0.0.1:8000/v1/chats \
119
+ -H 'Content-Type: application/json' \
120
+ -d "{\"title\":\"First chat\",\"character_ids\":[\"$CHAR\"]}" \
121
+ | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')
122
+
123
+ # Add a user message
124
+ curl -s -X POST "http://127.0.0.1:8000/v1/chats/$CHAT/messages" \
125
+ -H 'Content-Type: application/json' \
126
+ -d '{"role":"user","content":"I am building a local chatbot API."}'
127
+
128
+ # Generate a reply
129
+ curl -s -X POST "http://127.0.0.1:8000/v1/chats/$CHAT/generate" \
130
+ -H 'Content-Type: application/json' \
131
+ -d '{"num_messages":1}'
132
+ ```
133
+
134
+ See [`examples/curl.sh`](examples/curl.sh) for a complete scripted walkthrough. It auto-detects
135
+ a server on ports 8000, 8080, or 3000; override with `BASE=http://127.0.0.1:PORT bash examples/curl.sh`.
136
+
137
+ ## Terminal chat client
138
+
139
+ `assistant-chat` is a terminal client for a character named **assistant**. It reuses the
140
+ same character and chat between runs, streams replies, and keeps memory in the API.
141
+
142
+ ```bash
143
+ assistant-chat
144
+ ```
145
+
146
+ It checks ports 8080, 8000, and 3000. To choose one:
147
+
148
+ ```bash
149
+ ASSISTANT_API_BASE=http://127.0.0.1:8080 assistant-chat
150
+ ```
151
+
152
+ From a source checkout, `python3 examples/assistant_chat.py` runs the same client.
153
+
154
+ Character and chat IDs are stored in `~/.assistant_chat.json`. Use `--state PATH` for another
155
+ session.
156
+
157
+ Commands:
158
+
159
+ | Command | Meaning |
160
+ | --- | --- |
161
+ | `/help` | list commands |
162
+ | `/memory` | show stored memory |
163
+ | `/remember <text>` | add a durable memory |
164
+ | `/forget` | clear memory |
165
+ | `/summarize` | summarize recent chat into memory |
166
+ | `/history` | show the last 12 messages |
167
+ | `/image <prompt>` | generate an image into the chat |
168
+ | `/reset` | start a fresh chat |
169
+ | `/clear` | clear screen |
170
+ | `/exit` | leave |
171
+
172
+ One-shot flags:
173
+
174
+ ```bash
175
+ assistant-chat --remember "I prefer tea over coffee."
176
+ assistant-chat --show-memory
177
+ assistant-chat --once "What do I prefer to drink?"
178
+ ```
179
+
180
+ ## Endpoints
181
+
182
+ | Method | Path | Purpose |
183
+ | --- | --- | --- |
184
+ | GET | `/v1/health` | Server and backend status |
185
+ | POST/GET | `/v1/characters` | Create/list characters |
186
+ | GET/PATCH/DELETE | `/v1/characters/{id}` | Read/update/delete character |
187
+ | POST/GET | `/v1/characters/{id}/lore` | Create/list lorebook entries |
188
+ | PATCH/DELETE | `/v1/lore/{id}` | Update/delete lorebook entry |
189
+ | POST/GET | `/v1/chats` | Create/list chats |
190
+ | GET/PATCH/DELETE | `/v1/chats/{id}` | Read/update/delete chat |
191
+ | GET/POST | `/v1/chats/{id}/messages` | List/add messages |
192
+ | PUT | `/v1/chats/{id}/memory` | Replace chat memory |
193
+ | POST | `/v1/chats/{id}/memory/summarize` | Summarize recent messages into memory |
194
+ | POST | `/v1/chats/{id}/generate` | Generate and persist assistant messages |
195
+ | POST | `/v1/chats/{id}/generate/stream` | Same, streamed as SSE |
196
+ | POST | `/v1/images` | Generate a standalone image |
197
+ | POST | `/v1/chats/{id}/images` | Generate an image and attach it to a chat message |
198
+ | GET | `/v1/images` | List images |
199
+ | GET | `/v1/images/{id}` | Image metadata (includes `data_url`) |
200
+ | GET | `/v1/images/{id}/download` | Raw image bytes |
201
+
202
+ ### Streaming
203
+
204
+ `POST /v1/chats/{id}/generate/stream` returns Server-Sent Events:
205
+
206
+ ```text
207
+ data: {"type":"token","text":" Hi"}
208
+
209
+ data: {"type":"token","text":" there"}
210
+
211
+ data: {"type":"done","raw_text":" Hi there","messages":[...],"prompt_chars":1234}
212
+ ```
213
+
214
+ Errors arrive as `{"type":"error","detail":"...","code":"..."}`.
215
+
216
+ ### Multi-character chats
217
+
218
+ Provide several character IDs when creating a chat. By default the first character speaks.
219
+ Override with `"speaker": "Name"` in the chat settings or an individual generate request.
220
+ Each character's description, instruction, reminder, and rules are included in the prompt;
221
+ all characters can speak in the same conversation.
222
+
223
+ ### Lorebook and memory
224
+
225
+ Lorebook entries are matched against the last 10 messages using case-insensitive substring
226
+ matching on their keys. `before` entries are placed with the character notes; `after` entries
227
+ are placed just after the `<MESSAGES>` block. Higher `priority` entries are considered first.
228
+
229
+ Set `"settings": {"auto_memory": true, "auto_memory_every": 20}` on a chat to summarize every
230
+ 20 messages automatically. You can also call the summarize endpoint manually.
231
+
232
+ ## Configuration
233
+
234
+ All settings are read from `.env` with the `ACC_` prefix. See [`.env.example`](.env.example).
235
+
236
+ | Variable | Default | Description |
237
+ | --- | --- | --- |
238
+ | `ACC_HOST` / `ACC_PORT` | `127.0.0.1` / `8000` | Recommended uvicorn bind values |
239
+ | `ACC_DB_PATH` | `./data/perchance-chat.db` | SQLite database location |
240
+ | `ACC_API_KEY` | empty | Optional Bearer token |
241
+ | `ACC_HEADLESS` | `false` | Headless Chrome is often blocked by Cloudflare |
242
+ | `ACC_BROWSER_OFFSCREEN` | `false` | Keep Chrome headful but move its window off-screen |
243
+ | `ACC_CHROME_CHANNEL` | `chrome` | Chrome channel; clear it to use Playwright Chromium |
244
+ | `ACC_CHROME_CDP_URL` | empty | Attach to an existing Chrome via CDP (for example `http://127.0.0.1:9222`) |
245
+ | `ACC_VERIFY_TIMEOUT_SECONDS` | `60` | Turnstile wait time |
246
+ | `ACC_GENERATE_TIMEOUT_SECONDS` | `180` | Text generation timeout |
247
+ | `ACC_IMAGE_PROVIDER` | `perchance` | `perchance` browser UI or `http` custom endpoint |
248
+ | `ACC_IMAGE_API_URL` | empty | Required when `ACC_IMAGE_PROVIDER=http` |
249
+ | `ACC_IMAGE_API_KEY` | empty | Optional Bearer token for the HTTP image endpoint |
250
+
251
+ The HTTP image endpoint receives JSON:
252
+
253
+ ```json
254
+ {
255
+ "prompt": "...",
256
+ "negative_prompt": "...",
257
+ "shape": "square",
258
+ "resolution": "768x768",
259
+ "seed": -1,
260
+ "guidance_scale": 7.0,
261
+ "style": ""
262
+ }
263
+ ```
264
+
265
+ It should return `{"data_url": "data:image/png;base64,...", "width": 768, "height": 768}`
266
+ or `{"url": "https://..."}`.
267
+
268
+ ## Connecting to your own Chrome / Perchance session
269
+
270
+ By default the API launches its own headful Chrome profile. If you want it to use **your**
271
+ browser profile, cookies, and existing Perchance `userKey`, start Chrome with remote debugging:
272
+
273
+ ```bash
274
+ google-chrome --remote-debugging-port=9222 --user-data-dir="$HOME/.config/google-chrome-perchance-api"
275
+ ```
276
+
277
+ Then set in `.env`:
278
+
279
+ ```env
280
+ ACC_CHROME_CDP_URL=http://127.0.0.1:9222
281
+ ```
282
+
283
+ The API attaches to that browser and opens its own tab inside it. That tab shares the same
284
+ profile storage as your normal Perchance tabs, so an already-verified session is reused. It
285
+ does **not** take over or type into an existing chat tab; it drives its own tab through the
286
+ same origin so your identity carries over.
287
+
288
+ Restart the API after changing this setting. `GET /v1/health` reports
289
+ `"backend": {"mode": "attached"}` when CDP mode is active.
290
+
291
+ ## Scope
292
+
293
+ Included:
294
+
295
+ - per-character instruction, reminder, greeting, strict rules, and description
296
+ - lorebook and persistent summary memory
297
+ - multi-character group chats
298
+ - streaming replies for chat UIs
299
+
300
+ Limits:
301
+
302
+ - This is an unofficial wrapper around Perchance's web endpoints, not a supported public API.
303
+ - Cloudflare/Turnstile, Perchance rate limits, and prompt-format changes can break it.
304
+ - Image generation through Perchance is best-effort because of their ad-access/one-time setup.
305
+ - Attach-to-browser shares your profile, but the server still automates its own tab; it does
306
+ not expose Perchance's full website UI or your existing chat history in a supported way.
307
+
308
+ ## Running without a visible window
309
+
310
+ Cloudflare blocks normal headless Chrome here, so the browser still needs to run headful.
311
+ You can keep its window out of sight:
312
+
313
+ ```env
314
+ ACC_HEADLESS=false
315
+ ACC_BROWSER_OFFSCREEN=true
316
+ ```
317
+
318
+ This launches Chrome at an off-screen position. It works with the same verification path as a
319
+ visible window. If you attach with `ACC_CHROME_CDP_URL`, use your existing browser and its window
320
+ settings instead.
321
+
322
+ On a server without a desktop, Xvfb is another option:
323
+
324
+ ```bash
325
+ xvfb-run -a perchance-chat-api
326
+ ```
327
+
328
+ ## Troubleshooting
329
+
330
+ - **Cloudflare block / verification timeout:** keep `ACC_HEADLESS=false`, use a real Chrome
331
+ window, and move the mouse when asked. Do not hammer the endpoint; Perchance rate-limits.
332
+ - **`client_update_required`:** the live client changed. Update
333
+ `perchance_chat_api/perchance.py` to match the current `/api/generate` query and body fields.
334
+ - **`invalid_key`:** the backend automatically clears the key and retries verification.
335
+ - **Image generation stuck at "One-time setup":** Perchance currently gates this behind an
336
+ ad-access code and a one-time setup step that may not complete in an automated fresh profile.
337
+ Use `ACC_IMAGE_PROVIDER=http` with your own image endpoint for reliable image generation.
338
+ - **No display on a server:** run under Xvfb (`xvfb-run -a uvicorn ...`) or use a machine with
339
+ a desktop session. Headless mode may still be challenged.
340
+
341
+ ## Tests
342
+
343
+ ```bash
344
+ python3 -m pytest -q
345
+ ```
346
+
347
+ ## Notes on compatibility
348
+
349
+ The prompt template and stream format deliberately mirror Perchance's character-chat client
350
+ so existing character prompts behave similarly. This is a best-effort reimplementation,
351
+ not a guaranteed API contract. Because generation runs in Chrome, each server instance
352
+ serializes requests through a lock to avoid Perchance's `network_busy` errors.
353
+
354
+ ## Build and publish
355
+
356
+ Bump the version in `pyproject.toml` and `perchance_chat_api/__init__.py`, then:
357
+
358
+ ```bash
359
+ python3 -m build
360
+ python3 -m twine check dist/*
361
+ python3 -m twine upload dist/*
362
+ ```