Cadence (气口)
English | 中文
Let AI replies breathe.
气口 (qìkǒu) is a term from Chinese opera and storytelling. It is the breath point — the spot where a performer pauses mid-passage to take a new breath. A good qikou makes the words land naturally, with rhythm, never running out of air. A bad one leaves the audience behind and gasping. The English name, Cadence, comes from music: the close of a phrase, the rhythm of speech.
That is exactly what this project does for AI replies: find the breath points in a long reply — split one long response into several short messages so they read like a real person sending them one after another.
Table of Contents
- Why This Exists
- Features
- Installation
- Quick Start
- Using It as a Library
- Configuration
- Test Case Format
- Project Structure
- Design Tradeoffs
- Version History
- Roadmap
- Naming
- License
Why This Exists
AI replies tend to be long. Sent as-is to a social platform, they read like an essay. On WeChat, QQ, Discord, or Telegram, real people send messages like this:
- one idea per message, 10–40 characters
- a break after punctuation, with tone particles standing on their own
- lists, code blocks, and URLs kept intact
Chopping by character count breaks Markdown, URLs, and code blocks, and reads like a machine. Cadence does semantics-aware soft splitting.
Features
Core
- Chinese/English mixed sentence splitting: breaks after
。!?!?…, and after.when followed by whitespace or CJK - English abbreviation protection: 40+ entries such as
Mr.Dr.e.g.i.e.U.S.U.S.A.are never mis-split - Conjunction protection: Chinese correlatives (
虽然…但是,因为…所以) and English connectives (because,although,however) - Tilde as a soft sentence end: 8 variants (
~~〜and more), only after a real character; the operator~=, the range18~25, and the sub/superscriptH~2~Oare recognised and never treated as ends
Structure Awareness
- Markdown: never splits inside
**__~~`*_ - Quotes and brackets: never splits inside
“”「」『』()() - Code blocks: triple-backtick and
~~~fences are protected as a whole - URLs:
http(s)://is protected as a whole, and a short prefix is merged automatically - Lists: unordered, ordered, task, and nested lists become their own messages
- Tables: a Markdown table stays one message
- Headings:
#through######stand alone - Horizontal rules:
---***___stand alone - HTML breaks:
<br><br/><br />count as cut points
Kaomoji
- 55,000+ kaomoji in a trie index, exact match
- kaomoji at the end, the start, or the middle of a sentence are attached to the right message
- multiple upstream corpora can be merged
Post-processing
- Unclosed Markdown:
**and__are paired up at the end - Unclosed quotes:
“”「」『』are paired up at the end - Half-width brackets are never auto-closed: avoids misfiring inside kaomoji, formulas, and code
Output
- Adaptive length: long text relaxes the per-message cap so it does not shatter into pieces
- Message-count control: over the cap, the shortest adjacent pair is merged — but list items, headings, tables, and tilde endings are skipped
- Optional segment-level DP (v3.0.0): with
Config(use_dp=True)orqikou split --dp, prose lines/blocks overmax_charsare split by a global optimum. Off by default; output stays byte-identical to 2.2.2
Installation
Requirements: Python 3.9+. Zero third-party dependencies. The kaomoji corpus ships inside the package, so it works right after install.
git clone https://github.com/Grabrun/qikou.git
cd qikou
pip install .
This installs the qikou command; python -m qikou keeps working too. Installing is optional — you can also run it straight from the repository root.
Quick Start
Command line
qikou split file.txt # split a file
echo "long text" | qikou split # or read from stdin
qikou test # run the test cases (source checkout)
qikou menu # interactive menu
qikou --version
qikou --help
python -m qikou is equivalent to qikou; with no subcommand it prints the help.
Splitting
On a terminal you get decorated output:
$ qikou split reply.txt
====================================================
切分结果:5 条
参数:max=60 target=20 min=4 max_messages=6
====================================================
─── [1/5] 11 字 ───
好的,我来帮你规划。
─── [2/5] 27 字 ───
首先你需要确定目标,比如你想在三个月内学会 Python。
...
When the output is piped, only the message bodies are printed (blank-line separated), so grep / wc work as expected:
$ echo "你好。今天不错。再见。" | qikou split
你好。今天不错。
再见。
For machine-readable output use --json:
$ qikou split --json reply.txt
[
"好的,我来帮你规划。",
"首先你需要确定目标,比如你想在三个月内学会 Python。"
]
| Option | Effect |
|---|---|
-j, --json |
JSON output (array of strings) |
-q, --quiet |
message bodies only |
-c N, --max-chars N |
hard cap per message (smaller = choppier) |
-T N, --target-chars N |
ideal length |
-m N, --max-messages N |
soft cap on the message count |
--dp |
enable v3.0 segment-level DP (off by default; output changes) |
Interactive menu
qikou menu
====================================================
气口 —— AI 回复分句器
====================================================
[信息] 已加载 55213 条颜文字
请选择模式:
[1] 手动输入
[2] 自动测试(读取 test.txt)
[q] 退出
The command-line interface is currently Chinese-only; the menu labels above are quoted verbatim from the program. The split subcommand's output is your text, and --json is language-neutral.
Manual input
Choose [1], paste your text, and finish with a line containing EOF or with Ctrl-D:
> 好的,我来帮你规划。首先你需要确定目标,比如你想在三个月内学会 Python。然后每天安排 30 分钟练习基础语法。接着做一个小项目,比如爬虫或自动化脚本。最后定期复习并调整计划。
EOF
─── [1/5] 11 字 ───
好的,我来帮你规划。
─── [2/5] 27 字 ───
首先你需要确定目标,比如你想在三个月内学会 Python。
─── [3/5] 18 字 ───
然后每天安排 30 分钟练习基础语法。
─── [4/5] 21 字 ───
接着做一个小项目,比如爬虫或自动化脚本。
─── [5/5] 12 字 ───
最后定期复习并调整计划。
----------------------------------------------------
合计 89 字(最长 27 字)
The header of each block is [index/total] <character count> 字.
Running the test cases
qikou test # runs tests/test.txt
qikou test path/to/cases.txt # runs a specific file
Reads the case file, runs every case, and writes the report to tests/results/test_result_<timestamp>.txt. The report body is deterministic — no timestamps — so two runs over the same cases are byte-identical and can be diffed.
开始自动测试:.../tests/test.txt
----------------------------------------------------
[ 1/N] 001 中文句号后紧跟英文 → 2 条
[ 2/N] 002 中文问号后无空格 → 3 条
...
----------------------------------------------------
用时:<T> 秒
结果已保存到:
.../tests/results/test_result_<时间戳>.txt
Help
qikou --help
Using It as a Library
from qikou import split
text = "好的,我来帮你规划。首先你需要确定目标。然后每天练习。最后定期复习。"
for message in split(text):
print(message)
split() returns list[str]. The kaomoji corpus is loaded automatically on first use (about 0.25 s for 55213 entries); you normally never have to touch it.
Whitespace contract: leading/trailing whitespace of the input is dropped; whitespace at a message boundary (tabs included) is not preserved; whitespace inside a message is kept as-is.
A message that genuinely cannot be cut (an over-long bold run, a quoted run, a code block) is allowed to exceed max_chars. Pass a callback if you need to know:
def report(message, cap):
log.warning("oversize %d chars (cap %d): %s…", len(message), cap, message[:20])
messages = split(text, on_overflow=report)
v3.0 segment-level DP (optional)
use_dp is off by default. When enabled, build_units stops pre-splitting prose
lines into sentences and hands the whole line/block to DP; headings, tables,
and list markers remain hard boundaries. This release is segment-level only;
it does not run DP across paragraphs.
from qikou import Config, split_with_report
result = split_with_report(text, config=Config(use_dp=True))
print(result.messages)
print(result.fallback_count, result.over_max_chars, result.over_max_messages)
SplitResult fields:
| Field | Meaning |
|---|---|
messages |
split messages |
fallback_count |
prose units that entered the structural fallback pass |
unsafe_cuts |
fallback cuts inside unclosed Markdown / brackets |
over_max_chars |
messages still over max_chars |
over_max_messages |
messages above the soft max_messages cap |
split() keeps its old signature and still returns list[str].
Custom configuration
from qikou import Config, split
config = Config(
max_chars=80, # hard cap per message
target_chars=30, # ideal length
min_chars=5, # below this, try to merge
max_messages=8, # soft cap on the number of messages
)
messages = split(text, config=config) # config is never modified
Config is a dataclass, so dataclasses.replace() gives you a derived copy:
import dataclasses
from qikou import Config
loose = dataclasses.replace(Config(), max_chars=200, target_chars=80)
Preloading or replacing the corpus
from qikou import load_kaomojis, kaomoji_count
load_kaomojis() # preload the bundled corpus, returns the count
load_kaomojis("my-kaomojis.txt") # use your own
print(kaomoji_count()) # entries currently loaded
A missing corpus only logs a warning; splitting continues without kaomoji recognition.
Configuration
Every parameter of the Config class:
| Parameter | Default | Meaning |
|---|---|---|
max_chars |
60 | Hard cap per message. Exceeding it triggers a split. An explicit value is never scaled up |
target_chars |
20 | Ideal length. The preferred region for a cut |
min_chars |
4 | Below this, try to merge with a neighbour |
max_messages |
6 | Soft cap on the message count. Over it, adjacent pairs are merged; <= 0 means unlimited |
atomic_merge_prefix |
20 | Threshold for merging a short prefix with a long atomic fragment |
merge_max_chars |
60 | Cap after a merge (never above max_chars) |
auto_scale |
True |
Whether the defaults grow with the total length. Set False to pin the config |
use_dp |
False |
Enable v3.0 segment-level DP; off keeps 2.2.2 output |
dp_cut_cost |
1.20 | Fixed cost per DP cut (normalised scale) |
candidate_cap_per_100 |
12 | Max candidates per 100 visible characters |
Config validates its arguments: a wrong type raises TypeError, an impossible value such as max_chars <= 0 raises ValueError.
max_messages is a soft cap, and it competes with the per-message cap: over the limit, the shortest adjacent pair inside the same paragraph is merged first; if that cannot reach the cap, paragraphs are merged too (joined with a blank line). A merged message stays within min(merge_max_chars, max_chars). The count therefore has a hard floor ⌈visible chars / merge cap⌉; a cap below that floor cannot be met. Measured (the >800-character tier: 10 messages, merge cap 160):
| Total | Actual messages | Note |
|---|---|---|
| 793 chars (36 paragraphs) | 7 | meets the cap (8 for this tier) |
| 1598 chars (66 paragraphs) | 10 | meets the cap |
| 3248 chars (135 paragraphs) | 21 | equals the floor ⌈3248/160⌉; cannot go lower |
On top of that, list items, headings, tables, horizontal rules, standalone code blocks / URLs, and entries ending in a tilde never take part in a merge, so a reply full of structure can end up higher still.
Adaptive length: split() relaxes the fields that are still at their default (explicitly set fields are kept as given):
| Total length | max_chars | target_chars | max_messages | merge_max_chars |
|---|---|---|---|---|
| ≤ 150 | 60 | 20 | 6 | 60 |
| ≤ 400 | 90 | 30 | 6 | 90 |
| ≤ 800 | 120 | 45 | 8 | 120 |
| > 800 | 160 | 60 | 10 | 160 |
To shift the overall feel (choppier or longer), change max_chars and target_chars.
split() never modifies the Config you pass in; the scaling is applied to an internal copy.
Test Case Format
The format of tests/test.txt:
[CASE] 001 Chinese full stop
你好。今天不错。再见。
[CASE] 002 English period
Hello. How are you?
[CASE] 003 Tilde
好耶~ 就这么定了!
- every case starts with
[CASE] <number> <short description> - the body runs until the next
[CASE]or the end of the file - whitespace-only cases are kept (0 messages) for boundary testing
To add a case, just edit the file.
Cases hold inputs only — there are no expected outputs. --test is therefore a deterministic report generator rather than an assertion suite: it fails only if a case raises. Read the reports, or diff two of them, to catch behaviour changes.
Project Structure
ChatSplit/
├── qikou/ # core package (shipped in the wheel)
│ ├── __init__.py # public exports
│ ├── __main__.py # python -m qikou entry point
│ ├── cli.py # CLI / menu / auto test
│ ├── config.py # Config class
│ ├── candidates.py # v3.0 candidates and coverage-skeleton pruning
│ ├── dp.py # v3.0 segment-level DP solver
│ ├── patterns.py # regexes and structural checks
│ ├── lexicon.py # abbreviation list, conjunction list, base scores
│ ├── kaomoji.py # kaomoji trie
│ ├── protect.py # code block / URL placeholder protection
│ ├── postprocess.py # closing unclosed markers
│ ├── splitter.py # core splitting logic
│ ├── kaomojis.txt # kaomoji corpus, 55,213 entries (shipped in the wheel)
│ └── py.typed # PEP 561 marker
├── tests/
│ ├── test.txt # test cases (inputs only)
│ ├── test_qikou.py # pytest assertions
│ ├── test_candidates.py # v3.0 candidate tests
│ ├── test_dp.py # v3.0 DP and invariant tests
│ ├── bench.py # v3.0 DP smoke benchmark
│ ├── golden.py # golden-hash check
│ ├── baseline/cases.sha256 # default baseline for 205 case outputs
│ ├── baseline/cases-dp.sha256 # DP baseline for 205 case outputs
│ └── results/ # generated reports (not tracked)
├── docs/
│ ├── README.md # documentation index (Chinese)
│ └── project-layout.md # layout conventions and maintenance rules (Chinese)
├── local/ # machine-local, never committed (see local/README.md)
├── dist/ # build artifacts (not tracked)
├── pyproject.toml # packaging metadata (PEP 621)
├── MANIFEST.in # sdist contents
├── README.md # Chinese README
├── README_en-US.md # this file
└── LICENSE # MIT
Module responsibilities
| Module | Responsibility |
|---|---|
patterns.py |
all regexes, character sets, and structural predicates |
lexicon.py |
abbreviation list, conjunction list, base punctuation scores |
config.py |
configuration parameters, adaptive length |
candidates.py |
v3.0 candidate generation, density cap, coverage skeleton |
dp.py |
v3.0 DP: boundary scores, strict/fallback passes, tie-break |
kaomoji.py |
loading and matching the kaomoji trie |
protect.py |
protecting and restoring code block / URL placeholders |
postprocess.py |
closing unclosed Markdown and quotes |
splitter.py |
sentence splitting, packing, scoring, cut search, main entry point |
cli.py |
argument parsing, manual input, automated test |
Design Tradeoffs
Every decision in the splitter is a tradeoff between semantic completeness and length tidiness. The following are deliberate choices, not bugs:
| Scenario | Behaviour | Reason |
|---|---|---|
| Long run with no punctuation | kept whole, allowed to exceed the cap | an arbitrary hard cut would be meaningless |
| Over-long code block / table | stays one message | splitting it would break the structure |
A sentence after etc. |
not split | abbreviation ambiguity has no clean answer; stay conservative |
| Unclosed half-width bracket | not auto-closed | too risky inside kaomoji, formulas, and code |
A single message slightly over max_chars |
allowed | semantics first; better long than shattered |
| Very long text cut after a preposition | unsolved | the ceiling of the rule approach; v3.0b addresses it |
| Kaomoji next to a tilde | each becomes its own message | ~ is a soft sentence end and stands semantically alone |
| Uncuttable over-long run (bold / quoted / code) | kept whole, may far exceed max_chars |
cutting it would break Markdown and quoting; use on_overflow to observe |
| Multi-paragraph long text | paragraphs are merged (blank line) when the cap is otherwise unreachable | otherwise every paragraph is a message and the count grows with paragraph count |
| v3.0 segment-level DP | global optimum only inside a prose line/block, not across paragraphs | tables, headings, lists, and code blocks must stay atomic; whole-document DP is deferred to 3.1 |
| Half-width single quote | not paired-protected | it doubles as the English apostrophe; opener vs possessive is undecidable |
Version History
v3.0.0 (current)
The first stage of "Prosody": zero-data, zero-model segment-level DP, off by
default. The default path is byte-identical to 2.2.2 (old golden
D2678A2D…185392 unchanged); enabling it changes output and has its own
baseline, tests/baseline/cases-dp.sha256.
Config(use_dp=True)/qikou split --dp: prose lines are no longer pre-split into sentences; DP finds the best cut inside each line/block- candidate generation with a 12-per-100-character density cap, plus a coverage skeleton that keeps at least one candidate per
max_charswindow - two-pass structural policy: the strict pass forbids cuts inside unclosed Markdown/brackets; the fallback pass allows them and marks the result
split_with_report()/SplitResultexposes fallback, unsafe-cut, oversize and over-count numbers- new
dp_cut_costandcandidate_cap_per_100options; new tests andtests/bench.py - performance (local Python 3.13): 500-char DP P95 about 1.1–1.4 ms, 2,000 chars 5–6 ms, 10,000 chars about 46 ms
- scope is explicit: 3.0.0 is segment-level DP; cross-paragraph/whole-document DP and the model belong to 3.1
v2.2.2
Fixes from the 2026-11 deep audit. Behaviour is unchanged on the 205-case corpus (byte-identical output); what changed is the contract and the scaling.
- an explicit
max_charsis no longer scaled up:Config(max_chars=30)means 30, andqikou split -c 30now applies to long texts - long-text cost is linear instead of quadratic: 118.9k chars 135.9 s → 187 ms, unclosed fence 80k chars 8.2 s → 201 ms
- list markers stay attached to their content (no more bubbles containing only
-) - the message cap works on multi-paragraph text (paragraphs are merged when the cap is otherwise unreachable)
- placeholders moved to the private-use area and are escaped, so input containing NUL or placeholder-shaped runs round-trips losslessly
Configvalidates its arguments;max_messages <= 0explicitly means unlimitedsplit()gained anon_overflowcallback for messages that cannot be cutqikou testlocates the repo viaQIKOU_REPOor a real case file;QIKOU_REPORT_DIRpicks the report directory- CI adds a Windows matrix and a 205-case golden check (
tests/golden.py --check)
v2.2.1
requires-pythonraised to>=3.9(required by thesetuptools>=77build backend); the runtime still works on 3.8
v2.2.0
- first public release: standard packaging,
py.typed, a console entry point, a test suite and GitHub Actions
v2.1
- packaging standardised:
pyproject.toml(PEP 621),py.typed(PEP 561), aqikouconsole entry point - API standardised:
split(text, config=None) -> list[str],Configis a dataclass - CLI switched to subcommands:
qikou split/qikou test/qikou menu, with stdin and--json - the kaomoji corpus ships inside the wheel and is loaded lazily on first use
- human-like delays removed — the project now focuses on splitting quality alone
v2.0
Cadence. Rules plus scoring.
- split into the
qikoupackage - modularised: patterns / lexicon / config / kaomoji / protect / postprocess / splitter / cli
- 120 test cases covering a broad range of edge cases, all running without error
- command:
python -m qikou ChatSplit-v1.0.py/ChatSplit-v2.0.pyarchived underlocal/archive/legacy-v1-v2/(kept locally, not committed)- human-like delay timeline (removed in v2.1)
v1.0
ChatSplit. Single-file rule-based version.
- basic sentence splitting:
。!?!?… - 8 tilde variants as soft sentence ends
- kaomoji trie
- code block and URL protection
- list, table, and quote detection
- unclosed Markdown / quote completion
- human-like delay timeline
- interactive menu plus automated test
Roadmap
v3.0 Prosody (in progress)
v3.0a (3.0.0, shipped): zero-data, zero-model segment-level DP, off by default. It first makes the structural/length guardrails and performance a reversible baseline.
v3.0b (3.1.0, gated): candidate binary classification + pure-Python inference + gated fusion. Start with a 50-document human gold pilot; only a Kappa ≥0.8 allows the data/model phase. If it fails, stop at 3.0.0 instead of expanding data to hide the problem.
- data: LLM synthesis + rule weak supervision + real logs (anonymised), with three-level deduplication
- features: local characters + position/length + semantic lexicon + structural state + rule score (first version ≤25 features)
- model: trained with LightGBM, shipped as a flat tree plus a pure-Python evaluator; runtime stays dependency-free
- hardware: an ordinary 4-core CPU and 8 GB RAM is enough — no GPU
It addresses the ceiling of the rule approach:
- semantic boundary ≠ punctuation boundary (e.g.
我觉得吧,这个方案,可能还需要再想想) - long-text cut optimisation (e.g. after
torather than afterand) - tone versus information (e.g. is
好吧。那就这样。one message or two?)
The full design and pre-research numbers are an internal document and are not shipped with the repository.
v4.0 Breathing (long term)
Small Transformer. Reconsider once there are more than 50,000 samples. Training needs a GPU; inference runs on CPU. Learns candidate generation, cut selection, and packing end to end.
Naming
气口 (qìkǒu) — a term from Chinese opera and storytelling: the spot where a performer breathes and pauses. A good qikou makes a passage land naturally, with rhythm, never out of air; a bad one leaves the listener gasping.
The English name is Cadence (the close of a musical phrase; the rhythm of speech), and the package name is qikou.
Version names:
| Version | Name | Kernel |
|---|---|---|
| v1 | 吐字 (Articulation) | hard rules |
| v2 | 气口 (Cadence) | rules + scoring |
| v3 | 韵律 (Prosody) | DP + segment model |
| v4 | 呼吸 (Breathing) | Transformer |
Each version is another step towards learning how to breathe.
License
MIT © 2026 Grabrun
Note on the kaomoji data
The kaomoji corpus in qikou/kaomojis.txt comes from https://kaomojis.jp.
A kaomoji is a combination of symbols and normally does not constitute a copyrightable original work. Terms of use differ between sources, however, so this project makes no legal warranty regarding the redistribution of the corpus.
If a rights holder considers the inclusion or redistribution of the corpus inappropriate, please reach out through a GitHub Issue and we will adjust or remove it promptly.
Metadata
Release files for qikou 3.0.0
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 |
|---|---|---|---|---|
| qikou-3.0.0.tar.gz | 542.0 kB | Without provenance | Details for qikou-3.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| qikou-3.0.0-py3-none-any.whl | Python 3 | none | any | Details for qikou-3.0.0-py3-none-any.whl |
Total release size: 1.0 MB
Release files / qikou-3.0.0.tar.gz
| Download URL | qikou-3.0.0.tar.gz |
|---|---|
| Size | 542.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4d76a4aa076a305f3be27d2e3a0c3282ce6b8797868a235621bc33c51936c085
|
|
BLAKE2b-256 checksum How to use checksums |
bf3e88aea151c31c3d0a2dd66a661d7216180186f4778f6754a15c8474ac751f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.18
|
Release files / qikou-3.0.0-py3-none-any.whl
| Download URL | qikou-3.0.0-py3-none-any.whl |
|---|---|
| Size | 495.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
21e928b4c0416993fd593d9513b5db7eeba794efd6af360467c7d82a441196c3
|
|
BLAKE2b-256 checksum How to use checksums |
4fb1a263b469bc7e5e51cc14ad6562c7cec1999232938bd063650173dd28c86a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.18
|
Security for qikou 3.0.0
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.